int dyngen_code(TCGContext *s, uint8_t *gen_code_buf)

{

#ifdef CONFIG_PROFILER

    {

        extern int64_t dyngen_op_count;

        extern int dyngen_op_count_max;

        int n;

        n = (gen_opc_ptr - gen_opc_buf);

        dyngen_op_count += n;

        if (n > dyngen_op_count_max)

            dyngen_op_count_max = n;

    }

#endif

    tcg_gen_code_common(s, gen_code_buf, 0, NULL);

    /* flush instruction cache */

    flush_icache_range((unsigned long)gen_code_buf,

                       (unsigned long)s->code_ptr);

    return s->code_ptr -  gen_code_buf;

}


static int alloc_refcount_block(BlockDriverState *bs,
                                int64_t cluster_index, void **refcount_block)
{
    BDRVQcow2State *s = bs->opaque;
    unsigned int refcount_table_index;
    int64_t ret;
    BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
    /* Find the refcount block for the given cluster */
    refcount_table_index = cluster_index >> s->refcount_block_bits;
    if (refcount_table_index < s->refcount_table_size) {
        uint64_t refcount_block_offset =
            s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK;
        /* If it's already there, we're done */
        if (refcount_block_offset) {
            if (offset_into_cluster(s, refcount_block_offset)) {
                qcow2_signal_corruption(bs, true, -1, -1, "Refblock offset %#"
                                        PRIx64 " unaligned (reftable index: "
                                        "%#x)", refcount_block_offset,
                                        refcount_table_index);
             return load_refcount_block(bs, refcount_block_offset,
                                        refcount_block);
    /*
     * If we came here, we need to allocate something. Something is at least
     * a cluster for the new refcount block. It may also include a new refcount
     * table if the old refcount table is too small.
     *
     * Note that allocating clusters here needs some special care:
     *
     * - We can't use the normal qcow2_alloc_clusters(), it would try to
     *   increase the refcount and very likely we would end up with an endless
     *   recursion. Instead we must place the refcount blocks in a way that
     *   they can describe them themselves.
     *
     * - We need to consider that at this point we are inside update_refcounts
     *   and potentially doing an initial refcount increase. This means that
     *   some clusters have already been allocated by the caller, but their
     *   refcount isn't accurate yet. If we allocate clusters for metadata, we
     *   need to return -EAGAIN to signal the caller that it needs to restart
     *   the search for free clusters.
     *
     * - alloc_clusters_noref and qcow2_free_clusters may load a different
     *   refcount block into the cache
     */
    *refcount_block = NULL;
    /* We write to the refcount table, so we might depend on L2 tables */
    ret = qcow2_cache_flush(bs, s->l2_table_cache);
    if (ret < 0) {
        return ret;
    /* Allocate the refcount block itself and mark it as used */
    int64_t new_block = alloc_clusters_noref(bs, s->cluster_size);
    if (new_block < 0) {
        return new_block;
#ifdef DEBUG_ALLOC2
    fprintf(stderr, "qcow2: Allocate refcount block %d for %" PRIx64
        " at %" PRIx64 "\n",
        refcount_table_index, cluster_index << s->cluster_bits, new_block);
#endif
    if (in_same_refcount_block(s, new_block, cluster_index << s->cluster_bits)) {
        /* Zero the new refcount block before updating it */
        ret = qcow2_cache_get_empty(bs, s->refcount_block_cache, new_block,
                                    refcount_block);
        if (ret < 0) {
            goto fail;
        memset(*refcount_block, 0, s->cluster_size);
        /* The block describes itself, need to update the cache */
        int block_index = (new_block >> s->cluster_bits) &
            (s->refcount_block_size - 1);
        s->set_refcount(*refcount_block, block_index, 1);
    } else {
        /* Described somewhere else. This can recurse at most twice before we
         * arrive at a block that describes itself. */
        ret = update_refcount(bs, new_block, s->cluster_size, 1, false,
                              QCOW2_DISCARD_NEVER);
        if (ret < 0) {
            goto fail;
        ret = qcow2_cache_flush(bs, s->refcount_block_cache);
        if (ret < 0) {
            goto fail;
        /* Initialize the new refcount block only after updating its refcount,
         * update_refcount uses the refcount cache itself */
        ret = qcow2_cache_get_empty(bs, s->refcount_block_cache, new_block,
                                    refcount_block);
        if (ret < 0) {
            goto fail;
        memset(*refcount_block, 0, s->cluster_size);
    /* Now the new refcount block needs to be written to disk */
    BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE);
    qcow2_cache_entry_mark_dirty(bs, s->refcount_block_cache, *refcount_block);
    ret = qcow2_cache_flush(bs, s->refcount_block_cache);
    if (ret < 0) {
        goto fail;
    /* If the refcount table is big enough, just hook the block up there */
    if (refcount_table_index < s->refcount_table_size) {
        uint64_t data64 = cpu_to_be64(new_block);
        BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_HOOKUP);
        ret = bdrv_pwrite_sync(bs->file,
            s->refcount_table_offset + refcount_table_index * sizeof(uint64_t),
            &data64, sizeof(data64));
        if (ret < 0) {
            goto fail;
        s->refcount_table[refcount_table_index] = new_block;
        /* If there's a hole in s->refcount_table then it can happen
         * that refcount_table_index < s->max_refcount_table_index */
        s->max_refcount_table_index =
            MAX(s->max_refcount_table_index, refcount_table_index);
        /* The new refcount block may be where the caller intended to put its
         * data, so let it restart the search. */
        return -EAGAIN;
    qcow2_cache_put(bs, s->refcount_block_cache, refcount_block);
    /*
     * If we come here, we need to grow the refcount table. Again, a new
     * refcount table needs some space and we can't simply allocate to avoid
     * endless recursion.
     *
     * Therefore let's grab new refcount blocks at the end of the image, which
     * will describe themselves and the new refcount table. This way we can
     * reference them only in the new table and do the switch to the new
     * refcount table at once without producing an inconsistent state in
     * between.
     */
    BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_GROW);
    /* Calculate the number of refcount blocks needed so far; this will be the
     * basis for calculating the index of the first cluster used for the
     * self-describing refcount structures which we are about to create.
     *
     * Because we reached this point, there cannot be any refcount entries for
     * cluster_index or higher indices yet. However, because new_block has been
     * allocated to describe that cluster (and it will assume this role later
     * on), we cannot use that index; also, new_block may actually have a higher
     * cluster index than cluster_index, so it needs to be taken into account
     * here (and 1 needs to be added to its value because that cluster is used).
     */
    uint64_t blocks_used = DIV_ROUND_UP(MAX(cluster_index + 1,
                                            (new_block >> s->cluster_bits) + 1),
                                        s->refcount_block_size);
    /* Create the new refcount table and blocks */
    uint64_t meta_offset = (blocks_used * s->refcount_block_size) *
        s->cluster_size;
    ret = qcow2_refcount_area(bs, meta_offset, 0, false,
                              refcount_table_index, new_block);
    if (ret < 0) {
        return ret;
    ret = load_refcount_block(bs, new_block, refcount_block);
    if (ret < 0) {
        return ret;
    /* If we were trying to do the initial refcount update for some cluster
     * allocation, we might have used the same clusters to store newly
     * allocated metadata. Make the caller search some new space. */
    return -EAGAIN;
fail:
    if (*refcount_block != NULL) {
        qcow2_cache_put(bs, s->refcount_block_cache, refcount_block);
    return ret;


static int x8_setup_spatial_predictor(IntraX8Context * const w, const int chroma){

    MpegEncContext * const s= w->s;

    int range;

    int sum;

    int quant;

    w->dsp.setup_spatial_compensation(s->dest[chroma], s->edge_emu_buffer,

                                      s->current_picture.f.linesize[chroma>0],

                                      &range, &sum, w->edges);

    if(chroma){

        w->orient=w->chroma_orient;

        quant=w->quant_dc_chroma;

    }else{

        quant=w->quant;

    }

    w->flat_dc=0;

    if(range < quant || range < 3){

        w->orient=0;

        if(range < 3){//yep you read right, a +-1 idct error may break decoding!

            w->flat_dc=1;

            sum+=9;

            w->predicted_dc = (sum*6899)>>17;//((1<<17)+9)/(8+8+1+2)=6899

        }

    }

    if(chroma)

        return 0;

    assert(w->orient < 3);

    if(range < 2*w->quant){

        if( (w->edges&3) == 0){

            if(w->orient==1) w->orient=11;

            if(w->orient==2) w->orient=10;

        }else{

            w->orient=0;

        }

        w->raw_orient=0;

    }else{

        static const uint8_t prediction_table[3][12]={

            {0,8,4, 10,11, 2,6,9,1,3,5,7},

            {4,0,8, 11,10, 3,5,2,6,9,1,7},

            {8,0,4, 10,11, 1,7,2,6,9,3,5}

        };

        w->raw_orient=x8_get_orient_vlc(w);

        if(w->raw_orient<0) return -1;

        assert(w->raw_orient < 12 );

        assert(w->orient<3);

        w->orient=prediction_table[w->orient][w->raw_orient];

    }

    return 0;

}


static void vc1_mc_4mv_chroma4(VC1Context *v, int dir, int dir2, int avg)

{

    MpegEncContext *s = &v->s;

    H264ChromaContext *h264chroma = &v->h264chroma;

    uint8_t *srcU, *srcV;

    int uvsrc_x, uvsrc_y;

    int uvmx_field[4], uvmy_field[4];

    int i, off, tx, ty;

    int fieldmv = v->blk_mv_type[s->block_index[0]];

    static const int s_rndtblfield[16] = { 0, 0, 1, 2, 4, 4, 5, 6, 2, 2, 3, 8, 6, 6, 7, 12 };

    int v_dist = fieldmv ? 1 : 4; // vertical offset for lower sub-blocks

    int v_edge_pos = s->v_edge_pos >> 1;

    int use_ic;

    uint8_t (*lutuv)[256];

    if (s->flags & CODEC_FLAG_GRAY)

        return;

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

        int d = i < 2 ? dir: dir2;

        tx = s->mv[d][i][0];

        uvmx_field[i] = (tx + ((tx & 3) == 3)) >> 1;

        ty = s->mv[d][i][1];

        if (fieldmv)

            uvmy_field[i] = (ty >> 4) * 8 + s_rndtblfield[ty & 0xF];

        else

            uvmy_field[i] = (ty + ((ty & 3) == 3)) >> 1;

    }

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

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

        uvsrc_x = s->mb_x * 8 +  (i & 1) * 4           + (uvmx_field[i] >> 2);

        uvsrc_y = s->mb_y * 8 + ((i & 2) ? v_dist : 0) + (uvmy_field[i] >> 2);

        // FIXME: implement proper pull-back (see vc1cropmv.c, vc1CROPMV_ChromaPullBack())

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

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

        if (i < 2 ? dir : dir2) {

            srcU = s->next_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;

            srcV = s->next_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;

            lutuv  = v->next_lutuv;

            use_ic = v->next_use_ic;

        } else {

            srcU = s->last_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;

            srcV = s->last_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;

            lutuv  = v->last_lutuv;

            use_ic = v->last_use_ic;

        }

        uvmx_field[i] = (uvmx_field[i] & 3) << 1;

        uvmy_field[i] = (uvmy_field[i] & 3) << 1;

        if (fieldmv && !(uvsrc_y & 1))

            v_edge_pos--;

        if (fieldmv && (uvsrc_y & 1) && uvsrc_y < 2)

            uvsrc_y--;

        if (use_ic

            || s->h_edge_pos < 10 || v_edge_pos < (5 << fieldmv)

            || (unsigned)uvsrc_x > (s->h_edge_pos >> 1) - 5

            || (unsigned)uvsrc_y > v_edge_pos - (5 << fieldmv)) {

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

                                     s->uvlinesize, s->uvlinesize,

                                     5, (5 << fieldmv), uvsrc_x, uvsrc_y,

                                     s->h_edge_pos >> 1, v_edge_pos);

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

                                     s->uvlinesize, s->uvlinesize,

                                     5, (5 << fieldmv), uvsrc_x, uvsrc_y,

                                     s->h_edge_pos >> 1, v_edge_pos);

            srcU = s->edge_emu_buffer;

            srcV = s->edge_emu_buffer + 16;

            /* if we deal with intensity compensation we need to scale source blocks */

            if (use_ic) {

                int i, j;

                uint8_t *src, *src2;

                src  = srcU;

                src2 = srcV;

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

                    int f = (uvsrc_y + (j << fieldmv)) & 1;

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

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

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

                    }

                    src  += s->uvlinesize << fieldmv;

                    src2 += s->uvlinesize << fieldmv;

                }

            }

        }

        if (avg) {

            if (!v->rnd) {

                h264chroma->avg_h264_chroma_pixels_tab[1](s->dest[1] + off, srcU, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

                h264chroma->avg_h264_chroma_pixels_tab[1](s->dest[2] + off, srcV, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

            } else {

                v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[1](s->dest[1] + off, srcU, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

                v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[1](s->dest[2] + off, srcV, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

            }

        } else {

            if (!v->rnd) {

                h264chroma->put_h264_chroma_pixels_tab[1](s->dest[1] + off, srcU, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

                h264chroma->put_h264_chroma_pixels_tab[1](s->dest[2] + off, srcV, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

            } else {

                v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[1](s->dest[1] + off, srcU, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

                v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[1](s->dest[2] + off, srcV, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

            }

        }

    }

}


static void moxie_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    MoxieCPU *cpu = MOXIE_CPU(obj);

    static int inited;

    cs->env_ptr = &cpu->env;

    cpu_exec_init(cs, &error_abort);

    if (tcg_enabled() && !inited) {

        inited = 1;

        moxie_translate_init();

    }

}


static int rtp_asf_fix_header(uint8_t *buf, int len)

{

    uint8_t *p = buf, *end = buf + len;

    if (len < sizeof(ff_asf_guid) * 2 + 22 ||

        memcmp(p, ff_asf_header, sizeof(ff_asf_guid))) {

        return -1;

    }

    p += sizeof(ff_asf_guid) + 14;

    do {

        uint64_t chunksize = AV_RL64(p + sizeof(ff_asf_guid));

        if (memcmp(p, ff_asf_file_header, sizeof(ff_asf_guid))) {

            if (chunksize > end - p)

                return -1;

            p += chunksize;

            continue;

        }

        /* skip most of the file header, to min_pktsize */

        p += 6 * 8 + 3 * 4 + sizeof(ff_asf_guid) * 2;

        if (p + 8 <= end && AV_RL32(p) == AV_RL32(p + 4)) {

            /* and set that to zero */

            AV_WL32(p, 0);

            return 0;

        }

        break;

    } while (end - p >= sizeof(ff_asf_guid) + 8);

    return -1;

}


static int vmdk_open(BlockDriverState *bs, const char *filename, int flags)

{

    BDRVVmdkState *s = bs->opaque;

    uint32_t magic;

    int l1_size, i, ret;

    if (parent_open)

        // Parent must be opened as RO.

        flags = BDRV_O_RDONLY;

    fprintf(stderr, "(VMDK) image open: flags=0x%x filename=%s\n", flags, bs->filename);

    ret = bdrv_file_open(&s->hd, filename, flags | BDRV_O_AUTOGROW);

    if (ret < 0)

        return ret;

    if (bdrv_pread(s->hd, 0, &magic, sizeof(magic)) != sizeof(magic))

        goto fail;

    magic = be32_to_cpu(magic);

    if (magic == VMDK3_MAGIC) {

        VMDK3Header header;

        if (bdrv_pread(s->hd, sizeof(magic), &header, sizeof(header)) != sizeof(header))

            goto fail;

        s->cluster_sectors = le32_to_cpu(header.granularity);

        s->l2_size = 1 << 9;

        s->l1_size = 1 << 6;

        bs->total_sectors = le32_to_cpu(header.disk_sectors);

        s->l1_table_offset = le32_to_cpu(header.l1dir_offset) << 9;

        s->l1_backup_table_offset = 0;

        s->l1_entry_sectors = s->l2_size * s->cluster_sectors;

    } else if (magic == VMDK4_MAGIC) {

        VMDK4Header header;

        if (bdrv_pread(s->hd, sizeof(magic), &header, sizeof(header)) != sizeof(header))

            goto fail;

        bs->total_sectors = le64_to_cpu(header.capacity);

        s->cluster_sectors = le64_to_cpu(header.granularity);

        s->l2_size = le32_to_cpu(header.num_gtes_per_gte);

        s->l1_entry_sectors = s->l2_size * s->cluster_sectors;

        if (s->l1_entry_sectors <= 0)

            goto fail;

        s->l1_size = (bs->total_sectors + s->l1_entry_sectors - 1)

            / s->l1_entry_sectors;

        s->l1_table_offset = le64_to_cpu(header.rgd_offset) << 9;

        s->l1_backup_table_offset = le64_to_cpu(header.gd_offset) << 9;

        if (parent_open)

            s->is_parent = 1;

        else

            s->is_parent = 0;

        // try to open parent images, if exist

        if (vmdk_parent_open(bs, filename) != 0)

            goto fail;

        // write the CID once after the image creation

        s->parent_cid = vmdk_read_cid(bs,1);

    } else {

        goto fail;

    }

    /* read the L1 table */

    l1_size = s->l1_size * sizeof(uint32_t);

    s->l1_table = qemu_malloc(l1_size);

    if (!s->l1_table)

        goto fail;

    if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, l1_size) != l1_size)

        goto fail;

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

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

    }

    if (s->l1_backup_table_offset) {

        s->l1_backup_table = qemu_malloc(l1_size);

        if (!s->l1_backup_table)

            goto fail;

        if (bdrv_pread(s->hd, s->l1_backup_table_offset, s->l1_backup_table, l1_size) != l1_size)

            goto fail;

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

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

        }

    }

    s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint32_t));

    if (!s->l2_cache)

        goto fail;

    return 0;

 fail:

    qemu_free(s->l1_backup_table);

    qemu_free(s->l1_table);

    qemu_free(s->l2_cache);

    bdrv_delete(s->hd);

    return -1;

}


static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options, Error **errp)

{

    SocketAddress *saddr = NULL;

    QDict *addr = NULL;

    QObject *crumpled_addr = NULL;

    Visitor *iv = NULL;

    Error *local_err = NULL;

    qdict_extract_subqdict(options, &addr, "server.");

    if (!qdict_size(addr)) {

        error_setg(errp, "NBD server address missing");

        goto done;

    }

    crumpled_addr = qdict_crumple(addr, errp);

    if (!crumpled_addr) {

        goto done;

    }

    iv = qobject_input_visitor_new(crumpled_addr);

    visit_type_SocketAddress(iv, NULL, &saddr, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto done;

    }

done:

    QDECREF(addr);

    qobject_decref(crumpled_addr);

    visit_free(iv);

    return saddr;

}


static inline void RENAME(uyvyToY)(uint8_t *dst, uint8_t *src, long width)

{

#ifdef HAVE_MMX

	asm volatile(

		"mov %0, %%"REG_a"		\n\t"

		"1:				\n\t"

		"movq (%1, %%"REG_a",2), %%mm0	\n\t"

		"movq 8(%1, %%"REG_a",2), %%mm1	\n\t"

		"psrlw $8, %%mm0		\n\t"

		"psrlw $8, %%mm1		\n\t"

		"packuswb %%mm1, %%mm0		\n\t"

		"movq %%mm0, (%2, %%"REG_a")	\n\t"

		"add $8, %%"REG_a"		\n\t"

		" js 1b				\n\t"

		: : "g" (-width), "r" (src+width*2), "r" (dst+width)

		: "%"REG_a

	);

#else

	int i;

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

		dst[i]= src[2*i+1];

#endif

}


static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y,

                             const uint8_t *src, int src_size)

{

    int width, height;

    int hdr, zsize, npal, tidx = -1, ret;

    int i, j;

    const uint8_t *src_end = src + src_size;

    uint8_t pal[768], transp[3];

    uLongf dlen = (c->tile_width + 1) * c->tile_height;

    int sub_type;

    int nblocks, cblocks, bstride;

    int bits, bitbuf, coded;

    uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 +

                   tile_y * c->tile_height * c->framebuf_stride;

    if (src_size < 2)

    width  = FFMIN(c->width  - tile_x * c->tile_width,  c->tile_width);

    height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);

    hdr = *src++;

    sub_type = hdr >> 5;

    if (sub_type == 0) {

        int j;

        memcpy(transp, src, 3);

        src += 3;

        for (j = 0; j < height; j++, dst += c->framebuf_stride)

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

                memcpy(dst + i * 3, transp, 3);

        return 0;

    } else if (sub_type == 1) {

        return jpg_decode_data(&c->jc, width, height, src, src_end - src,

                               dst, c->framebuf_stride, NULL, 0, 0, 0);

    }

    if (sub_type != 2) {

        memcpy(transp, src, 3);

        src += 3;

    }

    npal = *src++ + 1;

    memcpy(pal, src, npal * 3); src += npal * 3;

    if (sub_type != 2) {

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

            if (!memcmp(pal + i * 3, transp, 3)) {

               tidx = i;

               break;

            }

        }

    }

    if (src_end - src < 2)

        return 0;

    zsize = (src[0] << 8) | src[1]; src += 2;

    if (src_end - src < zsize + (sub_type != 2))

    ret = uncompress(c->kempf_buf, &dlen, src, zsize);

    if (ret)

    src += zsize;

    if (sub_type == 2) {

        kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,

                          NULL, 0, width, height, pal, npal, tidx);

        return 0;

    }

    nblocks = *src++ + 1;

    cblocks = 0;

    bstride = FFALIGN(width, 16) >> 4;

    // blocks are coded LSB and we need normal bitreader for JPEG data

    bits = 0;

    for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) {

        for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) {

            if (!bits) {

                if (src >= src_end)

                bitbuf = *src++;

                bits   = 8;

            }

            coded = bitbuf & 1;

            bits--;

            bitbuf >>= 1;

            cblocks += coded;

            if (cblocks > nblocks)

            c->kempf_flags[j + i * bstride] = coded;

        }

    }

    memset(c->jpeg_tile, 0, c->tile_stride * height);

    jpg_decode_data(&c->jc, width, height, src, src_end - src,

                    c->jpeg_tile, c->tile_stride,

                    c->kempf_flags, bstride, nblocks, 0);

    kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,

                      c->jpeg_tile, c->tile_stride,

                      width, height, pal, npal, tidx);

    return 0;

}


static void interpolate_refplane(DiracContext *s, DiracFrame *ref, int plane, int width, int height)

{

    /* chroma allocates an edge of 8 when subsampled

       which for 4:2:2 means an h edge of 16 and v edge of 8

       just use 8 for everything for the moment */

    int i, edge = EDGE_WIDTH/2;

    ref->hpel[plane][0] = ref->avframe->data[plane];

    s->mpvencdsp.draw_edges(ref->hpel[plane][0], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM); /* EDGE_TOP | EDGE_BOTTOM values just copied to make it build, this needs to be ensured */

    /* no need for hpel if we only have fpel vectors */

    if (!s->mv_precision)

        return;

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

        if (!ref->hpel_base[plane][i])

            ref->hpel_base[plane][i] = av_malloc((height+2*edge) * ref->avframe->linesize[plane] + 32);

        /* we need to be 16-byte aligned even for chroma */

        ref->hpel[plane][i] = ref->hpel_base[plane][i] + edge*ref->avframe->linesize[plane] + 16;

    }

    if (!ref->interpolated[plane]) {

        s->diracdsp.dirac_hpel_filter(ref->hpel[plane][1], ref->hpel[plane][2],

                                      ref->hpel[plane][3], ref->hpel[plane][0],

                                      ref->avframe->linesize[plane], width, height);

        s->mpvencdsp.draw_edges(ref->hpel[plane][1], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);

        s->mpvencdsp.draw_edges(ref->hpel[plane][2], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);

        s->mpvencdsp.draw_edges(ref->hpel[plane][3], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);

    }

    ref->interpolated[plane] = 1;

}


static void scsi_read_complete(void * opaque, int ret)

{

    SCSIGenericReq *r = (SCSIGenericReq *)opaque;

    int len;

    if (ret) {

        DPRINTF("IO error ret %d\n", ret);

        scsi_command_complete(r, ret);

        return;

    }

    len = r->io_header.dxfer_len - r->io_header.resid;

    DPRINTF("Data ready tag=0x%x len=%d\n", r->req.tag, len);

    r->len = -1;

    r->req.bus->complete(r->req.bus, SCSI_REASON_DATA, r->req.tag, len);

    if (len == 0)

        scsi_command_complete(r, 0);

}


int avfilter_process_command(AVFilterContext *filter, const char *cmd, const char *arg, char *res, int res_len, int flags)
{
    if(!strcmp(cmd, "ping")){
        av_strlcatf(res, res_len, "pong from:%s %s\n", filter->filter->name, filter->name);
        return 0;
    }else if(!strcmp(cmd, "enable")) {
        return set_enable_expr(filter, arg);
    }else if(filter->filter->process_command) {
        return filter->filter->process_command(filter, cmd, arg, res, res_len, flags);
    return AVERROR(ENOSYS);


static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,

                           int width, int height, int bpno, int bandno,

                           int seg_symbols)

{

    int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;

    for (y0 = 0; y0 < height; y0 += 4)

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

            if (y0 + 3 < height &&

                !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||

                  (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||

                  (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||

                  (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {

                if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))

                    continue;

                runlen = ff_mqc_decode(&t1->mqc,

                                       t1->mqc.cx_states + MQC_CX_UNI);

                runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,

                                                       t1->mqc.cx_states +

                                                       MQC_CX_UNI);

                dec = 1;

            } else {

                runlen = 0;

                dec    = 0;

            }

            for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {

                if (!dec) {

                    if (!(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)))

                        dec = ff_mqc_decode(&t1->mqc,

                                            t1->mqc.cx_states +

                                            ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],

                                                                   bandno));

                }

                if (dec) {

                    int xorbit;

                    int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],

                                                        &xorbit);

                    t1->data[y][x] = (ff_mqc_decode(&t1->mqc,

                                                    t1->mqc.cx_states + ctxno) ^

                                      xorbit)

                                     ? -mask : mask;

                    ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);

                }

                dec = 0;

                t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;

            }

        }

    if (seg_symbols) {

        int val;

        val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);

        val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);

        val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);

        val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);

        if (val != 0xa)

            av_log(s->avctx, AV_LOG_ERROR,

                   "Segmentation symbol value incorrect\n");

    }

}


void ff_put_h264_qpel8_mc03_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_vt_qrt_8w_msa(src - (stride * 2), stride, dst, stride, 8, 1);

}


static av_cold int audio_write_header(AVFormatContext *s1)

{

    AlsaData *s = s1->priv_data;

    AVStream *st;

    unsigned int sample_rate;

    enum AVCodecID codec_id;

    int res;

    st = s1->streams[0];

    sample_rate = st->codec->sample_rate;

    codec_id    = st->codec->codec_id;

    res = ff_alsa_open(s1, SND_PCM_STREAM_PLAYBACK, &sample_rate,

        st->codec->channels, &codec_id);

    if (sample_rate != st->codec->sample_rate) {

        av_log(s1, AV_LOG_ERROR,

               "sample rate %d not available, nearest is %d\n",

               st->codec->sample_rate, sample_rate);

        goto fail;

    }

    avpriv_set_pts_info(st, 64, 1, sample_rate);

    return res;

fail:

    snd_pcm_close(s->h);

    return AVERROR(EIO);

}


int ff_jpegls_decode_lse(MJpegDecodeContext *s)

{

    int id;

    int tid, wt, maxtab, i, j;

    int len = get_bits(&s->gb, 16);  /* length: FIXME: verify field validity */

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

    switch (id) {

    case 1:

        s->maxval = get_bits(&s->gb, 16);

        s->t1     = get_bits(&s->gb, 16);

        s->t2     = get_bits(&s->gb, 16);

        s->t3     = get_bits(&s->gb, 16);

        s->reset  = get_bits(&s->gb, 16);

//        ff_jpegls_reset_coding_parameters(s, 0);

        //FIXME quant table?

        break;

    case 2:

        s->palette_index = 0;

    case 3:

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

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

        if (len < 5)

            return AVERROR_INVALIDDATA;

        if (wt < 1 || wt > MAX_COMPONENTS) {

            avpriv_request_sample(s->avctx, "wt %d", wt);

            return AVERROR_PATCHWELCOME;

        }

        if (!s->maxval)

            maxtab = 255;

        else if ((5 + wt*(s->maxval+1)) < 65535)

            maxtab = s->maxval;

        else

            maxtab = 65530/wt - 1;

        if(s->avctx->debug & FF_DEBUG_PICT_INFO) {

            av_log(s->avctx, AV_LOG_DEBUG, "LSE palette %d tid:%d wt:%d maxtab:%d\n", id, tid, wt, maxtab);

        }

        if (maxtab >= 256) {

            avpriv_request_sample(s->avctx, ">8bit palette");

            return AVERROR_PATCHWELCOME;

        }

        maxtab = FFMIN(maxtab, (len - 5) / wt + s->palette_index);

        if (s->palette_index > maxtab)

            return AVERROR_INVALIDDATA;

        if ((s->avctx->pix_fmt == AV_PIX_FMT_GRAY8 || s->avctx->pix_fmt == AV_PIX_FMT_PAL8) &&

            (s->picture_ptr->format == AV_PIX_FMT_GRAY8 || s->picture_ptr->format == AV_PIX_FMT_PAL8)) {

            uint32_t *pal = s->picture_ptr->data[1];

            s->picture_ptr->format =

            s->avctx->pix_fmt = AV_PIX_FMT_PAL8;

            for (i=s->palette_index; i<=maxtab; i++) {

                pal[i] = 0;

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

                    pal[i] |= get_bits(&s->gb, 8) << (8*(wt-j-1));

                }

            }

            s->palette_index = i;

        }

        break;

    case 4:

        avpriv_request_sample(s->avctx, "oversize image");

        return AVERROR(ENOSYS);

    default:

        av_log(s->avctx, AV_LOG_ERROR, "invalid id %d\n", id);

        return AVERROR_INVALIDDATA;

    }

    av_dlog(s->avctx, "ID=%i, T=%i,%i,%i\n", id, s->t1, s->t2, s->t3);

    return 0;

}


static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    MOVStreamContext *sc;

    unsigned int i, entries;

    if (c->fc->nb_streams < 1)

        return 0;

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

    sc = st->priv_data;

    avio_r8(pb); /* version */

    avio_rb24(pb); /* flags */

    entries = avio_rb32(pb);

    av_dlog(c->fc, "keyframe_count = %d\n", entries);

    if (!entries)

    {

        sc->keyframe_absent = 1;

        if (!st->need_parsing)

            st->need_parsing = AVSTREAM_PARSE_HEADERS;

        return 0;

    }

    if (entries >= UINT_MAX / sizeof(int))

        return AVERROR_INVALIDDATA;

    sc->keyframes = av_malloc(entries * sizeof(int));

    if (!sc->keyframes)

        return AVERROR(ENOMEM);

    for (i = 0; i < entries && !pb->eof_reached; i++) {

        sc->keyframes[i] = avio_rb32(pb);

        //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);

    }

    sc->keyframe_count = i;

    if (pb->eof_reached)

        return AVERROR_EOF;

    return 0;

}


void swr_compensate(struct SwrContext *s, int sample_delta, int compensation_distance){

    ResampleContext *c= s->resample;

//    sample_delta += (c->ideal_dst_incr - c->dst_incr)*(int64_t)c->compensation_distance / c->ideal_dst_incr;

    c->compensation_distance= compensation_distance;

    c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr * (int64_t)sample_delta / compensation_distance;

}


int MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)

{

    int i;

    Picture *pic;

    s->mb_skipped = 0;

    assert(s->last_picture_ptr==NULL || s->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3);

    /* mark&release old frames */

    if (s->pict_type != FF_B_TYPE && s->last_picture_ptr && s->last_picture_ptr != s->next_picture_ptr && s->last_picture_ptr->data[0]) {

      if(s->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3){

          free_frame_buffer(s, s->last_picture_ptr);

        /* release forgotten pictures */

        /* if(mpeg124/h263) */

        if(!s->encoding){

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

                if(s->picture[i].data[0] && &s->picture[i] != s->next_picture_ptr && s->picture[i].reference){

                    av_log(avctx, AV_LOG_ERROR, "releasing zombie picture\n");

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

                }

            }

        }

      }

    }

alloc:

    if(!s->encoding){

        /* release non reference frames */

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

            if(s->picture[i].data[0] && !s->picture[i].reference /*&& s->picture[i].type!=FF_BUFFER_TYPE_SHARED*/){

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

            }

        }

        if(s->current_picture_ptr && s->current_picture_ptr->data[0]==NULL)

            pic= s->current_picture_ptr; //we already have a unused image (maybe it was set before reading the header)

        else{

            i= ff_find_unused_picture(s, 0);

            pic= &s->picture[i];

        }

        pic->reference= 0;

        if (!s->dropable){

            if (s->codec_id == CODEC_ID_H264)

                pic->reference = s->picture_structure;

            else if (s->pict_type != FF_B_TYPE)

                pic->reference = 3;

        }

        pic->coded_picture_number= s->coded_picture_number++;

        if(ff_alloc_picture(s, pic, 0) < 0)

            return -1;

        s->current_picture_ptr= pic;

        s->current_picture_ptr->top_field_first= s->top_field_first; //FIXME use only the vars from current_pic

        s->current_picture_ptr->interlaced_frame= !s->progressive_frame && !s->progressive_sequence;

    }

    s->current_picture_ptr->pict_type= s->pict_type;

//    if(s->flags && CODEC_FLAG_QSCALE)

  //      s->current_picture_ptr->quality= s->new_picture_ptr->quality;

    s->current_picture_ptr->key_frame= s->pict_type == FF_I_TYPE;

    ff_copy_picture(&s->current_picture, s->current_picture_ptr);

    if (s->pict_type != FF_B_TYPE) {

        s->last_picture_ptr= s->next_picture_ptr;

        if(!s->dropable)

            s->next_picture_ptr= s->current_picture_ptr;

    }

/*    av_log(s->avctx, AV_LOG_DEBUG, "L%p N%p C%p L%p N%p C%p type:%d drop:%d\n", s->last_picture_ptr, s->next_picture_ptr,s->current_picture_ptr,

        s->last_picture_ptr    ? s->last_picture_ptr->data[0] : NULL,

        s->next_picture_ptr    ? s->next_picture_ptr->data[0] : NULL,

        s->current_picture_ptr ? s->current_picture_ptr->data[0] : NULL,

        s->pict_type, s->dropable);*/

    if(s->last_picture_ptr) ff_copy_picture(&s->last_picture, s->last_picture_ptr);

    if(s->next_picture_ptr) ff_copy_picture(&s->next_picture, s->next_picture_ptr);

    if(s->pict_type != FF_I_TYPE && (s->last_picture_ptr==NULL || s->last_picture_ptr->data[0]==NULL) && !s->dropable && s->codec_id != CODEC_ID_H264){

        av_log(avctx, AV_LOG_ERROR, "warning: first frame is no keyframe\n");

        assert(s->pict_type != FF_B_TYPE); //these should have been dropped if we don't have a reference

        goto alloc;

    }

    assert(s->pict_type == FF_I_TYPE || (s->last_picture_ptr && s->last_picture_ptr->data[0]));

    if(s->picture_structure!=PICT_FRAME && s->out_format != FMT_H264){

        int i;

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

            if(s->picture_structure == PICT_BOTTOM_FIELD){

                 s->current_picture.data[i] += s->current_picture.linesize[i];

            }

            s->current_picture.linesize[i] *= 2;

            s->last_picture.linesize[i] *=2;

            s->next_picture.linesize[i] *=2;

        }

    }

    s->hurry_up= s->avctx->hurry_up;

    s->error_recognition= avctx->error_recognition;

    /* set dequantizer, we can't do it during init as it might change for mpeg4

       and we can't do it in the header decode as init is not called for mpeg4 there yet */

    if(s->mpeg_quant || s->codec_id == CODEC_ID_MPEG2VIDEO){

        s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra;

        s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter;

    }else if(s->out_format == FMT_H263 || s->out_format == FMT_H261){

        s->dct_unquantize_intra = s->dct_unquantize_h263_intra;

        s->dct_unquantize_inter = s->dct_unquantize_h263_inter;

    }else{

        s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra;

        s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;

    }

    if(s->dct_error_sum){

        assert(s->avctx->noise_reduction && s->encoding);

        update_noise_reduction(s);

    }

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

        return ff_xvmc_field_start(s, avctx);

    return 0;

}


udp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,

           u_int lport, int flags)

{

	struct sockaddr_in addr;

	struct socket *so;

	socklen_t addrlen = sizeof(struct sockaddr_in);

	so = socreate(slirp);

	if (!so) {

	so->s = qemu_socket(AF_INET,SOCK_DGRAM,0);

	so->so_expire = curtime + SO_EXPIRE;

	insque(so, &slirp->udb);

	addr.sin_family = AF_INET;

	addr.sin_addr.s_addr = haddr;

	addr.sin_port = hport;

	if (bind(so->s,(struct sockaddr *)&addr, addrlen) < 0) {

		udp_detach(so);

	socket_set_fast_reuse(so->s);

	getsockname(so->s,(struct sockaddr *)&addr,&addrlen);

	so->fhost.sin = addr;

	sotranslate_accept(so);

	so->so_lfamily = AF_INET;

	so->so_lport = lport;

	so->so_laddr.s_addr = laddr;

	if (flags != SS_FACCEPTONCE)

	   so->so_expire = 0;

	so->so_state &= SS_PERSISTENT_MASK;

	so->so_state |= SS_ISFCONNECTED | flags;

	return so;


static int local_post_create_passthrough(FsContext *fs_ctx, const char *path,

        FsCred *credp)

{

    if (chmod(rpath(fs_ctx, path), credp->fc_mode & 07777) < 0) {

        return -1;

    }

    if (chown(rpath(fs_ctx, path), credp->fc_uid, credp->fc_gid) < 0) {

        return -1;

    }

    return 0;

}


static int piix4_device_hotplug(DeviceState *qdev, PCIDevice *dev,

				PCIHotplugState state)

{

    int slot = PCI_SLOT(dev->devfn);

    PIIX4PMState *s = DO_UPCAST(PIIX4PMState, dev,

                                PCI_DEVICE(qdev));

    /* Don't send event when device is enabled during qemu machine creation:

     * it is present on boot, no hotplug event is necessary. We do send an

     * event when the device is disabled later. */

    if (state == PCI_COLDPLUG_ENABLED) {

        return 0;

    }

    s->pci0_status.up = 0;

    s->pci0_status.down = 0;

    if (state == PCI_HOTPLUG_ENABLED) {

        enable_device(s, slot);

    } else {

        disable_device(s, slot);

    }

    pm_update_sci(s);

    return 0;

}


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

                                int *got_frame_ptr, AVPacket *avpkt)

{

    AVFrame *frame     = data;

    const uint8_t *src = avpkt->data;

    int buf_size       = avpkt->size;

    PCMDVDContext *s   = avctx->priv_data;

    int retval;

    int blocks;

    void *dst;

    if (buf_size < 3) {

        av_log(avctx, AV_LOG_ERROR, "PCM packet too small\n");

        return AVERROR_INVALIDDATA;

    if ((retval = pcm_dvd_parse_header(avctx, src)))

        return retval;

    src      += 3;

    buf_size -= 3;

    blocks = (buf_size + s->extra_sample_count) / s->block_size;

    /* get output buffer */

    frame->nb_samples = blocks * s->samples_per_block;

    if ((retval = ff_get_buffer(avctx, frame, 0)) < 0) {

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

        return retval;

    dst = frame->data[0];

    /* consume leftover samples from last packet */

    if (s->extra_sample_count) {

        int missing_samples = s->block_size - s->extra_sample_count;

        if (buf_size >= missing_samples) {

            memcpy(s->extra_samples + s->extra_sample_count, src,

                   missing_samples);

            dst = pcm_dvd_decode_samples(avctx, s->extra_samples, dst, 1);

            src += missing_samples;

            buf_size -= missing_samples;

            blocks--;

        } else {

            /* new packet still doesn't have enough samples */

            memcpy(s->extra_samples + s->extra_sample_count, src, buf_size);

            s->extra_sample_count += buf_size;

            return avpkt->size;

    /* decode remaining complete samples */

    if (blocks) {

        pcm_dvd_decode_samples(avctx, src, dst, blocks);

        buf_size -= blocks * s->block_size;

    /* store leftover samples */

    if (buf_size) {

        src += blocks * s->block_size;

        memcpy(s->extra_samples, src, buf_size);

        s->extra_sample_count = buf_size;

    *got_frame_ptr = 1;

    return avpkt->size;


void qmp_migrate_set_cache_size(int64_t value, Error **errp)

{

    MigrationState *s = migrate_get_current();

    int64_t new_size;

    /* Check for truncation */

    if (value != (size_t)value) {

        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",

                  "exceeding address space");

        return;

    }

    /* Cache should not be larger than guest ram size */

    if (value > ram_bytes_total()) {

        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",

                  "exceeds guest ram size ");

        return;

    }

    new_size = xbzrle_cache_resize(value);

    if (new_size < 0) {

        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",

                  "is smaller than page size");

        return;

    }

    s->xbzrle_cache_size = new_size;

}


static inline void ls_decode_line(JLSState *state, MJpegDecodeContext *s,

                                  void *last, void *dst, int last2, int w,

                                  int stride, int comp, int bits)

{

    int i, x = 0;

    int Ra, Rb, Rc, Rd;

    int D0, D1, D2;

    while (x < w) {

        int err, pred;

        /* compute gradients */

        Ra = x ? R(dst, x - stride) : R(last, x);

        Rb = R(last, x);

        Rc = x ? R(last, x - stride) : last2;

        Rd = (x >= w - stride) ? R(last, x) : R(last, x + stride);

        D0 = Rd - Rb;

        D1 = Rb - Rc;

        D2 = Rc - Ra;

        /* run mode */

        if ((FFABS(D0) <= state->near) &&

            (FFABS(D1) <= state->near) &&

            (FFABS(D2) <= state->near)) {

            int r;

            int RItype;

            /* decode full runs while available */

            while (get_bits1(&s->gb)) {

                int r;

                r = 1 << ff_log2_run[state->run_index[comp]];

                if (x + r * stride > w)

                    r = (w - x) / stride;

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

                    W(dst, x, Ra);

                    x += stride;

                }

                /* if EOL reached, we stop decoding */

                if (r != 1 << ff_log2_run[state->run_index[comp]])

                    return;

                if (state->run_index[comp] < 31)

                    state->run_index[comp]++;

                if (x + stride > w)

                    return;

            }

            /* decode aborted run */

            r = ff_log2_run[state->run_index[comp]];

            if (r)

                r = get_bits_long(&s->gb, r);

            if (x + r * stride > w) {

                r = (w - x) / stride;

            }

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

                W(dst, x, Ra);

                x += stride;

            }

            if (x >= w) {

                av_log(NULL, AV_LOG_ERROR, "run overflow\n");

                return;

            }

            /* decode run termination value */

            Rb     = R(last, x);

            RItype = (FFABS(Ra - Rb) <= state->near) ? 1 : 0;

            err    = ls_get_code_runterm(&s->gb, state, RItype,

                                         ff_log2_run[state->run_index[comp]]);

            if (state->run_index[comp])

                state->run_index[comp]--;

            if (state->near && RItype) {

                pred = Ra + err;

            } else {

                if (Rb < Ra)

                    pred = Rb - err;

                else

                    pred = Rb + err;

            }

        } else { /* regular mode */

            int context, sign;

            context = ff_jpegls_quantize(state, D0) * 81 +

                      ff_jpegls_quantize(state, D1) *  9 +

                      ff_jpegls_quantize(state, D2);

            pred    = mid_pred(Ra, Ra + Rb - Rc, Rb);

            if (context < 0) {

                context = -context;

                sign    = 1;

            } else {

                sign = 0;

            }

            if (sign) {

                pred = av_clip(pred - state->C[context], 0, state->maxval);

                err  = -ls_get_code_regular(&s->gb, state, context);

            } else {

                pred = av_clip(pred + state->C[context], 0, state->maxval);

                err  = ls_get_code_regular(&s->gb, state, context);

            }

            /* we have to do something more for near-lossless coding */

            pred += err;

        }

        if (state->near) {

            if (pred < -state->near)

                pred += state->range * state->twonear;

            else if (pred > state->maxval + state->near)

                pred -= state->range * state->twonear;

            pred = av_clip(pred, 0, state->maxval);

        }

        pred &= state->maxval;

        W(dst, x, pred);

        x += stride;

    }

}


static void do_video_out(AVFormatContext *s,

                         OutputStream *ost,

                         AVFrame *in_picture,

                         float quality)

{

    int ret, format_video_sync;

    AVPacket pkt;

    AVCodecContext *enc = ost->st->codec;

    int nb_frames;

    double sync_ipts, delta;

    double duration = 0;

    int frame_size = 0;

    InputStream *ist = NULL;

    if (ost->source_index >= 0)

        ist = input_streams[ost->source_index];

    if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)

        duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));

    sync_ipts = in_picture->pts;

    delta = sync_ipts - ost->sync_opts + duration;

    /* by default, we output a single frame */

    nb_frames = 1;

    format_video_sync = video_sync_method;

    if (format_video_sync == VSYNC_AUTO)

        format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;

    switch (format_video_sync) {

    case VSYNC_CFR:

        // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c

        if (delta < -1.1)

            nb_frames = 0;

        else if (delta > 1.1)

            nb_frames = lrintf(delta);

        break;

    case VSYNC_VFR:

        if (delta <= -0.6)

            nb_frames = 0;

        else if (delta > 0.6)

            ost->sync_opts = lrint(sync_ipts);

        break;

    case VSYNC_DROP:

    case VSYNC_PASSTHROUGH:

        ost->sync_opts = lrint(sync_ipts);

        break;

    default:

        av_assert0(0);

    }

    nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);

    if (nb_frames == 0) {

        nb_frames_drop++;

        av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");

        return;

    } else if (nb_frames > 1) {

        if (nb_frames > dts_error_threshold * 30) {

            av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skiping\n", nb_frames - 1);

            nb_frames_drop++;

            return;

        }

        nb_frames_dup += nb_frames - 1;

        av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);

    }

duplicate_frame:

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

    in_picture->pts = ost->sync_opts;

    if (!check_recording_time(ost))

        return;

    if (s->oformat->flags & AVFMT_RAWPICTURE &&

        enc->codec->id == CODEC_ID_RAWVIDEO) {

        /* raw pictures are written as AVPicture structure to

           avoid any copies. We support temporarily the older

           method. */

        enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;

        enc->coded_frame->top_field_first  = in_picture->top_field_first;

        pkt.data   = (uint8_t *)in_picture;

        pkt.size   =  sizeof(AVPicture);

        pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);

        pkt.flags |= AV_PKT_FLAG_KEY;

        write_frame(s, &pkt, ost);

        video_size += pkt.size;

    } else {

        int got_packet;

        AVFrame big_picture;

        big_picture = *in_picture;

        /* better than nothing: use input picture interlaced

           settings */

        big_picture.interlaced_frame = in_picture->interlaced_frame;

        if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {

            if (ost->top_field_first == -1)

                big_picture.top_field_first = in_picture->top_field_first;

            else

                big_picture.top_field_first = !!ost->top_field_first;

        }

        /* handles same_quant here. This is not correct because it may

           not be a global option */

        big_picture.quality = quality;

        if (!enc->me_threshold)

            big_picture.pict_type = 0;

        if (ost->forced_kf_index < ost->forced_kf_count &&

            big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {

            big_picture.pict_type = AV_PICTURE_TYPE_I;

            ost->forced_kf_index++;

        }

        update_benchmark(NULL);

        ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);

        update_benchmark("encode_video %d.%d", ost->file_index, ost->index);

        if (ret < 0) {

            av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");

            exit_program(1);

        }

        if (got_packet) {

            if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))

                pkt.pts = ost->sync_opts;

            if (pkt.pts != AV_NOPTS_VALUE)

                pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);

            if (pkt.dts != AV_NOPTS_VALUE)

                pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);

            if (debug_ts) {

                av_log(NULL, AV_LOG_INFO, "encoder -> type:video "

                    "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",

                    av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),

                    av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));

            }

            write_frame(s, &pkt, ost);

            frame_size = pkt.size;

            video_size += pkt.size;

            av_free_packet(&pkt);

            /* if two pass, output log */

            if (ost->logfile && enc->stats_out) {

                fprintf(ost->logfile, "%s", enc->stats_out);

            }

        }

    }

    ost->sync_opts++;

    /*

     * For video, number of frames in == number of packets out.

     * But there may be reordering, so we can't throw away frames on encoder

     * flush, we need to limit them here, before they go into encoder.

     */

    ost->frame_number++;

    if(--nb_frames)

        goto duplicate_frame;

    if (vstats_filename && frame_size)

        do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);

}


int opt_loglevel(void *optctx, const char *opt, const char *arg)

{

    const struct { const char *name; int level; } log_levels[] = {

        { "quiet"  , AV_LOG_QUIET   },

        { "panic"  , AV_LOG_PANIC   },

        { "fatal"  , AV_LOG_FATAL   },

        { "error"  , AV_LOG_ERROR   },

        { "warning", AV_LOG_WARNING },

        { "info"   , AV_LOG_INFO    },

        { "verbose", AV_LOG_VERBOSE },

        { "debug"  , AV_LOG_DEBUG   },

    };

    char *tail;

    int level;

    int i;

    for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {

        if (!strcmp(log_levels[i].name, arg)) {

            av_log_set_level(log_levels[i].level);

            return 0;

        }

    }

    level = strtol(arg, &tail, 10);

    if (*tail) {

        av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "

               "Possible levels are numbers or:\n", arg);

        for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)

            av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);

        exit(1);

    }

    av_log_set_level(level);

    return 0;

}


static void ram_save_cleanup(void *opaque)

{

    RAMState **rsp = opaque;

    RAMBlock *block;

    /* caller have hold iothread lock or is in a bh, so there is

     * no writing race against this migration_bitmap

     */

    memory_global_dirty_log_stop();

    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {

        g_free(block->bmap);

        block->bmap = NULL;

        g_free(block->unsentmap);

        block->unsentmap = NULL;

    }

    XBZRLE_cache_lock();

    if (XBZRLE.cache) {

        cache_fini(XBZRLE.cache);

        g_free(XBZRLE.encoded_buf);

        g_free(XBZRLE.current_buf);

        g_free(XBZRLE.zero_target_page);

        XBZRLE.cache = NULL;

        XBZRLE.encoded_buf = NULL;

        XBZRLE.current_buf = NULL;

        XBZRLE.zero_target_page = NULL;

    }

    XBZRLE_cache_unlock();

    compress_threads_save_cleanup();

    ram_state_cleanup(rsp);

}


const AVOption *av_opt_next(void *obj, const AVOption *last)

{

    AVClass *class = *(AVClass**)obj;

    if (!last && class->option && class->option[0].name)

        return class->option;

    if (last && last[1].name)

        return ++last;

    return NULL;

}


int avfilter_graph_create_filter(AVFilterContext **filt_ctx, AVFilter *filt,

                                 const char *name, const char *args, void *opaque,

                                 AVFilterGraph *graph_ctx)

{

    int ret;

    *filt_ctx = avfilter_graph_alloc_filter(graph_ctx, filt, name);

    if (!*filt_ctx)

        return AVERROR(ENOMEM);

    ret = avfilter_init_filter(*filt_ctx, args, opaque);

    if (ret < 0)

        goto fail;

    return 0;

fail:

    if (*filt_ctx)

        avfilter_free(*filt_ctx);

    *filt_ctx = NULL;

    return ret;

}


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

{

    DeviceClass *dc = DEVICE_CLASS (klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS (klass);

    k->realize = es1370_realize;

    k->vendor_id = PCI_VENDOR_ID_ENSONIQ;

    k->device_id = PCI_DEVICE_ID_ENSONIQ_ES1370;

    k->class_id = PCI_CLASS_MULTIMEDIA_AUDIO;

    k->subsystem_vendor_id = 0x4942;

    k->subsystem_id = 0x4c4c;

    set_bit(DEVICE_CATEGORY_SOUND, dc->categories);

    dc->desc = "ENSONIQ AudioPCI ES1370";

    dc->vmsd = &vmstate_es1370;

}


static inline int64_t add64(const int64_t a, const int64_t b)

{

	return a + b;

}


static void slavio_timer_init_all(target_phys_addr_t addr, qemu_irq master_irq,

                                  qemu_irq *cpu_irqs, unsigned int num_cpus)

{

    DeviceState *dev;

    SysBusDevice *s;

    unsigned int i;

    dev = qdev_create(NULL, "slavio_timer");

    qdev_prop_set_uint32(dev, "num_cpus", num_cpus);

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    sysbus_connect_irq(s, 0, master_irq);

    sysbus_mmio_map(s, 0, addr + SYS_TIMER_OFFSET);

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

        sysbus_mmio_map(s, i + 1, addr + (target_phys_addr_t)CPU_TIMER_OFFSET(i));

        sysbus_connect_irq(s, i + 1, cpu_irqs[i]);

    }

}


int ff_pred_weight_table(H264Context *h)
{
    int list, i;
    int luma_def, chroma_def;
    h->use_weight             = 0;
    h->use_weight_chroma      = 0;
    h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
    if (h->sps.chroma_format_idc)
        h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
    luma_def   = 1 << h->luma_log2_weight_denom;
    chroma_def = 1 << h->chroma_log2_weight_denom;
    for (list = 0; list < 2; list++) {
        h->luma_weight_flag[list]   = 0;
        h->chroma_weight_flag[list] = 0;
        for (i = 0; i < h->ref_count[list]; i++) {
            int luma_weight_flag, chroma_weight_flag;
            luma_weight_flag = get_bits1(&h->gb);
            if (luma_weight_flag) {
                h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
                h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
                if (h->luma_weight[i][list][0] != luma_def ||
                    h->luma_weight[i][list][1] != 0) {
                    h->use_weight             = 1;
                    h->luma_weight_flag[list] = 1;
            } else {
                h->luma_weight[i][list][0] = luma_def;
                h->luma_weight[i][list][1] = 0;
            if (h->sps.chroma_format_idc) {
                chroma_weight_flag = get_bits1(&h->gb);
                if (chroma_weight_flag) {
                    int j;
                    for (j = 0; j < 2; j++) {
                        h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
                        h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
                        if (h->chroma_weight[i][list][j][0] != chroma_def ||
                            h->chroma_weight[i][list][j][1] != 0) {
                            h->use_weight_chroma        = 1;
                            h->chroma_weight_flag[list] = 1;
                } else {
                    int j;
                    for (j = 0; j < 2; j++) {
                        h->chroma_weight[i][list][j][0] = chroma_def;
                        h->chroma_weight[i][list][j][1] = 0;
        if (h->slice_type_nos != AV_PICTURE_TYPE_B)
            break;
    h->use_weight = h->use_weight || h->use_weight_chroma;
    return 0;


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

                             int *got_output, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    Mpeg1Context *s = avctx->priv_data;

    AVFrame *picture = data;

    MpegEncContext *s2 = &s->mpeg_enc_ctx;

    av_dlog(avctx, "fill_buffer\n");

    if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) {

        /* special case for last picture */

        if (s2->low_delay == 0 && s2->next_picture_ptr) {

            int ret = av_frame_ref(picture, &s2->next_picture_ptr->f);

            if (ret < 0)

                return ret;

            s2->next_picture_ptr = NULL;

            *got_output = 1;

        }

        return buf_size;

    }

    if (s2->flags & CODEC_FLAG_TRUNCATED) {

        int next = ff_mpeg1_find_frame_end(&s2->parse_context, buf,

                                           buf_size, NULL);

        if (ff_combine_frame(&s2->parse_context, next,

                             (const uint8_t **) &buf, &buf_size) < 0)

            return buf_size;

    }

    if (s->mpeg_enc_ctx_allocated == 0 && avctx->codec_tag == AV_RL32("VCR2"))

        vcr2_init_sequence(avctx);

    s->slice_count = 0;

    if (avctx->extradata && !s->extradata_decoded) {

        int ret = decode_chunks(avctx, picture, got_output,

                                avctx->extradata, avctx->extradata_size);

        s->extradata_decoded = 1;

        if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))

            return ret;

    }

    return decode_chunks(avctx, picture, got_output, buf, buf_size);

}


static void blur(CoverContext *cover, AVFrame *in, int offx, int offy)

{

    int x, y, p;

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

        int ox = offx>>!!p;

        int oy = offy>>!!p;

        int stride = in->linesize[p];

        uint8_t *data = in->data[p] + ox + oy * stride;

        int w = FF_CEIL_RSHIFT(cover->width , !!p);

        int h = FF_CEIL_RSHIFT(cover->height, !!p);

        int iw = FF_CEIL_RSHIFT(in->width , !!p);

        int ih = FF_CEIL_RSHIFT(in->height, !!p);

        for (y = 0; y < h; y++) {

            for (x = 0; x < w; x++) {

                int c = 0;

                int s = 0;

                if (ox) {

                    int scale = 65536 / (x + 1);

                    s += data[-1 + y*stride] * scale;

                    c += scale;

                }

                if (oy) {

                    int scale = 65536 / (y + 1);

                    s += data[x - stride] * scale;

                    c += scale;

                }

                if (ox + w < iw) {

                    int scale = 65536 / (w - x);

                    s += data[w + y*stride] * scale;

                    c += scale;

                }

                if (oy + h < ih) {

                    int scale = 65536 / (h - y);

                    s += data[x + h*stride] * scale;

                    c += scale;

                }

                data[x + y*stride] = (s + (c>>1)) / c;

            }

        }

    }

}


static int wav_read_header(AVFormatContext *s)
{
    int64_t size, av_uninit(data_size);
    int64_t sample_count = 0;
    int rf64 = 0;
    char start_code[32];
    uint32_t tag;
    AVIOContext *pb      = s->pb;
    AVStream *st         = NULL;
    WAVDemuxContext *wav = s->priv_data;
    int ret, got_fmt = 0;
    int64_t next_tag_ofs, data_ofs = -1;
    wav->unaligned = avio_tell(s->pb) & 1;
    wav->smv_data_ofs = -1;
    /* read chunk ID */
    tag = avio_rl32(pb);
    switch (tag) {
    case MKTAG('R', 'I', 'F', 'F'):
        break;
    case MKTAG('R', 'I', 'F', 'X'):
        wav->rifx = 1;
        break;
    case MKTAG('R', 'F', '6', '4'):
        rf64 = 1;
        break;
    default:
        av_get_codec_tag_string(start_code, sizeof(start_code), tag);
        av_log(s, AV_LOG_ERROR, "invalid start code %s in RIFF header\n", start_code);
        return AVERROR_INVALIDDATA;
    /* read chunk size */
    avio_rl32(pb);
    /* read format */
    if (avio_rl32(pb) != MKTAG('W', 'A', 'V', 'E')) {
        av_log(s, AV_LOG_ERROR, "invalid format in RIFF header\n");
        return AVERROR_INVALIDDATA;
    if (rf64) {
        if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
            return AVERROR_INVALIDDATA;
        size = avio_rl32(pb);
        if (size < 24)
            return AVERROR_INVALIDDATA;
        avio_rl64(pb); /* RIFF size */
        data_size    = avio_rl64(pb);
        sample_count = avio_rl64(pb);
        if (data_size < 0 || sample_count < 0) {
            av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
                   "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
                   data_size, sample_count);
            return AVERROR_INVALIDDATA;
        avio_skip(pb, size - 24); /* skip rest of ds64 chunk */
    for (;;) {
        AVStream *vst;
        size         = next_tag(pb, &tag, wav->rifx);
        next_tag_ofs = avio_tell(pb) + size;
        if (avio_feof(pb))
            break;
        switch (tag) {
        case MKTAG('f', 'm', 't', ' '):
            /* only parse the first 'fmt ' tag found */
            if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {
                return ret;
            } else if (got_fmt)
                av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
            got_fmt = 1;
            break;
        case MKTAG('d', 'a', 't', 'a'):
            if (!got_fmt) {
                av_log(s, AV_LOG_ERROR,
                       "found no 'fmt ' tag before the 'data' tag\n");
                return AVERROR_INVALIDDATA;
            if (rf64) {
                next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
            } else if (size != 0xFFFFFFFF) {
                data_size    = size;
                next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
            } else {
                av_log(s, AV_LOG_WARNING, "Ignoring maximum wav data size, "
                       "file may be invalid\n");
                data_size    = 0;
                next_tag_ofs = wav->data_end = INT64_MAX;
            data_ofs = avio_tell(pb);
            /* don't look for footer metadata if we can't seek or if we don't
             * know where the data tag ends
             */
            if (!pb->seekable || (!rf64 && !size))
                goto break_loop;
            break;
        case MKTAG('f', 'a', 'c', 't'):
            if (!sample_count)
                sample_count = (!wav->rifx ? avio_rl32(pb) : avio_rb32(pb));
            break;
        case MKTAG('b', 'e', 'x', 't'):
            if ((ret = wav_parse_bext_tag(s, size)) < 0)
                return ret;
            break;
        case MKTAG('S','M','V','0'):
            if (!got_fmt) {
                av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'SMV0' tag\n");
                return AVERROR_INVALIDDATA;
            // SMV file, a wav file with video appended.
            if (size != MKTAG('0','2','0','0')) {
                av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");
                goto break_loop;
            av_log(s, AV_LOG_DEBUG, "Found SMV data\n");
            wav->smv_given_first = 0;
            vst = avformat_new_stream(s, NULL);
            if (!vst)
                return AVERROR(ENOMEM);
            avio_r8(pb);
            vst->id = 1;
            vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
            vst->codec->codec_id = AV_CODEC_ID_SMVJPEG;
            vst->codec->width  = avio_rl24(pb);
            vst->codec->height = avio_rl24(pb);
            if (ff_alloc_extradata(vst->codec, 4)) {
                av_log(s, AV_LOG_ERROR, "Could not allocate extradata.\n");
                return AVERROR(ENOMEM);
            size = avio_rl24(pb);
            wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;
            avio_rl24(pb);
            wav->smv_block_size = avio_rl24(pb);
            avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));
            vst->duration = avio_rl24(pb);
            avio_rl24(pb);
            avio_rl24(pb);
            wav->smv_frames_per_jpeg = avio_rl24(pb);
            if (wav->smv_frames_per_jpeg > 65536) {
                av_log(s, AV_LOG_ERROR, "too many frames per jpeg\n");
                return AVERROR_INVALIDDATA;
            AV_WL32(vst->codec->extradata, wav->smv_frames_per_jpeg);
            wav->smv_cur_pt = 0;
            goto break_loop;
        case MKTAG('L', 'I', 'S', 'T'):
            if (size < 4) {
                av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
                return AVERROR_INVALIDDATA;
            switch (avio_rl32(pb)) {
            case MKTAG('I', 'N', 'F', 'O'):
                ff_read_riff_info(s, size - 4);
            break;
        /* seek to next tag unless we know that we'll run into EOF */
        if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
            wav_seek_tag(wav, pb, next_tag_ofs, SEEK_SET) < 0) {
            break;
break_loop:
    if (data_ofs < 0) {
        av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
        return AVERROR_INVALIDDATA;
    avio_seek(pb, data_ofs, SEEK_SET);
    if (   data_size > 0 && sample_count && st->codec->channels
        && (data_size << 3) / sample_count / st->codec->channels > st->codec->bits_per_coded_sample) {
        av_log(s, AV_LOG_WARNING, "ignoring wrong sample_count %"PRId64"\n", sample_count);
        sample_count = 0;
    if (!sample_count || av_get_exact_bits_per_sample(st->codec->codec_id) > 0)
        if (   st->codec->channels
            && data_size
            && av_get_bits_per_sample(st->codec->codec_id)
            && wav->data_end <= avio_size(pb))
            sample_count = (data_size << 3)
                                  /
                (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
    if (sample_count)
        st->duration = sample_count;
    ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
    ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
    return 0;


static int parse_bsfs(void *log_ctx, const char *bsfs_spec,

                      AVBitStreamFilterContext **bsfs)

{

    char *bsf_name, *buf, *saveptr;

    int ret = 0;

    if (!(buf = av_strdup(bsfs_spec)))

        return AVERROR(ENOMEM);

    while (bsf_name = av_strtok(buf, ",", &saveptr)) {

        AVBitStreamFilterContext *bsf = av_bitstream_filter_init(bsf_name);

        if (!bsf) {

            av_log(log_ctx, AV_LOG_ERROR,

                   "Cannot initialize bitstream filter with name '%s', "

                   "unknown filter or internal error happened\n",

                   bsf_name);

            ret = AVERROR_UNKNOWN;

            goto end;

        }

        /* append bsf context to the list of bsf contexts */

        *bsfs = bsf;

        bsfs = &bsf->next;

        buf = NULL;

    }

end:

    av_free(buf);

    return ret;

}


void ff_ivi_output_plane(IVIPlaneDesc *plane, uint8_t *dst, int dst_pitch)
{
    int             x, y;
    const int16_t   *src  = plane->bands[0].buf;
    uint32_t        pitch = plane->bands[0].pitch;
    for (y = 0; y < plane->height; y++) {
        for (x = 0; x < plane->width; x++)
            dst[x] = av_clip_uint8(src[x] + 128);
        src += pitch;
        dst += dst_pitch;
    }
}


static void secondary_do_checkpoint(BDRVReplicationState *s, Error **errp)
{
    Error *local_err = NULL;
    int ret;
    if (!s->secondary_disk->bs->job) {
        error_setg(errp, "Backup job was cancelled unexpectedly");
    backup_do_checkpoint(s->secondary_disk->bs->job, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
    ret = s->active_disk->bs->drv->bdrv_make_empty(s->active_disk->bs);
    if (ret < 0) {
        error_setg(errp, "Cannot make active disk empty");
    ret = s->hidden_disk->bs->drv->bdrv_make_empty(s->hidden_disk->bs);
    if (ret < 0) {
        error_setg(errp, "Cannot make hidden disk empty");


static void vnc_dpy_update(DisplayChangeListener *dcl,

                           DisplayState *ds,

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

{

    int i;

    VncDisplay *vd = ds->opaque;

    struct VncSurface *s = &vd->guest;

    int width = ds_get_width(ds);

    int height = ds_get_height(ds);

    h += y;

    /* round x down to ensure the loop only spans one 16-pixel block per,

       iteration.  otherwise, if (x % 16) != 0, the last iteration may span

       two 16-pixel blocks but we only mark the first as dirty

    */

    w += (x % 16);

    x -= (x % 16);

    x = MIN(x, width);

    y = MIN(y, height);

    w = MIN(x + w, width) - x;

    h = MIN(h, height);

    for (; y < h; y++)

        for (i = 0; i < w; i += 16)

            set_bit((x + i) / 16, s->dirty[y]);

}


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

{

    int nr_iov, c;

    struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);

    ctx->blk = blk;

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

        switch (c) {

        case 'C':

            ctx->Cflag = 1;

            break;

        case 'P':

            ctx->Pflag = 1;

            ctx->pattern = parse_pattern(optarg);

            if (ctx->pattern < 0) {

                g_free(ctx);

                return 0;

            }

            break;

        case 'q':

            ctx->qflag = 1;

            break;

        case 'v':

            ctx->vflag = 1;

            break;

        default:

            g_free(ctx);

            return qemuio_command_usage(&aio_read_cmd);

        }

    }

    if (optind > argc - 2) {

        g_free(ctx);

        return qemuio_command_usage(&aio_read_cmd);

    }

    ctx->offset = cvtnum(argv[optind]);

    if (ctx->offset < 0) {

        print_cvtnum_err(ctx->offset, argv[optind]);

        g_free(ctx);

        return 0;

    }

    optind++;

    if (ctx->offset & 0x1ff) {

        printf("offset %" PRId64 " is not sector aligned\n",

               ctx->offset);

        g_free(ctx);

        return 0;

    }

    nr_iov = argc - optind;

    ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov, 0xab);

    if (ctx->buf == NULL) {

        g_free(ctx);

        return 0;

    }

    gettimeofday(&ctx->t1, NULL);

    block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,

                     BLOCK_ACCT_READ);

    blk_aio_readv(blk, ctx->offset >> 9, &ctx->qiov,

                  ctx->qiov.size >> 9, aio_read_done, ctx);

    return 0;

}


static int ff_estimate_motion_b(MpegEncContext * s,

                       int mb_x, int mb_y, int16_t (*mv_table)[2], int ref_index, int f_code)

{

    MotionEstContext * const c= &s->me;

    int mx, my, dmin;

    int P[10][2];

    const int shift= 1+s->quarter_sample;

    const int mot_stride = s->mb_stride;

    const int mot_xy = mb_y*mot_stride + mb_x;

    uint8_t * const mv_penalty= c->mv_penalty[f_code] + MAX_MV;

    int mv_scale;

    c->penalty_factor    = get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_cmp);

    c->sub_penalty_factor= get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_sub_cmp);

    c->mb_penalty_factor = get_penalty_factor(s->lambda, s->lambda2, c->avctx->mb_cmp);

    c->current_mv_penalty= mv_penalty;

    get_limits(s, 16*mb_x, 16*mb_y);

    switch(s->me_method) {

    case ME_ZERO:

    default:

	no_motion_search(s, &mx, &my);

        dmin = 0;

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

#if 0

    case ME_FULL:

	dmin = full_motion_search(s, &mx, &my, range, ref_picture);

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

    case ME_LOG:

	dmin = log_motion_search(s, &mx, &my, range / 2, ref_picture);

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

    case ME_PHODS:

	dmin = phods_motion_search(s, &mx, &my, range / 2, ref_picture);

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

#endif

    case ME_X1:

    case ME_EPZS:

       {

            P_LEFT[0]        = mv_table[mot_xy - 1][0];

            P_LEFT[1]        = mv_table[mot_xy - 1][1];

            if(P_LEFT[0]       > (c->xmax<<shift)) P_LEFT[0]       = (c->xmax<<shift);

            /* special case for first line */

            if (!s->first_slice_line) {

                P_TOP[0] = mv_table[mot_xy - mot_stride             ][0];

                P_TOP[1] = mv_table[mot_xy - mot_stride             ][1];

                P_TOPRIGHT[0] = mv_table[mot_xy - mot_stride + 1         ][0];

                P_TOPRIGHT[1] = mv_table[mot_xy - mot_stride + 1         ][1];

                if(P_TOP[1] > (c->ymax<<shift)) P_TOP[1]= (c->ymax<<shift);

                if(P_TOPRIGHT[0] < (c->xmin<<shift)) P_TOPRIGHT[0]= (c->xmin<<shift);

                if(P_TOPRIGHT[1] > (c->ymax<<shift)) P_TOPRIGHT[1]= (c->ymax<<shift);

                P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);

                P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);

            }

            c->pred_x= P_LEFT[0];

            c->pred_y= P_LEFT[1];

        }

        if(mv_table == s->b_forw_mv_table){

            mv_scale= (s->pb_time<<16) / (s->pp_time<<shift);

        }else{

            mv_scale= ((s->pb_time - s->pp_time)<<16) / (s->pp_time<<shift);

        }

        dmin = ff_epzs_motion_search(s, &mx, &my, P, 0, ref_index, s->p_mv_table, mv_scale, 0, 16);

        break;

    }

    dmin= c->sub_motion_search(s, &mx, &my, dmin, 0, ref_index, 0, 16);

    if(c->avctx->me_sub_cmp != c->avctx->mb_cmp && !c->skip)

        dmin= get_mb_score(s, mx, my, 0, ref_index);

//printf("%d %d %d %d//", s->mb_x, s->mb_y, mx, my);

//    s->mb_type[mb_y*s->mb_width + mb_x]= mb_type;

    mv_table[mot_xy][0]= mx;

    mv_table[mot_xy][1]= my;

    return dmin;

}


static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,

        uint64_t *l2_table, uint64_t stop_flags)

{

    int i;

    uint64_t mask = stop_flags | L2E_OFFSET_MASK | QCOW2_CLUSTER_COMPRESSED;

    uint64_t first_entry = be64_to_cpu(l2_table[0]);

    uint64_t offset = first_entry & mask;

    if (!offset)

        return 0;

    assert(qcow2_get_cluster_type(first_entry) != QCOW2_CLUSTER_COMPRESSED);

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

        uint64_t l2_entry = be64_to_cpu(l2_table[i]) & mask;

        if (offset + (uint64_t) i * cluster_size != l2_entry) {

            break;

        }

    }

	return i;

}


AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)

{

    PCIBus *bus = PCI_BUS(dev->bus);

    if (bus->iommu_fn) {

        return bus->iommu_fn(bus, bus->iommu_opaque, dev->devfn);

    }

    if (bus->parent_dev) {

        /** We are ignoring the bus master DMA bit of the bridge

         *  as it would complicate things such as VFIO for no good reason */

        return pci_device_iommu_address_space(bus->parent_dev);

    }

    return &address_space_memory;

}


static int vc1_decode_b_mb_intfr(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    GetBitContext *gb = &s->gb;

    int i, j;

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

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

    int mqdiff, mquant; /* MB quantization */

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

    int mvsw = 0; /* motion vector switch */

    int mb_has_coeffs = 1; /* last_flag */

    int dmv_x, dmv_y; /* Differential MV components */

    int val; /* temp value */

    int first_block = 1;

    int dst_idx, off;

    int skipped, direct, twomv = 0;

    int block_cbp = 0, pat, block_tt = 0;

    int idx_mbmode = 0, mvbp;

    int stride_y, fieldtx;

    int bmvtype = BMV_TYPE_BACKWARD;

    int dir, dir2;

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

    s->mb_intra = 0;

    if (v->skip_is_raw)

        skipped = get_bits1(gb);

    else

        skipped = v->s.mbskip_table[mb_pos];

    if (!skipped) {

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

        if (ff_vc1_mbmode_intfrp[0][idx_mbmode][0] == MV_PMODE_INTFR_2MV_FIELD) {

            twomv = 1;

            v->blk_mv_type[s->block_index[0]] = 1;

            v->blk_mv_type[s->block_index[1]] = 1;

            v->blk_mv_type[s->block_index[2]] = 1;

            v->blk_mv_type[s->block_index[3]] = 1;

        } else {

            v->blk_mv_type[s->block_index[0]] = 0;

            v->blk_mv_type[s->block_index[1]] = 0;

            v->blk_mv_type[s->block_index[2]] = 0;

            v->blk_mv_type[s->block_index[3]] = 0;

        }

    }

    if (v->dmb_is_raw)

        direct = get_bits1(gb);

    else

        direct = v->direct_mb_plane[mb_pos];

    if (direct) {

        s->mv[0][0][0] = s->current_picture.motion_val[0][s->block_index[0]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][0], v->bfraction, 0, s->quarter_sample);

        s->mv[0][0][1] = s->current_picture.motion_val[0][s->block_index[0]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][1], v->bfraction, 0, s->quarter_sample);

        s->mv[1][0][0] = s->current_picture.motion_val[1][s->block_index[0]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][0], v->bfraction, 1, s->quarter_sample);

        s->mv[1][0][1] = s->current_picture.motion_val[1][s->block_index[0]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][1], v->bfraction, 1, s->quarter_sample);

        if (twomv) {

            s->mv[0][2][0] = s->current_picture.motion_val[0][s->block_index[2]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][0], v->bfraction, 0, s->quarter_sample);

            s->mv[0][2][1] = s->current_picture.motion_val[0][s->block_index[2]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][1], v->bfraction, 0, s->quarter_sample);

            s->mv[1][2][0] = s->current_picture.motion_val[1][s->block_index[2]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][0], v->bfraction, 1, s->quarter_sample);

            s->mv[1][2][1] = s->current_picture.motion_val[1][s->block_index[2]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][1], v->bfraction, 1, s->quarter_sample);

            for (i = 1; i < 4; i += 2) {

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

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

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

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

            }

        } else {

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

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

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

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

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

            }

        }

    }

    if (ff_vc1_mbmode_intfrp[0][idx_mbmode][0] == MV_PMODE_INTFR_INTRA) { // intra MB

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

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

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

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

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

        }

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

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

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

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

        fieldtx = v->fieldtx_plane[mb_pos] = get_bits1(gb);

        mb_has_coeffs = get_bits1(gb);

        if (mb_has_coeffs)

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

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

        GET_MQUANT();

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

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

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

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

        dst_idx = 0;

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

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

            dst_idx += i >> 2;

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

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

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

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

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

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

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

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

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

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

                continue;

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

            if (i < 4) {

                stride_y = s->linesize << fieldtx;

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

            } else {

                stride_y = s->uvlinesize;

                off = 0;

            }

            s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, stride_y);

        }

    } else {

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

        if (!direct) {

            if (skipped || !s->mb_intra) {

                bmvtype = decode012(gb);

                switch (bmvtype) {

                case 0:

                    bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_BACKWARD : BMV_TYPE_FORWARD;

                    break;

                case 1:

                    bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_FORWARD : BMV_TYPE_BACKWARD;

                    break;

                case 2:

                    bmvtype  = BMV_TYPE_INTERPOLATED;

                }

            }

            if (twomv && bmvtype != BMV_TYPE_INTERPOLATED)

                mvsw = get_bits1(gb);

        }

        if (!skipped) { // inter MB

            mb_has_coeffs = ff_vc1_mbmode_intfrp[0][idx_mbmode][3];

            if (mb_has_coeffs)

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

            if (!direct) {

                if (bmvtype == BMV_TYPE_INTERPOLATED && twomv) {

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

                } else if (bmvtype == BMV_TYPE_INTERPOLATED || twomv) {

                    v->twomvbp = get_vlc2(gb, v->twomvbp_vlc->table, VC1_2MV_BLOCK_PATTERN_VLC_BITS, 1);

                }

            }

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

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

            fieldtx = v->fieldtx_plane[mb_pos] = ff_vc1_mbmode_intfrp[0][idx_mbmode][1];

            /* for all motion vector read MVDATA and motion compensate each block */

            dst_idx = 0;

            if (direct) {

                if (twomv) {

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

                        vc1_mc_4mv_luma(v, i, 0, 0);

                        vc1_mc_4mv_luma(v, i, 1, 1);

                    }

                    vc1_mc_4mv_chroma4(v, 0, 0, 0);

                    vc1_mc_4mv_chroma4(v, 1, 1, 1);

                } else {

                    vc1_mc_1mv(v, 0);

                    vc1_interp_mc(v);

                }

            } else if (twomv && bmvtype == BMV_TYPE_INTERPOLATED) {

                mvbp = v->fourmvbp;

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

                    dir = i==1 || i==3;

                    dmv_x = dmv_y = 0;

                    val = ((mvbp >> (3 - i)) & 1);

                    if (val)

                        get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                    j = i > 1 ? 2 : 0;

                    vc1_pred_mv_intfr(v, j, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir);

                    vc1_mc_4mv_luma(v, j, dir, dir);

                    vc1_mc_4mv_luma(v, j+1, dir, dir);

                }

                vc1_mc_4mv_chroma4(v, 0, 0, 0);

                vc1_mc_4mv_chroma4(v, 1, 1, 1);

            } else if (bmvtype == BMV_TYPE_INTERPOLATED) {

                mvbp = v->twomvbp;

                dmv_x = dmv_y = 0;

                if (mvbp & 2)

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 0);

                vc1_mc_1mv(v, 0);

                dmv_x = dmv_y = 0;

                if (mvbp & 1)

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 1);

                vc1_interp_mc(v);

            } else if (twomv) {

                dir = bmvtype == BMV_TYPE_BACKWARD;

                dir2 = dir;

                if (mvsw)

                    dir2 = !dir;

                mvbp = v->twomvbp;

                dmv_x = dmv_y = 0;

                if (mvbp & 2)

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir);

                dmv_x = dmv_y = 0;

                if (mvbp & 1)

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                vc1_pred_mv_intfr(v, 2, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir2);

                if (mvsw) {

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

                        s->mv[dir][i+2][0] = s->mv[dir][i][0] = s->current_picture.motion_val[dir][s->block_index[i+2]][0] = s->current_picture.motion_val[dir][s->block_index[i]][0];

                        s->mv[dir][i+2][1] = s->mv[dir][i][1] = s->current_picture.motion_val[dir][s->block_index[i+2]][1] = s->current_picture.motion_val[dir][s->block_index[i]][1];

                        s->mv[dir2][i+2][0] = s->mv[dir2][i][0] = s->current_picture.motion_val[dir2][s->block_index[i]][0] = s->current_picture.motion_val[dir2][s->block_index[i+2]][0];

                        s->mv[dir2][i+2][1] = s->mv[dir2][i][1] = s->current_picture.motion_val[dir2][s->block_index[i]][1] = s->current_picture.motion_val[dir2][s->block_index[i+2]][1];

                    }

                } else {

                    vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, v->mb_type[0], !dir);

                    vc1_pred_mv_intfr(v, 2, 0, 0, 2, v->range_x, v->range_y, v->mb_type[0], !dir);

                }

                vc1_mc_4mv_luma(v, 0, dir, 0);

                vc1_mc_4mv_luma(v, 1, dir, 0);

                vc1_mc_4mv_luma(v, 2, dir2, 0);

                vc1_mc_4mv_luma(v, 3, dir2, 0);

                vc1_mc_4mv_chroma4(v, dir, dir2, 0);

            } else {

                dir = bmvtype == BMV_TYPE_BACKWARD;

                mvbp = ff_vc1_mbmode_intfrp[0][idx_mbmode][2];

                dmv_x = dmv_y = 0;

                if (mvbp)

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], dir);

                v->blk_mv_type[s->block_index[0]] = 1;

                v->blk_mv_type[s->block_index[1]] = 1;

                v->blk_mv_type[s->block_index[2]] = 1;

                v->blk_mv_type[s->block_index[3]] = 1;

                vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, 0, !dir);

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

                    s->mv[!dir][i+2][0] = s->mv[!dir][i][0] = s->current_picture.motion_val[!dir][s->block_index[i+2]][0] = s->current_picture.motion_val[!dir][s->block_index[i]][0];

                    s->mv[!dir][i+2][1] = s->mv[!dir][i][1] = s->current_picture.motion_val[!dir][s->block_index[i+2]][1] = s->current_picture.motion_val[!dir][s->block_index[i]][1];

                }

                vc1_mc_1mv(v, dir);

            }

            if (cbp)

                GET_MQUANT();  // p. 227

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

            if (!v->ttmbf && cbp)

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

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

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

                dst_idx += i >> 2;

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

                if (!fieldtx)

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

                else

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

                if (val) {

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

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

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

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

                    block_cbp |= pat << (i << 2);

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

                        ttmb = -1;

                    first_block = 0;

                }

            }

        } else { // skipped

            dir = 0;

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

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

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

            }

            s->current_picture.mb_type[mb_pos]      = MB_TYPE_SKIP;

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

            v->blk_mv_type[s->block_index[0]] = 0;

            v->blk_mv_type[s->block_index[1]] = 0;

            v->blk_mv_type[s->block_index[2]] = 0;

            v->blk_mv_type[s->block_index[3]] = 0;

            if (!direct) {

                if (bmvtype == BMV_TYPE_INTERPOLATED) {

                    vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 0);

                    vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 1);

                } else {

                    dir = bmvtype == BMV_TYPE_BACKWARD;

                    vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], dir);

                    if (mvsw) {

                        int dir2 = dir;

                        if (mvsw)

                            dir2 = !dir;

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

                            s->mv[dir][i+2][0] = s->mv[dir][i][0] = s->current_picture.motion_val[dir][s->block_index[i+2]][0] = s->current_picture.motion_val[dir][s->block_index[i]][0];

                            s->mv[dir][i+2][1] = s->mv[dir][i][1] = s->current_picture.motion_val[dir][s->block_index[i+2]][1] = s->current_picture.motion_val[dir][s->block_index[i]][1];

                            s->mv[dir2][i+2][0] = s->mv[dir2][i][0] = s->current_picture.motion_val[dir2][s->block_index[i]][0] = s->current_picture.motion_val[dir2][s->block_index[i+2]][0];

                            s->mv[dir2][i+2][1] = s->mv[dir2][i][1] = s->current_picture.motion_val[dir2][s->block_index[i]][1] = s->current_picture.motion_val[dir2][s->block_index[i+2]][1];

                        }

                    } else {

                        v->blk_mv_type[s->block_index[0]] = 1;

                        v->blk_mv_type[s->block_index[1]] = 1;

                        v->blk_mv_type[s->block_index[2]] = 1;

                        v->blk_mv_type[s->block_index[3]] = 1;

                        vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, 0, !dir);

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

                            s->mv[!dir][i+2][0] = s->mv[!dir][i][0] = s->current_picture.motion_val[!dir][s->block_index[i+2]][0] = s->current_picture.motion_val[!dir][s->block_index[i]][0];

                            s->mv[!dir][i+2][1] = s->mv[!dir][i][1] = s->current_picture.motion_val[!dir][s->block_index[i+2]][1] = s->current_picture.motion_val[!dir][s->block_index[i]][1];

                        }

                    }

                }

            }

            vc1_mc_1mv(v, dir);

            if (direct || bmvtype == BMV_TYPE_INTERPOLATED) {

                vc1_interp_mc(v);

            }

        }

    }

    if (s->mb_x == s->mb_width - 1)

        memmove(v->is_intra_base, v->is_intra, sizeof(v->is_intra_base[0]) * s->mb_stride);

    v->cbp[s->mb_x]      = block_cbp;

    v->ttblk[s->mb_x]    = block_tt;

    return 0;

}