int ff_vdpau_common_init(AVCodecContext *avctx, VdpDecoderProfile profile,
                         int level)
{
    VDPAUHWContext *hwctx = avctx->hwaccel_context;
    VDPAUContext *vdctx = avctx->internal->hwaccel_priv_data;
    VdpVideoSurfaceQueryCapabilities *surface_query_caps;
    VdpDecoderQueryCapabilities *decoder_query_caps;
    VdpDecoderCreate *create;
    VdpGetInformationString *info;
    const char *info_string;
    void *func;
    VdpStatus status;
    VdpBool supported;
    uint32_t max_level, max_mb, max_width, max_height;
    VdpChromaType type;
    uint32_t width;
    uint32_t height;
    vdctx->width            = UINT32_MAX;
    vdctx->height           = UINT32_MAX;
    if (av_vdpau_get_surface_parameters(avctx, &type, &width, &height))
        return AVERROR(ENOSYS);
    if (hwctx) {
        hwctx->reset            = 0;
        if (hwctx->context.decoder != VDP_INVALID_HANDLE) {
            vdctx->decoder = hwctx->context.decoder;
            vdctx->render  = hwctx->context.render;
            vdctx->device  = VDP_INVALID_HANDLE;
            return 0; /* Decoder created by user */
        vdctx->device           = hwctx->device;
        vdctx->get_proc_address = hwctx->get_proc_address;
        if (hwctx->flags & AV_HWACCEL_FLAG_IGNORE_LEVEL)
            level = 0;
        if (!(hwctx->flags & AV_HWACCEL_FLAG_ALLOW_HIGH_DEPTH) &&
            type != VDP_CHROMA_TYPE_420)
            return AVERROR(ENOSYS);
    } else {
        AVHWFramesContext *frames_ctx = NULL;
        AVVDPAUDeviceContext *dev_ctx;
        // We assume the hw_frames_ctx always survives until ff_vdpau_common_uninit
        // is called. This holds true as the user is not allowed to touch
        // hw_device_ctx, or hw_frames_ctx after get_format (and ff_get_format
        // itself also uninits before unreffing hw_frames_ctx).
        if (avctx->hw_frames_ctx) {
            frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
        } else if (avctx->hw_device_ctx) {
            int ret;
            avctx->hw_frames_ctx = av_hwframe_ctx_alloc(avctx->hw_device_ctx);
            if (!avctx->hw_frames_ctx)
                return AVERROR(ENOMEM);
            frames_ctx            = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
            frames_ctx->format    = AV_PIX_FMT_VDPAU;
            frames_ctx->sw_format = avctx->sw_pix_fmt;
            frames_ctx->width     = avctx->coded_width;
            frames_ctx->height    = avctx->coded_height;
            ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
            if (ret < 0) {
                av_buffer_unref(&avctx->hw_frames_ctx);
                return ret;
        if (!frames_ctx) {
            av_log(avctx, AV_LOG_ERROR, "A hardware frames context is "
                   "required for VDPAU decoding.\n");
            return AVERROR(EINVAL);
        dev_ctx = frames_ctx->device_ctx->hwctx;
        vdctx->device           = dev_ctx->device;
        vdctx->get_proc_address = dev_ctx->get_proc_address;
        if (avctx->hwaccel_flags & AV_HWACCEL_FLAG_IGNORE_LEVEL)
            level = 0;
    if (level < 0)
                                     VDP_FUNC_ID_VIDEO_SURFACE_QUERY_CAPABILITIES,
        surface_query_caps = func;
    status = surface_query_caps(vdctx->device, type, &supported,
                                &max_width, &max_height);
    if (supported != VDP_TRUE ||
        max_width < width || max_height < height)
                                     VDP_FUNC_ID_DECODER_QUERY_CAPABILITIES,
        decoder_query_caps = func;
    status = decoder_query_caps(vdctx->device, profile, &supported, &max_level,
                                &max_mb, &max_width, &max_height);
#ifdef VDP_DECODER_PROFILE_H264_CONSTRAINED_BASELINE
    if ((status != VDP_STATUS_OK || supported != VDP_TRUE) && profile == VDP_DECODER_PROFILE_H264_CONSTRAINED_BASELINE) {
        profile = VDP_DECODER_PROFILE_H264_MAIN;
        status = decoder_query_caps(vdctx->device, profile, &supported,
                                    &max_level, &max_mb,
                                    &max_width, &max_height);
#endif
    if (supported != VDP_TRUE || max_level < level ||
        max_width < width || max_height < height)
    status = vdctx->get_proc_address(vdctx->device, VDP_FUNC_ID_DECODER_CREATE,
        create = func;
    status = vdctx->get_proc_address(vdctx->device, VDP_FUNC_ID_DECODER_RENDER,
        vdctx->render = func;
    status = create(vdctx->device, profile, width, height, avctx->refs,
                    &vdctx->decoder);
    if (status == VDP_STATUS_OK) {
        vdctx->width  = avctx->coded_width;
        vdctx->height = avctx->coded_height;


int do_migrate(Monitor *mon, const QDict *qdict, QObject **ret_data)
{
    MigrationState *s = NULL;
    const char *p;
    int detach = qdict_get_try_bool(qdict, "detach", 0);
    int blk = qdict_get_try_bool(qdict, "blk", 0);
    int inc = qdict_get_try_bool(qdict, "inc", 0);
    const char *uri = qdict_get_str(qdict, "uri");
    if (current_migration &&
        current_migration->get_status(current_migration) == MIG_STATE_ACTIVE) {
        monitor_printf(mon, "migration already in progress\n");
    if (strstart(uri, "tcp:", &p)) {
        s = tcp_start_outgoing_migration(mon, p, max_throttle, detach,
                                         blk, inc);
#if !defined(WIN32)
    } else if (strstart(uri, "exec:", &p)) {
        s = exec_start_outgoing_migration(mon, p, max_throttle, detach,
                                          blk, inc);
    } else if (strstart(uri, "unix:", &p)) {
        s = unix_start_outgoing_migration(mon, p, max_throttle, detach,
                                          blk, inc);
    } else if (strstart(uri, "fd:", &p)) {
        s = fd_start_outgoing_migration(mon, p, max_throttle, detach,
                                        blk, inc);
#endif
    } else {
        monitor_printf(mon, "unknown migration protocol: %s\n", uri);
    if (s == NULL) {
        monitor_printf(mon, "migration failed\n");
    if (current_migration) {
        current_migration->release(current_migration);
    current_migration = s;
    return 0;


static void init_custom_qm(VC2EncContext *s)

{

    int level, orientation;

    if (s->quant_matrix == VC2_QM_DEF) {

        for (level = 0; level < s->wavelet_depth; level++) {

            for (orientation = 0; orientation < 4; orientation++) {

                if (level <= 3)

                    s->quant[level][orientation] = ff_dirac_default_qmat[s->wavelet_idx][level][orientation];

                else

                    s->quant[level][orientation] = vc2_qm_col_tab[level][orientation];

            }

        }

    } else if (s->quant_matrix == VC2_QM_COL) {

        for (level = 0; level < s->wavelet_depth; level++) {

            for (orientation = 0; orientation < 4; orientation++) {

                s->quant[level][orientation] = vc2_qm_col_tab[level][orientation];

            }

        }

    } else {

        for (level = 0; level < s->wavelet_depth; level++) {

            for (orientation = 0; orientation < 4; orientation++) {

                s->quant[level][orientation] = vc2_qm_flat_tab[level][orientation];

            }

        }

    }

}


void bareetraxfs_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)

{

    DeviceState *dev;

    SysBusDevice *s;

    CPUState *env;

    qemu_irq irq[30], nmi[2], *cpu_irq;

    void *etraxfs_dmac;

    struct etraxfs_dma_client *eth[2] = {NULL, NULL};

    int kernel_size;

    DriveInfo *dinfo;

    int i;

    ram_addr_t phys_ram;

    ram_addr_t phys_flash;

    ram_addr_t phys_intmem;

    /* init CPUs */

    if (cpu_model == NULL) {

        cpu_model = "crisv32";

    }

    env = cpu_init(cpu_model);

    qemu_register_reset(main_cpu_reset, env);

    /* allocate RAM */

    phys_ram = qemu_ram_alloc(ram_size);

    cpu_register_physical_memory(0x40000000, ram_size, phys_ram | IO_MEM_RAM);

    /* The ETRAX-FS has 128Kb on chip ram, the docs refer to it as the

       internal memory.  */

    phys_intmem = qemu_ram_alloc(INTMEM_SIZE);

    cpu_register_physical_memory(0x38000000, INTMEM_SIZE,

                                 phys_intmem | IO_MEM_RAM);

    phys_flash = qemu_ram_alloc(FLASH_SIZE);

    dinfo = drive_get(IF_PFLASH, 0, 0);

    pflash_cfi02_register(0x0, phys_flash,

                          dinfo ? dinfo->bdrv : NULL, (64 * 1024),

                          FLASH_SIZE >> 16,

                          1, 2, 0x0000, 0x0000, 0x0000, 0x0000,

                          0x555, 0x2aa);

    cpu_irq = cris_pic_init_cpu(env);

    dev = qdev_create(NULL, "etraxfs,pic");

    /* FIXME: Is there a proper way to signal vectors to the CPU core?  */

    qdev_prop_set_ptr(dev, "interrupt_vector", &env->interrupt_vector);

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    sysbus_mmio_map(s, 0, 0x3001c000);

    sysbus_connect_irq(s, 0, cpu_irq[0]);

    sysbus_connect_irq(s, 1, cpu_irq[1]);

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

        irq[i] = qdev_get_gpio_in(dev, i);

    }

    nmi[0] = qdev_get_gpio_in(dev, 30);

    nmi[1] = qdev_get_gpio_in(dev, 31);

    etraxfs_dmac = etraxfs_dmac_init(0x30000000, 10);

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

        /* On ETRAX, odd numbered channels are inputs.  */

        etraxfs_dmac_connect(etraxfs_dmac, i, irq + 7 + i, i & 1);

    }

    /* Add the two ethernet blocks.  */

    eth[0] = etraxfs_eth_init(&nd_table[0], 0x30034000, 1);

    if (nb_nics > 1)

        eth[1] = etraxfs_eth_init(&nd_table[1], 0x30036000, 2);

    /* The DMA Connector block is missing, hardwire things for now.  */

    etraxfs_dmac_connect_client(etraxfs_dmac, 0, eth[0]);

    etraxfs_dmac_connect_client(etraxfs_dmac, 1, eth[0] + 1);

    if (eth[1]) {

        etraxfs_dmac_connect_client(etraxfs_dmac, 6, eth[1]);

        etraxfs_dmac_connect_client(etraxfs_dmac, 7, eth[1] + 1);

    }

    /* 2 timers.  */

    sysbus_create_varargs("etraxfs,timer", 0x3001e000, irq[0x1b], nmi[1], NULL);

    sysbus_create_varargs("etraxfs,timer", 0x3005e000, irq[0x1b], nmi[1], NULL);

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

        sysbus_create_simple("etraxfs,serial", 0x30026000 + i * 0x2000,

                             irq[0x14 + i]);

    }

    if (kernel_filename) {

        uint64_t entry, high;

        int kcmdline_len;

        /* Boots a kernel elf binary, os/linux-2.6/vmlinux from the axis

           devboard SDK.  */

        kernel_size = load_elf(kernel_filename, -0x80000000LL,

                               &entry, NULL, &high, 0, ELF_MACHINE, 0);

        bootstrap_pc = entry;

        if (kernel_size < 0) {

            /* Takes a kimage from the axis devboard SDK.  */

            kernel_size = load_image_targphys(kernel_filename, 0x40004000,

                                              ram_size);

            bootstrap_pc = 0x40004000;

            env->regs[9] = 0x40004000 + kernel_size;

        }

        env->regs[8] = 0x56902387; /* RAM init magic.  */

        if (kernel_cmdline && (kcmdline_len = strlen(kernel_cmdline))) {

            if (kcmdline_len > 256) {

                fprintf(stderr, "Too long CRIS kernel cmdline (max 256)\n");

                exit(1);

            }

            /* Let the kernel know we are modifying the cmdline.  */

            env->regs[10] = 0x87109563;

            env->regs[11] = 0x40000000;

            pstrcpy_targphys(env->regs[11], 256, kernel_cmdline);

        }

    }

    env->pc = bootstrap_pc;

    printf ("pc =%x\n", env->pc);

    printf ("ram size =%ld\n", ram_size);

}


envlist_to_environ(const envlist_t *envlist, size_t *count)

{

	struct envlist_entry *entry;

	char **env, **penv;

	penv = env = malloc((envlist->el_count + 1) * sizeof (char *));

	if (env == NULL)

		return (NULL);

	for (entry = envlist->el_entries.lh_first; entry != NULL;

	    entry = entry->ev_link.le_next) {

		*(penv++) = strdup(entry->ev_var);

	}

	*penv = NULL; /* NULL terminate the list */

	if (count != NULL)

		*count = envlist->el_count;

	return (env);

}


void monitor_flush(Monitor *mon)

{

    int rc;

    size_t len;

    const char *buf;

    if (mon->skip_flush) {

        return;

    }

    buf = qstring_get_str(mon->outbuf);

    len = qstring_get_length(mon->outbuf);

    if (len && !mon->mux_out) {

        rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);

        if (rc == len) {

            /* all flushed */

            QDECREF(mon->outbuf);

            mon->outbuf = qstring_new();

            return;

        }

        if (rc > 0) {

            /* partinal write */

            QString *tmp = qstring_from_str(buf + rc);

            QDECREF(mon->outbuf);

            mon->outbuf = tmp;

        }

        if (mon->watch == 0) {

            mon->watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT,

                                               monitor_unblocked, mon);

        }

    }

}


static ssize_t sdp_attr_get(struct bt_l2cap_sdp_state_s *sdp,

                uint8_t *rsp, const uint8_t *req, ssize_t len)

{

    ssize_t seqlen;

    int i, start, end, max;

    int32_t handle;

    struct sdp_service_record_s *record;

    uint8_t *lst;

    /* Perform the search */

    if (len < 7)

        return -SDP_INVALID_SYNTAX;

    memcpy(&handle, req, 4);

    req += 4;

    len -= 4;

    if (handle < 0 || handle > sdp->services)

        return -SDP_INVALID_RECORD_HANDLE;

    record = &sdp->service_list[handle];

    for (i = 0; i < record->attributes; i ++)

        record->attribute_list[i].match = 0;

    max = (req[0] << 8) | req[1];

    req += 2;

    len -= 2;

    if (max < 0x0007)

        return -SDP_INVALID_SYNTAX;

    if ((*req & ~SDP_DSIZE_MASK) == SDP_DTYPE_SEQ) {

        seqlen = sdp_datalen(&req, &len);

        if (seqlen < 3 || len < seqlen)

            return -SDP_INVALID_SYNTAX;

        len -= seqlen;

        while (seqlen)

            if (sdp_attr_match(record, &req, &seqlen))

                return -SDP_INVALID_SYNTAX;

    } else if (sdp_attr_match(record, &req, &seqlen))

        return -SDP_INVALID_SYNTAX;

    if (len < 1)

        return -SDP_INVALID_SYNTAX;

    if (*req) {

        if (len <= sizeof(int))

            return -SDP_INVALID_SYNTAX;

        len -= sizeof(int);

        memcpy(&start, req + 1, sizeof(int));

    } else

        start = 0;

    if (len > 1)

        return -SDP_INVALID_SYNTAX;

    /* Output the results */

    lst = rsp + 2;

    max = MIN(max, MAX_RSP_PARAM_SIZE);

    len = 3 - start;

    end = 0;

    for (i = 0; i < record->attributes; i ++)

        if (record->attribute_list[i].match) {

            if (len >= 0 && len + record->attribute_list[i].len < max) {

                memcpy(lst + len, record->attribute_list[i].pair,

                                record->attribute_list[i].len);

                end = len + record->attribute_list[i].len;

            }

            len += record->attribute_list[i].len;

        }

    if (0 >= start) {

       lst[0] = SDP_DTYPE_SEQ | SDP_DSIZE_NEXT2;

       lst[1] = (len + start - 3) >> 8;

       lst[2] = (len + start - 3) & 0xff;

    }

    rsp[0] = end >> 8;

    rsp[1] = end & 0xff;

    if (end < len) {

        len = end + start;

        lst[end ++] = sizeof(int);

        memcpy(lst + end, &len, sizeof(int));

        end += sizeof(int);

    } else

        lst[end ++] = 0;

    return end + 2;

}


static void virtio_pci_device_plugged(DeviceState *d)

{

    VirtIOPCIProxy *proxy = VIRTIO_PCI(d);

    VirtioBusState *bus = &proxy->bus;

    uint8_t *config;

    uint32_t size;

    VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);

    config = proxy->pci_dev.config;

    if (proxy->class_code) {

        pci_config_set_class(config, proxy->class_code);

    }

    pci_set_word(config + PCI_SUBSYSTEM_VENDOR_ID,

                 pci_get_word(config + PCI_VENDOR_ID));

    pci_set_word(config + PCI_SUBSYSTEM_ID, virtio_bus_get_vdev_id(bus));

    config[PCI_INTERRUPT_PIN] = 1;

    if (proxy->nvectors &&

        msix_init_exclusive_bar(&proxy->pci_dev, proxy->nvectors, 1)) {

        error_report("unable to init msix vectors to %" PRIu32,

                     proxy->nvectors);

        proxy->nvectors = 0;

    }

    proxy->pci_dev.config_write = virtio_write_config;

    size = VIRTIO_PCI_REGION_SIZE(&proxy->pci_dev)

         + virtio_bus_get_vdev_config_len(bus);

    if (size & (size - 1)) {

        size = 1 << qemu_fls(size);

    }

    memory_region_init_io(&proxy->bar, OBJECT(proxy), &virtio_pci_config_ops,

                          proxy, "virtio-pci", size);

    pci_register_bar(&proxy->pci_dev, 0, PCI_BASE_ADDRESS_SPACE_IO,

                     &proxy->bar);

    if (!kvm_has_many_ioeventfds()) {

        proxy->flags &= ~VIRTIO_PCI_FLAG_USE_IOEVENTFD;

    }

    virtio_add_feature(&vdev->host_features, VIRTIO_F_BAD_FEATURE);

}


static void vc1_decode_b_mb_intfi(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    GetBitContext *gb = &s->gb;

    int i, j;

    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;

    int cbp = 0; /* cbp decoding stuff */

    int mqdiff, mquant; /* MB quantization */

    int ttmb = v->ttfrm; /* MB Transform type */

    int mb_has_coeffs = 0; /* last_flag */

    int val; /* temp value */

    int first_block = 1;

    int dst_idx, off;

    int fwd;

    int dmv_x[2], dmv_y[2], pred_flag[2];

    int bmvtype = BMV_TYPE_BACKWARD;

    int idx_mbmode;

    int av_uninit(interpmvp);

    mquant      = v->pq; /* Lossy initialization */

    s->mb_intra = 0;

    idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_IF_MBMODE_VLC_BITS, 2);

    if (idx_mbmode <= 1) { // intra MB

        s->mb_intra = v->is_intra[s->mb_x] = 1;

        s->current_picture.motion_val[1][s->block_index[0]][0] = 0;

        s->current_picture.motion_val[1][s->block_index[0]][1] = 0;

        s->current_picture.mb_type[mb_pos + v->mb_off]         = MB_TYPE_INTRA;

        GET_MQUANT();

        s->current_picture.qscale_table[mb_pos] = mquant;

        /* Set DC scale - y and c use the same (not sure if necessary here) */

        s->y_dc_scale = s->y_dc_scale_table[mquant];

        s->c_dc_scale = s->c_dc_scale_table[mquant];

        v->s.ac_pred  = v->acpred_plane[mb_pos] = get_bits1(gb);

        mb_has_coeffs = idx_mbmode & 1;

        if (mb_has_coeffs)

            cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_ICBPCY_VLC_BITS, 2);

        dst_idx = 0;

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

            s->dc_val[0][s->block_index[i]] = 0;

            dst_idx += i >> 2;

            val = ((cbp >> (5 - i)) & 1);

            v->mb_type[0][s->block_index[i]] = s->mb_intra;

            v->a_avail                       = v->c_avail = 0;

            if (i == 2 || i == 3 || !s->first_slice_line)

                v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];

            if (i == 1 || i == 3 || s->mb_x)

                v->c_avail = v->mb_type[0][s->block_index[i] - 1];

            vc1_decode_intra_block(v, s->block[i], i, val, mquant,

                                   (i & 4) ? v->codingset2 : v->codingset);

            if ((i>3) && (s->flags & CODEC_FLAG_GRAY))

                continue;

            v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);

            if (v->rangeredfrm)

                for (j = 0; j < 64; j++)

                    s->block[i][j] <<= 1;

            off  = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);

            s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize);

            // TODO: yet to perform loop filter

        }

    } else {

        s->mb_intra = v->is_intra[s->mb_x] = 0;

        s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_16x16;

        for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0;

        if (v->fmb_is_raw)

            fwd = v->forward_mb_plane[mb_pos] = get_bits1(gb);

        else

            fwd = v->forward_mb_plane[mb_pos];

        if (idx_mbmode <= 5) { // 1-MV

            dmv_x[0]     = dmv_x[1] = dmv_y[0] = dmv_y[1] = 0;

            pred_flag[0] = pred_flag[1] = 0;

            if (fwd)

                bmvtype = BMV_TYPE_FORWARD;

            else {

                bmvtype = decode012(gb);

                switch (bmvtype) {

                case 0:

                    bmvtype = BMV_TYPE_BACKWARD;

                    break;

                case 1:

                    bmvtype = BMV_TYPE_DIRECT;

                    break;

                case 2:

                    bmvtype   = BMV_TYPE_INTERPOLATED;

                    interpmvp = get_bits1(gb);

                }

            }

            v->bmvtype = bmvtype;

            if (bmvtype != BMV_TYPE_DIRECT && idx_mbmode & 1) {

                get_mvdata_interlaced(v, &dmv_x[bmvtype == BMV_TYPE_BACKWARD], &dmv_y[bmvtype == BMV_TYPE_BACKWARD], &pred_flag[bmvtype == BMV_TYPE_BACKWARD]);

            }

            if (bmvtype == BMV_TYPE_INTERPOLATED && interpmvp) {

                get_mvdata_interlaced(v, &dmv_x[1], &dmv_y[1], &pred_flag[1]);

            }

            if (bmvtype == BMV_TYPE_DIRECT) {

                dmv_x[0] = dmv_y[0] = pred_flag[0] = 0;

                dmv_x[1] = dmv_y[1] = pred_flag[0] = 0;

            }

            vc1_pred_b_mv_intfi(v, 0, dmv_x, dmv_y, 1, pred_flag);

            vc1_b_mc(v, dmv_x, dmv_y, (bmvtype == BMV_TYPE_DIRECT), bmvtype);

            mb_has_coeffs = !(idx_mbmode & 2);

        } else { // 4-MV

            if (fwd)

                bmvtype = BMV_TYPE_FORWARD;

            v->bmvtype  = bmvtype;

            v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);

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

                if (i < 4) {

                    dmv_x[0] = dmv_y[0] = pred_flag[0] = 0;

                    dmv_x[1] = dmv_y[1] = pred_flag[1] = 0;

                    val = ((v->fourmvbp >> (3 - i)) & 1);

                    if (val) {

                        get_mvdata_interlaced(v, &dmv_x[bmvtype == BMV_TYPE_BACKWARD],

                                                 &dmv_y[bmvtype == BMV_TYPE_BACKWARD],

                                             &pred_flag[bmvtype == BMV_TYPE_BACKWARD]);

                    }

                    vc1_pred_b_mv_intfi(v, i, dmv_x, dmv_y, 0, pred_flag);

                    vc1_mc_4mv_luma(v, i, bmvtype == BMV_TYPE_BACKWARD, 0);

                } else if (i == 4)

                    vc1_mc_4mv_chroma(v, bmvtype == BMV_TYPE_BACKWARD);

            }

            mb_has_coeffs = idx_mbmode & 1;

        }

        if (mb_has_coeffs)

            cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

        if (cbp) {

            GET_MQUANT();

        }

        s->current_picture.qscale_table[mb_pos] = mquant;

        if (!v->ttmbf && cbp) {

            ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);

        }

        dst_idx = 0;

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

            s->dc_val[0][s->block_index[i]] = 0;

            dst_idx += i >> 2;

            val = ((cbp >> (5 - i)) & 1);

            off = (i & 4) ? 0 : (i & 1) * 8 + (i & 2) * 4 * s->linesize;

            if (val) {

                vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,

                                   first_block, s->dest[dst_idx] + off,

                                   (i & 4) ? s->uvlinesize : s->linesize,

                                   (i & 4) && (s->flags & CODEC_FLAG_GRAY), NULL);

                if (!v->ttmbf && ttmb < 8)

                    ttmb = -1;

                first_block = 0;

            }

        }

    }

}


void HELPER(set_cp_reg)(CPUARMState *env, void *rip, uint32_t value)

{

    const ARMCPRegInfo *ri = rip;

    ri->writefn(env, ri, value);

}


static int libspeex_decode_frame(AVCodecContext *avctx, void *data,

                                 int *got_frame_ptr, AVPacket *avpkt)

{

    uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    LibSpeexContext *s = avctx->priv_data;

    int16_t *output;

    int ret, consumed = 0;

    /* get output buffer */

    s->frame.nb_samples = s->frame_size;

    if ((ret = ff_get_buffer(avctx, &s->frame)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return ret;

    }

    output = (int16_t *)s->frame.data[0];

    /* if there is not enough data left for the smallest possible frame or the

       next 5 bits are a terminator code, reset the libspeex buffer using the

       current packet, otherwise ignore the current packet and keep decoding

       frames from the libspeex buffer. */

    if (speex_bits_remaining(&s->bits) < 5 ||

        speex_bits_peek_unsigned(&s->bits, 5) == 0x1F) {

        /* check for flush packet */

        if (!buf || !buf_size) {

            *got_frame_ptr = 0;

            return buf_size;

        }

        /* set new buffer */

        speex_bits_read_from(&s->bits, buf, buf_size);

        consumed = buf_size;

    }

    /* decode a single frame */

    ret = speex_decode_int(s->dec_state, &s->bits, output);

    if (ret <= -2) {

        av_log(avctx, AV_LOG_ERROR, "Error decoding Speex frame.\n");

        return AVERROR_INVALIDDATA;

    }

    if (avctx->channels == 2)

        speex_decode_stereo_int(output, s->frame_size, &s->stereo);

    *got_frame_ptr   = 1;

    *(AVFrame *)data = s->frame;

    return consumed;

}


static void vmport_class_initfn(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = vmport_realizefn;

    dc->no_user = 1;

}


void qemu_file_skip(QEMUFile *f, int size)

{

    if (f->buf_index + size <= f->buf_size) {

        f->buf_index += size;

    }

}


static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,

                  enum PixelFormat srcFormat, enum PixelFormat dstFormat,

                  int srcW, int srcH, int dstW, int dstH, int flags)

{

    uint8_t *src[4] = {0};

    uint8_t *dst[4] = {0};

    uint8_t *out[4] = {0};

    int srcStride[4], dstStride[4];

    int i;

    uint64_t ssdY, ssdU=0, ssdV=0, ssdA=0;

    struct SwsContext *srcContext = NULL, *dstContext = NULL,

                      *outContext = NULL;

    int res;

    res = 0;

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

        // avoid stride % bpp != 0

        if (srcFormat==PIX_FMT_RGB24 || srcFormat==PIX_FMT_BGR24)

            srcStride[i]= srcW*3;

        else if (srcFormat==PIX_FMT_RGB48BE || srcFormat==PIX_FMT_RGB48LE)

            srcStride[i]= srcW*6;

        else

            srcStride[i]= srcW*4;

        if (dstFormat==PIX_FMT_RGB24 || dstFormat==PIX_FMT_BGR24)

            dstStride[i]= dstW*3;

        else if (dstFormat==PIX_FMT_RGB48BE || dstFormat==PIX_FMT_RGB48LE)

            dstStride[i]= dstW*6;

        else

            dstStride[i]= dstW*4;

        /* Image buffers passed into libswscale can be allocated any way you

         * prefer, as long as they're aligned enough for the architecture, and

         * they're freed appropriately (such as using av_free for buffers

         * allocated with av_malloc). */

        /* An extra 16 bytes is being allocated because some scalers may write

         * out of bounds. */

        src[i]= av_mallocz(srcStride[i]*srcH+16);

        dst[i]= av_mallocz(dstStride[i]*dstH+16);

        out[i]= av_mallocz(refStride[i]*h);

        if (!src[i] || !dst[i] || !out[i]) {

            perror("Malloc");

            res = -1;

            goto end;

        }

    }

    srcContext= sws_getContext(w, h, PIX_FMT_YUVA420P, srcW, srcH, srcFormat, flags, NULL, NULL, NULL);

    if (!srcContext) {

        fprintf(stderr, "Failed to get %s ---> %s\n",

                av_pix_fmt_descriptors[PIX_FMT_YUVA420P].name,

                av_pix_fmt_descriptors[srcFormat].name);

        res = -1;

        goto end;

    }

    dstContext= sws_getContext(srcW, srcH, srcFormat, dstW, dstH, dstFormat, flags, NULL, NULL, NULL);

    if (!dstContext) {

        fprintf(stderr, "Failed to get %s ---> %s\n",

                av_pix_fmt_descriptors[srcFormat].name,

                av_pix_fmt_descriptors[dstFormat].name);

        res = -1;

        goto end;

    }

    outContext= sws_getContext(dstW, dstH, dstFormat, w, h, PIX_FMT_YUVA420P, flags, NULL, NULL, NULL);

    if (!outContext) {

        fprintf(stderr, "Failed to get %s ---> %s\n",

                av_pix_fmt_descriptors[dstFormat].name,

                av_pix_fmt_descriptors[PIX_FMT_YUVA420P].name);

        res = -1;

        goto end;

    }

//    printf("test %X %X %X -> %X %X %X\n", (int)ref[0], (int)ref[1], (int)ref[2],

//        (int)src[0], (int)src[1], (int)src[2]);

    sws_scale(srcContext, ref, refStride, 0, h   , src, srcStride);

    sws_scale(dstContext, src, srcStride, 0, srcH, dst, dstStride);

    sws_scale(outContext, dst, dstStride, 0, dstH, out, refStride);

    ssdY= getSSD(ref[0], out[0], refStride[0], refStride[0], w, h);

    if (hasChroma(srcFormat) && hasChroma(dstFormat)) {

        //FIXME check that output is really gray

        ssdU= getSSD(ref[1], out[1], refStride[1], refStride[1], (w+1)>>1, (h+1)>>1);

        ssdV= getSSD(ref[2], out[2], refStride[2], refStride[2], (w+1)>>1, (h+1)>>1);

    }

    if (isALPHA(srcFormat) && isALPHA(dstFormat))

        ssdA= getSSD(ref[3], out[3], refStride[3], refStride[3], w, h);

    ssdY/= w*h;

    ssdU/= w*h/4;

    ssdV/= w*h/4;

    ssdA/= w*h;

    printf(" %s %dx%d -> %s %4dx%4d flags=%2d SSD=%5"PRId64",%5"PRId64",%5"PRId64",%5"PRId64"\n",

           av_pix_fmt_descriptors[srcFormat].name, srcW, srcH,

           av_pix_fmt_descriptors[dstFormat].name, dstW, dstH,

           flags, ssdY, ssdU, ssdV, ssdA);

    fflush(stdout);

end:

    sws_freeContext(srcContext);

    sws_freeContext(dstContext);

    sws_freeContext(outContext);

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

        av_free(src[i]);

        av_free(dst[i]);

        av_free(out[i]);

    }

    return res;

}


static int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts)

{

        mp_image_t *dmpi;

        // hope we'll get DR buffer:

        dmpi=ff_vf_get_image(vf->next, IMGFMT_YV12,

                          MP_IMGTYPE_TEMP, MP_IMGFLAG_ACCEPT_STRIDE |

                          ((vf->priv->scaleh == 1) ? MP_IMGFLAG_READABLE : 0),

                          mpi->w * vf->priv->scalew,

                          mpi->h / vf->priv->scaleh - vf->priv->skipline);

        toright(dmpi->planes, mpi->planes, dmpi->stride,

                mpi->stride, mpi->w, mpi->h, vf->priv);

        return ff_vf_next_put_image(vf,dmpi, pts);

}


static void runstate_init(void)

{

    const RunStateTransition *p;

    memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));

    for (p = &runstate_transitions_def[0]; p->from != RUN_STATE_MAX; p++) {

        runstate_valid_transitions[p->from][p->to] = true;

    }

}


static void decode_vui(HEVCContext *s, HEVCSPS *sps)

{

    VUI *vui          = &sps->vui;

    GetBitContext *gb = &s->HEVClc->gb;

    GetBitContext backup;

    int sar_present, alt = 0;

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

    sar_present = get_bits1(gb);

    if (sar_present) {

        uint8_t sar_idx = get_bits(gb, 8);

        if (sar_idx < FF_ARRAY_ELEMS(vui_sar))

            vui->sar = vui_sar[sar_idx];

        else if (sar_idx == 255) {

            vui->sar.num = get_bits(gb, 16);

            vui->sar.den = get_bits(gb, 16);

        } else

            av_log(s->avctx, AV_LOG_WARNING,

                   "Unknown SAR index: %u.\n", sar_idx);

    }

    vui->overscan_info_present_flag = get_bits1(gb);

    if (vui->overscan_info_present_flag)

        vui->overscan_appropriate_flag = get_bits1(gb);

    vui->video_signal_type_present_flag = get_bits1(gb);

    if (vui->video_signal_type_present_flag) {

        vui->video_format                    = get_bits(gb, 3);

        vui->video_full_range_flag           = get_bits1(gb);

        vui->colour_description_present_flag = get_bits1(gb);

        if (vui->video_full_range_flag && sps->pix_fmt == AV_PIX_FMT_YUV420P)

            sps->pix_fmt = AV_PIX_FMT_YUVJ420P;

        if (vui->colour_description_present_flag) {

            vui->colour_primaries        = get_bits(gb, 8);

            vui->transfer_characteristic = get_bits(gb, 8);

            vui->matrix_coeffs           = get_bits(gb, 8);

            // Set invalid values to "unspecified"

            if (vui->colour_primaries >= AVCOL_PRI_NB)

                vui->colour_primaries = AVCOL_PRI_UNSPECIFIED;

            if (vui->transfer_characteristic >= AVCOL_TRC_NB)

                vui->transfer_characteristic = AVCOL_TRC_UNSPECIFIED;

            if (vui->matrix_coeffs >= AVCOL_SPC_NB)

                vui->matrix_coeffs = AVCOL_SPC_UNSPECIFIED;

        }

    }

    vui->chroma_loc_info_present_flag = get_bits1(gb);

    if (vui->chroma_loc_info_present_flag) {

        vui->chroma_sample_loc_type_top_field    = get_ue_golomb_long(gb);

        vui->chroma_sample_loc_type_bottom_field = get_ue_golomb_long(gb);

    }

    vui->neutra_chroma_indication_flag = get_bits1(gb);

    vui->field_seq_flag                = get_bits1(gb);

    vui->frame_field_info_present_flag = get_bits1(gb);

    vui->default_display_window_flag = get_bits1(gb);

    // Backup context in case an alternate header is detected

    if( get_bits_left(gb) >= 66)

        memcpy(&backup, gb, sizeof(backup));

    if (vui->default_display_window_flag) {

        //TODO: * 2 is only valid for 420

        vui->def_disp_win.left_offset   = get_ue_golomb_long(gb) * 2;

        vui->def_disp_win.right_offset  = get_ue_golomb_long(gb) * 2;

        vui->def_disp_win.top_offset    = get_ue_golomb_long(gb) * 2;

        vui->def_disp_win.bottom_offset = get_ue_golomb_long(gb) * 2;

        if (s->apply_defdispwin &&

            s->avctx->flags2 & CODEC_FLAG2_IGNORE_CROP) {

            av_log(s->avctx, AV_LOG_DEBUG,

                   "discarding vui default display window, "

                   "original values are l:%u r:%u t:%u b:%u\n",

                   vui->def_disp_win.left_offset,

                   vui->def_disp_win.right_offset,

                   vui->def_disp_win.top_offset,

                   vui->def_disp_win.bottom_offset);

            vui->def_disp_win.left_offset   =

            vui->def_disp_win.right_offset  =

            vui->def_disp_win.top_offset    =

            vui->def_disp_win.bottom_offset = 0;

        }

    }

    vui->vui_timing_info_present_flag = get_bits1(gb);

    if (vui->vui_timing_info_present_flag) {

        if( get_bits_left(gb) < 66) {

            // The alternate syntax seem to have timing info located

            // at where def_disp_win is normally located

            av_log(s->avctx, AV_LOG_WARNING,

                   "Strange VUI timing information, retrying...\n");

            vui->default_display_window_flag = 0;

            memset(&vui->def_disp_win, 0, sizeof(vui->def_disp_win));

            memcpy(gb, &backup, sizeof(backup));

            alt = 1;

        }

        vui->vui_num_units_in_tick               = get_bits_long(gb, 32);

        vui->vui_time_scale                      = get_bits_long(gb, 32);

        if (alt) {

            av_log(s->avctx, AV_LOG_INFO, "Retry got %i/%i fps\n",

                   vui->vui_time_scale, vui->vui_num_units_in_tick);

        }

        vui->vui_poc_proportional_to_timing_flag = get_bits1(gb);

        if (vui->vui_poc_proportional_to_timing_flag)

            vui->vui_num_ticks_poc_diff_one_minus1 = get_ue_golomb_long(gb);

        vui->vui_hrd_parameters_present_flag = get_bits1(gb);

        if (vui->vui_hrd_parameters_present_flag)

            decode_hrd(s, 1, sps->max_sub_layers);

    }

    vui->bitstream_restriction_flag = get_bits1(gb);

    if (vui->bitstream_restriction_flag) {

        vui->tiles_fixed_structure_flag              = get_bits1(gb);

        vui->motion_vectors_over_pic_boundaries_flag = get_bits1(gb);

        vui->restricted_ref_pic_lists_flag           = get_bits1(gb);

        vui->min_spatial_segmentation_idc            = get_ue_golomb_long(gb);

        vui->max_bytes_per_pic_denom                 = get_ue_golomb_long(gb);

        vui->max_bits_per_min_cu_denom               = get_ue_golomb_long(gb);

        vui->log2_max_mv_length_horizontal           = get_ue_golomb_long(gb);

        vui->log2_max_mv_length_vertical             = get_ue_golomb_long(gb);

    }

}


void ff_vc1_interp_mc(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    H264ChromaContext *h264chroma = &v->h264chroma;

    uint8_t *srcY, *srcU, *srcV;

    int dxy, mx, my, uvmx, uvmy, src_x, src_y, uvsrc_x, uvsrc_y;

    int off, off_uv;

    int v_edge_pos = s->v_edge_pos >> v->field_mode;

    int use_ic = v->next_use_ic;

    if (!v->field_mode && !v->s.next_picture.f->data[0])

        return;

    mx   = s->mv[1][0][0];

    my   = s->mv[1][0][1];

    uvmx = (mx + ((mx & 3) == 3)) >> 1;

    uvmy = (my + ((my & 3) == 3)) >> 1;

    if (v->field_mode) {

        if (v->cur_field_type != v->ref_field_type[1])

            my   = my   - 2 + 4 * v->cur_field_type;

            uvmy = uvmy - 2 + 4 * v->cur_field_type;

    }

    if (v->fastuvmc) {

        uvmx = uvmx + ((uvmx < 0) ? -(uvmx & 1) : (uvmx & 1));

        uvmy = uvmy + ((uvmy < 0) ? -(uvmy & 1) : (uvmy & 1));

    }

    srcY = s->next_picture.f->data[0];

    srcU = s->next_picture.f->data[1];

    srcV = s->next_picture.f->data[2];

    src_x   = s->mb_x * 16 + (mx   >> 2);

    src_y   = s->mb_y * 16 + (my   >> 2);

    uvsrc_x = s->mb_x *  8 + (uvmx >> 2);

    uvsrc_y = s->mb_y *  8 + (uvmy >> 2);

    if (v->profile != PROFILE_ADVANCED) {

        src_x   = av_clip(  src_x, -16, s->mb_width  * 16);

        src_y   = av_clip(  src_y, -16, s->mb_height * 16);

        uvsrc_x = av_clip(uvsrc_x,  -8, s->mb_width  *  8);

        uvsrc_y = av_clip(uvsrc_y,  -8, s->mb_height *  8);

    } else {

        src_x   = av_clip(  src_x, -17, s->avctx->coded_width);

        src_y   = av_clip(  src_y, -18, s->avctx->coded_height + 1);

        uvsrc_x = av_clip(uvsrc_x,  -8, s->avctx->coded_width  >> 1);

        uvsrc_y = av_clip(uvsrc_y,  -8, s->avctx->coded_height >> 1);

    }

    srcY += src_y   * s->linesize   + src_x;

    srcU += uvsrc_y * s->uvlinesize + uvsrc_x;

    srcV += uvsrc_y * s->uvlinesize + uvsrc_x;

    if (v->field_mode && v->ref_field_type[1]) {

        srcY += s->current_picture_ptr->f->linesize[0];

        srcU += s->current_picture_ptr->f->linesize[1];

        srcV += s->current_picture_ptr->f->linesize[2];

    }

    /* for grayscale we should not try to read from unknown area */

    if (s->flags & CODEC_FLAG_GRAY) {

        srcU = s->edge_emu_buffer + 18 * s->linesize;

        srcV = s->edge_emu_buffer + 18 * s->linesize;

    }

    if (v->rangeredfrm || s->h_edge_pos < 22 || v_edge_pos < 22 || use_ic

        || (unsigned)(src_x - 1) > s->h_edge_pos - (mx & 3) - 16 - 3

        || (unsigned)(src_y - 1) > v_edge_pos    - (my & 3) - 16 - 3) {

        uint8_t *uvbuf = s->edge_emu_buffer + 19 * s->linesize;

        srcY -= s->mspel * (1 + s->linesize);

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer, srcY,

                                 s->linesize, s->linesize,

                                 17 + s->mspel * 2, 17 + s->mspel * 2,

                                 src_x - s->mspel, src_y - s->mspel,

                                 s->h_edge_pos, v_edge_pos);

        srcY = s->edge_emu_buffer;

        s->vdsp.emulated_edge_mc(uvbuf, srcU,

                                 s->uvlinesize, s->uvlinesize,

                                 8 + 1, 8 + 1,

                                 uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, v_edge_pos >> 1);

        s->vdsp.emulated_edge_mc(uvbuf + 16, srcV,

                                 s->uvlinesize, s->uvlinesize,

                                 8 + 1, 8 + 1,

                                 uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, v_edge_pos >> 1);

        srcU = uvbuf;

        srcV = uvbuf + 16;

        /* if we deal with range reduction we need to scale source blocks */

        if (v->rangeredfrm) {

            int i, j;

            uint8_t *src, *src2;

            src = srcY;

            for (j = 0; j < 17 + s->mspel * 2; j++) {

                for (i = 0; i < 17 + s->mspel * 2; i++)

                    src[i] = ((src[i] - 128) >> 1) + 128;

                src += s->linesize;

            }

            src = srcU;

            src2 = srcV;

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

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

                    src[i]  = ((src[i]  - 128) >> 1) + 128;

                    src2[i] = ((src2[i] - 128) >> 1) + 128;

                }

                src  += s->uvlinesize;

                src2 += s->uvlinesize;

            }

        }

        if (use_ic) {

            uint8_t (*luty )[256] = v->next_luty;

            uint8_t (*lutuv)[256] = v->next_lutuv;

            int i, j;

            uint8_t *src, *src2;

            src = srcY;

            for (j = 0; j < 17 + s->mspel * 2; j++) {

                int f = v->field_mode ? v->ref_field_type[1] : ((j+src_y - s->mspel) & 1);

                for (i = 0; i < 17 + s->mspel * 2; i++)

                    src[i] = luty[f][src[i]];

                src += s->linesize;

            }

            src  = srcU;

            src2 = srcV;

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

                int f = v->field_mode ? v->ref_field_type[1] : ((j+uvsrc_y) & 1);

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

                    src[i]  = lutuv[f][src[i]];

                    src2[i] = lutuv[f][src2[i]];

                }

                src  += s->uvlinesize;

                src2 += s->uvlinesize;

            }

        }

        srcY += s->mspel * (1 + s->linesize);

    }

    off    = 0;

    off_uv = 0;

    if (s->mspel) {

        dxy = ((my & 3) << 2) | (mx & 3);

        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + off    , srcY    , s->linesize, v->rnd);

        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + off + 8, srcY + 8, s->linesize, v->rnd);

        srcY += s->linesize * 8;

        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + off + 8 * s->linesize    , srcY    , s->linesize, v->rnd);

        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + off + 8 * s->linesize + 8, srcY + 8, s->linesize, v->rnd);

    } else { // hpel mc

        dxy = (my & 2) | ((mx & 2) >> 1);

        if (!v->rnd)

            s->hdsp.avg_pixels_tab[0][dxy](s->dest[0] + off, srcY, s->linesize, 16);

        else

            s->hdsp.avg_no_rnd_pixels_tab[dxy](s->dest[0] + off, srcY, s->linesize, 16);

    }

    if (s->flags & CODEC_FLAG_GRAY) return;

    /* Chroma MC always uses qpel blilinear */

    uvmx = (uvmx & 3) << 1;

    uvmy = (uvmy & 3) << 1;

    if (!v->rnd) {

        h264chroma->avg_h264_chroma_pixels_tab[0](s->dest[1] + off_uv, srcU, s->uvlinesize, 8, uvmx, uvmy);

        h264chroma->avg_h264_chroma_pixels_tab[0](s->dest[2] + off_uv, srcV, s->uvlinesize, 8, uvmx, uvmy);

    } else {

        v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1] + off_uv, srcU, s->uvlinesize, 8, uvmx, uvmy);

        v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2] + off_uv, srcV, s->uvlinesize, 8, uvmx, uvmy);

    }

}


static av_cold int msrle_decode_init(AVCodecContext *avctx)

{

    MsrleContext *s = avctx->priv_data;

    s->avctx = avctx;

    switch (avctx->bits_per_coded_sample) {

    case 4:

    case 8:

        avctx->pix_fmt = AV_PIX_FMT_PAL8;

        break;

    case 24:

        avctx->pix_fmt = AV_PIX_FMT_BGR24;

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "unsupported bits per sample\n");

        return AVERROR_INVALIDDATA;

    }

    s->frame.data[0] = NULL;

    return 0;

}


static int mm_decode_intra(MmContext * s, int half_horiz, int half_vert)

{

    int x = 0, y = 0;

    while (bytestream2_get_bytes_left(&s->gb) > 0) {

        int run_length, color;

        if (y >= s->avctx->height)

            return 0;

        color = bytestream2_get_byte(&s->gb);

        if (color & 0x80) {

            run_length = 1;

        }else{

            run_length = (color & 0x7f) + 2;

            color = bytestream2_get_byte(&s->gb);

        }

        if (half_horiz)

            run_length *=2;

        if (run_length > s->avctx->width - x)

            return AVERROR_INVALIDDATA;

        if (color) {

            memset(s->frame->data[0] + y*s->frame->linesize[0] + x, color, run_length);

            if (half_vert)

                memset(s->frame->data[0] + (y+1)*s->frame->linesize[0] + x, color, run_length);

        }

        x+= run_length;

        if (x >= s->avctx->width) {

            x=0;

            y += 1 + half_vert;

        }

    }

    return 0;

}


static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)

{

    MXFContext *mxf = arg;

    MXFPartition *partition;

    UID op;

    uint64_t footer_partition;

    uint32_t nb_essence_containers;

    int err;

    if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))

        return AVERROR(ENOMEM);

    if ((err = av_reallocp_array(&mxf->partitions, mxf->partitions_count + 1,

                                 sizeof(*mxf->partitions))) < 0) {

        mxf->partitions_count = 0;

        return err;

    }

    if (mxf->parsing_backward) {

        /* insert the new partition pack in the middle

         * this makes the entries in mxf->partitions sorted by offset */

        memmove(&mxf->partitions[mxf->last_forward_partition+1],

                &mxf->partitions[mxf->last_forward_partition],

                (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));

        partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];

    } else {

        mxf->last_forward_partition++;

        partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];

    }

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

    mxf->partitions_count++;

    partition->pack_length = avio_tell(pb) - klv_offset + size;

    switch(uid[13]) {

    case 2:

        partition->type = Header;

        break;

    case 3:

        partition->type = BodyPartition;

        break;

    case 4:

        partition->type = Footer;

        break;

    default:

        av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);

        return AVERROR_INVALIDDATA;

    }

    /* consider both footers to be closed (there is only Footer and CompleteFooter) */

    partition->closed = partition->type == Footer || !(uid[14] & 1);

    partition->complete = uid[14] > 2;

    avio_skip(pb, 4);

    partition->kag_size = avio_rb32(pb);

    partition->this_partition = avio_rb64(pb);

    partition->previous_partition = avio_rb64(pb);

    footer_partition = avio_rb64(pb);

    partition->header_byte_count = avio_rb64(pb);

    partition->index_byte_count = avio_rb64(pb);

    partition->index_sid = avio_rb32(pb);

    avio_skip(pb, 8);

    partition->body_sid = avio_rb32(pb);

    avio_read(pb, op, sizeof(UID));

    nb_essence_containers = avio_rb32(pb);

    /* some files don'thave FooterPartition set in every partition */

    if (footer_partition) {

        if (mxf->footer_partition && mxf->footer_partition != footer_partition) {

            av_log(mxf->fc, AV_LOG_ERROR,

                   "inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n",

                   mxf->footer_partition, footer_partition);

        } else {

            mxf->footer_partition = footer_partition;

        }

    }

    av_dlog(mxf->fc,

            "PartitionPack: ThisPartition = 0x%"PRIX64

            ", PreviousPartition = 0x%"PRIX64", "

            "FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n",

            partition->this_partition,

            partition->previous_partition, footer_partition,

            partition->index_sid, partition->body_sid);

    /* sanity check PreviousPartition if set */

    if (partition->previous_partition &&

        mxf->run_in + partition->previous_partition >= klv_offset) {

        av_log(mxf->fc, AV_LOG_ERROR,

               "PreviousPartition points to this partition or forward\n");

        return AVERROR_INVALIDDATA;

    }

    if      (op[12] == 1 && op[13] == 1) mxf->op = OP1a;

    else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;

    else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;

    else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;

    else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;

    else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;

    else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;

    else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;

    else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;

    else if (op[12] == 64&& op[13] == 1) mxf->op = OPSonyOpt;

    else if (op[12] == 0x10) {

        /* SMPTE 390m: "There shall be exactly one essence container"

         * The following block deals with files that violate this, namely:

         * 2011_DCPTEST_24FPS.V.mxf - two ECs, OP1a

         * abcdefghiv016f56415e.mxf - zero ECs, OPAtom, output by Avid AirSpeed */

        if (nb_essence_containers != 1) {

            MXFOP op = nb_essence_containers ? OP1a : OPAtom;

            /* only nag once */

            if (!mxf->op)

                av_log(mxf->fc, AV_LOG_WARNING,

                       "\"OPAtom\" with %u ECs - assuming %s\n",

                       nb_essence_containers,

                       op == OP1a ? "OP1a" : "OPAtom");

            mxf->op = op;

        } else

            mxf->op = OPAtom;

    } else {

        av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);

        mxf->op = OP1a;

    }

    if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {

        av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %i - guessing ", partition->kag_size);

        if (mxf->op == OPSonyOpt)

            partition->kag_size = 512;

        else

            partition->kag_size = 1;

        av_log(mxf->fc, AV_LOG_WARNING, "%i\n", partition->kag_size);

    }

    return 0;

}


char *av_base64_encode(uint8_t * src, int len)

{

    static const char b64[] =

        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    char *ret, *dst;

    unsigned i_bits = 0;

    int i_shift = 0;

    int bytes_remaining = len;

    if (len < UINT_MAX / 4) {

        ret = dst = av_malloc(len * 4 / 3 + 12);

    } else

        return NULL;

    if (len) {                  // special edge case, what should we really do here?

        while (bytes_remaining) {

            i_bits = (i_bits << 8) + *src++;

            bytes_remaining--;

            i_shift += 8;

            do {

                *dst++ = b64[(i_bits << 6 >> i_shift) & 0x3f];

                i_shift -= 6;

            } while (i_shift > 6 || (bytes_remaining == 0 && i_shift > 0));

        }

        while ((dst - ret) & 3)

            *dst++ = '=';

    }

    *dst = '\0';

    return ret;

}


av_cold void ff_blockdsp_init_x86(BlockDSPContext *c,

                                  AVCodecContext *avctx)

#else

av_cold void ff_blockdsp_init_x86(BlockDSPContext *c)

#endif /* FF_API_XVMC */

{

#if HAVE_INLINE_ASM

    int cpu_flags = av_get_cpu_flags();

    if (INLINE_MMX(cpu_flags)) {

        c->clear_block  = clear_block_mmx;

        c->clear_blocks = clear_blocks_mmx;

    }

#if FF_API_XVMC

FF_DISABLE_DEPRECATION_WARNINGS

    /* XvMCCreateBlocks() may not allocate 16-byte aligned blocks */

    if (CONFIG_MPEG_XVMC_DECODER && avctx->xvmc_acceleration > 1)

        return;

FF_ENABLE_DEPRECATION_WARNINGS

#endif /* FF_API_XVMC */

    if (INLINE_SSE(cpu_flags)) {

        c->clear_block  = clear_block_sse;

        c->clear_blocks = clear_blocks_sse;

    }

#endif /* HAVE_INLINE_ASM */

}


static int read_bfraction(VC1Context *v, GetBitContext* gb) {

    v->bfraction_lut_index = get_vlc2(gb, ff_vc1_bfraction_vlc.table, VC1_BFRACTION_VLC_BITS, 1);

    v->bfraction           = ff_vc1_bfraction_lut[v->bfraction_lut_index];

    return 0;

}


AVStream *add_video_stream(AVFormatContext *oc, int codec_id)

{

    AVCodec *codec;

    AVCodecContext *c;

    AVStream *st;

    uint8_t *picture_buf;

    int size;

    st = av_new_stream(oc, 0);

    if (!st) {

        fprintf(stderr, "Could not alloc stream\n");

        exit(1);

    }

    /* find the mpeg1 video encoder */

    codec = avcodec_find_encoder(codec_id);

    if (!codec) {

        fprintf(stderr, "codec not found\n");

        exit(1);

    }

    c = &st->codec;

    c->codec_type = CODEC_TYPE_VIDEO;

    /* put sample parameters */

    c->bit_rate = 400000;

    /* resolution must be a multiple of two */

    c->width = 352;

    c->height = 288;

    /* frames per second */

    c->frame_rate = 25;

    c->frame_rate_base= 1;

    c->gop_size = 12; /* emit one intra frame every twelve frames */

    /* open it */

    if (avcodec_open(c, codec) < 0) {

        fprintf(stderr, "could not open codec\n");

        exit(1);

    }

    /* alloc various buffers */

    picture= avcodec_alloc_frame();

    video_outbuf_size = 100000;

    video_outbuf = malloc(video_outbuf_size);

    size = c->width * c->height;

    picture_buf = malloc((size * 3) / 2); /* size for YUV 420 */

    picture->data[0] = picture_buf;

    picture->data[1] = picture->data[0] + size;

    picture->data[2] = picture->data[1] + size / 4;

    picture->linesize[0] = c->width;

    picture->linesize[1] = c->width / 2;

    picture->linesize[2] = c->width / 2;

    return st;

}


const uint8_t *get_submv_prob(uint32_t left, uint32_t top)

{

    if (left == top)

        return vp8_submv_prob[4 - !!left];

    if (!top)

        return vp8_submv_prob[2];

    return vp8_submv_prob[1 - !!left];

}


static inline void cpu_handle_interrupt(CPUState *cpu,

                                        TranslationBlock **last_tb)

{

    CPUClass *cc = CPU_GET_CLASS(cpu);

    int interrupt_request = cpu->interrupt_request;

    if (unlikely(interrupt_request)) {

        if (unlikely(cpu->singlestep_enabled & SSTEP_NOIRQ)) {

            /* Mask out external interrupts for this step. */

            interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK;

        }

        if (interrupt_request & CPU_INTERRUPT_DEBUG) {

            cpu->interrupt_request &= ~CPU_INTERRUPT_DEBUG;

            cpu->exception_index = EXCP_DEBUG;

            cpu_loop_exit(cpu);

        }

        if (replay_mode == REPLAY_MODE_PLAY && !replay_has_interrupt()) {

            /* Do nothing */

        } else if (interrupt_request & CPU_INTERRUPT_HALT) {

            replay_interrupt();

            cpu->interrupt_request &= ~CPU_INTERRUPT_HALT;

            cpu->halted = 1;

            cpu->exception_index = EXCP_HLT;

            cpu_loop_exit(cpu);

        }

#if defined(TARGET_I386)

        else if (interrupt_request & CPU_INTERRUPT_INIT) {

            X86CPU *x86_cpu = X86_CPU(cpu);

            CPUArchState *env = &x86_cpu->env;

            replay_interrupt();

            cpu_svm_check_intercept_param(env, SVM_EXIT_INIT, 0);

            do_cpu_init(x86_cpu);

            cpu->exception_index = EXCP_HALTED;

            cpu_loop_exit(cpu);

        }

#else

        else if (interrupt_request & CPU_INTERRUPT_RESET) {

            replay_interrupt();

            cpu_reset(cpu);

            cpu_loop_exit(cpu);

        }

#endif

        /* The target hook has 3 exit conditions:

           False when the interrupt isn't processed,

           True when it is, and we should restart on a new TB,

           and via longjmp via cpu_loop_exit.  */

        else {

            replay_interrupt();

            if (cc->cpu_exec_interrupt(cpu, interrupt_request)) {

                *last_tb = NULL;

            }

            /* The target hook may have updated the 'cpu->interrupt_request';

             * reload the 'interrupt_request' value */

            interrupt_request = cpu->interrupt_request;

        }

        if (interrupt_request & CPU_INTERRUPT_EXITTB) {

            cpu->interrupt_request &= ~CPU_INTERRUPT_EXITTB;

            /* ensure that no TB jump will be modified as

               the program flow was changed */

            *last_tb = NULL;

        }

    }

    if (unlikely(cpu->exit_request || replay_has_interrupt())) {

        cpu->exit_request = 0;

        cpu->exception_index = EXCP_INTERRUPT;

        cpu_loop_exit(cpu);

    }

}


int qemu_get_byte(QEMUFile *f)

{

    int result;

    result = qemu_peek_byte(f, 0);

    qemu_file_skip(f, 1);

    return result;

}


bool cpu_restore_state(CPUState *cpu, uintptr_t retaddr)
{
    TranslationBlock *tb;
    bool r = false;
    tb_lock();
    tb = tb_find_pc(retaddr);
    if (tb) {
        cpu_restore_state_from_tb(cpu, tb, retaddr);
        if (tb->cflags & CF_NOCACHE) {
            /* one-shot translation, invalidate it immediately */
            tb_phys_invalidate(tb, -1);
            tb_free(tb);
        r = true;
    tb_unlock();


pflash_t *pflash_cfi01_register(target_phys_addr_t base,

                                DeviceState *qdev, const char *name,

                                target_phys_addr_t size,

                                BlockDriverState *bs, uint32_t sector_len,

                                int nb_blocs, int width,

                                uint16_t id0, uint16_t id1,

                                uint16_t id2, uint16_t id3, int be)

{

    pflash_t *pfl;

    target_phys_addr_t total_len;

    int ret;

    total_len = sector_len * nb_blocs;

    /* XXX: to be fixed */

#if 0

    if (total_len != (8 * 1024 * 1024) && total_len != (16 * 1024 * 1024) &&

        total_len != (32 * 1024 * 1024) && total_len != (64 * 1024 * 1024))

        return NULL;

#endif

    pfl = g_malloc0(sizeof(pflash_t));

    memory_region_init_rom_device(

        &pfl->mem, be ? &pflash_cfi01_ops_be : &pflash_cfi01_ops_le, pfl,

        name, size);

    vmstate_register_ram(&pfl->mem, qdev);

    pfl->storage = memory_region_get_ram_ptr(&pfl->mem);

    memory_region_add_subregion(get_system_memory(), base, &pfl->mem);

    pfl->bs = bs;

    if (pfl->bs) {

        /* read the initial flash content */

        ret = bdrv_read(pfl->bs, 0, pfl->storage, total_len >> 9);

        if (ret < 0) {

            memory_region_del_subregion(get_system_memory(), &pfl->mem);

            vmstate_unregister_ram(&pfl->mem, qdev);

            memory_region_destroy(&pfl->mem);

            g_free(pfl);

            return NULL;

        }

        bdrv_attach_dev_nofail(pfl->bs, pfl);

    }

    if (pfl->bs) {

        pfl->ro = bdrv_is_read_only(pfl->bs);

    } else {

        pfl->ro = 0;

    }

    pfl->timer = qemu_new_timer_ns(vm_clock, pflash_timer, pfl);

    pfl->base = base;

    pfl->sector_len = sector_len;

    pfl->total_len = total_len;

    pfl->width = width;

    pfl->wcycle = 0;

    pfl->cmd = 0;

    pfl->status = 0;

    pfl->ident[0] = id0;

    pfl->ident[1] = id1;

    pfl->ident[2] = id2;

    pfl->ident[3] = id3;

    /* Hardcoded CFI table */

    pfl->cfi_len = 0x52;

    /* Standard "QRY" string */

    pfl->cfi_table[0x10] = 'Q';

    pfl->cfi_table[0x11] = 'R';

    pfl->cfi_table[0x12] = 'Y';

    /* Command set (Intel) */

    pfl->cfi_table[0x13] = 0x01;

    pfl->cfi_table[0x14] = 0x00;

    /* Primary extended table address (none) */

    pfl->cfi_table[0x15] = 0x31;

    pfl->cfi_table[0x16] = 0x00;

    /* Alternate command set (none) */

    pfl->cfi_table[0x17] = 0x00;

    pfl->cfi_table[0x18] = 0x00;

    /* Alternate extended table (none) */

    pfl->cfi_table[0x19] = 0x00;

    pfl->cfi_table[0x1A] = 0x00;

    /* Vcc min */

    pfl->cfi_table[0x1B] = 0x45;

    /* Vcc max */

    pfl->cfi_table[0x1C] = 0x55;

    /* Vpp min (no Vpp pin) */

    pfl->cfi_table[0x1D] = 0x00;

    /* Vpp max (no Vpp pin) */

    pfl->cfi_table[0x1E] = 0x00;

    /* Reserved */

    pfl->cfi_table[0x1F] = 0x07;

    /* Timeout for min size buffer write */

    pfl->cfi_table[0x20] = 0x07;

    /* Typical timeout for block erase */

    pfl->cfi_table[0x21] = 0x0a;

    /* Typical timeout for full chip erase (4096 ms) */

    pfl->cfi_table[0x22] = 0x00;

    /* Reserved */

    pfl->cfi_table[0x23] = 0x04;

    /* Max timeout for buffer write */

    pfl->cfi_table[0x24] = 0x04;

    /* Max timeout for block erase */

    pfl->cfi_table[0x25] = 0x04;

    /* Max timeout for chip erase */

    pfl->cfi_table[0x26] = 0x00;

    /* Device size */

    pfl->cfi_table[0x27] = ctz32(total_len); // + 1;

    /* Flash device interface (8 & 16 bits) */

    pfl->cfi_table[0x28] = 0x02;

    pfl->cfi_table[0x29] = 0x00;

    /* Max number of bytes in multi-bytes write */

    if (width == 1) {

        pfl->cfi_table[0x2A] = 0x08;

    } else {

        pfl->cfi_table[0x2A] = 0x0B;

    }

    pfl->writeblock_size = 1 << pfl->cfi_table[0x2A];

    pfl->cfi_table[0x2B] = 0x00;

    /* Number of erase block regions (uniform) */

    pfl->cfi_table[0x2C] = 0x01;

    /* Erase block region 1 */

    pfl->cfi_table[0x2D] = nb_blocs - 1;

    pfl->cfi_table[0x2E] = (nb_blocs - 1) >> 8;

    pfl->cfi_table[0x2F] = sector_len >> 8;

    pfl->cfi_table[0x30] = sector_len >> 16;

    /* Extended */

    pfl->cfi_table[0x31] = 'P';

    pfl->cfi_table[0x32] = 'R';

    pfl->cfi_table[0x33] = 'I';

    pfl->cfi_table[0x34] = '1';

    pfl->cfi_table[0x35] = '1';

    pfl->cfi_table[0x36] = 0x00;

    pfl->cfi_table[0x37] = 0x00;

    pfl->cfi_table[0x38] = 0x00;

    pfl->cfi_table[0x39] = 0x00;

    pfl->cfi_table[0x3a] = 0x00;

    pfl->cfi_table[0x3b] = 0x00;

    pfl->cfi_table[0x3c] = 0x00;

    return pfl;

}


static int uhci_handle_td(UHCIState *s, UHCIQueue *q, uint32_t qh_addr,
                          UHCI_TD *td, uint32_t td_addr, uint32_t *int_mask)
{
    int len = 0, max_len;
    bool spd;
    bool queuing = (q != NULL);
    uint8_t pid = td->token & 0xff;
    UHCIAsync *async = uhci_async_find_td(s, td_addr);
    if (async) {
        if (uhci_queue_verify(async->queue, qh_addr, td, td_addr, queuing)) {
            assert(q == NULL || q == async->queue);
            q = async->queue;
        } else {
            uhci_queue_free(async->queue, "guest re-used pending td");
            async = NULL;
    if (q == NULL) {
        q = uhci_queue_find(s, td);
        if (q && !uhci_queue_verify(q, qh_addr, td, td_addr, queuing)) {
            uhci_queue_free(q, "guest re-used qh");
            q = NULL;
    if (q) {
        q->valid = 32;
    /* Is active ? */
    if (!(td->ctrl & TD_CTRL_ACTIVE)) {
        if (async) {
            /* Guest marked a pending td non-active, cancel the queue */
            uhci_queue_free(async->queue, "pending td non-active");
        /*
         * ehci11d spec page 22: "Even if the Active bit in the TD is already
         * cleared when the TD is fetched ... an IOC interrupt is generated"
         */
        if (td->ctrl & TD_CTRL_IOC) {
                *int_mask |= 0x01;
        return TD_RESULT_NEXT_QH;
    if (async) {
        if (queuing) {
            /* we are busy filling the queue, we are not prepared
               to consume completed packages then, just leave them
               in async state */
            return TD_RESULT_ASYNC_CONT;
        if (!async->done) {
            UHCI_TD last_td;
            UHCIAsync *last = QTAILQ_LAST(&async->queue->asyncs, asyncs_head);
            /*
             * While we are waiting for the current td to complete, the guest
             * may have added more tds to the queue. Note we re-read the td
             * rather then caching it, as we want to see guest made changes!
             */
            uhci_read_td(s, &last_td, last->td_addr);
            uhci_queue_fill(async->queue, &last_td);
            return TD_RESULT_ASYNC_CONT;
        uhci_async_unlink(async);
        goto done;
    /* Allocate new packet */
    if (q == NULL) {
        USBDevice *dev = uhci_find_device(s, (td->token >> 8) & 0x7f);
        USBEndpoint *ep = usb_ep_get(dev, pid, (td->token >> 15) & 0xf);
        q = uhci_queue_new(s, qh_addr, td, ep);
    async = uhci_async_alloc(q, td_addr);
    max_len = ((td->token >> 21) + 1) & 0x7ff;
    spd = (pid == USB_TOKEN_IN && (td->ctrl & TD_CTRL_SPD) != 0);
    usb_packet_setup(&async->packet, pid, q->ep, td_addr, spd,
                     (td->ctrl & TD_CTRL_IOC) != 0);
    qemu_sglist_add(&async->sgl, td->buffer, max_len);
    usb_packet_map(&async->packet, &async->sgl);
    switch(pid) {
    case USB_TOKEN_OUT:
    case USB_TOKEN_SETUP:
        len = usb_handle_packet(q->ep->dev, &async->packet);
        if (len >= 0)
            len = max_len;
        break;
    case USB_TOKEN_IN:
        len = usb_handle_packet(q->ep->dev, &async->packet);
        break;
    default:
        /* invalid pid : frame interrupted */
        usb_packet_unmap(&async->packet, &async->sgl);
        uhci_async_free(async);
        s->status |= UHCI_STS_HCPERR;
        uhci_update_irq(s);
        return TD_RESULT_STOP_FRAME;
    if (len == USB_RET_ASYNC) {
        uhci_async_link(async);
        if (!queuing) {
            uhci_queue_fill(q, td);
        return TD_RESULT_ASYNC_START;
    async->packet.result = len;
done:
    len = uhci_complete_td(s, td, async, int_mask);
    usb_packet_unmap(&async->packet, &async->sgl);
    uhci_async_free(async);
    return len;


static int writev_f(BlockBackend *blk, int argc, char **argv)

{

    struct timeval t1, t2;

    bool Cflag = false, qflag = false;

    int flags = 0;

    int c, cnt;

    char *buf;

    int64_t offset;

    /* Some compilers get confused and warn if this is not initialized.  */

    int total = 0;

    int nr_iov;

    int pattern = 0xcd;

    QEMUIOVector qiov;

    while ((c = getopt(argc, argv, "CqP:")) != -1) {

        switch (c) {

        case 'C':

            Cflag = true;

            break;

        case 'f':

            flags |= BDRV_REQ_FUA;

            break;

        case 'q':

            qflag = true;

            break;

        case 'P':

            pattern = parse_pattern(optarg);

            if (pattern < 0) {

                return 0;

            }

            break;

        default:

            return qemuio_command_usage(&writev_cmd);

        }

    }

    if (optind > argc - 2) {

        return qemuio_command_usage(&writev_cmd);

    }

    offset = cvtnum(argv[optind]);

    if (offset < 0) {

        print_cvtnum_err(offset, argv[optind]);

        return 0;

    }

    optind++;

    nr_iov = argc - optind;

    buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, pattern);

    if (buf == NULL) {

        return 0;

    }

    gettimeofday(&t1, NULL);

    cnt = do_aio_writev(blk, &qiov, offset, flags, &total);

    gettimeofday(&t2, NULL);

    if (cnt < 0) {

        printf("writev failed: %s\n", strerror(-cnt));

        goto out;

    }

    if (qflag) {

        goto out;

    }

    /* Finally, report back -- -C gives a parsable format */

    t2 = tsub(t2, t1);

    print_report("wrote", &t2, offset, qiov.size, total, cnt, Cflag);

out:

    qemu_iovec_destroy(&qiov);

    qemu_io_free(buf);

    return 0;

}


libAVMemInputPin_Receive(libAVMemInputPin *this, IMediaSample *sample)

{

    libAVPin *pin = (libAVPin *) ((uint8_t *) this - imemoffset);

    enum dshowDeviceType devtype = pin->filter->type;

    void *priv_data;

    uint8_t *buf;

    int buf_size;

    int index;

    int64_t curtime;

    dshowdebug("libAVMemInputPin_Receive(%p)\n", this);

    if (!sample)

        return E_POINTER;

    if (devtype == VideoDevice) {

        /* PTS from video devices is unreliable. */

        IReferenceClock *clock = pin->filter->clock;

        IReferenceClock_GetTime(clock, &curtime);

    } else {

        int64_t dummy;

        IMediaSample_GetTime(sample, &curtime, &dummy);

        curtime += pin->filter->start_time;

    }

    buf_size = IMediaSample_GetActualDataLength(sample);

    IMediaSample_GetPointer(sample, &buf);

    priv_data = pin->filter->priv_data;

    index = pin->filter->stream_index;

    pin->filter->callback(priv_data, index, buf, buf_size, curtime);

    return S_OK;

}


static int vp9_decode_frame(AVCodecContext *avctx, AVFrame *frame,

                            int *got_frame, const uint8_t *data, int size)

{

    VP9Context *s = avctx->priv_data;

    int ret, tile_row, tile_col, i, ref = -1, row, col;

    ptrdiff_t yoff = 0, uvoff = 0;

    ret = decode_frame_header(avctx, data, size, &ref);

    if (ret < 0) {

        return ret;

    } else if (!ret) {

        if (!s->refs[ref]->buf[0]) {

            av_log(avctx, AV_LOG_ERROR,

                   "Requested reference %d not available\n", ref);

            return AVERROR_INVALIDDATA;

        }

        ret = av_frame_ref(frame, s->refs[ref]);

        if (ret < 0)

            return ret;

        *got_frame = 1;

        return 0;

    }

    data += ret;

    size -= ret;

    s->cur_frame = frame;

    av_frame_unref(s->cur_frame);

    if ((ret = ff_get_buffer(avctx, s->cur_frame,

                             s->refreshrefmask ? AV_GET_BUFFER_FLAG_REF : 0)) < 0)

        return ret;

    s->cur_frame->key_frame = s->keyframe;

    s->cur_frame->pict_type = s->keyframe ? AV_PICTURE_TYPE_I

                                          : AV_PICTURE_TYPE_P;

    // main tile decode loop

    memset(s->above_partition_ctx, 0, s->cols);

    memset(s->above_skip_ctx, 0, s->cols);

    if (s->keyframe || s->intraonly)

        memset(s->above_mode_ctx, DC_PRED, s->cols * 2);

    else

        memset(s->above_mode_ctx, NEARESTMV, s->cols);

    memset(s->above_y_nnz_ctx, 0, s->sb_cols * 16);

    memset(s->above_uv_nnz_ctx[0], 0, s->sb_cols * 8);

    memset(s->above_uv_nnz_ctx[1], 0, s->sb_cols * 8);

    memset(s->above_segpred_ctx, 0, s->cols);

    for (tile_row = 0; tile_row < s->tiling.tile_rows; tile_row++) {

        set_tile_offset(&s->tiling.tile_row_start, &s->tiling.tile_row_end,

                        tile_row, s->tiling.log2_tile_rows, s->sb_rows);

        for (tile_col = 0; tile_col < s->tiling.tile_cols; tile_col++) {

            int64_t tile_size;

            if (tile_col == s->tiling.tile_cols - 1 &&

                tile_row == s->tiling.tile_rows - 1) {

                tile_size = size;

            } else {

                tile_size = AV_RB32(data);

                data     += 4;

                size     -= 4;

            }

            if (tile_size > size)

                return AVERROR_INVALIDDATA;

            ff_vp56_init_range_decoder(&s->c_b[tile_col], data, tile_size);

            if (vp56_rac_get_prob_branchy(&s->c_b[tile_col], 128)) // marker bit

                return AVERROR_INVALIDDATA;

            data += tile_size;

            size -= tile_size;

        }

        for (row = s->tiling.tile_row_start;

             row < s->tiling.tile_row_end;

             row += 8, yoff += s->cur_frame->linesize[0] * 64,

             uvoff += s->cur_frame->linesize[1] * 32) {

            VP9Filter *lflvl = s->lflvl;

            ptrdiff_t yoff2 = yoff, uvoff2 = uvoff;

            for (tile_col = 0; tile_col < s->tiling.tile_cols; tile_col++) {

                set_tile_offset(&s->tiling.tile_col_start,

                                &s->tiling.tile_col_end,

                                tile_col, s->tiling.log2_tile_cols, s->sb_cols);

                memset(s->left_partition_ctx, 0, 8);

                memset(s->left_skip_ctx, 0, 8);

                if (s->keyframe || s->intraonly)

                    memset(s->left_mode_ctx, DC_PRED, 16);

                else

                    memset(s->left_mode_ctx, NEARESTMV, 8);

                memset(s->left_y_nnz_ctx, 0, 16);

                memset(s->left_uv_nnz_ctx, 0, 16);

                memset(s->left_segpred_ctx, 0, 8);

                memcpy(&s->c, &s->c_b[tile_col], sizeof(s->c));

                for (col = s->tiling.tile_col_start;

                     col < s->tiling.tile_col_end;

                     col += 8, yoff2 += 64, uvoff2 += 32, lflvl++) {

                    // FIXME integrate with lf code (i.e. zero after each

                    // use, similar to invtxfm coefficients, or similar)

                    memset(lflvl->mask, 0, sizeof(lflvl->mask));

                    if ((ret = decode_subblock(avctx, row, col, lflvl,

                                               yoff2, uvoff2, BL_64X64)) < 0)

                        return ret;

                }

                memcpy(&s->c_b[tile_col], &s->c, sizeof(s->c));

            }

            // backup pre-loopfilter reconstruction data for intra

            // prediction of next row of sb64s

            if (row + 8 < s->rows) {

                memcpy(s->intra_pred_data[0],

                       s->cur_frame->data[0] + yoff +

                       63 * s->cur_frame->linesize[0],

                       8 * s->cols);

                memcpy(s->intra_pred_data[1],

                       s->cur_frame->data[1] + uvoff +

                       31 * s->cur_frame->linesize[1],

                       4 * s->cols);

                memcpy(s->intra_pred_data[2],

                       s->cur_frame->data[2] + uvoff +

                       31 * s->cur_frame->linesize[2],

                       4 * s->cols);

            }

            // loopfilter one row

            if (s->filter.level) {

                yoff2  = yoff;

                uvoff2 = uvoff;

                lflvl  = s->lflvl;

                for (col = 0; col < s->cols;

                     col += 8, yoff2 += 64, uvoff2 += 32, lflvl++)

                    loopfilter_subblock(avctx, lflvl, row, col, yoff2, uvoff2);

            }

        }

    }

    // bw adaptivity (or in case of parallel decoding mode, fw adaptivity

    // probability maintenance between frames)

    if (s->refreshctx) {

        if (s->parallelmode) {

            memcpy(s->prob_ctx[s->framectxid].coef, s->prob.coef,

                   sizeof(s->prob.coef));

            s->prob_ctx[s->framectxid].p = s->prob.p;

        } else {

            ff_vp9_adapt_probs(s);

        }

    }

    FFSWAP(VP9MVRefPair *, s->mv[0], s->mv[1]);

    // ref frame setup

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

        if (s->refreshrefmask & (1 << i)) {

            av_frame_unref(s->refs[i]);

            ret = av_frame_ref(s->refs[i], s->cur_frame);

            if (ret < 0)

                return ret;

        }

    if (s->invisible)

        av_frame_unref(s->cur_frame);

    else

        *got_frame = 1;

    return 0;

}


static int parallels_open(BlockDriverState *bs, int flags)

{

    BDRVParallelsState *s = bs->opaque;

    int i;

    struct parallels_header ph;

    bs->read_only = 1; // no write support yet

    if (bdrv_pread(bs->file, 0, &ph, sizeof(ph)) != sizeof(ph))

        goto fail;

    if (memcmp(ph.magic, HEADER_MAGIC, 16) ||

	(le32_to_cpu(ph.version) != HEADER_VERSION)) {

        goto fail;

    }

    bs->total_sectors = le32_to_cpu(ph.nb_sectors);

    s->tracks = le32_to_cpu(ph.tracks);

    s->catalog_size = le32_to_cpu(ph.catalog_entries);

    s->catalog_bitmap = g_malloc(s->catalog_size * 4);

    if (bdrv_pread(bs->file, 64, s->catalog_bitmap, s->catalog_size * 4) !=

	s->catalog_size * 4)

	goto fail;

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

	le32_to_cpus(&s->catalog_bitmap[i]);

    qemu_co_mutex_init(&s->lock);

    return 0;

fail:

    if (s->catalog_bitmap)

	g_free(s->catalog_bitmap);

    return -1;

}


int inet_aton (const char * str, struct in_addr * add)

{

    const char * pch = str;

    unsigned int add1 = 0, add2 = 0, add3 = 0, add4 = 0;

    add1 = atoi(pch);

    pch = strpbrk(pch,".");

    if (pch == 0 || ++pch == 0) goto done;

    add2 = atoi(pch);

    pch = strpbrk(pch,".");

    if (pch == 0 || ++pch == 0) goto done;

    add3 = atoi(pch);

    pch = strpbrk(pch,".");

    if (pch == 0 || ++pch == 0) goto done;

    add4 = atoi(pch);

done:

    add->s_addr=(add4<<24)+(add3<<16)+(add2<<8)+add1;

    return 1;

}


static void pci_indirect(void)

{

    QVirtioPCIDevice *dev;

    QPCIBus *bus;

    QVirtQueuePCI *vqpci;

    QGuestAllocator *alloc;

    QVirtioBlkReq req;

    QVRingIndirectDesc *indirect;

    void *addr;

    uint64_t req_addr;

    uint64_t capacity;

    uint32_t features;

    uint32_t free_head;

    uint8_t status;

    char *data;

    bus = test_start();

    dev = virtio_blk_init(bus);

    /* MSI-X is not enabled */

    addr = dev->addr + QVIRTIO_DEVICE_SPECIFIC_NO_MSIX;

    capacity = qvirtio_config_readq(&qvirtio_pci, &dev->vdev, addr);

    g_assert_cmpint(capacity, ==, TEST_IMAGE_SIZE / 512);

    features = qvirtio_get_features(&qvirtio_pci, &dev->vdev);

    g_assert_cmphex(features & QVIRTIO_F_RING_INDIRECT_DESC, !=, 0);

    features = features & ~(QVIRTIO_F_BAD_FEATURE | QVIRTIO_F_RING_EVENT_IDX |

                                                            QVIRTIO_BLK_F_SCSI);

    qvirtio_set_features(&qvirtio_pci, &dev->vdev, features);

    alloc = pc_alloc_init();

    vqpci = (QVirtQueuePCI *)qvirtqueue_setup(&qvirtio_pci, &dev->vdev,

                                                                    alloc, 0);

    qvirtio_set_driver_ok(&qvirtio_pci, &dev->vdev);

    /* Write request */

    req.type = QVIRTIO_BLK_T_OUT;

    req.ioprio = 1;

    req.sector = 0;

    req.data = g_malloc0(512);

    strcpy(req.data, "TEST");

    req_addr = virtio_blk_request(alloc, &req, 512);

    g_free(req.data);

    indirect = qvring_indirect_desc_setup(&dev->vdev, alloc, 2);

    qvring_indirect_desc_add(indirect, req_addr, 528, false);

    qvring_indirect_desc_add(indirect, req_addr + 528, 1, true);

    free_head = qvirtqueue_add_indirect(&vqpci->vq, indirect);

    qvirtqueue_kick(&qvirtio_pci, &dev->vdev, &vqpci->vq, free_head);

    g_assert(qvirtio_wait_queue_isr(&qvirtio_pci, &dev->vdev, &vqpci->vq,

                                                        QVIRTIO_BLK_TIMEOUT));

    status = readb(req_addr + 528);

    g_assert_cmpint(status, ==, 0);

    g_free(indirect);

    guest_free(alloc, req_addr);

    /* Read request */

    req.type = QVIRTIO_BLK_T_IN;

    req.ioprio = 1;

    req.sector = 0;

    req.data = g_malloc0(512);

    strcpy(req.data, "TEST");

    req_addr = virtio_blk_request(alloc, &req, 512);

    g_free(req.data);

    indirect = qvring_indirect_desc_setup(&dev->vdev, alloc, 2);

    qvring_indirect_desc_add(indirect, req_addr, 16, false);

    qvring_indirect_desc_add(indirect, req_addr + 16, 513, true);

    free_head = qvirtqueue_add_indirect(&vqpci->vq, indirect);

    qvirtqueue_kick(&qvirtio_pci, &dev->vdev, &vqpci->vq, free_head);

    g_assert(qvirtio_wait_queue_isr(&qvirtio_pci, &dev->vdev, &vqpci->vq,

                                                        QVIRTIO_BLK_TIMEOUT));

    status = readb(req_addr + 528);

    g_assert_cmpint(status, ==, 0);

    data = g_malloc0(512);

    memread(req_addr + 16, data, 512);

    g_assert_cmpstr(data, ==, "TEST");

    g_free(data);

    g_free(indirect);

    guest_free(alloc, req_addr);

    /* End test */

    guest_free(alloc, vqpci->vq.desc);

    qvirtio_pci_device_disable(dev);

    g_free(dev);

    test_end();

}


static void qvirtio_scsi_pci_free(QVirtIOSCSI *vs)

{

    int i;

    for (i = 0; i < vs->num_queues + 2; i++) {

        qvirtqueue_cleanup(vs->dev->bus, vs->vq[i], vs->qs->alloc);

    }

    qvirtio_pci_device_disable(container_of(vs->dev, QVirtioPCIDevice, vdev));

    g_free(vs->dev);

    qvirtio_scsi_stop(vs->qs);

    g_free(vs);

}


static void *circular_buffer_task_tx( void *_URLContext)

{

    URLContext *h = _URLContext;

    UDPContext *s = h->priv_data;

    int old_cancelstate;

    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);

    for(;;) {

        int len;

        uint8_t tmp[4];

        pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancelstate);

        av_usleep(s->packet_gap);

        pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);

        pthread_mutex_lock(&s->mutex);

        len=av_fifo_size(s->fifo);

        while (len<4) {

            if (pthread_cond_wait(&s->cond, &s->mutex) < 0) {

                goto end;

            }

            len=av_fifo_size(s->fifo);

        }

        av_fifo_generic_peek(s->fifo, tmp, 4, NULL);

        len=AV_RL32(tmp);

        if (len>0 && av_fifo_size(s->fifo)>=len+4) {

            av_fifo_drain(s->fifo, 4); /* skip packet length */

            av_fifo_generic_read(s->fifo, h, len, do_udp_write); /* use function for write from fifo buffer */

            if (s->circular_buffer_error == len) {

                /* all ok - reset error */

                s->circular_buffer_error=0;

            }

        }

        pthread_mutex_unlock(&s->mutex);

    }

end:

    pthread_mutex_unlock(&s->mutex);

    return NULL;

}


int ff_lpc_calc_coefs(LPCContext *s,

                      const int32_t *samples, int blocksize, int min_order,

                      int max_order, int precision,

                      int32_t coefs[][MAX_LPC_ORDER], int *shift,

                      enum FFLPCType lpc_type, int lpc_passes,

                      int omethod, int max_shift, int zero_shift)

{

    double autoc[MAX_LPC_ORDER+1];

    double ref[MAX_LPC_ORDER];

    double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];

    int i, j, pass = 0;

    int opt_order;

    av_assert2(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER &&

           lpc_type > FF_LPC_TYPE_FIXED);

    /* reinit LPC context if parameters have changed */

    if (blocksize != s->blocksize || max_order != s->max_order ||

        lpc_type  != s->lpc_type) {

        ff_lpc_end(s);

        ff_lpc_init(s, blocksize, max_order, lpc_type);

    }

    if(lpc_passes <= 0)

        lpc_passes = 2;

    if (lpc_type == FF_LPC_TYPE_LEVINSON || (lpc_type == FF_LPC_TYPE_CHOLESKY && lpc_passes > 1)) {

        s->lpc_apply_welch_window(samples, blocksize, s->windowed_samples);

        s->lpc_compute_autocorr(s->windowed_samples, blocksize, max_order, autoc);

        compute_lpc_coefs(autoc, max_order, &lpc[0][0], MAX_LPC_ORDER, 0, 1);

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

            ref[i] = fabs(lpc[i][i]);

        pass++;

    }

    if (lpc_type == FF_LPC_TYPE_CHOLESKY) {

        LLSModel m[2];

        LOCAL_ALIGNED(32, double, var, [FFALIGN(MAX_LPC_ORDER+1,4)]);

        double av_uninit(weight);

        memset(var, 0, FFALIGN(MAX_LPC_ORDER+1,4)*sizeof(*var));

        for(j=0; j<max_order; j++)

            m[0].coeff[max_order-1][j] = -lpc[max_order-1][j];

        for(; pass<lpc_passes; pass++){

            avpriv_init_lls(&m[pass&1], max_order);

            weight=0;

            for(i=max_order; i<blocksize; i++){

                for(j=0; j<=max_order; j++)

                    var[j]= samples[i-j];

                if(pass){

                    double eval, inv, rinv;

                    eval= m[(pass-1)&1].evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);

                    eval= (512>>pass) + fabs(eval - var[0]);

                    inv = 1/eval;

                    rinv = sqrt(inv);

                    for(j=0; j<=max_order; j++)

                        var[j] *= rinv;

                    weight += inv;

                }else

                    weight++;

                m[pass&1].update_lls(&m[pass&1], var);

            }

            avpriv_solve_lls(&m[pass&1], 0.001, 0);

        }

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

            for(j=0; j<max_order; j++)

                lpc[i][j]=-m[(pass-1)&1].coeff[i][j];

            ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;

        }

        for(i=max_order-1; i>0; i--)

            ref[i] = ref[i-1] - ref[i];

    }

    opt_order = max_order;

    if(omethod == ORDER_METHOD_EST) {

        opt_order = estimate_best_order(ref, min_order, max_order);

        i = opt_order-1;

        quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift);

    } else {

        for(i=min_order-1; i<max_order; i++) {

            quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift);

        }

    }

    return opt_order;

}


static void string_deserialize(void **native_out, void *datap,

                               VisitorFunc visit, Error **errp)

{

    StringSerializeData *d = datap;

    d->siv = string_input_visitor_new(string_output_get_string(d->sov));

    visit(string_input_get_visitor(d->siv), native_out, errp);

}


static int rtp_read_header(AVFormatContext *s)

{

    uint8_t recvbuf[RTP_MAX_PACKET_LENGTH];

    char host[500], sdp[500];

    int ret, port;

    URLContext* in = NULL;

    int payload_type;

    AVCodecContext codec = { 0 };

    struct sockaddr_storage addr;

    AVIOContext pb;

    socklen_t addrlen = sizeof(addr);

    RTSPState *rt = s->priv_data;

    if (!ff_network_init())

        return AVERROR(EIO);

    if (!rt->protocols) {

        rt->protocols = ffurl_get_protocols(NULL, NULL);

        if (!rt->protocols)

            return AVERROR(ENOMEM);

    }

    ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ,

                     &s->interrupt_callback, NULL, rt->protocols);

    if (ret)

        goto fail;

    while (1) {

        ret = ffurl_read(in, recvbuf, sizeof(recvbuf));

        if (ret == AVERROR(EAGAIN))

            continue;

        if (ret < 0)

            goto fail;

        if (ret < 12) {

            av_log(s, AV_LOG_WARNING, "Received too short packet\n");

            continue;

        }

        if ((recvbuf[0] & 0xc0) != 0x80) {

            av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "

                                      "received\n");

            continue;

        }

        if (RTP_PT_IS_RTCP(recvbuf[1]))

            continue;

        payload_type = recvbuf[1] & 0x7f;

        break;

    }

    getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);

    ffurl_close(in);

    in = NULL;

    if (ff_rtp_get_codec_info(&codec, payload_type)) {

        av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "

                                "without an SDP file describing it\n",

                                 payload_type);

        goto fail;

    }

    if (codec.codec_type != AVMEDIA_TYPE_DATA) {

        av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "

                                  "properly you need an SDP file "

                                  "describing it\n");

    }

    av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,

                 NULL, 0, s->filename);

    snprintf(sdp, sizeof(sdp),

             "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",

             addr.ss_family == AF_INET ? 4 : 6, host,

             codec.codec_type == AVMEDIA_TYPE_DATA  ? "application" :

             codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",

             port, payload_type);

    av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);

    ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);

    s->pb = &pb;

    /* sdp_read_header initializes this again */

    ff_network_close();

    rt->media_type_mask = (1 << (AVMEDIA_TYPE_DATA+1)) - 1;

    ret = sdp_read_header(s);

    s->pb = NULL;

    return ret;

fail:

    if (in)

        ffurl_close(in);

    ff_network_close();

    return ret;

}


static void qemu_aio_wait_all(void)

{

    while (aio_poll(ctx, true)) {

        /* Do nothing */

    }

}


static int send_invoke_response(URLContext *s, RTMPPacket *pkt)

{

    RTMPContext *rt = s->priv_data;

    double seqnum;

    char filename[64];

    char command[64];

    int stringlen;

    char *pchar;

    const uint8_t *p = pkt->data;

    uint8_t *pp      = NULL;

    RTMPPacket spkt  = { 0 };

    GetByteContext gbc;

    int ret;

    bytestream2_init(&gbc, p, pkt->size);

    if (ff_amf_read_string(&gbc, command, sizeof(command),

                           &stringlen)) {

        av_log(s, AV_LOG_ERROR, "Error in PT_INVOKE\n");

        return AVERROR_INVALIDDATA;

    }

    ret = ff_amf_read_number(&gbc, &seqnum);

    if (ret)

        return ret;

    ret = ff_amf_read_null(&gbc);

    if (ret)

        return ret;

    if (!strcmp(command, "FCPublish") ||

        !strcmp(command, "publish")) {

        ret = ff_amf_read_string(&gbc, filename,

                                 sizeof(filename), &stringlen);

        if (ret) {

            if (ret == AVERROR(EINVAL))

                av_log(s, AV_LOG_ERROR, "Unable to parse stream name - name too long?\n");

            else

                av_log(s, AV_LOG_ERROR, "Unable to parse stream name\n");

            return ret;

        }

        // check with url

        if (s->filename) {

            pchar = strrchr(s->filename, '/');

            if (!pchar) {

                av_log(s, AV_LOG_WARNING,

                       "Unable to find / in url %s, bad format\n",

                       s->filename);

                pchar = s->filename;

            }

            pchar++;

            if (strcmp(pchar, filename))

                av_log(s, AV_LOG_WARNING, "Unexpected stream %s, expecting"

                       " %s\n", filename, pchar);

        }

        rt->state = STATE_RECEIVING;

    }

    if (!strcmp(command, "FCPublish")) {

        if ((ret = ff_rtmp_packet_create(&spkt, RTMP_SYSTEM_CHANNEL,

                                         RTMP_PT_INVOKE, 0,

                                         RTMP_PKTDATA_DEFAULT_SIZE)) < 0) {

            av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");

            return ret;

        }

        pp = spkt.data;

        ff_amf_write_string(&pp, "onFCPublish");

    } else if (!strcmp(command, "publish")) {

        ret = write_begin(s);

        if (ret < 0)

            return ret;

        // Send onStatus(NetStream.Publish.Start)

        return write_status(s, pkt, "NetStream.Publish.Start",

                           filename);

    } else if (!strcmp(command, "play")) {

        ret = write_begin(s);

        if (ret < 0)

            return ret;

        rt->state = STATE_SENDING;

        return write_status(s, pkt, "NetStream.Play.Start",

                            filename);

    } else {

        if ((ret = ff_rtmp_packet_create(&spkt, RTMP_SYSTEM_CHANNEL,

                                         RTMP_PT_INVOKE, 0,

                                         RTMP_PKTDATA_DEFAULT_SIZE)) < 0) {

            av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");

            return ret;

        }

        pp = spkt.data;

        ff_amf_write_string(&pp, "_result");

        ff_amf_write_number(&pp, seqnum);

        ff_amf_write_null(&pp);

        if (!strcmp(command, "createStream")) {

            rt->nb_streamid++;

            if (rt->nb_streamid == 0 || rt->nb_streamid == 2)

                rt->nb_streamid++; /* Values 0 and 2 are reserved */

            ff_amf_write_number(&pp, rt->nb_streamid);

            /* By now we don't control which streams are removed in

             * deleteStream. There is no stream creation control

             * if a client creates more than 2^32 - 2 streams. */

        }

    }

    spkt.size = pp - spkt.data;

    ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,

                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);

    ff_rtmp_packet_destroy(&spkt);

    return ret;

}


static void coroutine_fn v9fs_open(void *opaque)

{

    int flags;

    int32_t fid;

    int32_t mode;

    V9fsQID qid;

    int iounit = 0;

    ssize_t err = 0;

    size_t offset = 7;

    struct stat stbuf;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    if (s->proto_version == V9FS_PROTO_2000L) {

        err = pdu_unmarshal(pdu, offset, "dd", &fid, &mode);

    } else {

        uint8_t modebyte;

        err = pdu_unmarshal(pdu, offset, "db", &fid, &modebyte);

        mode = modebyte;

    }

    if (err < 0) {

        goto out_nofid;

    }

    trace_v9fs_open(pdu->tag, pdu->id, fid, mode);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    BUG_ON(fidp->fid_type != P9_FID_NONE);

    err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);

    if (err < 0) {

        goto out;

    }

    stat_to_qid(&stbuf, &qid);

    if (S_ISDIR(stbuf.st_mode)) {

        err = v9fs_co_opendir(pdu, fidp);

        if (err < 0) {

            goto out;

        }

        fidp->fid_type = P9_FID_DIR;

        err = pdu_marshal(pdu, offset, "Qd", &qid, 0);

        if (err < 0) {

            goto out;

        }

        err += offset;

    } else {

        if (s->proto_version == V9FS_PROTO_2000L) {

            flags = get_dotl_openflags(s, mode);

        } else {

            flags = omode_to_uflags(mode);

        }

        if (is_ro_export(&s->ctx)) {

            if (mode & O_WRONLY || mode & O_RDWR ||

                mode & O_APPEND || mode & O_TRUNC) {

                err = -EROFS;

                goto out;

            }

        }

        err = v9fs_co_open(pdu, fidp, flags);

        if (err < 0) {

            goto out;

        }

        fidp->fid_type = P9_FID_FILE;

        fidp->open_flags = flags;

        if (flags & O_EXCL) {

            /*

             * We let the host file system do O_EXCL check

             * We should not reclaim such fd

             */

            fidp->flags |= FID_NON_RECLAIMABLE;

        }

        iounit = get_iounit(pdu, &fidp->path);

        err = pdu_marshal(pdu, offset, "Qd", &qid, iounit);

        if (err < 0) {

            goto out;

        }

        err += offset;

    }

    trace_v9fs_open_return(pdu->tag, pdu->id,

                           qid.type, qid.version, qid.path, iounit);

out:

    put_fid(pdu, fidp);

out_nofid:

    pdu_complete(pdu, err);

}


static void init_blk_migration_it(void *opaque, BlockDriverState *bs)

{

    BlkMigDevState *bmds;

    int64_t sectors;

    if (!bdrv_is_read_only(bs)) {

        sectors = bdrv_nb_sectors(bs);

        if (sectors <= 0) {

            return;

        }

        bmds = g_malloc0(sizeof(BlkMigDevState));

        bmds->bs = bs;

        bmds->bulk_completed = 0;

        bmds->total_sectors = sectors;

        bmds->completed_sectors = 0;

        bmds->shared_base = block_mig_state.shared_base;

        alloc_aio_bitmap(bmds);

        error_setg(&bmds->blocker, "block device is in use by migration");

        bdrv_op_block_all(bs, bmds->blocker);

        bdrv_ref(bs);

        block_mig_state.total_sector_sum += sectors;

        if (bmds->shared_base) {

            DPRINTF("Start migration for %s with shared base image\n",

                    bs->device_name);

        } else {

            DPRINTF("Start full migration for %s\n", bs->device_name);

        }

        QSIMPLEQ_INSERT_TAIL(&block_mig_state.bmds_list, bmds, entry);

    }

}


static void megasas_command_complete(SCSIRequest *req, uint32_t status,

                                     size_t resid)

{

    MegasasCmd *cmd = req->hba_private;

    uint8_t cmd_status = MFI_STAT_OK;

    trace_megasas_command_complete(cmd->index, status, resid);

    if (req->io_canceled) {

        return;

    }

    if (cmd->req == NULL) {

        /*

         * Internal command complete

         */

        cmd_status = megasas_finish_internal_dcmd(cmd, req, resid);

        if (cmd_status == MFI_STAT_INVALID_STATUS) {

            return;

        }

    } else {

        req->status = status;

        trace_megasas_scsi_complete(cmd->index, req->status,

                                    cmd->iov_size, req->cmd.xfer);

        if (req->status != GOOD) {

            cmd_status = MFI_STAT_SCSI_DONE_WITH_ERROR;

        }

        if (req->status == CHECK_CONDITION) {

            megasas_copy_sense(cmd);

        }

        cmd->frame->header.scsi_status = req->status;

    }

    cmd->frame->header.cmd_status = cmd_status;

    megasas_complete_command(cmd);

}


static void GLZWDecodeInit(GifState * s, int csize)

{

    /* read buffer */

    s->eob_reached = 0;

    s->pbuf = s->buf;

    s->ebuf = s->buf;

    s->bbuf = 0;

    s->bbits = 0;

    /* decoder */

    s->codesize = csize;

    s->cursize = s->codesize + 1;

    s->curmask = mask[s->cursize];

    s->top_slot = 1 << s->cursize;

    s->clear_code = 1 << s->codesize;

    s->end_code = s->clear_code + 1;

    s->slot = s->newcodes = s->clear_code + 2;

    s->oc = s->fc = 0;

    s->sp = s->stack;

}


SchroFrame *ff_create_schro_frame(AVCodecContext *avctx,

                                  SchroFrameFormat schro_frame_fmt)

{

    AVFrame *p_pic;

    SchroFrame *p_frame;

    int y_width, uv_width;

    int y_height, uv_height;

    int i;

    y_width   = avctx->width;

    y_height  = avctx->height;

    uv_width  = y_width  >> (SCHRO_FRAME_FORMAT_H_SHIFT(schro_frame_fmt));

    uv_height = y_height >> (SCHRO_FRAME_FORMAT_V_SHIFT(schro_frame_fmt));

    p_pic = av_frame_alloc();

    if (!p_pic)

        return NULL;

    if (ff_get_buffer(avctx, p_pic, AV_GET_BUFFER_FLAG_REF) < 0) {

        av_frame_free(&p_pic);

        return NULL;

    }

    p_frame         = schro_frame_new();

    p_frame->format = schro_frame_fmt;

    p_frame->width  = y_width;

    p_frame->height = y_height;

    schro_frame_set_free_callback(p_frame, free_schro_frame, p_pic);

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

        p_frame->components[i].width  = i ? uv_width : y_width;

        p_frame->components[i].stride = p_pic->linesize[i];

        p_frame->components[i].height = i ? uv_height : y_height;

        p_frame->components[i].length =

                 p_frame->components[i].stride * p_frame->components[i].height;

        p_frame->components[i].data   = p_pic->data[i];

        if (i) {

            p_frame->components[i].v_shift =

                SCHRO_FRAME_FORMAT_V_SHIFT(p_frame->format);

            p_frame->components[i].h_shift =

                SCHRO_FRAME_FORMAT_H_SHIFT(p_frame->format);

        }

    }

    return p_frame;

}