static int mjpeg_decode_init(AVCodecContext *avctx)

{

    MJpegDecodeContext *s = avctx->priv_data;

    MpegEncContext s2;

    s->avctx = avctx;

    /* ugly way to get the idct & scantable FIXME */

    memset(&s2, 0, sizeof(MpegEncContext));

    s2.avctx= avctx;

//    s2->out_format = FMT_MJPEG;

    dsputil_init(&s2.dsp, avctx);

    DCT_common_init(&s2);

    s->scantable= s2.intra_scantable;

    s->idct_put= s2.dsp.idct_put;

    s->mpeg_enc_ctx_allocated = 0;

    s->buffer_size = 102400; /* smaller buffer should be enough,

				but photojpg files could ahive bigger sizes */

    s->buffer = av_malloc(s->buffer_size);

    if (!s->buffer)

	return -1;

    s->start_code = -1;

    s->first_picture = 1;

    s->org_height = avctx->coded_height;

    build_vlc(&s->vlcs[0][0], bits_dc_luminance, val_dc_luminance, 12);

    build_vlc(&s->vlcs[0][1], bits_dc_chrominance, val_dc_chrominance, 12);

    build_vlc(&s->vlcs[1][0], bits_ac_luminance, val_ac_luminance, 251);

    build_vlc(&s->vlcs[1][1], bits_ac_chrominance, val_ac_chrominance, 251);

    if (avctx->flags & CODEC_FLAG_EXTERN_HUFF)

    {

	av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");

	init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size*8);

	mjpeg_decode_dht(s);

	/* should check for error - but dunno */

    }

    return 0;

}


int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)

{

    int ret;

    dst->owner = src->owner;

    ret = av_frame_ref(dst->f, src->f);

    if (ret < 0)

        return ret;

    av_assert0(!dst->progress);

    if (src->progress &&

        !(dst->progress = av_buffer_ref(src->progress))) {

        ff_thread_release_buffer(dst->owner, dst);

        return AVERROR(ENOMEM);

    }

    return 0;

}


void zipl_load(void)

{

    ScsiMbr *mbr = (void *)sec;

    LDL_VTOC *vlbl = (void *)sec;

    /* Grab the MBR */

    memset(sec, FREE_SPACE_FILLER, sizeof(sec));

    read_block(0, mbr, "Cannot read block 0");

    dputs("checking magic\n");

    if (magic_match(mbr->magic, ZIPL_MAGIC)) {

        ipl_scsi(); /* no return */

    }

    /* Check if we can boot as ISO media */

    if (virtio_guessed_disk_nature()) {

        virtio_assume_iso9660();

    }

    ipl_iso_el_torito();

    /* We have failed to follow the SCSI scheme, so */

    if (virtio_guessed_disk_nature()) {

        sclp_print("Using guessed DASD geometry.\n");

        virtio_assume_eckd();

    }

    print_eckd_msg();

    if (magic_match(mbr->magic, IPL1_MAGIC)) {

        ipl_eckd_cdl(); /* no return */

    }

    /* LDL/CMS? */

    memset(sec, FREE_SPACE_FILLER, sizeof(sec));

    read_block(2, vlbl, "Cannot read block 2");

    if (magic_match(vlbl->magic, CMS1_MAGIC)) {

        ipl_eckd_ldl(ECKD_CMS); /* no return */

    }

    if (magic_match(vlbl->magic, LNX1_MAGIC)) {

        ipl_eckd_ldl(ECKD_LDL); /* no return */

    }

    ipl_eckd_ldl(ECKD_LDL_UNLABELED); /* it still may return */

    /*

     * Ok, it is not a LDL by any means.

     * It still might be a CDL with zero record keys for IPL1 and IPL2

     */

    ipl_eckd_cdl();

    virtio_panic("\n* this can never happen *\n");

}


void ppc_set_irq(PowerPCCPU *cpu, int n_IRQ, int level)

{

    CPUState *cs = CPU(cpu);

    CPUPPCState *env = &cpu->env;

    unsigned int old_pending = env->pending_interrupts;

    if (level) {

        env->pending_interrupts |= 1 << n_IRQ;

        cpu_interrupt(cs, CPU_INTERRUPT_HARD);

    } else {

        env->pending_interrupts &= ~(1 << n_IRQ);

        if (env->pending_interrupts == 0) {

            cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);

        }

    }

    if (old_pending != env->pending_interrupts) {

#ifdef CONFIG_KVM

        kvmppc_set_interrupt(cpu, n_IRQ, level);

#endif

    }

    LOG_IRQ("%s: %p n_IRQ %d level %d => pending %08" PRIx32

                "req %08x\n", __func__, env, n_IRQ, level,

                env->pending_interrupts, CPU(cpu)->interrupt_request);

}


static void vfio_vga_probe_ati_3c3_quirk(VFIOPCIDevice *vdev)

{

    VFIOQuirk *quirk;

    /*

     * As long as the BAR is >= 256 bytes it will be aligned such that the

     * lower byte is always zero.  Filter out anything else, if it exists.

     */

    if (!vfio_pci_is(vdev, PCI_VENDOR_ID_ATI, PCI_ANY_ID) ||

        !vdev->bars[4].ioport || vdev->bars[4].region.size < 256) {

        return;

    }

    quirk = g_malloc0(sizeof(*quirk));

    quirk->mem = g_malloc0(sizeof(MemoryRegion));

    quirk->nr_mem = 1;

    memory_region_init_io(quirk->mem, OBJECT(vdev), &vfio_ati_3c3_quirk, vdev,

                          "vfio-ati-3c3-quirk", 1);

    memory_region_add_subregion(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem,

                                3 /* offset 3 bytes from 0x3c0 */, quirk->mem);

    QLIST_INSERT_HEAD(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].quirks,

                      quirk, next);

    trace_vfio_quirk_ati_3c3_probe(vdev->vbasedev.name);

}


static void mem_info(Monitor *mon)

{

    CPUState *env;

    int l1, l2, prot, last_prot;

    uint32_t pgd, pde, pte, start, end;

    env = mon_get_cpu();

    if (!env)

        return;

    if (!(env->cr[0] & CR0_PG_MASK)) {

        monitor_printf(mon, "PG disabled\n");

        return;

    }

    pgd = env->cr[3] & ~0xfff;

    last_prot = 0;

    start = -1;

    for(l1 = 0; l1 < 1024; l1++) {

        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);

        pde = le32_to_cpu(pde);

        end = l1 << 22;

        if (pde & PG_PRESENT_MASK) {

            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {

                prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);

                mem_print(mon, &start, &last_prot, end, prot);

            } else {

                for(l2 = 0; l2 < 1024; l2++) {

                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,

                                             (uint8_t *)&pte, 4);

                    pte = le32_to_cpu(pte);

                    end = (l1 << 22) + (l2 << 12);

                    if (pte & PG_PRESENT_MASK) {

                        prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);

                    } else {

                        prot = 0;

                    }

                    mem_print(mon, &start, &last_prot, end, prot);

                }

            }

        } else {

            prot = 0;

            mem_print(mon, &start, &last_prot, end, prot);

        }

    }

}


CharDriverState *chr_testdev_init(void)

{

    TestdevCharState *testdev;

    CharDriverState *chr;

    testdev = g_malloc0(sizeof(TestdevCharState));

    testdev->chr = chr = g_malloc0(sizeof(CharDriverState));

    chr->opaque = testdev;

    chr->chr_write = testdev_write;

    chr->chr_close = testdev_close;

    return chr;

}


static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
    int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
{
    BlockDriver *drv = bs->drv;
    BdrvTrackedRequest req;
    int ret;
    if (!bs->drv) {
        return -ENOMEDIUM;
    if (bs->read_only) {
        return -EACCES;
    if (bdrv_check_request(bs, sector_num, nb_sectors)) {
        return -EIO;
    /* throttling disk write I/O */
    if (bs->io_limits_enabled) {
        bdrv_io_limits_intercept(bs, true, nb_sectors);
    tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
    ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
    if (bs->dirty_bitmap) {
        set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
    if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
        bs->wr_highest_sector = sector_num + nb_sectors - 1;
    tracked_request_end(&req);
    return ret;


void *etraxfs_eth_init(NICInfo *nd, target_phys_addr_t base, int phyaddr)

{

	struct etraxfs_dma_client *dma = NULL;

	struct fs_eth *eth = NULL;

	qemu_check_nic_model(nd, "fseth");

	dma = qemu_mallocz(sizeof *dma * 2);

	eth = qemu_mallocz(sizeof *eth);

	dma[0].client.push = eth_tx_push;

	dma[0].client.opaque = eth;

	dma[1].client.opaque = eth;

	dma[1].client.pull = NULL;

	eth->dma_out = dma;

	eth->dma_in = dma + 1;

	/* Connect the phy.  */

	eth->phyaddr = phyaddr & 0x1f;

	tdk_init(&eth->phy);

	mdio_attach(&eth->mdio_bus, &eth->phy, eth->phyaddr);

	eth->ethregs = cpu_register_io_memory(eth_read, eth_write, eth);

	cpu_register_physical_memory (base, 0x5c, eth->ethregs);

	eth->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name,

				       eth_can_receive, eth_receive, NULL,

				       eth_cleanup, eth);

	eth->vc->opaque = eth;

	eth->vc->link_status_changed = eth_set_link;

	return dma;

}


static void do_udp_write(void *arg, void *buf, int size) {

    URLContext *h = arg;

    UDPContext *s = h->priv_data;

    int ret;

    if (!(h->flags & AVIO_FLAG_NONBLOCK)) {

        ret = ff_network_wait_fd(s->udp_fd, 1);

        if (ret < 0) {

            s->circular_buffer_error = ret;

            return;

        }

    }

    if (!s->is_connected) {

        ret = sendto (s->udp_fd, buf, size, 0,

                      (struct sockaddr *) &s->dest_addr,

                      s->dest_addr_len);

    } else

        ret = send(s->udp_fd, buf, size, 0);

    s->circular_buffer_error=ret;

}


av_cold struct FFPsyPreprocessContext* ff_psy_preprocess_init(AVCodecContext *avctx)

{

    FFPsyPreprocessContext *ctx;

    int i;

    float cutoff_coeff = 0;

    ctx        = av_mallocz(sizeof(FFPsyPreprocessContext));

    ctx->avctx = avctx;

    if (avctx->cutoff > 0)

        cutoff_coeff = 2.0 * avctx->cutoff / avctx->sample_rate;

    if (cutoff_coeff)

    ctx->fcoeffs = ff_iir_filter_init_coeffs(FF_FILTER_TYPE_BUTTERWORTH, FF_FILTER_MODE_LOWPASS,

                                             FILT_ORDER, cutoff_coeff, 0.0, 0.0);

    if (ctx->fcoeffs) {

        ctx->fstate = av_mallocz(sizeof(ctx->fstate[0]) * avctx->channels);

        for (i = 0; i < avctx->channels; i++)

            ctx->fstate[i] = ff_iir_filter_init_state(FILT_ORDER);

    }

    return ctx;

}


static QVirtioPCIDevice *virtio_blk_pci_init(QPCIBus *bus, int slot)

{

    QVirtioPCIDevice *dev;

    dev = qvirtio_pci_device_find(bus, VIRTIO_ID_BLOCK);

    g_assert(dev != NULL);

    g_assert_cmphex(dev->vdev.device_type, ==, VIRTIO_ID_BLOCK);

    g_assert_cmphex(dev->pdev->devfn, ==, ((slot << 3) | PCI_FN));

    qvirtio_pci_device_enable(dev);

    qvirtio_reset(&dev->vdev);

    qvirtio_set_acknowledge(&dev->vdev);

    qvirtio_set_driver(&dev->vdev);

    return dev;

}


static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,

                                                     int64_t sector_num,

                                                     int nb_sectors, int *pnum,

                                                     BlockDriverState **file)

{

    int64_t total_sectors;

    int64_t n;

    int64_t ret, ret2;

    total_sectors = bdrv_nb_sectors(bs);

    if (total_sectors < 0) {

        return total_sectors;

    }

    if (sector_num >= total_sectors) {

        *pnum = 0;

        return BDRV_BLOCK_EOF;

    }

    n = total_sectors - sector_num;

    if (n < nb_sectors) {

        nb_sectors = n;

    }

    if (!bs->drv->bdrv_co_get_block_status) {

        *pnum = nb_sectors;

        ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;

        if (sector_num + nb_sectors == total_sectors) {

            ret |= BDRV_BLOCK_EOF;

        }

        if (bs->drv->protocol_name) {

            ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);

        }

        return ret;

    }

    *file = NULL;

    bdrv_inc_in_flight(bs);

    ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum,

                                            file);

    if (ret < 0) {

        *pnum = 0;

        goto out;

    }

    if (ret & BDRV_BLOCK_RAW) {

        assert(ret & BDRV_BLOCK_OFFSET_VALID);

        ret = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS,

                                       *pnum, pnum, file);

        goto out;

    }

    if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {

        ret |= BDRV_BLOCK_ALLOCATED;

    } else {

        if (bdrv_unallocated_blocks_are_zero(bs)) {

            ret |= BDRV_BLOCK_ZERO;

        } else if (bs->backing) {

            BlockDriverState *bs2 = bs->backing->bs;

            int64_t nb_sectors2 = bdrv_nb_sectors(bs2);

            if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {

                ret |= BDRV_BLOCK_ZERO;

            }

        }

    }

    if (*file && *file != bs &&

        (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&

        (ret & BDRV_BLOCK_OFFSET_VALID)) {

        BlockDriverState *file2;

        int file_pnum;

        ret2 = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS,

                                        *pnum, &file_pnum, &file2);

        if (ret2 >= 0) {

            /* Ignore errors.  This is just providing extra information, it

             * is useful but not necessary.

             */

            if (ret2 & BDRV_BLOCK_EOF &&

                (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {

                /*

                 * It is valid for the format block driver to read

                 * beyond the end of the underlying file's current

                 * size; such areas read as zero.

                 */

                ret |= BDRV_BLOCK_ZERO;

            } else {

                /* Limit request to the range reported by the protocol driver */

                *pnum = file_pnum;

                ret |= (ret2 & BDRV_BLOCK_ZERO);

            }

        }

    }

out:

    bdrv_dec_in_flight(bs);

    if (ret >= 0 && sector_num + *pnum == total_sectors) {

        ret |= BDRV_BLOCK_EOF;

    }

    return ret;

}


static int qcow2_do_open(BlockDriverState *bs, QDict *options, int flags,

                         Error **errp)

{

    BDRVQcow2State *s = bs->opaque;

    unsigned int len, i;

    int ret = 0;

    QCowHeader header;

    Error *local_err = NULL;

    uint64_t ext_end;

    uint64_t l1_vm_state_index;

    ret = bdrv_pread(bs->file, 0, &header, sizeof(header));

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not read qcow2 header");

        goto fail;

    }

    be32_to_cpus(&header.magic);

    be32_to_cpus(&header.version);

    be64_to_cpus(&header.backing_file_offset);

    be32_to_cpus(&header.backing_file_size);

    be64_to_cpus(&header.size);

    be32_to_cpus(&header.cluster_bits);

    be32_to_cpus(&header.crypt_method);

    be64_to_cpus(&header.l1_table_offset);

    be32_to_cpus(&header.l1_size);

    be64_to_cpus(&header.refcount_table_offset);

    be32_to_cpus(&header.refcount_table_clusters);

    be64_to_cpus(&header.snapshots_offset);

    be32_to_cpus(&header.nb_snapshots);

    if (header.magic != QCOW_MAGIC) {

        error_setg(errp, "Image is not in qcow2 format");

        ret = -EINVAL;

        goto fail;

    }

    if (header.version < 2 || header.version > 3) {

        error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);

        ret = -ENOTSUP;

        goto fail;

    }

    s->qcow_version = header.version;

    /* Initialise cluster size */

    if (header.cluster_bits < MIN_CLUSTER_BITS ||

        header.cluster_bits > MAX_CLUSTER_BITS) {

        error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,

                   header.cluster_bits);

        ret = -EINVAL;

        goto fail;

    }

    s->cluster_bits = header.cluster_bits;

    s->cluster_size = 1 << s->cluster_bits;

    s->cluster_sectors = 1 << (s->cluster_bits - 9);

    /* Initialise version 3 header fields */

    if (header.version == 2) {

        header.incompatible_features    = 0;

        header.compatible_features      = 0;

        header.autoclear_features       = 0;

        header.refcount_order           = 4;

        header.header_length            = 72;

    } else {

        be64_to_cpus(&header.incompatible_features);

        be64_to_cpus(&header.compatible_features);

        be64_to_cpus(&header.autoclear_features);

        be32_to_cpus(&header.refcount_order);

        be32_to_cpus(&header.header_length);

        if (header.header_length < 104) {

            error_setg(errp, "qcow2 header too short");

            ret = -EINVAL;

            goto fail;

        }

    }

    if (header.header_length > s->cluster_size) {

        error_setg(errp, "qcow2 header exceeds cluster size");

        ret = -EINVAL;

        goto fail;

    }

    if (header.header_length > sizeof(header)) {

        s->unknown_header_fields_size = header.header_length - sizeof(header);

        s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);

        ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,

                         s->unknown_header_fields_size);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "

                             "fields");

            goto fail;

        }

    }

    if (header.backing_file_offset > s->cluster_size) {

        error_setg(errp, "Invalid backing file offset");

        ret = -EINVAL;

        goto fail;

    }

    if (header.backing_file_offset) {

        ext_end = header.backing_file_offset;

    } else {

        ext_end = 1 << header.cluster_bits;

    }

    /* Handle feature bits */

    s->incompatible_features    = header.incompatible_features;

    s->compatible_features      = header.compatible_features;

    s->autoclear_features       = header.autoclear_features;

    if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {

        void *feature_table = NULL;

        qcow2_read_extensions(bs, header.header_length, ext_end,

                              &feature_table, NULL);

        report_unsupported_feature(errp, feature_table,

                                   s->incompatible_features &

                                   ~QCOW2_INCOMPAT_MASK);

        ret = -ENOTSUP;

        g_free(feature_table);

        goto fail;

    }

    if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {

        /* Corrupt images may not be written to unless they are being repaired

         */

        if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {

            error_setg(errp, "qcow2: Image is corrupt; cannot be opened "

                       "read/write");

            ret = -EACCES;

            goto fail;

        }

    }

    /* Check support for various header values */

    if (header.refcount_order > 6) {

        error_setg(errp, "Reference count entry width too large; may not "

                   "exceed 64 bits");

        ret = -EINVAL;

        goto fail;

    }

    s->refcount_order = header.refcount_order;

    s->refcount_bits = 1 << s->refcount_order;

    s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);

    s->refcount_max += s->refcount_max - 1;

    if (header.crypt_method > QCOW_CRYPT_AES) {

        error_setg(errp, "Unsupported encryption method: %" PRIu32,

                   header.crypt_method);

        ret = -EINVAL;

        goto fail;

    }

    s->crypt_method_header = header.crypt_method;

    if (s->crypt_method_header) {

        if (bdrv_uses_whitelist() &&

            s->crypt_method_header == QCOW_CRYPT_AES) {

            error_setg(errp,

                       "Use of AES-CBC encrypted qcow2 images is no longer "

                       "supported in system emulators");

            error_append_hint(errp,

                              "You can use 'qemu-img convert' to convert your "

                              "image to an alternative supported format, such "

                              "as unencrypted qcow2, or raw with the LUKS "

                              "format instead.\n");

            ret = -ENOSYS;

            goto fail;

        }

        bs->encrypted = true;

        bs->valid_key = true;

    }

    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */

    s->l2_size = 1 << s->l2_bits;

    /* 2^(s->refcount_order - 3) is the refcount width in bytes */

    s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);

    s->refcount_block_size = 1 << s->refcount_block_bits;

    bs->total_sectors = header.size / 512;

    s->csize_shift = (62 - (s->cluster_bits - 8));

    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;

    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;

    s->refcount_table_offset = header.refcount_table_offset;

    s->refcount_table_size =

        header.refcount_table_clusters << (s->cluster_bits - 3);

    if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {

        error_setg(errp, "Reference count table too large");

        ret = -EINVAL;

        goto fail;

    }

    ret = validate_table_offset(bs, s->refcount_table_offset,

                                s->refcount_table_size, sizeof(uint64_t));

    if (ret < 0) {

        error_setg(errp, "Invalid reference count table offset");

        goto fail;

    }

    /* Snapshot table offset/length */

    if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {

        error_setg(errp, "Too many snapshots");

        ret = -EINVAL;

        goto fail;

    }

    ret = validate_table_offset(bs, header.snapshots_offset,

                                header.nb_snapshots,

                                sizeof(QCowSnapshotHeader));

    if (ret < 0) {

        error_setg(errp, "Invalid snapshot table offset");

        goto fail;

    }

    /* read the level 1 table */

    if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {

        error_setg(errp, "Active L1 table too large");

        ret = -EFBIG;

        goto fail;

    }

    s->l1_size = header.l1_size;

    l1_vm_state_index = size_to_l1(s, header.size);

    if (l1_vm_state_index > INT_MAX) {

        error_setg(errp, "Image is too big");

        ret = -EFBIG;

        goto fail;

    }

    s->l1_vm_state_index = l1_vm_state_index;

    /* the L1 table must contain at least enough entries to put

       header.size bytes */

    if (s->l1_size < s->l1_vm_state_index) {

        error_setg(errp, "L1 table is too small");

        ret = -EINVAL;

        goto fail;

    }

    ret = validate_table_offset(bs, header.l1_table_offset,

                                header.l1_size, sizeof(uint64_t));

    if (ret < 0) {

        error_setg(errp, "Invalid L1 table offset");

        goto fail;

    }

    s->l1_table_offset = header.l1_table_offset;

    if (s->l1_size > 0) {

        s->l1_table = qemu_try_blockalign(bs->file->bs,

            align_offset(s->l1_size * sizeof(uint64_t), 512));

        if (s->l1_table == NULL) {

            error_setg(errp, "Could not allocate L1 table");

            ret = -ENOMEM;

            goto fail;

        }

        ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,

                         s->l1_size * sizeof(uint64_t));

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not read L1 table");

            goto fail;

        }

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

            be64_to_cpus(&s->l1_table[i]);

        }

    }

    /* Parse driver-specific options */

    ret = qcow2_update_options(bs, options, flags, errp);

    if (ret < 0) {

        goto fail;

    }

    s->cluster_cache = g_malloc(s->cluster_size);

    /* one more sector for decompressed data alignment */

    s->cluster_data = qemu_try_blockalign(bs->file->bs, QCOW_MAX_CRYPT_CLUSTERS

                                                    * s->cluster_size + 512);

    if (s->cluster_data == NULL) {

        error_setg(errp, "Could not allocate temporary cluster buffer");

        ret = -ENOMEM;

        goto fail;

    }

    s->cluster_cache_offset = -1;

    s->flags = flags;

    ret = qcow2_refcount_init(bs);

    if (ret != 0) {

        error_setg_errno(errp, -ret, "Could not initialize refcount handling");

        goto fail;

    }

    QLIST_INIT(&s->cluster_allocs);

    QTAILQ_INIT(&s->discards);

    /* read qcow2 extensions */

    if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,

        &local_err)) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    if (s->crypt_method_header == QCOW_CRYPT_AES) {

        unsigned int cflags = 0;

        if (flags & BDRV_O_NO_IO) {

            cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;

        }

        s->crypto = qcrypto_block_open(s->crypto_opts, NULL, NULL,

                                       cflags, errp);

        if (!s->crypto) {

            ret = -EINVAL;

            goto fail;

        }

    }

    /* read the backing file name */

    if (header.backing_file_offset != 0) {

        len = header.backing_file_size;

        if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||

            len >= sizeof(bs->backing_file)) {

            error_setg(errp, "Backing file name too long");

            ret = -EINVAL;

            goto fail;

        }

        ret = bdrv_pread(bs->file, header.backing_file_offset,

                         bs->backing_file, len);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not read backing file name");

            goto fail;

        }

        bs->backing_file[len] = '\0';

        s->image_backing_file = g_strdup(bs->backing_file);

    }

    /* Internal snapshots */

    s->snapshots_offset = header.snapshots_offset;

    s->nb_snapshots = header.nb_snapshots;

    ret = qcow2_read_snapshots(bs);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not read snapshots");

        goto fail;

    }

    /* Clear unknown autoclear feature bits */

    if (!bs->read_only && !(flags & BDRV_O_INACTIVE) && s->autoclear_features) {

        s->autoclear_features = 0;

        ret = qcow2_update_header(bs);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not update qcow2 header");

            goto fail;

        }

    }

    /* Initialise locks */

    qemu_co_mutex_init(&s->lock);

    bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;

    /* Repair image if dirty */

    if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&

        (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {

        BdrvCheckResult result = {0};

        ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not repair dirty image");

            goto fail;

        }

    }

#ifdef DEBUG_ALLOC

    {

        BdrvCheckResult result = {0};

        qcow2_check_refcounts(bs, &result, 0);

    }

#endif

    return ret;

 fail:

    g_free(s->unknown_header_fields);

    cleanup_unknown_header_ext(bs);

    qcow2_free_snapshots(bs);

    qcow2_refcount_close(bs);

    qemu_vfree(s->l1_table);

    /* else pre-write overlap checks in cache_destroy may crash */

    s->l1_table = NULL;

    cache_clean_timer_del(bs);

    if (s->l2_table_cache) {

        qcow2_cache_destroy(bs, s->l2_table_cache);

    }

    if (s->refcount_block_cache) {

        qcow2_cache_destroy(bs, s->refcount_block_cache);

    }

    g_free(s->cluster_cache);

    qemu_vfree(s->cluster_data);

    qcrypto_block_free(s->crypto);

    qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);

    return ret;

}


static void *qemu_tcg_cpu_thread_fn(void *arg)

{

    CPUState *cpu = arg;

    rcu_register_thread();

    qemu_mutex_lock_iothread();

    qemu_thread_get_self(cpu->thread);

    CPU_FOREACH(cpu) {

        cpu->thread_id = qemu_get_thread_id();

        cpu->created = true;

        cpu->can_do_io = 1;

    }

    qemu_cond_signal(&qemu_cpu_cond);

    /* wait for initial kick-off after machine start */

    while (first_cpu->stopped) {

        qemu_cond_wait(first_cpu->halt_cond, &qemu_global_mutex);

        /* process any pending work */

        CPU_FOREACH(cpu) {

            qemu_wait_io_event_common(cpu);

        }

    }

    start_tcg_kick_timer();

    cpu = first_cpu;

    /* process any pending work */

    cpu->exit_request = 1;

    while (1) {

        /* Account partial waits to QEMU_CLOCK_VIRTUAL.  */

        qemu_account_warp_timer();

        if (!cpu) {

            cpu = first_cpu;

        }

        while (cpu && !cpu->queued_work_first && !cpu->exit_request) {

            atomic_mb_set(&tcg_current_rr_cpu, cpu);

            qemu_clock_enable(QEMU_CLOCK_VIRTUAL,

                              (cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);

            if (cpu_can_run(cpu)) {

                int r;

                r = tcg_cpu_exec(cpu);

                if (r == EXCP_DEBUG) {

                    cpu_handle_guest_debug(cpu);

                    break;

                }

            } else if (cpu->stop || cpu->stopped) {

                if (cpu->unplug) {

                    cpu = CPU_NEXT(cpu);

                }

                break;

            }

            cpu = CPU_NEXT(cpu);

        } /* while (cpu && !cpu->exit_request).. */

        /* Does not need atomic_mb_set because a spurious wakeup is okay.  */

        atomic_set(&tcg_current_rr_cpu, NULL);

        if (cpu && cpu->exit_request) {

            atomic_mb_set(&cpu->exit_request, 0);

        }

        handle_icount_deadline();

        qemu_tcg_wait_io_event(QTAILQ_FIRST(&cpus));

        deal_with_unplugged_cpus();

    }

    return NULL;

}


static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,

                           uint8_t *src, uint8_t *last, int size, int bpp)

{

    int i, p, r, g, b, a;

    switch (filter_type) {

    case PNG_FILTER_VALUE_NONE:

        memcpy(dst, src, size);

        break;

    case PNG_FILTER_VALUE_SUB:

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

            dst[i] = src[i];

        }

        if (bpp == 4) {

            p = *(int*)dst;

            for (; i < size; i += bpp) {

                int s = *(int*)(src + i);

                p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);

                *(int*)(dst + i) = p;

            }

        } else {

#define OP_SUB(x,s,l) x+s

            UNROLL_FILTER(OP_SUB);

        }

        break;

    case PNG_FILTER_VALUE_UP:

        dsp->add_bytes_l2(dst, src, last, size);

        break;

    case PNG_FILTER_VALUE_AVG:

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

            p = (last[i] >> 1);

            dst[i] = p + src[i];

        }

#define OP_AVG(x,s,l) (((x + l) >> 1) + s) & 0xff

        UNROLL_FILTER(OP_AVG);

        break;

    case PNG_FILTER_VALUE_PAETH:

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

            p = last[i];

            dst[i] = p + src[i];

        }

        if (bpp > 2 && size > 4) {

            // would write off the end of the array if we let it process the last pixel with bpp=3

            int w = bpp == 4 ? size : size - 3;

            dsp->add_paeth_prediction(dst + i, src + i, last + i, w - i, bpp);

            i = w;

        }

        ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);

        break;

    }

}


static void vp56_mc(VP56Context *s, int b, int plane, uint8_t *src,

                    int stride, int x, int y)

{

    uint8_t *dst = s->frames[VP56_FRAME_CURRENT]->data[plane] + s->block_offset[b];

    uint8_t *src_block;

    int src_offset;

    int overlap_offset = 0;

    int mask = s->vp56_coord_div[b] - 1;

    int deblock_filtering = s->deblock_filtering;

    int dx;

    int dy;

    if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||

        (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY

         && !s->frames[VP56_FRAME_CURRENT]->key_frame))

        deblock_filtering = 0;

    dx = s->mv[b].x / s->vp56_coord_div[b];

    dy = s->mv[b].y / s->vp56_coord_div[b];

    if (b >= 4) {

        x /= 2;

        y /= 2;

    }

    x += dx - 2;

    y += dy - 2;

    if (x<0 || x+12>=s->plane_width[plane] ||

        y<0 || y+12>=s->plane_height[plane]) {

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

                            src + s->block_offset[b] + (dy-2)*stride + (dx-2),

                            stride, 12, 12, x, y,

                            s->plane_width[plane],

                            s->plane_height[plane]);

        src_block = s->edge_emu_buffer;

        src_offset = 2 + 2*stride;

    } else if (deblock_filtering) {

        /* only need a 12x12 block, but there is no such dsp function, */

        /* so copy a 16x12 block */

        s->hdsp.put_pixels_tab[0][0](s->edge_emu_buffer,

                                     src + s->block_offset[b] + (dy-2)*stride + (dx-2),

                                     stride, 12);

        src_block = s->edge_emu_buffer;

        src_offset = 2 + 2*stride;

    } else {

        src_block = src;

        src_offset = s->block_offset[b] + dy*stride + dx;

    }

    if (deblock_filtering)

        vp56_deblock_filter(s, src_block, stride, dx&7, dy&7);

    if (s->mv[b].x & mask)

        overlap_offset += (s->mv[b].x > 0) ? 1 : -1;

    if (s->mv[b].y & mask)

        overlap_offset += (s->mv[b].y > 0) ? stride : -stride;

    if (overlap_offset) {

        if (s->filter)

            s->filter(s, dst, src_block, src_offset, src_offset+overlap_offset,

                      stride, s->mv[b], mask, s->filter_selection, b<4);

        else

            s->vp3dsp.put_no_rnd_pixels_l2(dst, src_block+src_offset,

                                           src_block+src_offset+overlap_offset,

                                           stride, 8);

    } else {

        s->hdsp.put_pixels_tab[1][0](dst, src_block+src_offset, stride, 8);

    }

}


static int elf_core_dump(int signr, const CPUArchState *env)

{

    const CPUState *cpu = ENV_GET_CPU((CPUArchState *)env);

    const TaskState *ts = (const TaskState *)cpu->opaque;

    struct vm_area_struct *vma = NULL;

    char corefile[PATH_MAX];

    struct elf_note_info info;

    struct elfhdr elf;

    struct elf_phdr phdr;

    struct rlimit dumpsize;

    struct mm_struct *mm = NULL;

    off_t offset = 0, data_offset = 0;

    int segs = 0;

    int fd = -1;

    init_note_info(&info);

    errno = 0;

    getrlimit(RLIMIT_CORE, &dumpsize);

    if (dumpsize.rlim_cur == 0)

        return 0;

    if (core_dump_filename(ts, corefile, sizeof (corefile)) < 0)

        return (-errno);

    if ((fd = open(corefile, O_WRONLY | O_CREAT,

                   S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0)

        return (-errno);

    /*

     * Walk through target process memory mappings and

     * set up structure containing this information.  After

     * this point vma_xxx functions can be used.

     */

    if ((mm = vma_init()) == NULL)

        goto out;

    walk_memory_regions(mm, vma_walker);

    segs = vma_get_mapping_count(mm);

    /*

     * Construct valid coredump ELF header.  We also

     * add one more segment for notes.

     */

    fill_elf_header(&elf, segs + 1, ELF_MACHINE, 0);

    if (dump_write(fd, &elf, sizeof (elf)) != 0)

        goto out;

    /* fill in the in-memory version of notes */

    if (fill_note_info(&info, signr, env) < 0)

        goto out;

    offset += sizeof (elf);                             /* elf header */

    offset += (segs + 1) * sizeof (struct elf_phdr);    /* program headers */

    /* write out notes program header */

    fill_elf_note_phdr(&phdr, info.notes_size, offset);

    offset += info.notes_size;

    if (dump_write(fd, &phdr, sizeof (phdr)) != 0)

        goto out;

    /*

     * ELF specification wants data to start at page boundary so

     * we align it here.

     */

    data_offset = offset = roundup(offset, ELF_EXEC_PAGESIZE);

    /*

     * Write program headers for memory regions mapped in

     * the target process.

     */

    for (vma = vma_first(mm); vma != NULL; vma = vma_next(vma)) {

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

        phdr.p_type = PT_LOAD;

        phdr.p_offset = offset;

        phdr.p_vaddr = vma->vma_start;

        phdr.p_paddr = 0;

        phdr.p_filesz = vma_dump_size(vma);

        offset += phdr.p_filesz;

        phdr.p_memsz = vma->vma_end - vma->vma_start;

        phdr.p_flags = vma->vma_flags & PROT_READ ? PF_R : 0;

        if (vma->vma_flags & PROT_WRITE)

            phdr.p_flags |= PF_W;

        if (vma->vma_flags & PROT_EXEC)

            phdr.p_flags |= PF_X;

        phdr.p_align = ELF_EXEC_PAGESIZE;

        bswap_phdr(&phdr, 1);

        dump_write(fd, &phdr, sizeof (phdr));

    }

    /*

     * Next we write notes just after program headers.  No

     * alignment needed here.

     */

    if (write_note_info(&info, fd) < 0)

        goto out;

    /* align data to page boundary */

    if (lseek(fd, data_offset, SEEK_SET) != data_offset)

        goto out;

    /*

     * Finally we can dump process memory into corefile as well.

     */

    for (vma = vma_first(mm); vma != NULL; vma = vma_next(vma)) {

        abi_ulong addr;

        abi_ulong end;

        end = vma->vma_start + vma_dump_size(vma);

        for (addr = vma->vma_start; addr < end;

             addr += TARGET_PAGE_SIZE) {

            char page[TARGET_PAGE_SIZE];

            int error;

            /*

             *  Read in page from target process memory and

             *  write it to coredump file.

             */

            error = copy_from_user(page, addr, sizeof (page));

            if (error != 0) {

                (void) fprintf(stderr, "unable to dump " TARGET_ABI_FMT_lx "\n",

                               addr);

                errno = -error;

                goto out;

            }

            if (dump_write(fd, page, TARGET_PAGE_SIZE) < 0)

                goto out;

        }

    }

 out:

    free_note_info(&info);

    if (mm != NULL)

        vma_delete(mm);

    (void) close(fd);

    if (errno != 0)

        return (-errno);

    return (0);

}


void qemu_acl_reset(qemu_acl *acl)

{

    qemu_acl_entry *entry;

    /* Put back to deny by default, so there is no window

     * of "open access" while the user re-initializes the

     * access control list */

    acl->defaultDeny = 1;

    QTAILQ_FOREACH(entry, &acl->entries, next) {

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

        free(entry->match);

        free(entry);

    }

    acl->nentries = 0;

}


void ff_id3v2_read(AVFormatContext *s, const char *magic,

                   ID3v2ExtraMeta **extra_meta)

{

    id3v2_read_internal(s->pb, &s->metadata, s, magic, extra_meta);

}


static int qemu_loadvm_state(QEMUFile *f)

{

    SaveStateEntry *se;

    int len, ret, instance_id, record_len, version_id;

    int64_t total_len, end_pos, cur_pos;

    unsigned int v;

    char idstr[256];

    v = qemu_get_be32(f);

    if (v != QEMU_VM_FILE_MAGIC)

        goto fail;

    v = qemu_get_be32(f);

    if (v != QEMU_VM_FILE_VERSION) {

    fail:

        ret = -1;

        goto the_end;

    }

    total_len = qemu_get_be64(f);

    end_pos = total_len + qemu_ftell(f);

    for(;;) {

        if (qemu_ftell(f) >= end_pos)

            break;

        len = qemu_get_byte(f);

        qemu_get_buffer(f, (uint8_t *)idstr, len);

        idstr[len] = '\0';

        instance_id = qemu_get_be32(f);

        version_id = qemu_get_be32(f);

        record_len = qemu_get_be32(f);

#if 0

        printf("idstr=%s instance=0x%x version=%d len=%d\n",

               idstr, instance_id, version_id, record_len);

#endif

        cur_pos = qemu_ftell(f);

        se = find_se(idstr, instance_id);

        if (!se) {

            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",

                    instance_id, idstr);

        } else {

            ret = se->load_state(f, se->opaque, version_id);

            if (ret < 0) {

                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",

                        instance_id, idstr);

            }

        }

        /* always seek to exact end of record */

        qemu_fseek(f, cur_pos + record_len, SEEK_SET);

    }

    ret = 0;

 the_end:

    return ret;

}


int ff_h263_decode_picture_header(MpegEncContext *s)

{

    int format, width, height, i;

    uint32_t startcode;

    align_get_bits(&s->gb);

    if (show_bits(&s->gb, 2) == 2 && s->avctx->frame_number == 0) {

         av_log(s->avctx, AV_LOG_WARNING, "Header looks like RTP instead of H.263\n");

    }

    startcode= get_bits(&s->gb, 22-8);

    for(i= get_bits_left(&s->gb); i>24; i-=8) {

        startcode = ((startcode << 8) | get_bits(&s->gb, 8)) & 0x003FFFFF;

        if(startcode == 0x20)

            break;

    }

    if (startcode != 0x20) {

        av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n");

        return -1;

    }

    /* temporal reference */

    i = get_bits(&s->gb, 8); /* picture timestamp */

    if( (s->picture_number&~0xFF)+i < s->picture_number)

        i+= 256;

    s->picture_number= (s->picture_number&~0xFF) + i;

    /* PTYPE starts here */

    if (get_bits1(&s->gb) != 1) {

        /* marker */

        av_log(s->avctx, AV_LOG_ERROR, "Bad marker\n");

        return -1;

    }

    if (get_bits1(&s->gb) != 0) {

        av_log(s->avctx, AV_LOG_ERROR, "Bad H263 id\n");

        return -1;      /* h263 id */

    }

    skip_bits1(&s->gb);         /* split screen off */

    skip_bits1(&s->gb);         /* camera  off */

    skip_bits1(&s->gb);         /* freeze picture release off */

    format = get_bits(&s->gb, 3);

    /*

        0    forbidden

        1    sub-QCIF

        10   QCIF

        7       extended PTYPE (PLUSPTYPE)

    */

    if (format != 7 && format != 6) {

        s->h263_plus = 0;

        /* H.263v1 */

        width = ff_h263_format[format][0];

        height = ff_h263_format[format][1];

        if (!width)

            return -1;

        s->pict_type = AV_PICTURE_TYPE_I + get_bits1(&s->gb);

        s->h263_long_vectors = get_bits1(&s->gb);

        if (get_bits1(&s->gb) != 0) {

            av_log(s->avctx, AV_LOG_ERROR, "H263 SAC not supported\n");

            return -1; /* SAC: off */

        }

        s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */

        s->unrestricted_mv = s->h263_long_vectors || s->obmc;

        s->pb_frame = get_bits1(&s->gb);

        s->chroma_qscale= s->qscale = get_bits(&s->gb, 5);

        skip_bits1(&s->gb); /* Continuous Presence Multipoint mode: off */

        s->width = width;

        s->height = height;

        s->avctx->sample_aspect_ratio= (AVRational){12,11};

        s->avctx->framerate = (AVRational){ 30000, 1001 };

    } else {

        int ufep;

        /* H.263v2 */

        s->h263_plus = 1;

        ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */

        /* ufep other than 0 and 1 are reserved */

        if (ufep == 1) {

            /* OPPTYPE */

            format = get_bits(&s->gb, 3);

            av_dlog(s->avctx, "ufep=1, format: %d\n", format);

            s->custom_pcf= get_bits1(&s->gb);

            s->umvplus = get_bits1(&s->gb); /* Unrestricted Motion Vector */

            if (get_bits1(&s->gb) != 0) {

                av_log(s->avctx, AV_LOG_ERROR, "Syntax-based Arithmetic Coding (SAC) not supported\n");

            }

            s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */

            s->h263_aic = get_bits1(&s->gb); /* Advanced Intra Coding (AIC) */

            s->loop_filter= get_bits1(&s->gb);

            s->unrestricted_mv = s->umvplus || s->obmc || s->loop_filter;

            if(s->avctx->lowres)

                s->loop_filter = 0;

            s->h263_slice_structured= get_bits1(&s->gb);

            if (get_bits1(&s->gb) != 0) {

                av_log(s->avctx, AV_LOG_ERROR, "Reference Picture Selection not supported\n");

            }

            if (get_bits1(&s->gb) != 0) {

                av_log(s->avctx, AV_LOG_ERROR, "Independent Segment Decoding not supported\n");

            }

            s->alt_inter_vlc= get_bits1(&s->gb);

            s->modified_quant= get_bits1(&s->gb);

            if(s->modified_quant)

                s->chroma_qscale_table= ff_h263_chroma_qscale_table;

            skip_bits(&s->gb, 1); /* Prevent start code emulation */

            skip_bits(&s->gb, 3); /* Reserved */

        } else if (ufep != 0) {

            av_log(s->avctx, AV_LOG_ERROR, "Bad UFEP type (%d)\n", ufep);

            return -1;

        }

        /* MPPTYPE */

        s->pict_type = get_bits(&s->gb, 3);

        switch(s->pict_type){

        case 0: s->pict_type= AV_PICTURE_TYPE_I;break;

        case 1: s->pict_type= AV_PICTURE_TYPE_P;break;

        case 2: s->pict_type= AV_PICTURE_TYPE_P;s->pb_frame = 3;break;

        case 3: s->pict_type= AV_PICTURE_TYPE_B;break;

        case 7: s->pict_type= AV_PICTURE_TYPE_I;break; //ZYGO

        default:

            return -1;

        }

        skip_bits(&s->gb, 2);

        s->no_rounding = get_bits1(&s->gb);

        skip_bits(&s->gb, 4);

        /* Get the picture dimensions */

        if (ufep) {

            if (format == 6) {

                /* Custom Picture Format (CPFMT) */

                s->aspect_ratio_info = get_bits(&s->gb, 4);

                av_dlog(s->avctx, "aspect: %d\n", s->aspect_ratio_info);

                /* aspect ratios:

                0 - forbidden

                1 - 1:1

                2 - 12:11 (CIF 4:3)

                3 - 10:11 (525-type 4:3)

                4 - 16:11 (CIF 16:9)

                5 - 40:33 (525-type 16:9)

                6-14 - reserved

                */

                width = (get_bits(&s->gb, 9) + 1) * 4;

                skip_bits1(&s->gb);

                height = get_bits(&s->gb, 9) * 4;

                av_dlog(s->avctx, "\nH.263+ Custom picture: %dx%d\n",width,height);

                if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {

                    /* aspected dimensions */

                    s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 8);

                    s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 8);

                }else{

                    s->avctx->sample_aspect_ratio= ff_h263_pixel_aspect[s->aspect_ratio_info];

                }

            } else {

                width = ff_h263_format[format][0];

                height = ff_h263_format[format][1];

                s->avctx->sample_aspect_ratio= (AVRational){12,11};

            }

            s->avctx->sample_aspect_ratio.den <<= s->ehc_mode;

            if ((width == 0) || (height == 0))

                return -1;

            s->width = width;

            s->height = height;

            if(s->custom_pcf){

                int gcd;

                s->avctx->framerate.num  = 1800000;

                s->avctx->framerate.den  = 1000 + get_bits1(&s->gb);

                s->avctx->framerate.den *= get_bits(&s->gb, 7);

                if(s->avctx->framerate.den == 0){

                    av_log(s, AV_LOG_ERROR, "zero framerate\n");

                    return -1;

                }

                gcd= av_gcd(s->avctx->framerate.den, s->avctx->framerate.num);

                s->avctx->framerate.den /= gcd;

                s->avctx->framerate.num /= gcd;

            }else{

                s->avctx->framerate = (AVRational){ 30000, 1001 };

            }

        }

        if(s->custom_pcf){

            skip_bits(&s->gb, 2); //extended Temporal reference

        }

        if (ufep) {

            if (s->umvplus) {

                if(get_bits1(&s->gb)==0) /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */

                    skip_bits1(&s->gb);

            }

            if(s->h263_slice_structured){

                if (get_bits1(&s->gb) != 0) {

                    av_log(s->avctx, AV_LOG_ERROR, "rectangular slices not supported\n");

                }

                if (get_bits1(&s->gb) != 0) {

                    av_log(s->avctx, AV_LOG_ERROR, "unordered slices not supported\n");

                }

            }

        }

        s->qscale = get_bits(&s->gb, 5);

    }

    if (s->width == 0 || s->height == 0) {

        av_log(s->avctx, AV_LOG_ERROR, "dimensions 0\n");

        return -1;

    }

    s->mb_width = (s->width  + 15) / 16;

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

    s->mb_num = s->mb_width * s->mb_height;

    if (s->pb_frame) {

        skip_bits(&s->gb, 3); /* Temporal reference for B-pictures */

        if (s->custom_pcf)

            skip_bits(&s->gb, 2); //extended Temporal reference

        skip_bits(&s->gb, 2); /* Quantization information for B-pictures */

    }

    if (s->pict_type!=AV_PICTURE_TYPE_B) {

        s->time            = s->picture_number;

        s->pp_time         = s->time - s->last_non_b_time;

        s->last_non_b_time = s->time;

    }else{

        s->time    = s->picture_number;

        s->pb_time = s->pp_time - (s->last_non_b_time - s->time);

        if (s->pp_time <=s->pb_time ||

            s->pp_time <= s->pp_time - s->pb_time ||

            s->pp_time <= 0){

            s->pp_time = 2;

            s->pb_time = 1;

        }

        ff_mpeg4_init_direct_mv(s);

    }

    /* PEI */

    if (skip_1stop_8data_bits(&s->gb) < 0)

        return AVERROR_INVALIDDATA;

    if(s->h263_slice_structured){

        if (get_bits1(&s->gb) != 1) {

            av_log(s->avctx, AV_LOG_ERROR, "SEPB1 marker missing\n");

            return -1;

        }

        ff_h263_decode_mba(s);

        if (get_bits1(&s->gb) != 1) {

            av_log(s->avctx, AV_LOG_ERROR, "SEPB2 marker missing\n");

            return -1;

        }

    }

    s->f_code = 1;

    if(s->h263_aic){

         s->y_dc_scale_table=

         s->c_dc_scale_table= ff_aic_dc_scale_table;

    }else{

        s->y_dc_scale_table=

        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;

    }

        ff_h263_show_pict_info(s);

    if (s->pict_type == AV_PICTURE_TYPE_I && s->codec_tag == AV_RL32("ZYGO") && get_bits_left(&s->gb) >= 85 + 13*3*16 + 50){

        int i,j;

        for(i=0; i<85; i++) av_log(s->avctx, AV_LOG_DEBUG, "%d", get_bits1(&s->gb));

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

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

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

                int v= get_bits(&s->gb, 8);

                v |= get_sbits(&s->gb, 8)<<8;

                av_log(s->avctx, AV_LOG_DEBUG, " %5d", v);

            }

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

        }

        for(i=0; i<50; i++) av_log(s->avctx, AV_LOG_DEBUG, "%d", get_bits1(&s->gb));

    }

    return 0;

}


static inline void gen_op_arith_add(DisasContext *ctx, TCGv ret, TCGv arg1,

                                    TCGv arg2, bool add_ca, bool compute_ca,

                                    bool compute_ov, bool compute_rc0)

{

    TCGv t0 = ret;

    if (((compute_ca && add_ca) || compute_ov)

        && (TCGV_EQUAL(ret, arg1) || TCGV_EQUAL(ret, arg2)))  {

        t0 = tcg_temp_new();

    }

    if (compute_ca) {

        TCGv zero = tcg_const_tl(0);

        if (add_ca) {

            tcg_gen_add2_tl(t0, cpu_ca, arg1, zero, cpu_ca, zero);

            tcg_gen_add2_tl(t0, cpu_ca, t0, cpu_ca, arg2, zero);

        } else {

            tcg_gen_add2_tl(t0, cpu_ca, arg1, zero, arg2, zero);

        }

        tcg_temp_free(zero);

    } else {

        tcg_gen_add_tl(t0, arg1, arg2);

        if (add_ca) {

            tcg_gen_add_tl(t0, t0, cpu_ca);

        }

    }

    if (compute_ov) {

        gen_op_arith_compute_ov(ctx, t0, arg1, arg2, 0);

    }

    if (unlikely(compute_rc0)) {

        gen_set_Rc0(ctx, t0);

    }

    if (!TCGV_EQUAL(t0, ret)) {

        tcg_gen_mov_tl(ret, t0);

        tcg_temp_free(t0);

    }

}


static void qxl_check_state(PCIQXLDevice *d)

{

    QXLRam *ram = d->ram;

    assert(SPICE_RING_IS_EMPTY(&ram->cmd_ring));

    assert(SPICE_RING_IS_EMPTY(&ram->cursor_ring));

}


static inline uint64_t inline_cvttq(CPUAlphaState *env, uint64_t a,

                                    int roundmode, int VI)

{

    uint64_t frac, ret = 0;

    uint32_t exp, sign, exc = 0;

    int shift;

    sign = (a >> 63);

    exp = (uint32_t)(a >> 52) & 0x7ff;

    frac = a & 0xfffffffffffffull;

    if (exp == 0) {

        if (unlikely(frac != 0)) {

            goto do_underflow;

        }

    } else if (exp == 0x7ff) {

        exc = (frac ? FPCR_INV : VI ? FPCR_OVF : 0);

    } else {

        /* Restore implicit bit.  */

        frac |= 0x10000000000000ull;

        shift = exp - 1023 - 52;

        if (shift >= 0) {

            /* In this case the number is so large that we must shift

               the fraction left.  There is no rounding to do.  */

            if (shift < 63) {

                ret = frac << shift;

                if (VI && (ret >> shift) != frac) {

                    exc = FPCR_OVF;

                }

            }

        } else {

            uint64_t round;

            /* In this case the number is smaller than the fraction as

               represented by the 52 bit number.  Here we must think

               about rounding the result.  Handle this by shifting the

               fractional part of the number into the high bits of ROUND.

               This will let us efficiently handle round-to-nearest.  */

            shift = -shift;

            if (shift < 63) {

                ret = frac >> shift;

                round = frac << (64 - shift);

            } else {

                /* The exponent is so small we shift out everything.

                   Leave a sticky bit for proper rounding below.  */

            do_underflow:

                round = 1;

            }

            if (round) {

                exc = (VI ? FPCR_INE : 0);

                switch (roundmode) {

                case float_round_nearest_even:

                    if (round == (1ull << 63)) {

                        /* Fraction is exactly 0.5; round to even.  */

                        ret += (ret & 1);

                    } else if (round > (1ull << 63)) {

                        ret += 1;

                    }

                    break;

                case float_round_to_zero:

                    break;

                case float_round_up:

                    ret += 1 - sign;

                    break;

                case float_round_down:

                    ret += sign;

                    break;

                }

            }

        }

        if (sign) {

            ret = -ret;

        }

    }

    env->error_code = exc;

    return ret;

}


static inline void ff_mpeg4_set_one_direct_mv(MpegEncContext *s, int mx, int my, int i){

    static const int tab_size = sizeof(s->direct_scale_mv[0])/sizeof(int16_t);

    static const int tab_bias = (tab_size/2);

    int xy= s->block_index[i];

    uint16_t time_pp= s->pp_time;

    uint16_t time_pb= s->pb_time;

    int p_mx, p_my;

    p_mx= s->next_picture.motion_val[0][xy][0];

    if((unsigned)(p_mx + tab_bias) < tab_size){

        s->mv[0][i][0] = s->direct_scale_mv[0][p_mx + tab_bias] + mx;

        s->mv[1][i][0] = mx ? s->mv[0][i][0] - p_mx

                            : s->direct_scale_mv[1][p_mx + tab_bias];

    }else{

        s->mv[0][i][0] = p_mx*time_pb/time_pp + mx;

        s->mv[1][i][0] = mx ? s->mv[0][i][0] - p_mx

                            : p_mx*(time_pb - time_pp)/time_pp;

    }

    p_my= s->next_picture.motion_val[0][xy][1];

    if((unsigned)(p_my + tab_bias) < tab_size){

        s->mv[0][i][1] = s->direct_scale_mv[0][p_my + tab_bias] + my;

        s->mv[1][i][1] = my ? s->mv[0][i][1] - p_my

                            : s->direct_scale_mv[1][p_my + tab_bias];

    }else{

        s->mv[0][i][1] = p_my*time_pb/time_pp + my;

        s->mv[1][i][1] = my ? s->mv[0][i][1] - p_my

                            : p_my*(time_pb - time_pp)/time_pp;

    }

}


static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){

    AVIContext *avi = s->priv_data;

    AVIOContext *pb = s->pb;

    int longs_pre_entry= avio_rl16(pb);

    int index_sub_type = avio_r8(pb);

    int index_type     = avio_r8(pb);

    int entries_in_use = avio_rl32(pb);

    int chunk_id       = avio_rl32(pb);

    int64_t base       = avio_rl64(pb);

    int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');

    AVStream *st;

    AVIStream *ast;

    int i;

    int64_t last_pos= -1;

    int64_t filesize= avi->fsize;

    av_dlog(s, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",

            longs_pre_entry,index_type, entries_in_use, chunk_id, base);

    if(stream_id >= s->nb_streams || stream_id < 0)

        return -1;

    st= s->streams[stream_id];

    ast = st->priv_data;

    if(index_sub_type)

        return -1;

    avio_rl32(pb);

    if(index_type && longs_pre_entry != 2)

        return -1;

    if(index_type>1)

        return -1;

    if(filesize > 0 && base >= filesize){

        av_log(s, AV_LOG_ERROR, "ODML index invalid\n");

        if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)

            base &= 0xFFFFFFFF;

        else

            return -1;

    }

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

        if(index_type){

            int64_t pos= avio_rl32(pb) + base - 8;

            int len    = avio_rl32(pb);

            int key= len >= 0;

            len &= 0x7FFFFFFF;

#ifdef DEBUG_SEEK

            av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);

#endif

            if(url_feof(pb))

                return -1;

            if(last_pos == pos || pos == base - 8)

                avi->non_interleaved= 1;

            if(last_pos != pos && (len || !ast->sample_size))

                av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);

            ast->cum_len += get_duration(ast, len);

            last_pos= pos;

        }else{

            int64_t offset, pos;

            int duration;

            offset = avio_rl64(pb);

            avio_rl32(pb);       /* size */

            duration = avio_rl32(pb);

            if(url_feof(pb))

                return -1;

            pos = avio_tell(pb);

            if(avi->odml_depth > MAX_ODML_DEPTH){

                av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");

                return -1;

            }

            avio_seek(pb, offset+8, SEEK_SET);

            avi->odml_depth++;

            read_braindead_odml_indx(s, frame_num);

            avi->odml_depth--;

            frame_num += duration;

            avio_seek(pb, pos, SEEK_SET);

        }

    }

    avi->index_loaded=1;

    return 0;

}


static inline void RENAME(rgb24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    assert(src1==src2);

    RENAME(bgr24ToUV_mmx)(dstU, dstV, src1, width, PIX_FMT_RGB24);

#else

    int i;

    assert(src1==src2);

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

        int r= src1[3*i + 0];

        int g= src1[3*i + 1];

        int b= src1[3*i + 2];

        dstU[i]= (RU*r + GU*g + BU*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;

        dstV[i]= (RV*r + GV*g + BV*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;

    }

#endif

}


static Visitor *visitor_input_test_init_raw(TestInputVisitorData *data,

                                            const char *json_string)

{

    Visitor *v;

    data->obj = qobject_from_json(json_string);

    g_assert(data->obj != NULL);

    data->qiv = qmp_input_visitor_new(data->obj);

    g_assert(data->qiv != NULL);

    v = qmp_input_get_visitor(data->qiv);

    g_assert(v != NULL);

    return v;

}


ssize_t v9fs_get_xattr(FsContext *ctx, const char *path,

                       const char *name, void *value, size_t size)

{

    XattrOperations *xops = get_xattr_operations(ctx->xops, name);

    if (xops) {

        return xops->getxattr(ctx, path, name, value, size);

    }

    errno = -EOPNOTSUPP;

    return -1;

}


static void fdctrl_write_data(FDCtrl *fdctrl, uint32_t value)

{

    FDrive *cur_drv;

    int pos;

    /* Reset mode */

    if (!(fdctrl->dor & FD_DOR_nRESET)) {

        FLOPPY_DPRINTF("Floppy controller in RESET state !\n");

        return;

    }

    if (!(fdctrl->msr & FD_MSR_RQM) || (fdctrl->msr & FD_MSR_DIO)) {

        FLOPPY_DPRINTF("error: controller not ready for writing\n");

        return;

    }

    fdctrl->dsr &= ~FD_DSR_PWRDOWN;

    /* Is it write command time ? */

    if (fdctrl->msr & FD_MSR_NONDMA) {

        /* FIFO data write */

        pos = fdctrl->data_pos++;

        pos %= FD_SECTOR_LEN;

        fdctrl->fifo[pos] = value;

        if (pos == FD_SECTOR_LEN - 1 ||

            fdctrl->data_pos == fdctrl->data_len) {

            cur_drv = get_cur_drv(fdctrl);

            if (blk_write(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1)

                < 0) {

                FLOPPY_DPRINTF("error writing sector %d\n",

                               fd_sector(cur_drv));

                return;

            }

            if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) {

                FLOPPY_DPRINTF("error seeking to next sector %d\n",

                               fd_sector(cur_drv));

                return;

            }

        }

        /* Switch from transfer mode to status mode

         * then from status mode to command mode

         */

        if (fdctrl->data_pos == fdctrl->data_len)

            fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00);

        return;

    }

    if (fdctrl->data_pos == 0) {

        /* Command */

        pos = command_to_handler[value & 0xff];

        FLOPPY_DPRINTF("%s command\n", handlers[pos].name);

        fdctrl->data_len = handlers[pos].parameters + 1;

        fdctrl->msr |= FD_MSR_CMDBUSY;

    }

    FLOPPY_DPRINTF("%s: %02x\n", __func__, value);

    fdctrl->fifo[fdctrl->data_pos++] = value;

    if (fdctrl->data_pos == fdctrl->data_len) {

        /* We now have all parameters

         * and will be able to treat the command

         */

        if (fdctrl->data_state & FD_STATE_FORMAT) {

            fdctrl_format_sector(fdctrl);

            return;

        }

        pos = command_to_handler[fdctrl->fifo[0] & 0xff];

        FLOPPY_DPRINTF("treat %s command\n", handlers[pos].name);

        (*handlers[pos].handler)(fdctrl, handlers[pos].direction);

    }

}


static uint8_t *scsi_get_buf(SCSIDevice *d, uint32_t tag)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);

    SCSIDiskReq *r;

    r = scsi_find_request(s, tag);

    if (!r) {

        BADF("Bad buffer tag 0x%x\n", tag);

        return NULL;

    }

    return (uint8_t *)r->iov.iov_base;

}


static int noise(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args,

                     uint8_t **poutbuf, int *poutbuf_size,

                     const uint8_t *buf, int buf_size, int keyframe){

    unsigned int *state= bsfc->priv_data;

    int amount= args ? atoi(args) : (*state % 10001+1);

    int i;

    if(amount <= 0)

        return AVERROR(EINVAL);

    *poutbuf= av_malloc(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

    memcpy(*poutbuf, buf, buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

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

        (*state) += (*poutbuf)[i] + 1;

        if(*state % amount == 0)

            (*poutbuf)[i] = *state;

    }

    return 1;

}


static void qdev_print_devinfos(bool show_no_user)

{

    static const char *cat_name[DEVICE_CATEGORY_MAX + 1] = {

        [DEVICE_CATEGORY_BRIDGE]  = "Controller/Bridge/Hub",

        [DEVICE_CATEGORY_USB]     = "USB",

        [DEVICE_CATEGORY_STORAGE] = "Storage",

        [DEVICE_CATEGORY_NETWORK] = "Network",

        [DEVICE_CATEGORY_INPUT]   = "Input",

        [DEVICE_CATEGORY_DISPLAY] = "Display",

        [DEVICE_CATEGORY_SOUND]   = "Sound",

        [DEVICE_CATEGORY_MISC]    = "Misc",

        [DEVICE_CATEGORY_MAX]     = "Uncategorized",

    };

    GSList *list, *elt;

    int i;

    bool cat_printed;

    list = g_slist_sort(object_class_get_list(TYPE_DEVICE, false),

                        devinfo_cmp);

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

        cat_printed = false;

        for (elt = list; elt; elt = elt->next) {

            DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,

                                                 TYPE_DEVICE);

            if ((i < DEVICE_CATEGORY_MAX

                 ? !test_bit(i, dc->categories)

                 : !bitmap_empty(dc->categories, DEVICE_CATEGORY_MAX))

                || (!show_no_user && dc->no_user)) {

                continue;

            }

            if (!cat_printed) {

                error_printf("%s%s devices:\n", i ? "\n" : "",

                             cat_name[i]);

                cat_printed = true;

            }

            qdev_print_devinfo(dc);

        }

    }

    g_slist_free(list);

}


static void uhci_ioport_writew(void *opaque, uint32_t addr, uint32_t val)

{

    UHCIState *s = opaque;

    addr &= 0x1f;

    trace_usb_uhci_mmio_writew(addr, val);

    switch(addr) {

    case 0x00:

        if ((val & UHCI_CMD_RS) && !(s->cmd & UHCI_CMD_RS)) {

            /* start frame processing */

            trace_usb_uhci_schedule_start();

            s->expire_time = qemu_get_clock_ns(vm_clock) +

                (get_ticks_per_sec() / FRAME_TIMER_FREQ);

            qemu_mod_timer(s->frame_timer, qemu_get_clock_ns(vm_clock));

            s->status &= ~UHCI_STS_HCHALTED;

        } else if (!(val & UHCI_CMD_RS)) {

            s->status |= UHCI_STS_HCHALTED;

        }

        if (val & UHCI_CMD_GRESET) {

            UHCIPort *port;

            int i;

            /* send reset on the USB bus */

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

                port = &s->ports[i];

                usb_device_reset(port->port.dev);

            }

            uhci_reset(s);

            return;

        }

        if (val & UHCI_CMD_HCRESET) {

            uhci_reset(s);

            return;

        }

        s->cmd = val;

        break;

    case 0x02:

        s->status &= ~val;

        /* XXX: the chip spec is not coherent, so we add a hidden

           register to distinguish between IOC and SPD */

        if (val & UHCI_STS_USBINT)

            s->status2 = 0;

        uhci_update_irq(s);

        break;

    case 0x04:

        s->intr = val;

        uhci_update_irq(s);

        break;

    case 0x06:

        if (s->status & UHCI_STS_HCHALTED)

            s->frnum = val & 0x7ff;

        break;

    case 0x10 ... 0x1f:

        {

            UHCIPort *port;

            USBDevice *dev;

            int n;

            n = (addr >> 1) & 7;

            if (n >= NB_PORTS)

                return;

            port = &s->ports[n];

            dev = port->port.dev;

            if (dev && dev->attached) {

                /* port reset */

                if ( (val & UHCI_PORT_RESET) &&

                     !(port->ctrl & UHCI_PORT_RESET) ) {

                    usb_device_reset(dev);

                }

            }

            port->ctrl &= UHCI_PORT_READ_ONLY;

            /* enabled may only be set if a device is connected */

            if (!(port->ctrl & UHCI_PORT_CCS)) {

                val &= ~UHCI_PORT_EN;

            }

            port->ctrl |= (val & ~UHCI_PORT_READ_ONLY);

            /* some bits are reset when a '1' is written to them */

            port->ctrl &= ~(val & UHCI_PORT_WRITE_CLEAR);

        }

        break;

    }

}


static void to_meta_with_crop(AVCodecContext *avctx, AVFrame *p, int *dest)

{

    int blockx, blocky, x, y;

    int luma = 0;

    int height = FFMIN(avctx->height, C64YRES);

    int width  = FFMIN(avctx->width , C64XRES);

    uint8_t *src = p->data[0];

    for (blocky = 0; blocky < C64YRES; blocky += 8) {

        for (blockx = 0; blockx < C64XRES; blockx += 8) {

            for (y = blocky; y < blocky + 8 && y < C64YRES; y++) {

                for (x = blockx; x < blockx + 8 && x < C64XRES; x += 2) {

                    if(x < width && y < height) {

                        /* build average over 2 pixels */

                        luma = (src[(x + 0 + y * p->linesize[0])] +

                                src[(x + 1 + y * p->linesize[0])]) / 2;

                        /* write blocks as linear data now so they are suitable for elbg */

                        dest[0] = luma;

                    }

                    dest++;

                }

            }

        }

    }

}


static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)

{

    int ret = 0;

    int tileno;

    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {

        Jpeg2000Tile *tile = s->tile + tileno;

        if (ret = init_tile(s, tileno))

            return ret;

        s->g = tile->tile_part[0].tpg;

        if (ret = jpeg2000_decode_packets(s, tile))

            return ret;

    }

    return 0;

}


static void RENAME(yuv2yuvX_ar)(SwsContext *c, const int16_t *lumFilter,

                                const int16_t **lumSrc, int lumFilterSize,

                                const int16_t *chrFilter, const int16_t **chrUSrc,

                                const int16_t **chrVSrc,

                                int chrFilterSize, const int16_t **alpSrc,

                                uint8_t *dest, uint8_t *uDest, uint8_t *vDest,

                                uint8_t *aDest, int dstW, int chrDstW)

{

    if (uDest) {

        x86_reg uv_off = c->uv_off;

        YSCALEYUV2YV12X_ACCURATE(CHR_MMX_FILTER_OFFSET, uDest, chrDstW, 0)

        YSCALEYUV2YV12X_ACCURATE(CHR_MMX_FILTER_OFFSET, vDest - uv_off, chrDstW + uv_off, uv_off)

    }

    if (CONFIG_SWSCALE_ALPHA && aDest) {

        YSCALEYUV2YV12X_ACCURATE(ALP_MMX_FILTER_OFFSET, aDest, dstW, 0)

    }

    YSCALEYUV2YV12X_ACCURATE(LUM_MMX_FILTER_OFFSET, dest, dstW, 0)

}


av_cold void ff_dsputil_init_x86(DSPContext *c, AVCodecContext *avctx)

{

    int cpu_flags = av_get_cpu_flags();

#if HAVE_7REGS && HAVE_INLINE_ASM

    if (cpu_flags & AV_CPU_FLAG_CMOV)

        c->add_hfyu_median_prediction = ff_add_hfyu_median_prediction_cmov;

#endif

    if (cpu_flags & AV_CPU_FLAG_MMX)

        dsputil_init_mmx(c, avctx, cpu_flags);

    if (cpu_flags & AV_CPU_FLAG_MMXEXT)

        dsputil_init_mmxext(c, avctx, cpu_flags);

    if (cpu_flags & AV_CPU_FLAG_SSE)

        dsputil_init_sse(c, avctx, cpu_flags);

    if (cpu_flags & AV_CPU_FLAG_SSE2)

        dsputil_init_sse2(c, avctx, cpu_flags);

    if (cpu_flags & AV_CPU_FLAG_SSSE3)

        dsputil_init_ssse3(c, avctx, cpu_flags);

    if (cpu_flags & AV_CPU_FLAG_SSE4)

        dsputil_init_sse4(c, avctx, cpu_flags);

    if (CONFIG_ENCODERS)

        ff_dsputilenc_init_mmx(c, avctx);

}


matroska_read_close (AVFormatContext *s)

{

    MatroskaDemuxContext *matroska = s->priv_data;

    int n = 0;

    if (matroska->writing_app)

        av_free(matroska->writing_app);

    if (matroska->muxing_app)

        av_free(matroska->muxing_app);

    if (matroska->index)

        av_free(matroska->index);

    if (matroska->packets != NULL) {

        for (n = 0; n < matroska->num_packets; n++) {

            av_free_packet(matroska->packets[n]);

            av_free(matroska->packets[n]);

        }

        av_free(matroska->packets);

    }

    for (n = 0; n < matroska->num_tracks; n++) {

        MatroskaTrack *track = matroska->tracks[n];

        if (track->codec_id)

            av_free(track->codec_id);

        if (track->codec_name)

            av_free(track->codec_name);

        if (track->codec_priv)

            av_free(track->codec_priv);

        if (track->name)

            av_free(track->name);

        if (track->language)

            av_free(track->language);

        av_free(track);

    }

    memset(matroska, 0, sizeof(MatroskaDemuxContext));

    return 0;

}


av_cold int ff_intrax8_common_init(IntraX8Context *w, IDCTDSPContext *idsp,

                                   MpegEncContext *const s)

{

    int ret = x8_vlc_init();

    if (ret < 0)

        return ret;

    w->idsp = *idsp;

    w->s = s;

    // two rows, 2 blocks per cannon mb

    w->prediction_table = av_mallocz(s->mb_width * 2 * 2);

    if (!w->prediction_table)

        return AVERROR(ENOMEM);

    ff_init_scantable(w->idsp.idct_permutation, &w->scantable[0],

                      ff_wmv1_scantable[0]);

    ff_init_scantable(w->idsp.idct_permutation, &w->scantable[1],

                      ff_wmv1_scantable[2]);

    ff_init_scantable(w->idsp.idct_permutation, &w->scantable[2],

                      ff_wmv1_scantable[3]);

    ff_intrax8dsp_init(&w->dsp);

    return 0;

}


static int pcm_decode_frame(AVCodecContext *avctx, void *data,
                            int *got_frame_ptr, AVPacket *avpkt)
{
    const uint8_t *src = avpkt->data;
    int buf_size       = avpkt->size;
    PCMDecode *s       = avctx->priv_data;
    int sample_size, c, n, ret, samples_per_block;
    uint8_t *samples;
    int32_t *dst_int32_t;
    sample_size = av_get_bits_per_sample(avctx->codec_id) / 8;
    /* av_get_bits_per_sample returns 0 for AV_CODEC_ID_PCM_DVD */
    samples_per_block = 1;
    if (AV_CODEC_ID_PCM_DVD == avctx->codec_id) {
        if (avctx->bits_per_coded_sample != 20 &&
            avctx->bits_per_coded_sample != 24) {
            av_log(avctx, AV_LOG_ERROR,
                   "PCM DVD unsupported sample depth %i\n",
                   avctx->bits_per_coded_sample);
        /* 2 samples are interleaved per block in PCM_DVD */
        samples_per_block = 2;
        sample_size       = avctx->bits_per_coded_sample * 2 / 8;
    } else if (avctx->codec_id == AV_CODEC_ID_PCM_LXF) {
        /* we process 40-bit blocks per channel for LXF */
        samples_per_block = 2;
        sample_size       = 5;
    if (sample_size == 0) {
        av_log(avctx, AV_LOG_ERROR, "Invalid sample_size\n");
    n = avctx->channels * sample_size;
    if (n && buf_size % n) {
        if (buf_size < n) {
            av_log(avctx, AV_LOG_ERROR,
                   "Invalid PCM packet, data has size %d but at least a size of %d was expected\n",
                   buf_size, n);
            return AVERROR_INVALIDDATA;
        } else
            buf_size -= buf_size % n;
    n = buf_size / sample_size;
    /* get output buffer */
    s->frame.nb_samples = n * samples_per_block / avctx->channels;
    if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
        return ret;
    samples = s->frame.data[0];
    switch (avctx->codec->id) {
    case AV_CODEC_ID_PCM_U32LE:
        DECODE(32, le32, src, samples, n, 0, 0x80000000)
        break;
    case AV_CODEC_ID_PCM_U32BE:
        DECODE(32, be32, src, samples, n, 0, 0x80000000)
        break;
    case AV_CODEC_ID_PCM_S24LE:
        DECODE(32, le24, src, samples, n, 8, 0)
        break;
    case AV_CODEC_ID_PCM_S24BE:
        DECODE(32, be24, src, samples, n, 8, 0)
        break;
    case AV_CODEC_ID_PCM_U24LE:
        DECODE(32, le24, src, samples, n, 8, 0x800000)
        break;
    case AV_CODEC_ID_PCM_U24BE:
        DECODE(32, be24, src, samples, n, 8, 0x800000)
        break;
    case AV_CODEC_ID_PCM_S24DAUD:
        for (; n > 0; n--) {
            uint32_t v = bytestream_get_be24(&src);
            v >>= 4; // sync flags are here
            AV_WN16A(samples, ff_reverse[(v >> 8) & 0xff] +
                             (ff_reverse[v        & 0xff] << 8));
            samples += 2;
        break;
    case AV_CODEC_ID_PCM_S16LE_PLANAR:
    {
        int i;
        n /= avctx->channels;
        for (c = 0; c < avctx->channels; c++) {
            samples = s->frame.extended_data[c];
            for (i = n; i > 0; i--) {
                AV_WN16A(samples, bytestream_get_le16(&src));
                samples += 2;
        break;
    case AV_CODEC_ID_PCM_U16LE:
        DECODE(16, le16, src, samples, n, 0, 0x8000)
        break;
    case AV_CODEC_ID_PCM_U16BE:
        DECODE(16, be16, src, samples, n, 0, 0x8000)
        break;
    case AV_CODEC_ID_PCM_S8:
        for (; n > 0; n--)
            *samples++ = *src++ + 128;
        break;
#if HAVE_BIGENDIAN
    case AV_CODEC_ID_PCM_F64LE:
        DECODE(64, le64, src, samples, n, 0, 0)
        break;
    case AV_CODEC_ID_PCM_S32LE:
    case AV_CODEC_ID_PCM_F32LE:
        DECODE(32, le32, src, samples, n, 0, 0)
        break;
    case AV_CODEC_ID_PCM_S16LE:
        DECODE(16, le16, src, samples, n, 0, 0)
        break;
    case AV_CODEC_ID_PCM_F64BE:
    case AV_CODEC_ID_PCM_F32BE:
    case AV_CODEC_ID_PCM_S32BE:
    case AV_CODEC_ID_PCM_S16BE:
#else
    case AV_CODEC_ID_PCM_F64BE:
        DECODE(64, be64, src, samples, n, 0, 0)
        break;
    case AV_CODEC_ID_PCM_F32BE:
    case AV_CODEC_ID_PCM_S32BE:
        DECODE(32, be32, src, samples, n, 0, 0)
        break;
    case AV_CODEC_ID_PCM_S16BE:
        DECODE(16, be16, src, samples, n, 0, 0)
        break;
    case AV_CODEC_ID_PCM_F64LE:
    case AV_CODEC_ID_PCM_F32LE:
    case AV_CODEC_ID_PCM_S32LE:
    case AV_CODEC_ID_PCM_S16LE:
#endif /* HAVE_BIGENDIAN */
    case AV_CODEC_ID_PCM_U8:
        memcpy(samples, src, n * sample_size);
        break;
    case AV_CODEC_ID_PCM_ZORK:
        for (; n > 0; n--) {
            int v = *src++;
            if (v < 128)
                v = 128 - v;
            *samples++ = v;
        break;
    case AV_CODEC_ID_PCM_ALAW:
    case AV_CODEC_ID_PCM_MULAW:
        for (; n > 0; n--) {
            AV_WN16A(samples, s->table[*src++]);
            samples += 2;
        break;
    case AV_CODEC_ID_PCM_DVD:
    {
        const uint8_t *src8;
        dst_int32_t = (int32_t *)s->frame.data[0];
        n /= avctx->channels;
        switch (avctx->bits_per_coded_sample) {
        case 20:
            while (n--) {
                c    = avctx->channels;
                src8 = src + 4 * c;
                while (c--) {
                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8   & 0xf0) <<  8);
                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++ & 0x0f) << 12);
                src = src8;
            break;
        case 24:
            while (n--) {
                c    = avctx->channels;
                src8 = src + 4 * c;
                while (c--) {
                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++) << 8);
                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++) << 8);
                src = src8;
            break;
        break;
    case AV_CODEC_ID_PCM_LXF:
    {
        int i;
        n /= avctx->channels;
        for (c = 0; c < avctx->channels; c++) {
            dst_int32_t = (int32_t *)s->frame.extended_data[c];
            for (i = 0; i < n; i++) {
                // extract low 20 bits and expand to 32 bits
                *dst_int32_t++ =  (src[2]         << 28) |
                                  (src[1]         << 20) |
                                  (src[0]         << 12) |
                                 ((src[2] & 0x0F) <<  8) |
                                   src[1];
                // extract high 20 bits and expand to 32 bits
                *dst_int32_t++ =  (src[4]         << 24) |
                                  (src[3]         << 16) |
                                 ((src[2] & 0xF0) <<  8) |
                                  (src[4]         <<  4) |
                                  (src[3]         >>  4);
                src += 5;
        break;
    default:
        return -1;
    *got_frame_ptr   = 1;
    *(AVFrame *)data = s->frame;
    return buf_size;


static void vfio_probe_rtl8168_bar2_quirk(VFIOPCIDevice *vdev, int nr)

{

    VFIOQuirk *quirk;

    VFIOrtl8168Quirk *rtl;

    if (!vfio_pci_is(vdev, PCI_VENDOR_ID_REALTEK, 0x8168) || nr != 2) {

        return;

    }

    quirk = g_malloc0(sizeof(*quirk));

    quirk->mem = g_malloc0(sizeof(MemoryRegion) * 2);

    quirk->nr_mem = 2;

    quirk->data = rtl = g_malloc0(sizeof(*rtl));

    rtl->vdev = vdev;

    memory_region_init_io(&quirk->mem[0], OBJECT(vdev),

                          &vfio_rtl_address_quirk, rtl,

                          "vfio-rtl8168-window-address-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        0x74, &quirk->mem[0], 1);

    memory_region_init_io(&quirk->mem[1], OBJECT(vdev),

                          &vfio_rtl_data_quirk, rtl,

                          "vfio-rtl8168-window-data-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        0x70, &quirk->mem[1], 1);

    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    trace_vfio_quirk_rtl8168_probe(vdev->vbasedev.name);

}


static int gif_read_header1(GifState *s)

{

    ByteIOContext *f = s->f;

    uint8_t sig[6];

    int ret, v, n;

    int has_global_palette;

    /* read gif signature */

    ret = get_buffer(f, sig, 6);

    if (ret != 6)

        return -1;

    if (memcmp(sig, gif87a_sig, 6) != 0 &&

        memcmp(sig, gif89a_sig, 6) != 0)

        return -1;

    /* read screen header */

    s->transparent_color_index = -1;

    s->screen_width = get_le16(f);

    s->screen_height = get_le16(f);

    if(   (unsigned)s->screen_width  > 32767

       || (unsigned)s->screen_height > 32767){

        av_log(NULL, AV_LOG_ERROR, "picture size too large\n");

        return -1;

    }

    v = get_byte(f);

    s->color_resolution = ((v & 0x70) >> 4) + 1;

    has_global_palette = (v & 0x80);

    s->bits_per_pixel = (v & 0x07) + 1;

    s->background_color_index = get_byte(f);

    get_byte(f);                /* ignored */

#ifdef DEBUG

    printf("gif: screen_w=%d screen_h=%d bpp=%d global_palette=%d\n",

           s->screen_width, s->screen_height, s->bits_per_pixel,

           has_global_palette);

#endif

    if (has_global_palette) {

        n = 1 << s->bits_per_pixel;

        get_buffer(f, s->global_palette, n * 3);

    }

    return 0;

}


int tap_open(char *ifname, int ifname_size, int *vnet_hdr,

             int vnet_hdr_required, int mq_required)

{

    struct ifreq ifr;

    int fd, ret;

    int len = sizeof(struct virtio_net_hdr);

    TFR(fd = open(PATH_NET_TUN, O_RDWR));

    if (fd < 0) {

        error_report("could not open %s: %m", PATH_NET_TUN);

        return -1;

    }

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

    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;

    if (*vnet_hdr) {

        unsigned int features;

        if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&

            features & IFF_VNET_HDR) {

            *vnet_hdr = 1;

            ifr.ifr_flags |= IFF_VNET_HDR;

        } else {

            *vnet_hdr = 0;

        }

        if (vnet_hdr_required && !*vnet_hdr) {

            error_report("vnet_hdr=1 requested, but no kernel "

                         "support for IFF_VNET_HDR available");

            close(fd);

            return -1;

        }

        /*

         * Make sure vnet header size has the default value: for a persistent

         * tap it might have been modified e.g. by another instance of qemu.

         * Ignore errors since old kernels do not support this ioctl: in this

         * case the header size implicitly has the correct value.

         */

        ioctl(fd, TUNSETVNETHDRSZ, &len);

    }

    if (mq_required) {

        unsigned int features;

        if ((ioctl(fd, TUNGETFEATURES, &features) != 0) ||

            !(features & IFF_MULTI_QUEUE)) {

            error_report("multiqueue required, but no kernel "

                         "support for IFF_MULTI_QUEUE available");

            close(fd);

            return -1;

        } else {

            ifr.ifr_flags |= IFF_MULTI_QUEUE;

        }

    }

    if (ifname[0] != '\0')

        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);

    else

        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");

    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);

    if (ret != 0) {

        if (ifname[0] != '\0') {

            error_report("could not configure %s (%s): %m", PATH_NET_TUN, ifr.ifr_name);

        } else {

            error_report("could not configure %s: %m", PATH_NET_TUN);

        }

        close(fd);

        return -1;

    }

    pstrcpy(ifname, ifname_size, ifr.ifr_name);

    fcntl(fd, F_SETFL, O_NONBLOCK);

    return fd;

}


static int mkv_write_attachments(AVFormatContext *s)

{

    MatroskaMuxContext *mkv = s->priv_data;

    AVIOContext *dyn_cp, *pb = s->pb;

    ebml_master attachments;

    AVLFG c;

    int i, ret;

    if (!mkv->have_attachments)

        return 0;

    mkv->attachments = av_mallocz(sizeof(*mkv->attachments));

    if (!mkv->attachments)

        return ret;

    av_lfg_init(&c, av_get_random_seed());

    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));

    if (ret < 0) return ret;

    ret = start_ebml_master_crc32(pb, &dyn_cp, mkv, &attachments, MATROSKA_ID_ATTACHMENTS, 0);

    if (ret < 0) return ret;

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

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

        ebml_master attached_file;

        mkv_attachment *attachment = mkv->attachments->entries;

        AVDictionaryEntry *t;

        const char *mimetype = NULL;

        uint32_t fileuid;

        if (st->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT)

            continue;

        attachment = av_realloc_array(attachment, mkv->attachments->num_entries + 1, sizeof(mkv_attachment));

        if (!attachment)

            return AVERROR(ENOMEM);

        mkv->attachments->entries = attachment;

        attached_file = start_ebml_master(dyn_cp, MATROSKA_ID_ATTACHEDFILE, 0);

        if (t = av_dict_get(st->metadata, "title", NULL, 0))

            put_ebml_string(dyn_cp, MATROSKA_ID_FILEDESC, t->value);

        if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {

            av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);

            return AVERROR(EINVAL);

        }

        put_ebml_string(dyn_cp, MATROSKA_ID_FILENAME, t->value);

        if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))

            mimetype = t->value;

        else if (st->codecpar->codec_id != AV_CODEC_ID_NONE ) {

            int i;

            for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)

                if (ff_mkv_mime_tags[i].id == st->codecpar->codec_id) {

                    mimetype = ff_mkv_mime_tags[i].str;

                    break;

                }

            for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)

                if (ff_mkv_image_mime_tags[i].id == st->codecpar->codec_id) {

                    mimetype = ff_mkv_image_mime_tags[i].str;

                    break;

                }

        }

        if (!mimetype) {

            av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "

                                    "it cannot be deduced from the codec id.\n", i);

            return AVERROR(EINVAL);

        }

        if (s->flags & AVFMT_FLAG_BITEXACT) {

            struct AVSHA *sha = av_sha_alloc();

            uint8_t digest[20];

            if (!sha)

                return AVERROR(ENOMEM);

            av_sha_init(sha, 160);

            av_sha_update(sha, st->codecpar->extradata, st->codecpar->extradata_size);

            av_sha_final(sha, digest);

            av_free(sha);

            fileuid = AV_RL32(digest);

        } else {

            fileuid = av_lfg_get(&c);

        }

        av_log(s, AV_LOG_VERBOSE, "Using %.8"PRIx32" for attachment %d\n",

               fileuid, mkv->attachments->num_entries);

        put_ebml_string(dyn_cp, MATROSKA_ID_FILEMIMETYPE, mimetype);

        put_ebml_binary(dyn_cp, MATROSKA_ID_FILEDATA, st->codecpar->extradata, st->codecpar->extradata_size);

        put_ebml_uint(dyn_cp, MATROSKA_ID_FILEUID, fileuid);

        end_ebml_master(dyn_cp, attached_file);

        mkv->attachments->entries[mkv->attachments->num_entries].stream_idx = i;

        mkv->attachments->entries[mkv->attachments->num_entries++].fileuid  = fileuid;

    }

    end_ebml_master_crc32(pb, &dyn_cp, mkv, attachments);

    return 0;

}


void ff_rtp_send_jpeg(AVFormatContext *s1, const uint8_t *buf, int size)

{

    RTPMuxContext *s = s1->priv_data;

    const uint8_t *qtables = NULL;

    int nb_qtables = 0;

    uint8_t type = 1; /* default pixel format is AV_PIX_FMT_YUVJ420P */

    uint8_t w, h;

    uint8_t *p;

    int off = 0; /* fragment offset of the current JPEG frame */

    int len;

    int i;

    s->buf_ptr   = s->buf;

    s->timestamp = s->cur_timestamp;

    /* convert video pixel dimensions from pixels to blocks */

    w = s1->streams[0]->codec->width  >> 3;

    h = s1->streams[0]->codec->height >> 3;

    /* check if pixel format is not the normal 420 case */

    if (s1->streams[0]->codec->pix_fmt == AV_PIX_FMT_YUVJ422P) {

        type = 0;

    } else if (s1->streams[0]->codec->pix_fmt == AV_PIX_FMT_YUVJ420P) {

        type = 1;

    } else {

        av_log(s1, AV_LOG_ERROR, "Unsupported pixel format\n");

        return;

    }

    /* preparse the header for getting some infos */

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

        if (buf[i] != 0xff)

            continue;

        if (buf[i + 1] == DQT) {

            if (buf[i + 4])

                av_log(s1, AV_LOG_WARNING,

                       "Only 8-bit precision is supported.\n");

            /* a quantization table is 64 bytes long */

            nb_qtables = AV_RB16(&buf[i + 2]) / 65;

            if (i + 4 + nb_qtables * 65 > size) {

                av_log(s1, AV_LOG_ERROR, "Too short JPEG header. Aborted!\n");

                return;

            }

            qtables = &buf[i + 4];

        } else if (buf[i + 1] == SOF0) {

            if (buf[i + 14] != 17 || buf[i + 17] != 17) {

                av_log(s1, AV_LOG_ERROR,

                       "Only 1x1 chroma blocks are supported. Aborted!\n");

                return;

            }

        } else if (buf[i + 1] == SOS) {

            /* SOS is last marker in the header */

            i += AV_RB16(&buf[i + 2]) + 2;

            break;

        }

    }

    /* skip JPEG header */

    buf  += i;

    size -= i;

    for (i = size - 2; i >= 0; i--) {

        if (buf[i] == 0xff && buf[i + 1] == EOI) {

            /* Remove the EOI marker */

            size = i;

            break;

        }

    }

    p = s->buf_ptr;

    while (size > 0) {

        int hdr_size = 8;

        if (off == 0 && nb_qtables)

            hdr_size += 4 + 64 * nb_qtables;

        /* payload max in one packet */

        len = FFMIN(size, s->max_payload_size - hdr_size);

        /* set main header */

        bytestream_put_byte(&p, 0);

        bytestream_put_be24(&p, off);

        bytestream_put_byte(&p, type);

        bytestream_put_byte(&p, 255);

        bytestream_put_byte(&p, w);

        bytestream_put_byte(&p, h);

        if (off == 0 && nb_qtables) {

            /* set quantization tables header */

            bytestream_put_byte(&p, 0);

            bytestream_put_byte(&p, 0);

            bytestream_put_be16(&p, 64 * nb_qtables);

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

                bytestream_put_buffer(&p, &qtables[65 * i + 1], 64);

        }

        /* copy payload data */

        memcpy(p, buf, len);

        /* marker bit is last packet in frame */

        ff_rtp_send_data(s1, s->buf, len + hdr_size, size == len);

        buf  += len;

        size -= len;

        off  += len;

        p     = s->buf;

    }

}


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

                       int *got_frame_ptr, AVPacket *avpkt)

{

    ATDecodeContext *at = avctx->priv_data;

    AVFrame *frame = data;

    int pkt_size = avpkt->size;

    AVPacket filtered_packet = {0};

    OSStatus ret;

    AudioBufferList out_buffers;

    if (avctx->codec_id == AV_CODEC_ID_AAC && avpkt->size > 2 &&

        (AV_RB16(avpkt->data) & 0xfff0) == 0xfff0) {

        AVPacket filter_pkt = {0};

        if (!at->bsf) {

            const AVBitStreamFilter *bsf = av_bsf_get_by_name("aac_adtstoasc");

            if(!bsf)

                return AVERROR_BSF_NOT_FOUND;

            if ((ret = av_bsf_alloc(bsf, &at->bsf)))

                return ret;

            if (((ret = avcodec_parameters_from_context(at->bsf->par_in, avctx)) < 0) ||

                ((ret = av_bsf_init(at->bsf)) < 0)) {

                av_bsf_free(&at->bsf);

                return ret;

            }

        }

        if ((ret = av_packet_ref(&filter_pkt, avpkt)) < 0)

            return ret;

        if ((ret = av_bsf_send_packet(at->bsf, &filter_pkt)) < 0) {

            av_packet_unref(&filter_pkt);

            return ret;

        }

        if ((ret = av_bsf_receive_packet(at->bsf, &filtered_packet)) < 0)

            return ret;

        at->extradata = at->bsf->par_out->extradata;

        at->extradata_size = at->bsf->par_out->extradata_size;

        avpkt = &filtered_packet;

    }

    if (!at->converter) {

        if ((ret = ffat_create_decoder(avctx, avpkt)) < 0) {

            av_packet_unref(&filtered_packet);

            return ret;

        }

    }

    out_buffers = (AudioBufferList){

        .mNumberBuffers = 1,

        .mBuffers = {

            {

                .mNumberChannels = avctx->channels,

                .mDataByteSize = av_get_bytes_per_sample(avctx->sample_fmt) * avctx->frame_size

                                 * avctx->channels,

            }

        }

    };

    av_packet_unref(&at->new_in_pkt);

    if (avpkt->size) {

        if (filtered_packet.data) {

            at->new_in_pkt = filtered_packet;

        } else if ((ret = av_packet_ref(&at->new_in_pkt, avpkt)) < 0) {

            return ret;

        }

    } else {

        at->eof = 1;

    }

    frame->sample_rate = avctx->sample_rate;

    frame->nb_samples = avctx->frame_size;

    out_buffers.mBuffers[0].mData = at->decoded_data;

    ret = AudioConverterFillComplexBuffer(at->converter, ffat_decode_callback, avctx,

                                          &frame->nb_samples, &out_buffers, NULL);

    if ((!ret || ret == 1) && frame->nb_samples) {

        if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)

            return ret;

        ffat_copy_samples(avctx, frame);

        *got_frame_ptr = 1;

        if (at->last_pts != AV_NOPTS_VALUE) {

            frame->pts = at->last_pts;

#if FF_API_PKT_PTS

FF_DISABLE_DEPRECATION_WARNINGS

            frame->pkt_pts = at->last_pts;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

            at->last_pts = avpkt->pts;

        }

    } else if (ret && ret != 1) {

        av_log(avctx, AV_LOG_WARNING, "Decode error: %i\n", ret);

    } else {

        at->last_pts = avpkt->pts;

    }

    return pkt_size;

}


static void phys_section_destroy(MemoryRegion *mr)

{

    memory_region_unref(mr);

    if (mr->subpage) {

        subpage_t *subpage = container_of(mr, subpage_t, iomem);

        object_unref(OBJECT(&subpage->iomem));

        g_free(subpage);

    }

}


static void usb_ohci_init(OHCIState *ohci, DeviceState *dev,

                          int num_ports, int devfn,

                          qemu_irq irq, enum ohci_type type,

                          const char *name, uint32_t localmem_base)

{

    int i;

    if (usb_frame_time == 0) {

#ifdef OHCI_TIME_WARP

        usb_frame_time = get_ticks_per_sec();

        usb_bit_time = muldiv64(1, get_ticks_per_sec(), USB_HZ/1000);

#else

        usb_frame_time = muldiv64(1, get_ticks_per_sec(), 1000);

        if (get_ticks_per_sec() >= USB_HZ) {

            usb_bit_time = muldiv64(1, get_ticks_per_sec(), USB_HZ);

        } else {

            usb_bit_time = 1;

        }

#endif

        dprintf("usb-ohci: usb_bit_time=%" PRId64 " usb_frame_time=%" PRId64 "\n",

                usb_frame_time, usb_bit_time);

    }

    ohci->mem = cpu_register_io_memory(ohci_readfn, ohci_writefn, ohci);

    ohci->localmem_base = localmem_base;

    ohci->name = name;

    ohci->irq = irq;

    ohci->type = type;

    usb_bus_new(&ohci->bus, dev);

    ohci->num_ports = num_ports;

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

        usb_register_port(&ohci->bus, &ohci->rhport[i].port, ohci, i, ohci_attach);

    }

    ohci->async_td = 0;

    qemu_register_reset(ohci_reset, ohci);

    ohci_reset(ohci);

}


void helper_float_check_status (void)

{

#ifdef CONFIG_SOFTFLOAT

    if (env->exception_index == POWERPC_EXCP_PROGRAM &&

        (env->error_code & POWERPC_EXCP_FP)) {

        /* Differred floating-point exception after target FPR update */

        if (msr_fe0 != 0 || msr_fe1 != 0)

            helper_raise_exception_err(env->exception_index, env->error_code);

    } else {

        int status = get_float_exception_flags(&env->fp_status);

        if (status & float_flag_overflow) {

            float_overflow_excp();

        } else if (status & float_flag_underflow) {

            float_underflow_excp();

        } else if (status & float_flag_inexact) {

            float_inexact_excp();

        }

    }

#else

    if (env->exception_index == POWERPC_EXCP_PROGRAM &&

        (env->error_code & POWERPC_EXCP_FP)) {

        /* Differred floating-point exception after target FPR update */

        if (msr_fe0 != 0 || msr_fe1 != 0)

            helper_raise_exception_err(env->exception_index, env->error_code);

    }

#endif

}