print_syscall_ret_addr(const struct syscallname *name, abi_long ret)

{

    char *errstr = NULL;

    if (ret == -1) {

        errstr = target_strerror(errno);

    }

    if ((ret == -1) && errstr) {

        gemu_log(" = -1 errno=%d (%s)\n", errno, errstr);

    } else {

        gemu_log(" = 0x" TARGET_ABI_FMT_lx "\n", ret);

    }

}


static int rv30_decode_mb_info(RV34DecContext *r)

{

    static const int rv30_p_types[6] = { RV34_MB_SKIP, RV34_MB_P_16x16, RV34_MB_P_8x8, -1, RV34_MB_TYPE_INTRA, RV34_MB_TYPE_INTRA16x16 };

    static const int rv30_b_types[6] = { RV34_MB_SKIP, RV34_MB_B_DIRECT, RV34_MB_B_FORWARD, RV34_MB_B_BACKWARD, RV34_MB_TYPE_INTRA, RV34_MB_TYPE_INTRA16x16 };

    MpegEncContext *s = &r->s;

    GetBitContext *gb = &s->gb;

    int code = svq3_get_ue_golomb(gb);

    if(code > 11){

        av_log(s->avctx, AV_LOG_ERROR, "Incorrect MB type code\n");

        return -1;

    }

    if(code > 5){

        av_log(s->avctx, AV_LOG_ERROR, "dquant needed\n");

        code -= 6;

    }

    if(s->pict_type != AV_PICTURE_TYPE_B)

        return rv30_p_types[code];

    else

        return rv30_b_types[code];

}


static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)

{

    int i, j;

    int has_fg, has_bg;

    uint8_t *last_fg, *last_bg;

    vnc_framebuffer_update(vs, x, y, w, h, 5);

    last_fg = (uint8_t *) malloc(vs->depth);

    last_bg = (uint8_t *) malloc(vs->depth);

    has_fg = has_bg = 0;

    for (j = y; j < (y + h); j += 16) {

	for (i = x; i < (x + w); i += 16) {

            vs->send_hextile_tile(vs, i, j,

                                  MIN(16, x + w - i), MIN(16, y + h - j),

                                  last_bg, last_fg, &has_bg, &has_fg);

	}

    }

    free(last_fg);

    free(last_bg);

}


static av_cold int j2kenc_init(AVCodecContext *avctx)

{

    int i, ret;

    Jpeg2000EncoderContext *s = avctx->priv_data;

    Jpeg2000CodingStyle *codsty = &s->codsty;

    Jpeg2000QuantStyle  *qntsty = &s->qntsty;

    s->avctx = avctx;

    av_log(s->avctx, AV_LOG_DEBUG, "init\n");

    // defaults:

    // TODO: implement setting non-standard precinct size

    memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));

    memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));

    codsty->nreslevels2decode=

    codsty->nreslevels       = 7;

    codsty->log2_cblk_width  = 4;

    codsty->log2_cblk_height = 4;

    codsty->transform        = avctx->prediction_method ? FF_DWT53 : FF_DWT97_INT;

    qntsty->nguardbits       = 1;

    s->tile_width            = 256;

    s->tile_height           = 256;

    if (codsty->transform == FF_DWT53)

        qntsty->quantsty = JPEG2000_QSTY_NONE;

    else

        qntsty->quantsty = JPEG2000_QSTY_SE;

    s->width = avctx->width;

    s->height = avctx->height;

    for (i = 0; i < 3; i++)

        s->cbps[i] = 8;

    if (avctx->pix_fmt == AV_PIX_FMT_RGB24){

        s->ncomponents = 3;

    } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8){

        s->ncomponents = 1;

    } else{ // planar YUV

        s->planar = 1;

        s->ncomponents = 3;

        avcodec_get_chroma_sub_sample(avctx->pix_fmt,

                s->chroma_shift, s->chroma_shift + 1);

    }

    ff_jpeg2000_init_tier1_luts();

    ff_mqc_init_context_tables();

    init_luts();

    init_quantization(s);

    if (ret=init_tiles(s))

        return ret;

    av_log(s->avctx, AV_LOG_DEBUG, "after init\n");

    return 0;

}


static void ppc405_ocm_init(CPUPPCState *env)

{

    ppc405_ocm_t *ocm;

    ocm = g_malloc0(sizeof(ppc405_ocm_t));

    /* XXX: Size is 4096 or 0x04000000 */

    memory_region_init_ram(&ocm->isarc_ram, NULL, "ppc405.ocm", 4096,

                           &error_abort);

    vmstate_register_ram_global(&ocm->isarc_ram);

    memory_region_init_alias(&ocm->dsarc_ram, NULL, "ppc405.dsarc", &ocm->isarc_ram,

                             0, 4096);

    qemu_register_reset(&ocm_reset, ocm);

    ppc_dcr_register(env, OCM0_ISARC,

                     ocm, &dcr_read_ocm, &dcr_write_ocm);

    ppc_dcr_register(env, OCM0_ISACNTL,

                     ocm, &dcr_read_ocm, &dcr_write_ocm);

    ppc_dcr_register(env, OCM0_DSARC,

                     ocm, &dcr_read_ocm, &dcr_write_ocm);

    ppc_dcr_register(env, OCM0_DSACNTL,

                     ocm, &dcr_read_ocm, &dcr_write_ocm);

}


static int serial_load(QEMUFile *f, void *opaque, int version_id)

{

    SerialState *s = opaque;

    if(version_id > 2)

        return -EINVAL;

    if (version_id >= 2)

        qemu_get_be16s(f, &s->divider);

    else

        s->divider = qemu_get_byte(f);

    qemu_get_8s(f,&s->rbr);

    qemu_get_8s(f,&s->ier);

    qemu_get_8s(f,&s->iir);

    qemu_get_8s(f,&s->lcr);

    qemu_get_8s(f,&s->mcr);

    qemu_get_8s(f,&s->lsr);

    qemu_get_8s(f,&s->msr);

    qemu_get_8s(f,&s->scr);

    return 0;

}


void ff_release_unused_pictures(MpegEncContext *s, int remove_current)

{

    int i;

    /* release non reference frames */

    for(i=0; i<s->picture_count; i++){

        if(s->picture[i].data[0] && !s->picture[i].reference

           && s->picture[i].owner2 == s

           && (remove_current || &s->picture[i] != s->current_picture_ptr)

           /*&& s->picture[i].type!=FF_BUFFER_TYPE_SHARED*/){

            free_frame_buffer(s, &s->picture[i]);

        }

    }

}


static inline void vmsvga_update_rect(struct vmsvga_state_s *s,

                int x, int y, int w, int h)

{

#ifndef DIRECT_VRAM

    int line = h;

    int bypl = s->bypp * s->width;

    int width = s->bypp * w;

    int start = s->bypp * x + bypl * y;

    uint8_t *src = s->vram + start;

    uint8_t *dst = s->ds->data + start;

    for (; line > 0; line --, src += bypl, dst += bypl)

        memcpy(dst, src, width);

#endif

    dpy_update(s->ds, x, y, w, h);

}


static int os_host_main_loop_wait(uint32_t timeout)

{

    GMainContext *context = g_main_context_default();

    int select_ret, g_poll_ret, ret, i;

    PollingEntry *pe;

    WaitObjects *w = &wait_objects;

    gint poll_timeout;

    static struct timeval tv0;

    /* XXX: need to suppress polling by better using win32 events */

    ret = 0;

    for (pe = first_polling_entry; pe != NULL; pe = pe->next) {

        ret |= pe->func(pe->opaque);

    }

    if (ret != 0) {

        return ret;

    }

    g_main_context_prepare(context, &max_priority);

    n_poll_fds = g_main_context_query(context, max_priority, &poll_timeout,

                                      poll_fds, ARRAY_SIZE(poll_fds));

    g_assert(n_poll_fds <= ARRAY_SIZE(poll_fds));

    for (i = 0; i < w->num; i++) {

        poll_fds[n_poll_fds + i].fd = (DWORD_PTR)w->events[i];

        poll_fds[n_poll_fds + i].events = G_IO_IN;

    }

    if (poll_timeout < 0 || timeout < poll_timeout) {

        poll_timeout = timeout;

    }

    qemu_mutex_unlock_iothread();

    g_poll_ret = g_poll(poll_fds, n_poll_fds + w->num, poll_timeout);

    qemu_mutex_lock_iothread();

    if (g_poll_ret > 0) {

        for (i = 0; i < w->num; i++) {

            w->revents[i] = poll_fds[n_poll_fds + i].revents;

        }

        for (i = 0; i < w->num; i++) {

            if (w->revents[i] && w->func[i]) {

                w->func[i](w->opaque[i]);

            }

        }

    }

    if (g_main_context_check(context, max_priority, poll_fds, n_poll_fds)) {

        g_main_context_dispatch(context);

    }

    /* Call select after g_poll to avoid a useless iteration and therefore

     * improve socket latency.

     */

    if (nfds >= 0) {

        select_ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv0);

        if (select_ret != 0) {

            timeout = 0;

        }

    }

    return select_ret || g_poll_ret;

}


static void *spapr_create_fdt_skel(const char *cpu_model,

                                   target_phys_addr_t rma_size,

                                   target_phys_addr_t initrd_base,

                                   target_phys_addr_t initrd_size,

                                   const char *boot_device,

                                   const char *kernel_cmdline,

                                   long hash_shift)

{

    void *fdt;

    CPUState *env;

    uint64_t mem_reg_property[2];

    uint32_t start_prop = cpu_to_be32(initrd_base);

    uint32_t end_prop = cpu_to_be32(initrd_base + initrd_size);

    uint32_t pft_size_prop[] = {0, cpu_to_be32(hash_shift)};

    char hypertas_prop[] = "hcall-pft\0hcall-term\0hcall-dabr\0hcall-interrupt"

        "\0hcall-tce\0hcall-vio\0hcall-splpar\0hcall-bulk";

    uint32_t interrupt_server_ranges_prop[] = {0, cpu_to_be32(smp_cpus)};

    int i;

    char *modelname;

    int smt = kvmppc_smt_threads();

    unsigned char vec5[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x80};

    uint32_t refpoints[] = {cpu_to_be32(0x4), cpu_to_be32(0x4)};

    uint32_t associativity[] = {cpu_to_be32(0x4), cpu_to_be32(0x0),

                                cpu_to_be32(0x0), cpu_to_be32(0x0),

                                cpu_to_be32(0x0)};

    char mem_name[32];

    target_phys_addr_t node0_size, mem_start;

#define _FDT(exp) \

    do { \

        int ret = (exp);                                           \

        if (ret < 0) {                                             \

            fprintf(stderr, "qemu: error creating device tree: %s: %s\n", \

                    #exp, fdt_strerror(ret));                      \

            exit(1);                                               \

        }                                                          \

    } while (0)

    fdt = g_malloc0(FDT_MAX_SIZE);

    _FDT((fdt_create(fdt, FDT_MAX_SIZE)));

    _FDT((fdt_finish_reservemap(fdt)));

    /* Root node */

    _FDT((fdt_begin_node(fdt, "")));

    _FDT((fdt_property_string(fdt, "device_type", "chrp")));

    _FDT((fdt_property_string(fdt, "model", "IBM pSeries (emulated by qemu)")));

    _FDT((fdt_property_cell(fdt, "#address-cells", 0x2)));

    _FDT((fdt_property_cell(fdt, "#size-cells", 0x2)));

    /* /chosen */

    _FDT((fdt_begin_node(fdt, "chosen")));

    /* Set Form1_affinity */

    _FDT((fdt_property(fdt, "ibm,architecture-vec-5", vec5, sizeof(vec5))));

    _FDT((fdt_property_string(fdt, "bootargs", kernel_cmdline)));

    _FDT((fdt_property(fdt, "linux,initrd-start",

                       &start_prop, sizeof(start_prop))));

    _FDT((fdt_property(fdt, "linux,initrd-end",

                       &end_prop, sizeof(end_prop))));

    _FDT((fdt_property_string(fdt, "qemu,boot-device", boot_device)));

    /*

     * Because we don't always invoke any firmware, we can't rely on

     * that to do BAR allocation.  Long term, we should probably do

     * that ourselves, but for now, this setting (plus advertising the

     * current BARs as 0) causes sufficiently recent kernels to to the

     * BAR assignment themselves */

    _FDT((fdt_property_cell(fdt, "linux,pci-probe-only", 0)));

    _FDT((fdt_end_node(fdt)));

    /* memory node(s) */

    node0_size = (nb_numa_nodes > 1) ? node_mem[0] : ram_size;

    if (rma_size > node0_size) {

        rma_size = node0_size;

    }

    /* RMA */

    mem_reg_property[0] = 0;

    mem_reg_property[1] = cpu_to_be64(rma_size);

    _FDT((fdt_begin_node(fdt, "memory@0")));

    _FDT((fdt_property_string(fdt, "device_type", "memory")));

    _FDT((fdt_property(fdt, "reg", mem_reg_property,

        sizeof(mem_reg_property))));

    _FDT((fdt_property(fdt, "ibm,associativity", associativity,

        sizeof(associativity))));

    _FDT((fdt_end_node(fdt)));

    /* RAM: Node 0 */

    if (node0_size > rma_size) {

        mem_reg_property[0] = cpu_to_be64(rma_size);

        mem_reg_property[1] = cpu_to_be64(node0_size - rma_size);

        sprintf(mem_name, "memory@" TARGET_FMT_lx, rma_size);

        _FDT((fdt_begin_node(fdt, mem_name)));

        _FDT((fdt_property_string(fdt, "device_type", "memory")));

        _FDT((fdt_property(fdt, "reg", mem_reg_property,

                           sizeof(mem_reg_property))));

        _FDT((fdt_property(fdt, "ibm,associativity", associativity,

                           sizeof(associativity))));

        _FDT((fdt_end_node(fdt)));

    }

    /* RAM: Node 1 and beyond */

    mem_start = node0_size;

    for (i = 1; i < nb_numa_nodes; i++) {

        mem_reg_property[0] = cpu_to_be64(mem_start);

        mem_reg_property[1] = cpu_to_be64(node_mem[i]);

        associativity[3] = associativity[4] = cpu_to_be32(i);

        sprintf(mem_name, "memory@" TARGET_FMT_lx, mem_start);

        _FDT((fdt_begin_node(fdt, mem_name)));

        _FDT((fdt_property_string(fdt, "device_type", "memory")));

        _FDT((fdt_property(fdt, "reg", mem_reg_property,

            sizeof(mem_reg_property))));

        _FDT((fdt_property(fdt, "ibm,associativity", associativity,

            sizeof(associativity))));

        _FDT((fdt_end_node(fdt)));

        mem_start += node_mem[i];

    }

    /* cpus */

    _FDT((fdt_begin_node(fdt, "cpus")));

    _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));

    _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));

    modelname = g_strdup(cpu_model);

    for (i = 0; i < strlen(modelname); i++) {

        modelname[i] = toupper(modelname[i]);

    }

    /* This is needed during FDT finalization */

    spapr->cpu_model = g_strdup(modelname);

    for (env = first_cpu; env != NULL; env = env->next_cpu) {

        int index = env->cpu_index;

        uint32_t servers_prop[smp_threads];

        uint32_t gservers_prop[smp_threads * 2];

        char *nodename;

        uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40),

                           0xffffffff, 0xffffffff};

        uint32_t tbfreq = kvm_enabled() ? kvmppc_get_tbfreq() : TIMEBASE_FREQ;

        uint32_t cpufreq = kvm_enabled() ? kvmppc_get_clockfreq() : 1000000000;

        if ((index % smt) != 0) {

            continue;

        }

        if (asprintf(&nodename, "%s@%x", modelname, index) < 0) {

            fprintf(stderr, "Allocation failure\n");

            exit(1);

        }

        _FDT((fdt_begin_node(fdt, nodename)));

        free(nodename);

        _FDT((fdt_property_cell(fdt, "reg", index)));

        _FDT((fdt_property_string(fdt, "device_type", "cpu")));

        _FDT((fdt_property_cell(fdt, "cpu-version", env->spr[SPR_PVR])));

        _FDT((fdt_property_cell(fdt, "dcache-block-size",

                                env->dcache_line_size)));

        _FDT((fdt_property_cell(fdt, "icache-block-size",

                                env->icache_line_size)));

        _FDT((fdt_property_cell(fdt, "timebase-frequency", tbfreq)));

        _FDT((fdt_property_cell(fdt, "clock-frequency", cpufreq)));

        _FDT((fdt_property_cell(fdt, "ibm,slb-size", env->slb_nr)));

        _FDT((fdt_property(fdt, "ibm,pft-size",

                           pft_size_prop, sizeof(pft_size_prop))));

        _FDT((fdt_property_string(fdt, "status", "okay")));

        _FDT((fdt_property(fdt, "64-bit", NULL, 0)));

        /* Build interrupt servers and gservers properties */

        for (i = 0; i < smp_threads; i++) {

            servers_prop[i] = cpu_to_be32(index + i);

            /* Hack, direct the group queues back to cpu 0 */

            gservers_prop[i*2] = cpu_to_be32(index + i);

            gservers_prop[i*2 + 1] = 0;

        }

        _FDT((fdt_property(fdt, "ibm,ppc-interrupt-server#s",

                           servers_prop, sizeof(servers_prop))));

        _FDT((fdt_property(fdt, "ibm,ppc-interrupt-gserver#s",

                           gservers_prop, sizeof(gservers_prop))));

        if (env->mmu_model & POWERPC_MMU_1TSEG) {

            _FDT((fdt_property(fdt, "ibm,processor-segment-sizes",

                               segs, sizeof(segs))));

        }

        /* Advertise VMX/VSX (vector extensions) if available

         *   0 / no property == no vector extensions

         *   1               == VMX / Altivec available

         *   2               == VSX available */

        if (env->insns_flags & PPC_ALTIVEC) {

            uint32_t vmx = (env->insns_flags2 & PPC2_VSX) ? 2 : 1;

            _FDT((fdt_property_cell(fdt, "ibm,vmx", vmx)));

        }

        /* Advertise DFP (Decimal Floating Point) if available

         *   0 / no property == no DFP

         *   1               == DFP available */

        if (env->insns_flags2 & PPC2_DFP) {

            _FDT((fdt_property_cell(fdt, "ibm,dfp", 1)));

        }

        _FDT((fdt_end_node(fdt)));

    }

    g_free(modelname);

    _FDT((fdt_end_node(fdt)));

    /* RTAS */

    _FDT((fdt_begin_node(fdt, "rtas")));

    _FDT((fdt_property(fdt, "ibm,hypertas-functions", hypertas_prop,

                       sizeof(hypertas_prop))));

    _FDT((fdt_property(fdt, "ibm,associativity-reference-points",

        refpoints, sizeof(refpoints))));

    _FDT((fdt_end_node(fdt)));

    /* interrupt controller */

    _FDT((fdt_begin_node(fdt, "interrupt-controller")));

    _FDT((fdt_property_string(fdt, "device_type",

                              "PowerPC-External-Interrupt-Presentation")));

    _FDT((fdt_property_string(fdt, "compatible", "IBM,ppc-xicp")));

    _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));

    _FDT((fdt_property(fdt, "ibm,interrupt-server-ranges",

                       interrupt_server_ranges_prop,

                       sizeof(interrupt_server_ranges_prop))));

    _FDT((fdt_property_cell(fdt, "#interrupt-cells", 2)));

    _FDT((fdt_property_cell(fdt, "linux,phandle", PHANDLE_XICP)));

    _FDT((fdt_property_cell(fdt, "phandle", PHANDLE_XICP)));

    _FDT((fdt_end_node(fdt)));

    /* vdevice */

    _FDT((fdt_begin_node(fdt, "vdevice")));

    _FDT((fdt_property_string(fdt, "device_type", "vdevice")));

    _FDT((fdt_property_string(fdt, "compatible", "IBM,vdevice")));

    _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));

    _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));

    _FDT((fdt_property_cell(fdt, "#interrupt-cells", 0x2)));

    _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));

    _FDT((fdt_end_node(fdt)));

    _FDT((fdt_end_node(fdt))); /* close root node */

    _FDT((fdt_finish(fdt)));

    return fdt;

}


static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)

{

    AVStream *st = c->fc->streams[c->fc->nb_streams-1];

    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;

    int entries, i;

    print_atom("stsc", atom);

    get_byte(pb); /* version */

    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */

    entries = get_be32(pb);

#ifdef DEBUG

av_log(NULL, AV_LOG_DEBUG, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);

#endif

    sc->sample_to_chunk_sz = entries;

    sc->sample_to_chunk = (MOV_sample_to_chunk_tbl*) av_malloc(entries * sizeof(MOV_sample_to_chunk_tbl));

    if (!sc->sample_to_chunk)

        return -1;

    for(i=0; i<entries; i++) {

        sc->sample_to_chunk[i].first = get_be32(pb);

        sc->sample_to_chunk[i].count = get_be32(pb);

        sc->sample_to_chunk[i].id = get_be32(pb);

#ifdef DEBUG

/*        av_log(NULL, AV_LOG_DEBUG, "sample_to_chunk first=%ld count=%ld, id=%ld\n", sc->sample_to_chunk[i].first, sc->sample_to_chunk[i].count, sc->sample_to_chunk[i].id); */

#endif

    }

    return 0;

}


av_cold int ff_MPV_common_init(MpegEncContext *s)

{

    int i;

    int nb_slices = (HAVE_THREADS &&

                     s->avctx->active_thread_type & FF_THREAD_SLICE) ?

                    s->avctx->thread_count : 1;

    if (s->encoding && s->avctx->slices)

        nb_slices = s->avctx->slices;

    if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)

        s->mb_height = (s->height + 31) / 32 * 2;

    else

        s->mb_height = (s->height + 15) / 16;

    if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) {

        av_log(s->avctx, AV_LOG_ERROR,

               "decoding to AV_PIX_FMT_NONE is not supported.\n");

        return -1;

    }

    if (nb_slices > MAX_THREADS || (nb_slices > s->mb_height && s->mb_height)) {

        int max_slices;

        if (s->mb_height)

            max_slices = FFMIN(MAX_THREADS, s->mb_height);

        else

            max_slices = MAX_THREADS;

        av_log(s->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"

               " reducing to %d\n", nb_slices, max_slices);

        nb_slices = max_slices;

    }

    if ((s->width || s->height) &&

        av_image_check_size(s->width, s->height, 0, s->avctx))

        return -1;

    ff_dct_common_init(s);

    s->flags  = s->avctx->flags;

    s->flags2 = s->avctx->flags2;

    /* set chroma shifts */

    av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt,

                                     &s->chroma_x_shift,

                                     &s->chroma_y_shift);

    /* convert fourcc to upper case */

    s->codec_tag          = avpriv_toupper4(s->avctx->codec_tag);

    s->stream_codec_tag   = avpriv_toupper4(s->avctx->stream_codec_tag);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->picture,

                      MAX_PICTURE_COUNT * sizeof(Picture), fail);

    for (i = 0; i < MAX_PICTURE_COUNT; i++) {

        av_frame_unref(&s->picture[i].f);

    }

    memset(&s->next_picture, 0, sizeof(s->next_picture));

    memset(&s->last_picture, 0, sizeof(s->last_picture));

    memset(&s->current_picture, 0, sizeof(s->current_picture));

    av_frame_unref(&s->next_picture.f);

    av_frame_unref(&s->last_picture.f);

    av_frame_unref(&s->current_picture.f);

    if (s->width && s->height) {

        if (init_context_frame(s))

            goto fail;

        s->parse_context.state = -1;

    }

    s->context_initialized = 1;

    s->thread_context[0]   = s;

    if (s->width && s->height) {

        if (nb_slices > 1) {

            for (i = 1; i < nb_slices; i++) {

                s->thread_context[i] = av_malloc(sizeof(MpegEncContext));

                memcpy(s->thread_context[i], s, sizeof(MpegEncContext));

            }

            for (i = 0; i < nb_slices; i++) {

                if (init_duplicate_context(s->thread_context[i]) < 0)

                    goto fail;

                    s->thread_context[i]->start_mb_y =

                        (s->mb_height * (i) + nb_slices / 2) / nb_slices;

                    s->thread_context[i]->end_mb_y   =

                        (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;

            }

        } else {

            if (init_duplicate_context(s) < 0)

                goto fail;

            s->start_mb_y = 0;

            s->end_mb_y   = s->mb_height;

        }

        s->slice_context_count = nb_slices;

    }

    return 0;

 fail:

    ff_MPV_common_end(s);

    return -1;

}


static void handle_control_message(VirtIOSerial *vser, void *buf)

{

    struct VirtIOSerialPort *port;

    struct virtio_console_control cpkt, *gcpkt;

    uint8_t *buffer;

    size_t buffer_len;

    gcpkt = buf;

    cpkt.event = lduw_p(&gcpkt->event);

    cpkt.value = lduw_p(&gcpkt->value);

    port = find_port_by_id(vser, ldl_p(&gcpkt->id));

    if (!port && cpkt.event != VIRTIO_CONSOLE_DEVICE_READY)

        return;

    switch(cpkt.event) {

    case VIRTIO_CONSOLE_DEVICE_READY:

        if (!cpkt.value) {

            error_report("virtio-serial-bus: Guest failure in adding device %s\n",

                         vser->bus->qbus.name);

            break;

        }

        /*

         * The device is up, we can now tell the device about all the

         * ports we have here.

         */

        QTAILQ_FOREACH(port, &vser->ports, next) {

            send_control_event(port, VIRTIO_CONSOLE_PORT_ADD, 1);

        }

        break;

    case VIRTIO_CONSOLE_PORT_READY:

        if (!cpkt.value) {

            error_report("virtio-serial-bus: Guest failure in adding port %u for device %s\n",

                         port->id, vser->bus->qbus.name);

            break;

        }

        /*

         * Now that we know the guest asked for the port name, we're

         * sure the guest has initialised whatever state is necessary

         * for this port. Now's a good time to let the guest know if

         * this port is a console port so that the guest can hook it

         * up to hvc.

         */

        if (port->is_console) {

            send_control_event(port, VIRTIO_CONSOLE_CONSOLE_PORT, 1);

        }

        if (port->name) {

            stw_p(&cpkt.event, VIRTIO_CONSOLE_PORT_NAME);

            stw_p(&cpkt.value, 1);

            buffer_len = sizeof(cpkt) + strlen(port->name) + 1;

            buffer = qemu_malloc(buffer_len);

            memcpy(buffer, &cpkt, sizeof(cpkt));

            memcpy(buffer + sizeof(cpkt), port->name, strlen(port->name));

            buffer[buffer_len - 1] = 0;

            send_control_msg(port, buffer, buffer_len);

            qemu_free(buffer);

        }

        if (port->host_connected) {

            send_control_event(port, VIRTIO_CONSOLE_PORT_OPEN, 1);

        }

        /*

         * When the guest has asked us for this information it means

         * the guest is all setup and has its virtqueues

         * initialised. If some app is interested in knowing about

         * this event, let it know.

         */

        if (port->info->guest_ready) {

            port->info->guest_ready(port);

        }

        break;

    case VIRTIO_CONSOLE_PORT_OPEN:

        port->guest_connected = cpkt.value;

        if (cpkt.value && port->info->guest_open) {

            /* Send the guest opened notification if an app is interested */

            port->info->guest_open(port);

        }

        if (!cpkt.value && port->info->guest_close) {

            /* Send the guest closed notification if an app is interested */

            port->info->guest_close(port);

        }

        break;

    }

}


static int blend_frames(AVFilterContext *ctx, int interpolate)

{

    FrameRateContext *s = ctx->priv;

    AVFilterLink *outlink = ctx->outputs[0];

    double interpolate_scene_score = 0;

    if ((s->flags & FRAMERATE_FLAG_SCD)) {

        if (s->score >= 0.0)

            interpolate_scene_score = s->score;

        else

            interpolate_scene_score = s->score = get_scene_score(ctx, s->f0, s->f1);

        ff_dlog(ctx, "blend_frames() interpolate scene score:%f\n", interpolate_scene_score);

    }

    // decide if the shot-change detection allows us to blend two frames

    if (interpolate_scene_score < s->scene_score) {

        ThreadData td;

        td.copy_src1 = s->f0;

        td.copy_src2 = s->f1;

        td.src2_factor = interpolate;

        td.src1_factor = s->max - td.src2_factor;

        // get work-space for output frame

        s->work = ff_get_video_buffer(outlink, outlink->w, outlink->h);

        if (!s->work)

            return AVERROR(ENOMEM);

        av_frame_copy_props(s->work, s->f0);

        ff_dlog(ctx, "blend_frames() INTERPOLATE to create work frame\n");

        ctx->internal->execute(ctx, filter_slice, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));

        return 1;

    }

    return 0;

}


static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)

{

    unsigned flags = rhs->flags;

    lhs->selector = rhs->selector;

    lhs->base = rhs->base;

    lhs->limit = rhs->limit;

    lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;

    lhs->present = (flags & DESC_P_MASK) != 0;

    lhs->dpl = rhs->selector & 3;

    lhs->db = (flags >> DESC_B_SHIFT) & 1;

    lhs->s = (flags & DESC_S_MASK) != 0;

    lhs->l = (flags >> DESC_L_SHIFT) & 1;

    lhs->g = (flags & DESC_G_MASK) != 0;

    lhs->avl = (flags & DESC_AVL_MASK) != 0;

    lhs->unusable = 0;

}


static int parse_bintree(Indeo3DecodeContext *ctx, AVCodecContext *avctx,

                         Plane *plane, int code, Cell *ref_cell,

                         const int depth, const int strip_width)

{

    Cell    curr_cell;

    int     bytes_used;

    if (depth <= 0) {

        av_log(avctx, AV_LOG_ERROR, "Stack overflow (corrupted binary tree)!\n");

        return AVERROR_INVALIDDATA; // unwind recursion

    }

    curr_cell = *ref_cell; // clone parent cell

    if (code == H_SPLIT) {

        SPLIT_CELL(ref_cell->height, curr_cell.height);

        ref_cell->ypos   += curr_cell.height;

        ref_cell->height -= curr_cell.height;

    } else if (code == V_SPLIT) {

        if (curr_cell.width > strip_width) {

            /* split strip */

            curr_cell.width = (curr_cell.width <= (strip_width << 1) ? 1 : 2) * strip_width;

        } else

            SPLIT_CELL(ref_cell->width, curr_cell.width);

        ref_cell->xpos  += curr_cell.width;

        ref_cell->width -= curr_cell.width;

    }

    while (get_bits_left(&ctx->gb) >= 2) { /* loop until return */

        RESYNC_BITSTREAM;

        switch (code = get_bits(&ctx->gb, 2)) {

        case H_SPLIT:

        case V_SPLIT:

            if (parse_bintree(ctx, avctx, plane, code, &curr_cell, depth - 1, strip_width))

                return AVERROR_INVALIDDATA;

            break;

        case INTRA_NULL:

            if (!curr_cell.tree) { /* MC tree INTRA code */

                curr_cell.mv_ptr = 0; /* mark the current strip as INTRA */

                curr_cell.tree   = 1; /* enter the VQ tree */

            } else { /* VQ tree NULL code */

                RESYNC_BITSTREAM;

                code = get_bits(&ctx->gb, 2);

                if (code >= 2) {

                    av_log(avctx, AV_LOG_ERROR, "Invalid VQ_NULL code: %d\n", code);

                    return AVERROR_INVALIDDATA;

                }

                if (code == 1)

                    av_log(avctx, AV_LOG_ERROR, "SkipCell procedure not implemented yet!\n");

                CHECK_CELL

                if (!curr_cell.mv_ptr)

                    return AVERROR_INVALIDDATA;

                copy_cell(ctx, plane, &curr_cell);

                return 0;

            }

            break;

        case INTER_DATA:

            if (!curr_cell.tree) { /* MC tree INTER code */

                /* get motion vector index and setup the pointer to the mv set */

                if (!ctx->need_resync)

                    ctx->next_cell_data = &ctx->gb.buffer[(get_bits_count(&ctx->gb) + 7) >> 3];

                curr_cell.mv_ptr = &ctx->mc_vectors[*(ctx->next_cell_data++) << 1];

                curr_cell.tree   = 1; /* enter the VQ tree */

                UPDATE_BITPOS(8);

            } else { /* VQ tree DATA code */

                if (!ctx->need_resync)

                    ctx->next_cell_data = &ctx->gb.buffer[(get_bits_count(&ctx->gb) + 7) >> 3];

                CHECK_CELL

                bytes_used = decode_cell(ctx, avctx, plane, &curr_cell,

                                         ctx->next_cell_data, ctx->last_byte);

                if (bytes_used < 0)

                    return AVERROR_INVALIDDATA;

                UPDATE_BITPOS(bytes_used << 3);

                ctx->next_cell_data += bytes_used;

                return 0;

            }

            break;

        }

    }//while

    return AVERROR_INVALIDDATA;

}


static int parse_chunks(AVFormatContext *s, int mode, int64_t seekts, int *len_ptr)

{

    WtvContext *wtv = s->priv_data;

    ByteIOContext *pb = wtv->pb;

    while (!url_feof(pb)) {

        ff_asf_guid g;

        int len, sid, consumed;

        ff_get_guid(pb, &g);

        len = get_le32(pb);

        if (len < 32)

            break;

        sid = get_le32(pb) & 0x7FFF;

        url_fskip(pb, 8);

        consumed = 32;

        if (!ff_guidcmp(g, stream_guid)) {

            if (ff_find_stream_index(s, sid) < 0) {

                ff_asf_guid mediatype, subtype, formattype;

                int size;

                consumed += 20;

                url_fskip(pb, 16);

                if (get_le32(pb)) {

                    url_fskip(pb, 8);

                    ff_get_guid(pb, &mediatype);

                    ff_get_guid(pb, &subtype);

                    url_fskip(pb, 12);

                    ff_get_guid(pb, &formattype);

                    size = get_le32(pb);

                    parse_media_type(s, 0, sid, mediatype, subtype, formattype, size);

                    consumed += 72 + size;

                }

            }

        } else if (!ff_guidcmp(g, stream2_guid)) {

            int stream_index = ff_find_stream_index(s, sid);

            if (stream_index >= 0 && !((WtvStream*)s->streams[stream_index]->priv_data)->seen_data) {

                ff_asf_guid mediatype, subtype, formattype;

                int size;

                url_fskip(pb, 12);

                ff_get_guid(pb, &mediatype);

                ff_get_guid(pb, &subtype);

                url_fskip(pb, 12);

                ff_get_guid(pb, &formattype);

                size = get_le32(pb);

                parse_media_type(s, s->streams[stream_index], sid, mediatype, subtype, formattype, size);

                consumed += 76 + size;

            }

        } else if (!ff_guidcmp(g, EVENTID_AudioDescriptorSpanningEvent) ||

                   !ff_guidcmp(g, EVENTID_CtxADescriptorSpanningEvent) ||

                   !ff_guidcmp(g, EVENTID_CSDescriptorSpanningEvent) ||

                   !ff_guidcmp(g, EVENTID_StreamIDSpanningEvent) ||

                   !ff_guidcmp(g, EVENTID_SubtitleSpanningEvent) ||

                   !ff_guidcmp(g, EVENTID_TeletextSpanningEvent)) {

            int stream_index = ff_find_stream_index(s, sid);

            if (stream_index >= 0) {

                AVStream *st = s->streams[stream_index];

                uint8_t buf[258];

                const uint8_t *pbuf = buf;

                int buf_size;

                url_fskip(pb, 8);

                consumed += 8;

                if (!ff_guidcmp(g, EVENTID_CtxADescriptorSpanningEvent) ||

                    !ff_guidcmp(g, EVENTID_CSDescriptorSpanningEvent)) {

                    url_fskip(pb, 6);

                    consumed += 6;

                }

                buf_size = FFMIN(len - consumed, sizeof(buf));

                get_buffer(pb, buf, buf_size);

                consumed += buf_size;

                ff_parse_mpeg2_descriptor(s, st, 0, &pbuf, buf + buf_size, 0, 0, 0, 0);

            }

        } else if (!ff_guidcmp(g, EVENTID_DVBScramblingControlSpanningEvent)) {

            int stream_index = ff_find_stream_index(s, sid);

            if (stream_index >= 0) {

                url_fskip(pb, 12);

                if (get_le32(pb))

                    av_log(s, AV_LOG_WARNING, "DVB scrambled stream detected (st:%d), decoding will likely fail\n", stream_index);

                consumed += 16;

            }

        } else if (!ff_guidcmp(g, EVENTID_LanguageSpanningEvent)) {

            int stream_index = ff_find_stream_index(s, sid);

            if (stream_index >= 0) {

                AVStream *st = s->streams[stream_index];

                uint8_t language[4];

                url_fskip(pb, 12);

                get_buffer(pb, language, 3);

                if (language[0]) {

                    language[3] = 0;

                    av_metadata_set2(&st->metadata, "language", language, 0);

                }

                consumed += 15;

            }

        } else if (!ff_guidcmp(g, timestamp_guid)) {

            int stream_index = ff_find_stream_index(s, sid);

            if (stream_index >= 0) {

                url_fskip(pb, 8);

                wtv->pts = get_le64(pb);

                consumed += 16;

                if (wtv->pts == -1)

                    wtv->pts = AV_NOPTS_VALUE;

                else {

                    wtv->last_valid_pts = wtv->pts;

                    if (wtv->epoch == AV_NOPTS_VALUE || wtv->pts < wtv->epoch)

                        wtv->epoch = wtv->pts;

                if (mode == SEEK_TO_PTS && wtv->pts >= seekts) {

#define WTV_PAD8(x) (((x) + 7) & ~7)

                    url_fskip(pb, WTV_PAD8(len) - consumed);

                    return 0;

                }

                }

            }

        } else if (!ff_guidcmp(g, data_guid)) {

            int stream_index = ff_find_stream_index(s, sid);

            if (mode == SEEK_TO_DATA && stream_index >= 0) {

                WtvStream *wst = s->streams[stream_index]->priv_data;

                wst->seen_data = 1;

                if (len_ptr) {

                    *len_ptr = len;

                }

                return stream_index;

            }

        } else if (

            !ff_guidcmp(g, /* DSATTRIB_CAPTURE_STREAMTIME */ (const ff_asf_guid){0x14,0x56,0x1A,0x0C,0xCD,0x30,0x40,0x4F,0xBC,0xBF,0xD0,0x3E,0x52,0x30,0x62,0x07}) ||

            !ff_guidcmp(g, /* DSATTRIB_PicSampleSeq */ (const ff_asf_guid){0x02,0xAE,0x5B,0x2F,0x8F,0x7B,0x60,0x4F,0x82,0xD6,0xE4,0xEA,0x2F,0x1F,0x4C,0x99}) ||

            !ff_guidcmp(g, /* DSATTRIB_TRANSPORT_PROPERTIES */ (const ff_asf_guid){0x12,0xF6,0x22,0xB6,0xAD,0x47,0x71,0x46,0xAD,0x6C,0x05,0xA9,0x8E,0x65,0xDE,0x3A}) ||

            !ff_guidcmp(g, /* dvr_ms_vid_frame_rep_data */ (const ff_asf_guid){0xCC,0x32,0x64,0xDD,0x29,0xE2,0xDB,0x40,0x80,0xF6,0xD2,0x63,0x28,0xD2,0x76,0x1F}) ||

            !ff_guidcmp(g, /* EVENTID_AudioTypeSpanningEvent */ (const ff_asf_guid){0xBE,0xBF,0x1C,0x50,0x49,0xB8,0xCE,0x42,0x9B,0xE9,0x3D,0xB8,0x69,0xFB,0x82,0xB3}) ||

            !ff_guidcmp(g, /* EVENTID_ChannelChangeSpanningEvent */ (const ff_asf_guid){0xE5,0xC5,0x67,0x90,0x5C,0x4C,0x05,0x42,0x86,0xC8,0x7A,0xFE,0x20,0xFE,0x1E,0xFA}) ||

            !ff_guidcmp(g, /* EVENTID_ChannelInfoSpanningEvent */ (const ff_asf_guid){0x80,0x6D,0xF3,0x41,0x32,0x41,0xC2,0x4C,0xB1,0x21,0x01,0xA4,0x32,0x19,0xD8,0x1B}) ||

            !ff_guidcmp(g, /* EVENTID_ChannelTypeSpanningEvent */ (const ff_asf_guid){0x51,0x1D,0xAB,0x72,0xD2,0x87,0x9B,0x48,0xBA,0x11,0x0E,0x08,0xDC,0x21,0x02,0x43}) ||

            !ff_guidcmp(g, /* EVENTID_PIDListSpanningEvent */ (const ff_asf_guid){0x65,0x8F,0xFC,0x47,0xBB,0xE2,0x34,0x46,0x9C,0xEF,0xFD,0xBF,0xE6,0x26,0x1D,0x5C}) ||

            !ff_guidcmp(g, /* EVENTID_SignalAndServiceStatusSpanningEvent */ (const ff_asf_guid){0xCB,0xC5,0x68,0x80,0x04,0x3C,0x2B,0x49,0xB4,0x7D,0x03,0x08,0x82,0x0D,0xCE,0x51}) ||

            !ff_guidcmp(g, /* EVENTID_StreamTypeSpanningEvent */ (const ff_asf_guid){0xBC,0x2E,0xAF,0x82,0xA6,0x30,0x64,0x42,0xA8,0x0B,0xAD,0x2E,0x13,0x72,0xAC,0x60}) ||

            !ff_guidcmp(g, (const ff_asf_guid){0x1E,0xBE,0xC3,0xC5,0x43,0x92,0xDC,0x11,0x85,0xE5,0x00,0x12,0x3F,0x6F,0x73,0xB9}) ||

            !ff_guidcmp(g, (const ff_asf_guid){0x3B,0x86,0xA2,0xB1,0xEB,0x1E,0xC3,0x44,0x8C,0x88,0x1C,0xA3,0xFF,0xE3,0xE7,0x6A}) ||

            !ff_guidcmp(g, (const ff_asf_guid){0x4E,0x7F,0x4C,0x5B,0xC4,0xD0,0x38,0x4B,0xA8,0x3E,0x21,0x7F,0x7B,0xBF,0x52,0xE7}) ||

            !ff_guidcmp(g, (const ff_asf_guid){0x63,0x36,0xEB,0xFE,0xA1,0x7E,0xD9,0x11,0x83,0x08,0x00,0x07,0xE9,0x5E,0xAD,0x8D}) ||

            !ff_guidcmp(g, (const ff_asf_guid){0x70,0xE9,0xF1,0xF8,0x89,0xA4,0x4C,0x4D,0x83,0x73,0xB8,0x12,0xE0,0xD5,0xF8,0x1E}) ||

            !ff_guidcmp(g, (const ff_asf_guid){0x96,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D}) ||

            !ff_guidcmp(g, (const ff_asf_guid){0x97,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D}) ||

            !ff_guidcmp(g, (const ff_asf_guid){0xA1,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D})) {

            //ignore known guids

        } else

            av_log(s, AV_LOG_WARNING, "unsupported chunk:"PRI_GUID"\n", ARG_GUID(g));

        url_fskip(pb, WTV_PAD8(len) - consumed);

    }

    return AVERROR_EOF;

}


static void ac3_decode_transform_coeffs_ch(AC3DecodeContext *s, int ch_index, mant_groups *m)

{

    int start_freq = s->start_freq[ch_index];

    int end_freq   = s->end_freq[ch_index];

    uint8_t *baps  = s->bap[ch_index];

    int8_t *exps   = s->dexps[ch_index];

    int32_t *coeffs = s->fixed_coeffs[ch_index];

    int dither     = (ch_index == CPL_CH) || s->dither_flag[ch_index];

    GetBitContext *gbc = &s->gbc;

    int freq;

    for (freq = start_freq; freq < end_freq; freq++) {

        int bap = baps[freq];

        int mantissa;

        switch (bap) {

        case 0:

            /* random noise with approximate range of -0.707 to 0.707 */

            if (dither)

                mantissa = (((av_lfg_get(&s->dith_state)>>8)*181)>>8) - 5931008;

            else

                mantissa = 0;

            break;

        case 1:

            if (m->b1) {

                m->b1--;

                mantissa = m->b1_mant[m->b1];

            } else {

                int bits      = get_bits(gbc, 5);

                mantissa      = b1_mantissas[bits][0];

                m->b1_mant[1] = b1_mantissas[bits][1];

                m->b1_mant[0] = b1_mantissas[bits][2];

                m->b1         = 2;

            break;

        case 2:

            if (m->b2) {

                m->b2--;

                mantissa = m->b2_mant[m->b2];

            } else {

                int bits      = get_bits(gbc, 7);

                mantissa      = b2_mantissas[bits][0];

                m->b2_mant[1] = b2_mantissas[bits][1];

                m->b2_mant[0] = b2_mantissas[bits][2];

                m->b2         = 2;

            break;

        case 3:

            mantissa = b3_mantissas[get_bits(gbc, 3)];

            break;

        case 4:

            if (m->b4) {

                m->b4 = 0;

                mantissa = m->b4_mant;

            } else {

                int bits   = get_bits(gbc, 7);

                mantissa   = b4_mantissas[bits][0];

                m->b4_mant = b4_mantissas[bits][1];

                m->b4      = 1;

            break;

        case 5:

            mantissa = b5_mantissas[get_bits(gbc, 4)];

            break;

        default: /* 6 to 15 */

            /* Shift mantissa and sign-extend it. */

            mantissa = get_sbits(gbc, quantization_tab[bap]);

            mantissa <<= 24 - quantization_tab[bap];

            break;

        coeffs[freq] = mantissa >> exps[freq];


int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,

                        bool exact_size)

{

    BDRVQcowState *s = bs->opaque;

    int new_l1_size2, ret, i;

    uint64_t *new_l1_table;

    int64_t old_l1_table_offset, old_l1_size;

    int64_t new_l1_table_offset, new_l1_size;

    uint8_t data[12];

    if (min_size <= s->l1_size)

        return 0;

    /* Do a sanity check on min_size before trying to calculate new_l1_size

     * (this prevents overflows during the while loop for the calculation of

     * new_l1_size) */

    if (min_size > INT_MAX / sizeof(uint64_t)) {

        return -EFBIG;

    }

    if (exact_size) {

        new_l1_size = min_size;

    } else {

        /* Bump size up to reduce the number of times we have to grow */

        new_l1_size = s->l1_size;

        if (new_l1_size == 0) {

            new_l1_size = 1;

        }

        while (min_size > new_l1_size) {

            new_l1_size = (new_l1_size * 3 + 1) / 2;

        }

    }

    if (new_l1_size > INT_MAX / sizeof(uint64_t)) {

        return -EFBIG;

    }

#ifdef DEBUG_ALLOC2

    fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n",

            s->l1_size, new_l1_size);

#endif

    new_l1_size2 = sizeof(uint64_t) * new_l1_size;

    new_l1_table = g_malloc0(align_offset(new_l1_size2, 512));

    memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));

    /* write new table (align to cluster) */

    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);

    new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);

    if (new_l1_table_offset < 0) {

        g_free(new_l1_table);

        return new_l1_table_offset;

    }

    ret = qcow2_cache_flush(bs, s->refcount_block_cache);

    if (ret < 0) {

        goto fail;

    }

    /* the L1 position has not yet been updated, so these clusters must

     * indeed be completely free */

    ret = qcow2_pre_write_overlap_check(bs, 0, new_l1_table_offset,

                                        new_l1_size2);

    if (ret < 0) {

        goto fail;

    }

    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);

    for(i = 0; i < s->l1_size; i++)

        new_l1_table[i] = cpu_to_be64(new_l1_table[i]);

    ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2);

    if (ret < 0)

        goto fail;

    for(i = 0; i < s->l1_size; i++)

        new_l1_table[i] = be64_to_cpu(new_l1_table[i]);

    /* set new table */

    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);

    cpu_to_be32w((uint32_t*)data, new_l1_size);

    stq_be_p(data + 4, new_l1_table_offset);

    ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data));

    if (ret < 0) {

        goto fail;

    }

    g_free(s->l1_table);

    old_l1_table_offset = s->l1_table_offset;

    s->l1_table_offset = new_l1_table_offset;

    s->l1_table = new_l1_table;

    old_l1_size = s->l1_size;

    s->l1_size = new_l1_size;

    qcow2_free_clusters(bs, old_l1_table_offset, old_l1_size * sizeof(uint64_t),

                        QCOW2_DISCARD_OTHER);

    return 0;

 fail:

    g_free(new_l1_table);

    qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2,

                        QCOW2_DISCARD_OTHER);

    return ret;

}


static void r2d_init(ram_addr_t ram_size,

              const char *boot_device,

	      const char *kernel_filename, const char *kernel_cmdline,

	      const char *initrd_filename, const char *cpu_model)

{

    CPUState *env;

    struct SH7750State *s;

    ram_addr_t sdram_addr;

    qemu_irq *irq;

    PCIBus *pci;

    DriveInfo *dinfo;

    int i;

    if (!cpu_model)

        cpu_model = "SH7751R";

    env = cpu_init(cpu_model);

    if (!env) {

        fprintf(stderr, "Unable to find CPU definition\n");

        exit(1);

    }

    /* Allocate memory space */

    sdram_addr = qemu_ram_alloc(SDRAM_SIZE);

    cpu_register_physical_memory(SDRAM_BASE, SDRAM_SIZE, sdram_addr);

    /* Register peripherals */

    s = sh7750_init(env);

    irq = r2d_fpga_init(0x04000000, sh7750_irl(s));

    pci = sh_pci_register_bus(r2d_pci_set_irq, r2d_pci_map_irq, irq, 0, 4);

    sm501_init(0x10000000, SM501_VRAM_SIZE, irq[SM501], serial_hds[2]);

    /* onboard CF (True IDE mode, Master only). */

    if ((dinfo = drive_get(IF_IDE, 0, 0)) != NULL)

	mmio_ide_init(0x14001000, 0x1400080c, irq[CF_IDE], 1,

		      dinfo, NULL);

    /* NIC: rtl8139 on-board, and 2 slots. */

    for (i = 0; i < nb_nics; i++)

        pci_nic_init(&nd_table[i], "rtl8139", i==0 ? "2" : NULL);

    /* Todo: register on board registers */

    if (kernel_filename) {

      int kernel_size;

      /* initialization which should be done by firmware */

      stl_phys(SH7750_BCR1, 1<<3); /* cs3 SDRAM */

      stw_phys(SH7750_BCR2, 3<<(3*2)); /* cs3 32bit */

      if (kernel_cmdline) {

          kernel_size = load_image_targphys(kernel_filename,

				   SDRAM_BASE + LINUX_LOAD_OFFSET,

				   SDRAM_SIZE - LINUX_LOAD_OFFSET);

          env->pc = (SDRAM_BASE + LINUX_LOAD_OFFSET) | 0xa0000000;

          pstrcpy_targphys(SDRAM_BASE + 0x10100, 256, kernel_cmdline);

      } else {

          kernel_size = load_image_targphys(kernel_filename, SDRAM_BASE, SDRAM_SIZE);

          env->pc = SDRAM_BASE | 0xa0000000; /* Start from P2 area */

      }

      if (kernel_size < 0) {

        fprintf(stderr, "qemu: could not load kernel '%s'\n", kernel_filename);

        exit(1);

      }

    }

}


void ppc_tlb_invalidate_one(CPUPPCState *env, target_ulong addr)

{

#if !defined(FLUSH_ALL_TLBS)

    PowerPCCPU *cpu = ppc_env_get_cpu(env);

    CPUState *cs;

    addr &= TARGET_PAGE_MASK;

    switch (env->mmu_model) {

    case POWERPC_MMU_SOFT_6xx:

    case POWERPC_MMU_SOFT_74xx:

        ppc6xx_tlb_invalidate_virt(env, addr, 0);

        if (env->id_tlbs == 1) {

            ppc6xx_tlb_invalidate_virt(env, addr, 1);

        }

        break;

    case POWERPC_MMU_32B:

    case POWERPC_MMU_601:

        /* tlbie invalidate TLBs for all segments */

        addr &= ~((target_ulong)-1ULL << 28);

        cs = CPU(cpu);

        /* XXX: this case should be optimized,

         * giving a mask to tlb_flush_page

         */

        /* This is broken, some CPUs invalidate a whole congruence

         * class on an even smaller subset of bits and some OSes take

         * advantage of this. Just blow the whole thing away.

         */

#if 0

        tlb_flush_page(cs, addr | (0x0 << 28));

        tlb_flush_page(cs, addr | (0x1 << 28));

        tlb_flush_page(cs, addr | (0x2 << 28));

        tlb_flush_page(cs, addr | (0x3 << 28));

        tlb_flush_page(cs, addr | (0x4 << 28));

        tlb_flush_page(cs, addr | (0x5 << 28));

        tlb_flush_page(cs, addr | (0x6 << 28));

        tlb_flush_page(cs, addr | (0x7 << 28));

        tlb_flush_page(cs, addr | (0x8 << 28));

        tlb_flush_page(cs, addr | (0x9 << 28));

        tlb_flush_page(cs, addr | (0xA << 28));

        tlb_flush_page(cs, addr | (0xB << 28));

        tlb_flush_page(cs, addr | (0xC << 28));

        tlb_flush_page(cs, addr | (0xD << 28));

        tlb_flush_page(cs, addr | (0xE << 28));

        tlb_flush_page(cs, addr | (0xF << 28));

        break;

#if defined(TARGET_PPC64)

    case POWERPC_MMU_64B:

    case POWERPC_MMU_2_03:

    case POWERPC_MMU_2_06:

    case POWERPC_MMU_2_06a:

    case POWERPC_MMU_2_07:

    case POWERPC_MMU_2_07a:

        /* tlbie invalidate TLBs for all segments */

        /* XXX: given the fact that there are too many segments to invalidate,

         *      and we still don't have a tlb_flush_mask(env, n, mask) in QEMU,

         *      we just invalidate all TLBs

         */

        env->tlb_need_flush = 1;

        break;

#endif /* defined(TARGET_PPC64) */

    default:

        /* Should never reach here with other MMU models */

        assert(0);

    }

    ppc_tlb_invalidate_all(env);

}


static void draw_bar(TestSourceContext *test, const uint8_t color[4],

                     unsigned x, unsigned y, unsigned w, unsigned h,

                     AVFrame *frame)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);

    uint8_t *p, *p0;

    int plane;

    x = FFMIN(x, test->w - 1);

    y = FFMIN(y, test->h - 1);

    w = FFMIN(w, test->w - x);

    h = FFMIN(h, test->h - y);

    av_assert0(x + w <= test->w);

    av_assert0(y + h <= test->h);

    for (plane = 0; frame->data[plane]; plane++) {

        const int c = color[plane];

        const int linesize = frame->linesize[plane];

        int i, px, py, pw, ph;

        if (plane == 1 || plane == 2) {

            px = x >> desc->log2_chroma_w;

            pw = w >> desc->log2_chroma_w;

            py = y >> desc->log2_chroma_h;

            ph = h >> desc->log2_chroma_h;

        } else {

            px = x;

            pw = w;

            py = y;

            ph = h;

        }

        p0 = p = frame->data[plane] + py * linesize + px;

        memset(p, c, pw);

        p += linesize;

        for (i = 1; i < ph; i++, p += linesize)

            memcpy(p, p0, pw);

    }

}


static int qpa_init_in (HWVoiceIn *hw, struct audsettings *as)

{

    int error;

    static pa_sample_spec ss;

    struct audsettings obt_as = *as;

    PAVoiceIn *pa = (PAVoiceIn *) hw;

    ss.format = audfmt_to_pa (as->fmt, as->endianness);

    ss.channels = as->nchannels;

    ss.rate = as->freq;

    obt_as.fmt = pa_to_audfmt (ss.format, &obt_as.endianness);

    pa->s = pa_simple_new (

        conf.server,

        "qemu",

        PA_STREAM_RECORD,

        conf.source,

        "pcm.capture",

        &ss,

        NULL,                   /* channel map */

        NULL,                   /* buffering attributes */

        &error

        );

    if (!pa->s) {

        qpa_logerr (error, "pa_simple_new for capture failed\n");

        goto fail1;

    }

    audio_pcm_init_info (&hw->info, &obt_as);

    hw->samples = conf.samples;

    pa->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);

    pa->wpos = hw->wpos;

    if (!pa->pcm_buf) {

        dolog ("Could not allocate buffer (%d bytes)\n",

               hw->samples << hw->info.shift);

        goto fail2;

    }

    if (audio_pt_init (&pa->pt, qpa_thread_in, hw, AUDIO_CAP, AUDIO_FUNC)) {

        goto fail3;

    }

    return 0;

 fail3:

    g_free (pa->pcm_buf);

    pa->pcm_buf = NULL;

 fail2:

    pa_simple_free (pa->s);

    pa->s = NULL;

 fail1:

    return -1;

}


static inline int64_t gb_get_v(GetBitContext *gb)

{

    int64_t v = 0;

    int bits = 0;

    while(get_bits1(gb) && bits < 64-7){

        v <<= 7;

        v |= get_bits(gb, 7);

        bits += 7;

    }

    v <<= 7;

    v |= get_bits(gb, 7);

    return v;

}


int qed_check(BDRVQEDState *s, BdrvCheckResult *result, bool fix)

{

    QEDCheck check = {

        .s = s,

        .result = result,

        .nclusters = qed_bytes_to_clusters(s, s->file_size),

        .request = { .l2_table = NULL },

        .fix = fix,

    };

    int ret;

    check.used_clusters = g_try_malloc0(((check.nclusters + 31) / 32) *

                                        sizeof(check.used_clusters[0]));

    if (check.nclusters && check.used_clusters == NULL) {

        return -ENOMEM;

    }

    check.result->bfi.total_clusters =

        (s->header.image_size + s->header.cluster_size - 1) /

            s->header.cluster_size;

    ret = qed_check_l1_table(&check, s->l1_table);

    if (ret == 0) {

        /* Only check for leaks if entire image was scanned successfully */

        qed_check_for_leaks(&check);

        if (fix) {

            qed_check_mark_clean(s, result);

        }

    }

    g_free(check.used_clusters);

    return ret;

}


static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,

                        VLC *table, int coeff_index,

                        int plane,

                        int eob_run)

{

    int i, j = 0;

    int token;

    int zero_run = 0;

    DCTELEM coeff = 0;

    int bits_to_get;

    int blocks_ended;

    int coeff_i = 0;

    int num_coeffs = s->num_coded_frags[plane][coeff_index];

    int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];

    /* local references to structure members to avoid repeated deferences */

    int *coded_fragment_list = s->coded_fragment_list[plane];

    Vp3Fragment *all_fragments = s->all_fragments;

    VLC_TYPE (*vlc_table)[2] = table->table;

    if (num_coeffs < 0)

        av_log(s->avctx, AV_LOG_ERROR, "Invalid number of coefficents at level %d\n", coeff_index);

    if (eob_run > num_coeffs) {

        coeff_i = blocks_ended = num_coeffs;

        eob_run -= num_coeffs;

    } else {

        coeff_i = blocks_ended = eob_run;

        eob_run = 0;

    }

    // insert fake EOB token to cover the split between planes or zzi

    if (blocks_ended)

        dct_tokens[j++] = blocks_ended << 2;

    while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {

            /* decode a VLC into a token */

            token = get_vlc2(gb, vlc_table, 11, 3);

            /* use the token to get a zero run, a coefficient, and an eob run */

            if (token <= 6) {

                eob_run = eob_run_base[token];

                if (eob_run_get_bits[token])

                    eob_run += get_bits(gb, eob_run_get_bits[token]);

                // record only the number of blocks ended in this plane,

                // any spill will be recorded in the next plane.

                if (eob_run > num_coeffs - coeff_i) {

                    dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);

                    blocks_ended   += num_coeffs - coeff_i;

                    eob_run        -= num_coeffs - coeff_i;

                    coeff_i         = num_coeffs;

                } else {

                    dct_tokens[j++] = TOKEN_EOB(eob_run);

                    blocks_ended   += eob_run;

                    coeff_i        += eob_run;

                    eob_run = 0;

                }

            } else {

                bits_to_get = coeff_get_bits[token];

                if (bits_to_get)

                    bits_to_get = get_bits(gb, bits_to_get);

                coeff = coeff_tables[token][bits_to_get];

                zero_run = zero_run_base[token];

                if (zero_run_get_bits[token])

                    zero_run += get_bits(gb, zero_run_get_bits[token]);

                if (zero_run) {

                    dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);

                } else {

                    // Save DC into the fragment structure. DC prediction is

                    // done in raster order, so the actual DC can't be in with

                    // other tokens. We still need the token in dct_tokens[]

                    // however, or else the structure collapses on itself.

                    if (!coeff_index)

                        all_fragments[coded_fragment_list[coeff_i]].dc = coeff;

                    dct_tokens[j++] = TOKEN_COEFF(coeff);

                }

                if (coeff_index + zero_run > 64) {

                    av_log(s->avctx, AV_LOG_DEBUG, "Invalid zero run of %d with"

                           " %d coeffs left\n", zero_run, 64-coeff_index);

                    zero_run = 64 - coeff_index;

                }

                // zero runs code multiple coefficients,

                // so don't try to decode coeffs for those higher levels

                for (i = coeff_index+1; i <= coeff_index+zero_run; i++)

                    s->num_coded_frags[plane][i]--;

                coeff_i++;

            }

    }

    if (blocks_ended > s->num_coded_frags[plane][coeff_index])

        av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");

    // decrement the number of blocks that have higher coeffecients for each

    // EOB run at this level

    if (blocks_ended)

        for (i = coeff_index+1; i < 64; i++)

            s->num_coded_frags[plane][i] -= blocks_ended;

    // setup the next buffer

    if (plane < 2)

        s->dct_tokens[plane+1][coeff_index] = dct_tokens + j;

    else if (coeff_index < 63)

        s->dct_tokens[0][coeff_index+1] = dct_tokens + j;

    return eob_run;

}


int ff_copy_whitelists(AVFormatContext *dst, AVFormatContext *src)

{

    av_assert0(!dst->codec_whitelist && !dst->format_whitelist);

    dst-> codec_whitelist = av_strdup(src->codec_whitelist);

    dst->format_whitelist = av_strdup(src->format_whitelist);

    if (   (src-> codec_whitelist && !dst-> codec_whitelist)

        || (src->format_whitelist && !dst->format_whitelist)) {

        av_log(dst, AV_LOG_ERROR, "Failed to duplicate whitelist\n");

        return AVERROR(ENOMEM);

    }

    return 0;

}


static void init_dequant4_coeff_table(H264Context *h){

    int i,j,q,x;

    const int transpose = (h->h264dsp.h264_idct_add != ff_h264_idct_add_c); //FIXME ugly

    for(i=0; i<6; i++ ){

        h->dequant4_coeff[i] = h->dequant4_buffer[i];

        for(j=0; j<i; j++){

            if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){

                h->dequant4_coeff[i] = h->dequant4_buffer[j];

                break;

            }

        }

        if(j<i)

            continue;

        for(q=0; q<52; q++){

            int shift = div6[q] + 2;

            int idx = rem6[q];

            for(x=0; x<16; x++)

                h->dequant4_coeff[i][q][transpose ? (x>>2)|((x<<2)&0xF) : x] =

                    ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *

                    h->pps.scaling_matrix4[i][x]) << shift;

        }

    }

}


static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)

{

    MpegMuxContext *s = ctx->priv_data;

    int stream_index= pkt->stream_index;

    int size= pkt->size;

    uint8_t *buf= pkt->data;

    AVStream *st = ctx->streams[stream_index];

    StreamInfo *stream = st->priv_data;

    int64_t pts, dts, new_start_pts, new_start_dts;

    int len, avail_size;

    //XXX/FIXME this is and always was broken

//    compute_pts_dts(st, &pts, &dts, pkt->pts);

    pts= pkt->pts;

    dts= pkt->dts;

    if(s->is_svcd) {

        /* offset pts and dts slightly into the future to be able

           to do the compatibility fix below.*/

        pts = (pts + 2) & ((1LL << 33) - 1);

        dts = (dts + 2) & ((1LL << 33) - 1);

        if (stream->packet_number == 0 && dts == pts)

            /* For the very first packet we want to force the DTS to be included.

               This increases compatibility with lots of DVD players.

               Since the MPEG-2 standard mandates that DTS is only written when

               it is different from PTS we have to move it slightly into the past.*/

            dts = (dts - 2) & ((1LL << 33) - 1);

    }

    if(s->is_vcd) {

        /* We have to offset the PTS, so that it is consistent with the SCR.

           SCR starts at 36000, but the first two packs contain only padding

           and the first pack from the other stream, respectively, may also have

           been written before.

           So the real data starts at SCR 36000+3*1200. */

        pts = (pts + 36000 + 3600) & ((1LL << 33) - 1);

        dts = (dts + 36000 + 3600) & ((1LL << 33) - 1);

    }

#if 0

    update_scr(ctx,stream_index,pts);

    printf("%d: pts=%0.3f dts=%0.3f scr=%0.3f\n",

           stream_index,

           pts / 90000.0,

           dts / 90000.0,

           s->last_scr / 90000.0);

#endif

    /* we assume here that pts != AV_NOPTS_VALUE */

    new_start_pts = stream->start_pts;

    new_start_dts = stream->start_dts;

    if (stream->start_pts == AV_NOPTS_VALUE) {

        new_start_pts = pts;

        new_start_dts = dts;

    }

    avail_size = get_packet_payload_size(ctx, stream_index,

                                         new_start_pts,

                                         new_start_dts);

    if (stream->buffer_ptr >= avail_size) {

        update_scr(ctx,stream_index,stream->start_pts);

        /* unlikely case: outputing the pts or dts increase the packet

           size so that we cannot write the start of the next

           packet. In this case, we must flush the current packet with

           padding.

           Note: this always happens for the first audio and video packet

           in a VCD file, since they do not carry any data.*/

        flush_packet(ctx, stream_index,

                     stream->start_pts, stream->start_dts, s->last_scr);

        stream->buffer_ptr = 0;

    }

    stream->start_pts = new_start_pts;

    stream->start_dts = new_start_dts;

    stream->nb_frames++;

    if (stream->frame_start_offset == 0)

        stream->frame_start_offset = stream->buffer_ptr;

    while (size > 0) {

        avail_size = get_packet_payload_size(ctx, stream_index,

                                             stream->start_pts,

                                             stream->start_dts);

        len = avail_size - stream->buffer_ptr;

        if (len > size)

            len = size;

        memcpy(stream->buffer + stream->buffer_ptr, buf, len);

        stream->buffer_ptr += len;

        buf += len;

        size -= len;

        if (stream->buffer_ptr >= avail_size) {

            update_scr(ctx,stream_index,stream->start_pts);

            /* if packet full, we send it now */

            flush_packet(ctx, stream_index,

                         stream->start_pts, stream->start_dts, s->last_scr);

            stream->buffer_ptr = 0;

            if (s->is_vcd) {

                /* Write one or more padding sectors, if necessary, to reach

                   the constant overall bitrate.*/

                int vcd_pad_bytes;

                while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->start_pts) ) >= s->packet_size)

                    put_vcd_padding_sector(ctx);

            }

            /* Make sure only the FIRST pes packet for this frame has

               a timestamp */

            stream->start_pts = AV_NOPTS_VALUE;

            stream->start_dts = AV_NOPTS_VALUE;

        }

    }

    return 0;

}


SwsFilter *sws_getDefaultFilter(float lumaGBlur, float chromaGBlur,

                                float lumaSharpen, float chromaSharpen,

                                float chromaHShift, float chromaVShift,

                                int verbose)

{

    SwsFilter *filter = av_malloc(sizeof(SwsFilter));

    if (!filter)

        return NULL;

    if (lumaGBlur != 0.0) {

        filter->lumH = sws_getGaussianVec(lumaGBlur, 3.0);

        filter->lumV = sws_getGaussianVec(lumaGBlur, 3.0);

    } else {

        filter->lumH = sws_getIdentityVec();

        filter->lumV = sws_getIdentityVec();

    }

    if (chromaGBlur != 0.0) {

        filter->chrH = sws_getGaussianVec(chromaGBlur, 3.0);

        filter->chrV = sws_getGaussianVec(chromaGBlur, 3.0);

    } else {

        filter->chrH = sws_getIdentityVec();

        filter->chrV = sws_getIdentityVec();

    }

    if (!filter->lumH || !filter->lumV || !filter->chrH || !filter->chrV) {

        sws_freeVec(filter->lumH);

        sws_freeVec(filter->lumV);

        sws_freeVec(filter->chrH);

        sws_freeVec(filter->chrV);

        av_freep(&filter);

        return NULL;

    }

    if (chromaSharpen != 0.0) {

        SwsVector *id = sws_getIdentityVec();

        sws_scaleVec(filter->chrH, -chromaSharpen);

        sws_scaleVec(filter->chrV, -chromaSharpen);

        sws_addVec(filter->chrH, id);

        sws_addVec(filter->chrV, id);

        sws_freeVec(id);

    }

    if (lumaSharpen != 0.0) {

        SwsVector *id = sws_getIdentityVec();

        sws_scaleVec(filter->lumH, -lumaSharpen);

        sws_scaleVec(filter->lumV, -lumaSharpen);

        sws_addVec(filter->lumH, id);

        sws_addVec(filter->lumV, id);

        sws_freeVec(id);

    }

    if (chromaHShift != 0.0)

        sws_shiftVec(filter->chrH, (int)(chromaHShift + 0.5));

    if (chromaVShift != 0.0)

        sws_shiftVec(filter->chrV, (int)(chromaVShift + 0.5));

    sws_normalizeVec(filter->chrH, 1.0);

    sws_normalizeVec(filter->chrV, 1.0);

    sws_normalizeVec(filter->lumH, 1.0);

    sws_normalizeVec(filter->lumV, 1.0);

    if (verbose)

        sws_printVec2(filter->chrH, NULL, AV_LOG_DEBUG);

    if (verbose)

        sws_printVec2(filter->lumH, NULL, AV_LOG_DEBUG);

    return filter;

}


static int decode_frame(AVCodecContext * avctx, void *data, int *data_size,

                        AVPacket *avpkt)

{

    const uint8_t *buf  = avpkt->data;

    int buf_size        = avpkt->size;

    MPADecodeContext *s = avctx->priv_data;

    uint32_t header;

    int out_size;

    OUT_INT *out_samples = data;

    if (buf_size < HEADER_SIZE)

        return AVERROR_INVALIDDATA;

    header = AV_RB32(buf);

    if (ff_mpa_check_header(header) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Header missing\n");

        return AVERROR_INVALIDDATA;

    }

    if (avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {

        /* free format: prepare to compute frame size */

        s->frame_size = -1;

        return AVERROR_INVALIDDATA;

    }

    /* update codec info */

    avctx->channels       = s->nb_channels;

    avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;

    if (!avctx->bit_rate)

        avctx->bit_rate = s->bit_rate;

    avctx->sub_id = s->layer;

    if (*data_size < 1152 * avctx->channels * sizeof(OUT_INT))

        return AVERROR(EINVAL);

    *data_size = 0;

    if (s->frame_size <= 0 || s->frame_size > buf_size) {

        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");

        return AVERROR_INVALIDDATA;

    } else if (s->frame_size < buf_size) {

        av_log(avctx, AV_LOG_ERROR, "incorrect frame size\n");

        buf_size= s->frame_size;

    }

    out_size = mp_decode_frame(s, out_samples, buf, buf_size);

    if (out_size >= 0) {

        *data_size         = out_size;

        avctx->sample_rate = s->sample_rate;

        //FIXME maybe move the other codec info stuff from above here too

    } else {

        av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");

        /* Only return an error if the bad frame makes up the whole packet.

           If there is more data in the packet, just consume the bad frame

           instead of returning an error, which would discard the whole

           packet. */

        if (buf_size == avpkt->size)

            return out_size;

    }

    s->frame_size = 0;

    return buf_size;

}


int load_flt_binary(struct linux_binprm * bprm, struct target_pt_regs * regs,

                    struct image_info * info)

{

    struct lib_info libinfo[MAX_SHARED_LIBS];

    abi_ulong p = bprm->p;

    abi_ulong stack_len;

    abi_ulong start_addr;

    abi_ulong sp;

    int res;

    int i, j;

    memset(libinfo, 0, sizeof(libinfo));

    /*

     * We have to add the size of our arguments to our stack size

     * otherwise it's too easy for users to create stack overflows

     * by passing in a huge argument list.  And yes,  we have to be

     * pedantic and include space for the argv/envp array as it may have

     * a lot of entries.

     */

    stack_len = 0;

    for (i = 0; i < bprm->argc; ++i) {

        /* the argv strings */

        stack_len += strlen(bprm->argv[i]);

    }

    for (i = 0; i < bprm->envc; ++i) {

        /* the envp strings */

        stack_len += strlen(bprm->envp[i]);

    }

    stack_len += (bprm->argc + 1) * 4; /* the argv array */

    stack_len += (bprm->envc + 1) * 4; /* the envp array */

    res = load_flat_file(bprm, libinfo, 0, &stack_len);

    if (res > (unsigned long)-4096)

            return res;

    /* Update data segment pointers for all libraries */

    for (i=0; i<MAX_SHARED_LIBS; i++) {

        if (libinfo[i].loaded) {

            abi_ulong p;

            p = libinfo[i].start_data;

            for (j=0; j<MAX_SHARED_LIBS; j++) {

                p -= 4;

                /* FIXME - handle put_user() failures */

                if (put_user_ual(libinfo[j].loaded

                                 ? libinfo[j].start_data

                                 : UNLOADED_LIB,

                                 p))

                    return -EFAULT;

            }

        }

    }

    p = ((libinfo[0].start_brk + stack_len + 3) & ~3) - 4;

    DBG_FLT("p=%x\n", (int)p);

    /* Copy argv/envp.  */

    p = copy_strings(p, bprm->envc, bprm->envp);

    p = copy_strings(p, bprm->argc, bprm->argv);

    /* Align stack.  */

    sp = p & ~(abi_ulong)(sizeof(abi_ulong) - 1);

    /* Enforce final stack alignment of 16 bytes.  This is sufficient

       for all current targets, and excess alignment is harmless.  */

    stack_len = bprm->envc + bprm->argc + 2;

    stack_len += 3;	/* argc, arvg, argp */

    stack_len *= sizeof(abi_ulong);

    if ((sp + stack_len) & 15)

        sp -= 16 - ((sp + stack_len) & 15);

    sp = loader_build_argptr(bprm->envc, bprm->argc, sp, p, 1);

    /* Fake some return addresses to ensure the call chain will

     * initialise library in order for us.  We are required to call

     * lib 1 first, then 2, ... and finally the main program (id 0).

     */

    start_addr = libinfo[0].entry;

#ifdef CONFIG_BINFMT_SHARED_FLAT

#error here

    for (i = MAX_SHARED_LIBS-1; i>0; i--) {

            if (libinfo[i].loaded) {

                    /* Push previos first to call address */

                    --sp;

                    if (put_user_ual(start_addr, sp))

                        return -EFAULT;

                    start_addr = libinfo[i].entry;

            }

    }

#endif

    /* Stash our initial stack pointer into the mm structure */

    info->start_code = libinfo[0].start_code;

    info->end_code = libinfo[0].start_code = libinfo[0].text_len;

    info->start_data = libinfo[0].start_data;

    info->end_data = libinfo[0].end_data;

    info->start_brk = libinfo[0].start_brk;

    info->start_stack = sp;

    info->stack_limit = libinfo[0].start_brk;

    info->entry = start_addr;

    info->code_offset = info->start_code;

    info->data_offset = info->start_data - libinfo[0].text_len;

    DBG_FLT("start_thread(entry=0x%x, start_stack=0x%x)\n",

            (int)info->entry, (int)info->start_stack);

    return 0;

}


static always_inline void gen_farith2 (void *helper,

                                       int rb, int rc)

{

    if (unlikely(rc == 31))

      return;

    if (rb != 31)

        tcg_gen_helper_1_1(helper, cpu_fir[rc], cpu_fir[rb]);

    else {

        TCGv tmp = tcg_const_i64(0);

        tcg_gen_helper_1_1(helper, cpu_fir[rc], tmp);

        tcg_temp_free(tmp);

    }

}


static void qio_channel_socket_connect_worker(QIOTask *task,

                                              gpointer opaque)

{

    QIOChannelSocket *ioc = QIO_CHANNEL_SOCKET(qio_task_get_source(task));

    SocketAddress *addr = opaque;

    Error *err = NULL;

    qio_channel_socket_connect_sync(ioc, addr, &err);

    qio_task_set_error(task, err);

}


void pxa27x_timer_init(target_phys_addr_t base,

                qemu_irq *irqs, qemu_irq irq4)

{

    pxa2xx_timer_info *s = pxa2xx_timer_init(base, irqs);

    int i;

    s->freq = PXA27X_FREQ;

    s->tm4 = (PXA2xxTimer4 *) qemu_mallocz(8 *

                    sizeof(PXA2xxTimer4));

    for (i = 0; i < 8; i ++) {

        s->tm4[i].tm.value = 0;

        s->tm4[i].tm.irq = irq4;

        s->tm4[i].tm.info = s;

        s->tm4[i].tm.num = i + 4;

        s->tm4[i].tm.level = 0;

        s->tm4[i].freq = 0;

        s->tm4[i].control = 0x0;

        s->tm4[i].tm.qtimer = qemu_new_timer(vm_clock,

                        pxa2xx_timer_tick4, &s->tm4[i]);

    }

}


static void serial_init_core(SerialState *s)

{

    if (!s->chr) {

        fprintf(stderr, "Can't create serial device, empty char device\n");

	exit(1);

    }

    s->modem_status_poll = qemu_new_timer(vm_clock, (QEMUTimerCB *) serial_update_msl, s);

    s->fifo_timeout_timer = qemu_new_timer(vm_clock, (QEMUTimerCB *) fifo_timeout_int, s);

    s->transmit_timer = qemu_new_timer(vm_clock, (QEMUTimerCB *) serial_xmit, s);

    qemu_register_reset(serial_reset, s);

    serial_reset(s);

    qemu_chr_add_handlers(s->chr, serial_can_receive1, serial_receive1,

                          serial_event, s);

}


int bdrv_create_file(const char* filename, QEMUOptionParameter *options)

{

    BlockDriver *drv;

    drv = bdrv_find_protocol(filename);

    if (drv == NULL) {

        drv = bdrv_find_format("file");

    }

    return bdrv_create(drv, filename, options);

}


int qemu_acl_append(qemu_acl *acl,

                    int deny,

                    const char *match)

{

    qemu_acl_entry *entry;

    entry = qemu_malloc(sizeof(*entry));

    entry->match = qemu_strdup(match);

    entry->deny = deny;

    TAILQ_INSERT_TAIL(&acl->entries, entry, next);

    acl->nentries++;

    return acl->nentries;

}


void virtio_scsi_common_realize(DeviceState *dev, Error **errp,

                                HandleOutput ctrl, HandleOutput evt,

                                HandleOutput cmd)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(dev);

    VirtIOSCSICommon *s = VIRTIO_SCSI_COMMON(dev);

    int i;

    virtio_init(vdev, "virtio-scsi", VIRTIO_ID_SCSI,

                sizeof(VirtIOSCSIConfig));

    if (s->conf.num_queues <= 0 || s->conf.num_queues > VIRTIO_PCI_QUEUE_MAX) {

        error_setg(errp, "Invalid number of queues (= %" PRId32 "), "

                         "must be a positive integer less than %d.",

                   s->conf.num_queues, VIRTIO_PCI_QUEUE_MAX);

        virtio_cleanup(vdev);

        return;

    }

    s->cmd_vqs = g_malloc0(s->conf.num_queues * sizeof(VirtQueue *));

    s->sense_size = VIRTIO_SCSI_SENSE_SIZE;

    s->cdb_size = VIRTIO_SCSI_CDB_SIZE;

    s->ctrl_vq = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE,

                                  ctrl);

    s->event_vq = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE,

                                   evt);

    for (i = 0; i < s->conf.num_queues; i++) {

        s->cmd_vqs[i] = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE,

                                         cmd);

    }

    if (s->conf.iothread) {

        virtio_scsi_set_iothread(VIRTIO_SCSI(s), s->conf.iothread);

    }

}


static int write_elf32_load(DumpState *s, MemoryMapping *memory_mapping,

                            int phdr_index, hwaddr offset)

{

    Elf32_Phdr phdr;

    int ret;

    int endian = s->dump_info.d_endian;

    memset(&phdr, 0, sizeof(Elf32_Phdr));

    phdr.p_type = cpu_convert_to_target32(PT_LOAD, endian);

    phdr.p_offset = cpu_convert_to_target32(offset, endian);

    phdr.p_paddr = cpu_convert_to_target32(memory_mapping->phys_addr, endian);

    if (offset == -1) {

        /* When the memory is not stored into vmcore, offset will be -1 */

        phdr.p_filesz = 0;

    } else {

        phdr.p_filesz = cpu_convert_to_target32(memory_mapping->length, endian);

    }

    phdr.p_memsz = cpu_convert_to_target32(memory_mapping->length, endian);

    phdr.p_vaddr = cpu_convert_to_target32(memory_mapping->virt_addr, endian);

    ret = fd_write_vmcore(&phdr, sizeof(Elf32_Phdr), s);

    if (ret < 0) {

        dump_error(s, "dump: failed to write program header table.\n");

        return -1;

    }

    return 0;

}


static void qemu_laio_enqueue_completed(struct qemu_laio_state *s,

    struct qemu_laiocb* laiocb)

{

    if (laiocb->async_context_id == get_async_context_id()) {

        qemu_laio_process_completion(s, laiocb);

    } else {

        QLIST_INSERT_HEAD(&s->completed_reqs, laiocb, node);

    }

}


static inline void gen_goto_tb(DisasContext *s, int n, uint64_t dest)

{

    TranslationBlock *tb;

    tb = s->tb;

    if (use_goto_tb(s, n, dest)) {

        tcg_gen_goto_tb(n);

        gen_a64_set_pc_im(dest);

        tcg_gen_exit_tb((intptr_t)tb + n);

        s->is_jmp = DISAS_TB_JUMP;

    } else {

        gen_a64_set_pc_im(dest);

        if (s->singlestep_enabled) {

            gen_exception_internal(EXCP_DEBUG);

        }

        tcg_gen_exit_tb(0);

        s->is_jmp = DISAS_JUMP;

    }

}


static void gen_spr_BookE206(CPUPPCState *env, uint32_t mas_mask,

                              uint32_t *tlbncfg)

{

#if !defined(CONFIG_USER_ONLY)

    const char *mas_names[8] = {

        "MAS0", "MAS1", "MAS2", "MAS3", "MAS4", "MAS5", "MAS6", "MAS7",

    };

    int mas_sprn[8] = {

        SPR_BOOKE_MAS0, SPR_BOOKE_MAS1, SPR_BOOKE_MAS2, SPR_BOOKE_MAS3,

        SPR_BOOKE_MAS4, SPR_BOOKE_MAS5, SPR_BOOKE_MAS6, SPR_BOOKE_MAS7,

    };

    int i;

    /* TLB assist registers */

    /* XXX : not implemented */

    for (i = 0; i < 8; i++) {

        if (mas_mask & (1 << i)) {

            spr_register(env, mas_sprn[i], mas_names[i],

                         SPR_NOACCESS, SPR_NOACCESS,

                         &spr_read_generic, &spr_write_generic,

                         0x00000000);

        }

    }

    if (env->nb_pids > 1) {

        /* XXX : not implemented */

        spr_register(env, SPR_BOOKE_PID1, "PID1",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_booke_pid,

                     0x00000000);

    }

    if (env->nb_pids > 2) {

        /* XXX : not implemented */

        spr_register(env, SPR_BOOKE_PID2, "PID2",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_booke_pid,

                     0x00000000);

    }

    /* XXX : not implemented */

    spr_register(env, SPR_MMUCFG, "MMUCFG",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000); /* TOFIX */

    switch (env->nb_ways) {

    case 4:

        spr_register(env, SPR_BOOKE_TLB3CFG, "TLB3CFG",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, SPR_NOACCESS,

                     tlbncfg[3]);

        /* Fallthru */

    case 3:

        spr_register(env, SPR_BOOKE_TLB2CFG, "TLB2CFG",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, SPR_NOACCESS,

                     tlbncfg[2]);

        /* Fallthru */

    case 2:

        spr_register(env, SPR_BOOKE_TLB1CFG, "TLB1CFG",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, SPR_NOACCESS,

                     tlbncfg[1]);

        /* Fallthru */

    case 1:

        spr_register(env, SPR_BOOKE_TLB0CFG, "TLB0CFG",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, SPR_NOACCESS,

                     tlbncfg[0]);

        /* Fallthru */

    case 0:

    default:

        break;

    }

#endif

    gen_spr_usprgh(env);

}


static void vnc_tight_start(VncState *vs)

{

    buffer_reset(&vs->tight);

    // make the output buffer be the zlib buffer, so we can compress it later

    vs->tight_tmp = vs->output;

    vs->output = vs->tight;

}


static void error_mem_write(void *opaque, target_phys_addr_t addr,

                            uint64_t value, unsigned size)

{

    abort();

}


build_tpm_tcpa(GArray *table_data, GArray *linker, GArray *tcpalog)

{

    Acpi20Tcpa *tcpa = acpi_data_push(table_data, sizeof *tcpa);

    uint64_t log_area_start_address = acpi_data_len(tcpalog);

    tcpa->platform_class = cpu_to_le16(TPM_TCPA_ACPI_CLASS_CLIENT);

    tcpa->log_area_minimum_length = cpu_to_le32(TPM_LOG_AREA_MINIMUM_SIZE);

    tcpa->log_area_start_address = cpu_to_le64(log_area_start_address);

    bios_linker_loader_alloc(linker, ACPI_BUILD_TPMLOG_FILE, 1,

                             false /* high memory */);

    /* log area start address to be filled by Guest linker */

    bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE,

                                   ACPI_BUILD_TPMLOG_FILE,

                                   table_data, &tcpa->log_area_start_address,

                                   sizeof(tcpa->log_area_start_address));

    build_header(linker, table_data,

                 (void *)tcpa, "TCPA", sizeof(*tcpa), 2, NULL);

    acpi_data_push(tcpalog, TPM_LOG_AREA_MINIMUM_SIZE);

}


static void build_pci_bus_state_cleanup(AcpiBuildPciBusHotplugState *state)

{

    build_free_array(state->device_table);

    build_free_array(state->notify_table);

}


uint32_t HELPER(mvcle)(CPUS390XState *env, uint32_t r1, uint64_t a2,

                       uint32_t r3)

{

    uintptr_t ra = GETPC();

    uint64_t destlen = get_length(env, r1 + 1);

    uint64_t dest = get_address(env, r1);

    uint64_t srclen = get_length(env, r3 + 1);

    uint64_t src = get_address(env, r3);

    uint8_t pad = a2 & 0xff;

    uint8_t v;

    uint32_t cc;

    if (destlen == srclen) {

        cc = 0;

    } else if (destlen < srclen) {

        cc = 1;

    } else {

        cc = 2;

    }

    if (srclen > destlen) {

        srclen = destlen;

    }

    for (; destlen && srclen; src++, dest++, destlen--, srclen--) {

        v = cpu_ldub_data_ra(env, src, ra);

        cpu_stb_data_ra(env, dest, v, ra);

    }

    for (; destlen; dest++, destlen--) {

        cpu_stb_data_ra(env, dest, pad, ra);

    }

    set_length(env, r1 + 1 , destlen);

    /* can't use srclen here, we trunc'ed it */

    set_length(env, r3 + 1, env->regs[r3 + 1] - src - env->regs[r3]);

    set_address(env, r1, dest);

    set_address(env, r3, src);

    return cc;

}


static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)

{

    target_long *stack = (void *)infop->start_stack;

    memset(regs, 0, sizeof(*regs));

    regs->ARM_cpsr = 0x10;

    regs->ARM_pc = infop->entry;

    regs->ARM_sp = infop->start_stack;

    regs->ARM_r2 = tswapl(stack[2]); /* envp */

    regs->ARM_r1 = tswapl(stack[1]); /* argv */

    /* XXX: it seems that r0 is zeroed after ! */

    //    regs->ARM_r0 = tswapl(stack[0]); /* argc */

}


bool qemu_aio_wait(void)

{

    AioHandler *node;

    fd_set rdfds, wrfds;

    int max_fd = -1;

    int ret;

    bool busy;

    /*

     * If there are callbacks left that have been queued, we need to call then.

     * Do not call select in this case, because it is possible that the caller

     * does not need a complete flush (as is the case for qemu_aio_wait loops).

     */

    if (qemu_bh_poll()) {

        return true;

    }

    walking_handlers++;

    FD_ZERO(&rdfds);

    FD_ZERO(&wrfds);

    /* fill fd sets */

    busy = false;

    QLIST_FOREACH(node, &aio_handlers, node) {

        /* If there aren't pending AIO operations, don't invoke callbacks.

         * Otherwise, if there are no AIO requests, qemu_aio_wait() would

         * wait indefinitely.

         */

        if (node->io_flush) {

            if (node->io_flush(node->opaque) == 0) {

                continue;

            }

            busy = true;

        }

        if (!node->deleted && node->io_read) {

            FD_SET(node->fd, &rdfds);

            max_fd = MAX(max_fd, node->fd + 1);

        }

        if (!node->deleted && node->io_write) {

            FD_SET(node->fd, &wrfds);

            max_fd = MAX(max_fd, node->fd + 1);

        }

    }

    walking_handlers--;

    /* No AIO operations?  Get us out of here */

    if (!busy) {

        return false;

    }

    /* wait until next event */

    ret = select(max_fd, &rdfds, &wrfds, NULL, NULL);

    /* if we have any readable fds, dispatch event */

    if (ret > 0) {

        walking_handlers++;

        /* we have to walk very carefully in case

         * qemu_aio_set_fd_handler is called while we're walking */

        node = QLIST_FIRST(&aio_handlers);

        while (node) {

            AioHandler *tmp;

            if (!node->deleted &&

                FD_ISSET(node->fd, &rdfds) &&

                node->io_read) {

                node->io_read(node->opaque);

            }

            if (!node->deleted &&

                FD_ISSET(node->fd, &wrfds) &&

                node->io_write) {

                node->io_write(node->opaque);

            }

            tmp = node;

            node = QLIST_NEXT(node, node);

            if (tmp->deleted) {

                QLIST_REMOVE(tmp, node);

                g_free(tmp);

            }

        }

        walking_handlers--;

    }

    return true;

}


static uint64_t lsi_io_read(void *opaque, target_phys_addr_t addr,

                            unsigned size)

{

    LSIState *s = opaque;

    return lsi_reg_readb(s, addr & 0xff);

}


static av_cold int pcx_encode_close(AVCodecContext *avctx)

{

    av_frame_free(&avctx->coded_frame);

    return 0;

}


static void fill_double_array(AVLFG *lfg, double *a, int len)

{

    int i;

    double bmg[2], stddev = 10.0, mean = 0.0;

    for (i = 0; i < len; i += 2) {

        av_bmg_get(lfg, bmg);

        a[i]     = bmg[0] * stddev + mean;

        a[i + 1] = bmg[1] * stddev + mean;

    }

}


static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)

{

    InputStream *ist = NULL;

    enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);

    int i;

    // TODO: support other filter types

    if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {

        av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "

               "currently.\n");

        exit(1);

    }

    if (in->name) {

        AVFormatContext *s;

        AVStream       *st = NULL;

        char *p;

        int file_idx = strtol(in->name, &p, 0);

        if (file_idx < 0 || file_idx >= nb_input_files) {

            av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtegraph description %s.\n",

                   file_idx, fg->graph_desc);

            exit(1);

        }

        s = input_files[file_idx]->ctx;

        for (i = 0; i < s->nb_streams; i++) {

            if (s->streams[i]->codecpar->codec_type != type)

                continue;

            if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {

                st = s->streams[i];

                break;

            }

        }

        if (!st) {

            av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "

                   "matches no streams.\n", p, fg->graph_desc);

            exit(1);

        }

        ist = input_streams[input_files[file_idx]->ist_index + st->index];

    } else {

        /* find the first unused stream of corresponding type */

        for (i = 0; i < nb_input_streams; i++) {

            ist = input_streams[i];

            if (ist->dec_ctx->codec_type == type && ist->discard)

                break;

        }

        if (i == nb_input_streams) {

            av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "

                   "unlabeled input pad %d on filter %s\n", in->pad_idx,

                   in->filter_ctx->name);

            exit(1);

        }

    }

    av_assert0(ist);

    ist->discard         = 0;

    ist->decoding_needed = 1;

    ist->st->discard = AVDISCARD_NONE;

    GROW_ARRAY(fg->inputs, fg->nb_inputs);

    if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))

        exit(1);

    fg->inputs[fg->nb_inputs - 1]->ist   = ist;

    fg->inputs[fg->nb_inputs - 1]->graph = fg;

    fg->inputs[fg->nb_inputs - 1]->format = -1;

    fg->inputs[fg->nb_inputs - 1]->frame_queue = av_fifo_alloc(8 * sizeof(AVFrame*));

    if (!fg->inputs[fg->nb_inputs - 1])

        exit_program(1);

    GROW_ARRAY(ist->filters, ist->nb_filters);

    ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];

}


static int ccid_handle_data(USBDevice *dev, USBPacket *p)

{

    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);

    int ret = 0;

    uint8_t *data = p->data;

    int len = p->len;

    switch (p->pid) {

    case USB_TOKEN_OUT:

        ret = ccid_handle_bulk_out(s, p);

        break;

    case USB_TOKEN_IN:

        switch (p->devep & 0xf) {

        case CCID_BULK_IN_EP:

            if (!len) {

                ret = USB_RET_NAK;

            } else {

                ret = ccid_bulk_in_copy_to_guest(s, data, len);

            }

            break;

        case CCID_INT_IN_EP:

            if (s->notify_slot_change) {

                /* page 56, RDR_to_PC_NotifySlotChange */

                data[0] = CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange;

                data[1] = s->bmSlotICCState;

                ret = 2;

                s->notify_slot_change = false;

                s->bmSlotICCState &= ~SLOT_0_CHANGED_MASK;

                DPRINTF(s, D_INFO,

                        "handle_data: int_in: notify_slot_change %X, "

                        "requested len %d\n",

                        s->bmSlotICCState, len);

            }

            break;

        default:

            DPRINTF(s, 1, "Bad endpoint\n");

            break;

        }

        break;

    default:

        DPRINTF(s, 1, "Bad token\n");

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}