static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,

                              int n, int coded, int intra)

{

    int level, i, last, run;

    int dc_pred_dir;

    RLTable * rl;

    RL_VLC_ELEM * rl_vlc;

    const UINT8 * scan_table;

    int qmul, qadd;

    if(intra) {

	/* DC coef */

        if(s->partitioned_frame){

            level = s->dc_val[0][ s->block_index[n] ];

            if(n<4) level= (level + (s->y_dc_scale>>1))/s->y_dc_scale; //FIXME optimizs

            else    level= (level + (s->c_dc_scale>>1))/s->c_dc_scale;

            dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_width]<<n)&32;

        }else{

            level = mpeg4_decode_dc(s, n, &dc_pred_dir);

            if (level < 0)

                return -1;

        }

        block[0] = level;

        i = 0;

        if (!coded)

            goto not_coded;

        rl = &rl_intra;

        rl_vlc = rl_intra.rl_vlc[0];

        if (s->ac_pred) {

            if (dc_pred_dir == 0)

                scan_table = s->intra_v_scantable.permutated; /* left */

            else

                scan_table = s->intra_h_scantable.permutated; /* top */

        } else {

            scan_table = s->intra_scantable.permutated;

        }

        qmul=1;

        qadd=0;

    } else {

        i = -1;

        if (!coded) {

            s->block_last_index[n] = i;

            return 0;

        }

        rl = &rl_inter;

        scan_table = s->intra_scantable.permutated;

        if(s->mpeg_quant){

            qmul=1;

            qadd=0;

            rl_vlc = rl_inter.rl_vlc[0];

        }else{

            qmul = s->qscale << 1;

            qadd = (s->qscale - 1) | 1;

            rl_vlc = rl_inter.rl_vlc[s->qscale];

        }

    }

  {

    OPEN_READER(re, &s->gb);

    for(;;) {

        UPDATE_CACHE(re, &s->gb);

        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);

        if (level==0) {

            int cache;

            cache= GET_CACHE(re, &s->gb);

            /* escape */

            if (cache&0x80000000) {

                if (cache&0x40000000) {

                    /* third escape */

                    SKIP_CACHE(re, &s->gb, 2);

                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);

                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);

                    SKIP_COUNTER(re, &s->gb, 2+1+6);

                    UPDATE_CACHE(re, &s->gb);

                    if(SHOW_UBITS(re, &s->gb, 1)==0){

                        fprintf(stderr, "1. marker bit missing in 3. esc\n");

                        return -1;

                    }; SKIP_CACHE(re, &s->gb, 1);

                    level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);

                    if(SHOW_UBITS(re, &s->gb, 1)==0){

                        fprintf(stderr, "2. marker bit missing in 3. esc\n");

                        return -1;

                    }; LAST_SKIP_CACHE(re, &s->gb, 1);

                    SKIP_COUNTER(re, &s->gb, 1+12+1);

                    if(level*s->qscale>1024 || level*s->qscale<-1024){

                        fprintf(stderr, "|level| overflow in 3. esc, qp=%d\n", s->qscale);

                        return -1;

                    }

#if 1

                    {

                        const int abs_level= ABS(level);

                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN && ((s->workaround_bugs&FF_BUG_AC_VLC)==0)){

                            const int run1= run - rl->max_run[last][abs_level] - 1;

                            if(abs_level <= rl->max_level[last][run]){

                                fprintf(stderr, "illegal 3. esc, vlc encoding possible\n");

                                return -1;

                            }

                            if(abs_level <= rl->max_level[last][run]*2){

                                fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");

                                return -1;

                            }

                            if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){

                                fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");

                                return -1;

                            }

                        }

                    }

#endif

		    if (level>0) level= level * qmul + qadd;

                    else         level= level * qmul - qadd;

                    i+= run + 1;

                    if(last) i+=192;

                } else {

                    /* second escape */

#if MIN_CACHE_BITS < 20

                    LAST_SKIP_BITS(re, &s->gb, 2);

                    UPDATE_CACHE(re, &s->gb);

#else

                    SKIP_BITS(re, &s->gb, 2);

#endif

                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);

                    i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing

                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                    LAST_SKIP_BITS(re, &s->gb, 1);

                }

            } else {

                /* first escape */

#if MIN_CACHE_BITS < 19

                LAST_SKIP_BITS(re, &s->gb, 1);

                UPDATE_CACHE(re, &s->gb);

#else

                SKIP_BITS(re, &s->gb, 1);

#endif

                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);

                i+= run;

                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing

                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                LAST_SKIP_BITS(re, &s->gb, 1);

            }

        } else {

            i+= run;

            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

            LAST_SKIP_BITS(re, &s->gb, 1);

        }

        if (i > 62){

            i-= 192;

            if(i&(~63)){

                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);

                return -1;

            }

            block[scan_table[i]] = level;

            break;

        }

        block[scan_table[i]] = level;

    }

    CLOSE_READER(re, &s->gb);

  }

 not_coded:

    if (s->mb_intra) {

        mpeg4_pred_ac(s, block, n, dc_pred_dir);

        if (s->ac_pred) {

            i = 63; /* XXX: not optimal */

        }

    }

    s->block_last_index[n] = i;

    return 0;

}


int load_uboot(const char *filename, target_ulong *ep, int *is_linux)

{

    int fd;

    int size;

    uboot_image_header_t h;

    uboot_image_header_t *hdr = &h;

    uint8_t *data = NULL;

    fd = open(filename, O_RDONLY | O_BINARY);

    if (fd < 0)

        return -1;

    size = read(fd, hdr, sizeof(uboot_image_header_t));

    if (size < 0)

        goto fail;

    bswap_uboot_header(hdr);

    if (hdr->ih_magic != IH_MAGIC)

        goto fail;

    /* TODO: Implement Multi-File images.  */

    if (hdr->ih_type == IH_TYPE_MULTI) {

        fprintf(stderr, "Unable to load multi-file u-boot images\n");

        goto fail;

    }

    /* TODO: Implement compressed images.  */

    if (hdr->ih_comp != IH_COMP_NONE) {

        fprintf(stderr, "Unable to load compressed u-boot images\n");

        goto fail;

    }

    /* TODO: Check CPU type.  */

    if (is_linux) {

        if (hdr->ih_type == IH_TYPE_KERNEL && hdr->ih_os == IH_OS_LINUX)

            *is_linux = 1;

        else

            *is_linux = 0;

    }

    *ep = hdr->ih_ep;

    data = qemu_malloc(hdr->ih_size);

    if (!data)

        goto fail;

    if (read(fd, data, hdr->ih_size) != hdr->ih_size) {

        fprintf(stderr, "Error reading file\n");

        goto fail;

    }

    cpu_physical_memory_write_rom(hdr->ih_load, data, hdr->ih_size);

    return hdr->ih_size;

fail:

    if (data)

        qemu_free(data);

    close(fd);

    return -1;

}


static int64_t alloc_refcount_block(BlockDriverState *bs, int64_t cluster_index)

{

    BDRVQcowState *s = bs->opaque;

    unsigned int refcount_table_index;

    int ret;

    BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);

    /* Find the refcount block for the given cluster */

    refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);

    if (refcount_table_index < s->refcount_table_size) {

        uint64_t refcount_block_offset =

            s->refcount_table[refcount_table_index];

        /* If it's already there, we're done */

        if (refcount_block_offset) {

            if (refcount_block_offset != s->refcount_block_cache_offset) {

                ret = load_refcount_block(bs, refcount_block_offset);

                if (ret < 0) {

                    return ret;

                }

            }

            return refcount_block_offset;

        }

    }

    /*

     * 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 doing the initial refcount increase. This means that some clusters

     *   have already been allocated by the caller, but their refcount isn't

     *   accurate yet. free_cluster_index tells us where this allocation ends

     *   as long as we don't overwrite it by freeing clusters.

     *

     * - alloc_clusters_noref and qcow2_free_clusters may load a different

     *   refcount block into the cache

     */

    if (cache_refcount_updates) {

        ret = write_refcount_block(bs);

        if (ret < 0) {

            return ret;

        }

    }

    /* Allocate the refcount block itself and mark it as used */

    uint64_t new_block = alloc_clusters_noref(bs, s->cluster_size);

    memset(s->refcount_block_cache, 0, s->cluster_size);

    s->refcount_block_cache_offset = 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)) {

        /* The block describes itself, need to update the cache */

        int block_index = (new_block >> s->cluster_bits) &

            ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);

        s->refcount_block_cache[block_index] = cpu_to_be16(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);

        if (ret < 0) {

            goto fail_block;

        }

    }

    /* Now the new refcount block needs to be written to disk */

    BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE);

    ret = bdrv_pwrite(bs->file, new_block, s->refcount_block_cache,

        s->cluster_size);

    if (ret < 0) {

        goto fail_block;

    }

    /* 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(bs->file,

            s->refcount_table_offset + refcount_table_index * sizeof(uint64_t),

            &data64, sizeof(data64));

        if (ret < 0) {

            goto fail_block;

        }

        s->refcount_table[refcount_table_index] = new_block;

        return new_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 */

    uint64_t refcount_block_clusters = 1 << (s->cluster_bits - REFCOUNT_SHIFT);

    uint64_t blocks_used = (s->free_cluster_index +

        refcount_block_clusters - 1) / refcount_block_clusters;

    /* And now we need at least one block more for the new metadata */

    uint64_t table_size = next_refcount_table_size(s, blocks_used + 1);

    uint64_t last_table_size;

    uint64_t blocks_clusters;

    do {

        uint64_t table_clusters = size_to_clusters(s, table_size);

        blocks_clusters = 1 +

            ((table_clusters + refcount_block_clusters - 1)

            / refcount_block_clusters);

        uint64_t meta_clusters = table_clusters + blocks_clusters;

        last_table_size = table_size;

        table_size = next_refcount_table_size(s, blocks_used +

            ((meta_clusters + refcount_block_clusters - 1)

            / refcount_block_clusters));

    } while (last_table_size != table_size);

#ifdef DEBUG_ALLOC2

    fprintf(stderr, "qcow2: Grow refcount table %" PRId32 " => %" PRId64 "\n",

        s->refcount_table_size, table_size);

#endif

    /* Create the new refcount table and blocks */

    uint64_t meta_offset = (blocks_used * refcount_block_clusters) *

        s->cluster_size;

    uint64_t table_offset = meta_offset + blocks_clusters * s->cluster_size;

    uint16_t *new_blocks = qemu_mallocz(blocks_clusters * s->cluster_size);

    uint64_t *new_table = qemu_mallocz(table_size * sizeof(uint64_t));

    assert(meta_offset >= (s->free_cluster_index * s->cluster_size));

    /* Fill the new refcount table */

    memcpy(new_table, s->refcount_table,

        s->refcount_table_size * sizeof(uint64_t));

    new_table[refcount_table_index] = new_block;

    int i;

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

        new_table[blocks_used + i] = meta_offset + (i * s->cluster_size);

    }

    /* Fill the refcount blocks */

    uint64_t table_clusters = size_to_clusters(s, table_size * sizeof(uint64_t));

    int block = 0;

    for (i = 0; i < table_clusters + blocks_clusters; i++) {

        new_blocks[block++] = cpu_to_be16(1);

    }

    /* Write refcount blocks to disk */

    BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE_BLOCKS);

    ret = bdrv_pwrite(bs->file, meta_offset, new_blocks,

        blocks_clusters * s->cluster_size);

    qemu_free(new_blocks);

    if (ret < 0) {

        goto fail_table;

    }

    /* Write refcount table to disk */

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

        cpu_to_be64s(&new_table[i]);

    }

    BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE_TABLE);

    ret = bdrv_pwrite(bs->file, table_offset, new_table,

        table_size * sizeof(uint64_t));

    if (ret < 0) {

        goto fail_table;

    }

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

        cpu_to_be64s(&new_table[i]);

    }

    /* Hook up the new refcount table in the qcow2 header */

    uint8_t data[12];

    cpu_to_be64w((uint64_t*)data, table_offset);

    cpu_to_be32w((uint32_t*)(data + 8), table_clusters);

    BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_SWITCH_TABLE);

    ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, refcount_table_offset),

        data, sizeof(data));

    if (ret < 0) {

        goto fail_table;

    }

    /* And switch it in memory */

    uint64_t old_table_offset = s->refcount_table_offset;

    uint64_t old_table_size = s->refcount_table_size;

    qemu_free(s->refcount_table);

    s->refcount_table = new_table;

    s->refcount_table_size = table_size;

    s->refcount_table_offset = table_offset;

    /* Free old table. Remember, we must not change free_cluster_index */

    uint64_t old_free_cluster_index = s->free_cluster_index;

    qcow2_free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t));

    s->free_cluster_index = old_free_cluster_index;

    ret = load_refcount_block(bs, new_block);

    if (ret < 0) {

        goto fail_block;

    }

    return new_block;

fail_table:

    qemu_free(new_table);

fail_block:

    s->refcount_block_cache_offset = 0;

    return ret;

}


static int parse_vtrk(AVFormatContext *s,

                      FourxmDemuxContext *fourxm, uint8_t *buf, int size)

{

    AVStream *st;

    /* check that there is enough data */

    if (size != vtrk_SIZE) {

        return AVERROR_INVALIDDATA;

    }

    /* allocate a new AVStream */

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    avpriv_set_pts_info(st, 60, 1, fourxm->fps);

    fourxm->video_stream_index = st->index;

    st->codec->codec_type     = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id       = AV_CODEC_ID_4XM;

    st->codec->extradata_size = 4;

    st->codec->extradata      = av_malloc(4);

    AV_WL32(st->codec->extradata, AV_RL32(buf + 16));

    st->codec->width  = AV_RL32(buf + 36);

    st->codec->height = AV_RL32(buf + 40);

    return 0;

}


void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)

{

    if (bs->backing_hd) {

        assert(bs->backing_blocker);

        bdrv_op_unblock_all(bs->backing_hd, bs->backing_blocker);

    } else if (backing_hd) {

        error_setg(&bs->backing_blocker,

                   "device is used as backing hd of '%s'",

                   bdrv_get_device_name(bs));

    }

    bs->backing_hd = backing_hd;

    if (!backing_hd) {

        error_free(bs->backing_blocker);

        bs->backing_blocker = NULL;

        goto out;

    }

    bs->open_flags &= ~BDRV_O_NO_BACKING;

    pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);

    pstrcpy(bs->backing_format, sizeof(bs->backing_format),

            backing_hd->drv ? backing_hd->drv->format_name : "");

    bdrv_op_block_all(bs->backing_hd, bs->backing_blocker);

    /* Otherwise we won't be able to commit due to check in bdrv_commit */

    bdrv_op_unblock(bs->backing_hd, BLOCK_OP_TYPE_COMMIT,

                    bs->backing_blocker);

out:

    bdrv_refresh_limits(bs, NULL);

}


static void scsi_command_complete(void *opaque, int ret)

{

    SCSIGenericReq *r = (SCSIGenericReq *)opaque;

    SCSIGenericState *s = DO_UPCAST(SCSIGenericState, qdev, r->req.dev);

    r->req.aiocb = NULL;

    s->driver_status = r->io_header.driver_status;

    if (s->driver_status & SG_ERR_DRIVER_SENSE)

        s->senselen = r->io_header.sb_len_wr;

    if (ret != 0)

        r->req.status = BUSY;

    else {

        if (s->driver_status & SG_ERR_DRIVER_TIMEOUT) {

            r->req.status = BUSY;

            BADF("Driver Timeout\n");

        } else if (r->io_header.status)

            r->req.status = r->io_header.status;

        else if (s->driver_status & SG_ERR_DRIVER_SENSE)

            r->req.status = CHECK_CONDITION;

        else

            r->req.status = GOOD;

    }

    DPRINTF("Command complete 0x%p tag=0x%x status=%d\n",

            r, r->req.tag, r->req.status);

    scsi_req_complete(&r->req);

}


static int QEMU_WARN_UNUSED_RESULT update_refcount(BlockDriverState *bs,

                                                   int64_t offset,

                                                   int64_t length,

                                                   uint64_t addend,

                                                   bool decrease,

                                                   enum qcow2_discard_type type)

{

    BDRVQcowState *s = bs->opaque;

    int64_t start, last, cluster_offset;

    uint16_t *refcount_block = NULL;

    int64_t old_table_index = -1;

    int ret;

#ifdef DEBUG_ALLOC2

    fprintf(stderr, "update_refcount: offset=%" PRId64 " size=%" PRId64

            " addend=%s%" PRIu64 "\n", offset, length, decrease ? "-" : "",

            addend);

#endif

    if (length < 0) {

        return -EINVAL;

    } else if (length == 0) {

        return 0;

    }

    if (decrease) {

        qcow2_cache_set_dependency(bs, s->refcount_block_cache,

            s->l2_table_cache);

    }

    start = start_of_cluster(s, offset);

    last = start_of_cluster(s, offset + length - 1);

    for(cluster_offset = start; cluster_offset <= last;

        cluster_offset += s->cluster_size)

    {

        int block_index;

        uint64_t refcount;

        int64_t cluster_index = cluster_offset >> s->cluster_bits;

        int64_t table_index = cluster_index >> s->refcount_block_bits;

        /* Load the refcount block and allocate it if needed */

        if (table_index != old_table_index) {

            if (refcount_block) {

                ret = qcow2_cache_put(bs, s->refcount_block_cache,

                    (void**) &refcount_block);

                if (ret < 0) {

                    goto fail;

                }

            }

            ret = alloc_refcount_block(bs, cluster_index, &refcount_block);

            if (ret < 0) {

                goto fail;

            }

        }

        old_table_index = table_index;

        qcow2_cache_entry_mark_dirty(s->refcount_block_cache, refcount_block);

        /* we can update the count and save it */

        block_index = cluster_index & (s->refcount_block_size - 1);

        refcount = be16_to_cpu(refcount_block[block_index]);

        if (decrease ? (refcount - addend > refcount)

                     : (refcount + addend < refcount ||

                        refcount + addend > s->refcount_max))

        {

            ret = -EINVAL;

            goto fail;

        }

        if (decrease) {

            refcount -= addend;

        } else {

            refcount += addend;

        }

        if (refcount == 0 && cluster_index < s->free_cluster_index) {

            s->free_cluster_index = cluster_index;

        }

        refcount_block[block_index] = cpu_to_be16(refcount);

        if (refcount == 0 && s->discard_passthrough[type]) {

            update_refcount_discard(bs, cluster_offset, s->cluster_size);

        }

    }

    ret = 0;

fail:

    if (!s->cache_discards) {

        qcow2_process_discards(bs, ret);

    }

    /* Write last changed block to disk */

    if (refcount_block) {

        int wret;

        wret = qcow2_cache_put(bs, s->refcount_block_cache,

            (void**) &refcount_block);

        if (wret < 0) {

            return ret < 0 ? ret : wret;

        }

    }

    /*

     * Try do undo any updates if an error is returned (This may succeed in

     * some cases like ENOSPC for allocating a new refcount block)

     */

    if (ret < 0) {

        int dummy;

        dummy = update_refcount(bs, offset, cluster_offset - offset, addend,

                                !decrease, QCOW2_DISCARD_NEVER);

        (void)dummy;

    }

    return ret;

}


int ff_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf, int buf_size)

{

    GetBitContext gb;

    int specific_config_bitindex;

    init_get_bits(&gb, buf, buf_size*8);

    c->object_type = get_object_type(&gb);

    c->sample_rate = get_sample_rate(&gb, &c->sampling_index);

    c->chan_config = get_bits(&gb, 4);

    if (c->chan_config < FF_ARRAY_ELEMS(ff_mpeg4audio_channels))

        c->channels = ff_mpeg4audio_channels[c->chan_config];

    c->sbr = -1;

    if (c->object_type == AOT_SBR || (c->object_type == AOT_PS &&

        // check for W6132 Annex YYYY draft MP3onMP4

        !(show_bits(&gb, 3) & 0x03 && !(show_bits(&gb, 9) & 0x3F)))) {

        c->ext_object_type = AOT_SBR;

        c->sbr = 1;

        c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);

        c->object_type = get_object_type(&gb);

        if (c->object_type == AOT_ER_BSAC)

            c->ext_chan_config = get_bits(&gb, 4);

    } else {

        c->ext_object_type = AOT_NULL;

        c->ext_sample_rate = 0;

    }

    specific_config_bitindex = get_bits_count(&gb);

    if (c->object_type == AOT_ALS) {

        skip_bits(&gb, 5);

        if (show_bits_long(&gb, 24) != MKBETAG('\0','A','L','S'))

            skip_bits_long(&gb, 24);

        specific_config_bitindex = get_bits_count(&gb);

        if (parse_config_ALS(&gb, c))

            return -1;

    }

    if (c->ext_object_type != AOT_SBR) {

        int bits_left = buf_size*8 - get_bits_count(&gb);

        for (; bits_left > 15; bits_left--) {

            if (show_bits(&gb, 11) == 0x2b7) { // sync extension

                get_bits(&gb, 11);

                c->ext_object_type = get_object_type(&gb);

                if (c->ext_object_type == AOT_SBR && (c->sbr = get_bits1(&gb)) == 1)

                    c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);

                break;

            } else

                get_bits1(&gb); // skip 1 bit

        }

    }

    return specific_config_bitindex;

}


void ff_hevc_luma_mv_mvp_mode(HEVCContext *s, int x0, int y0, int nPbW,

                              int nPbH, int log2_cb_size, int part_idx,

                              int merge_idx, MvField *mv,

                              int mvp_lx_flag, int LX)

{

    HEVCLocalContext *lc = s->HEVClc;

    MvField *tab_mvf = s->ref->tab_mvf;

    int isScaledFlag_L0 = 0;

    int availableFlagLXA0 = 1;

    int availableFlagLXB0 = 1;

    int numMVPCandLX = 0;

    int min_pu_width = s->sps->min_pu_width;

    int xA0, yA0;

    int is_available_a0;

    int xA1, yA1;

    int is_available_a1;

    int xB0, yB0;

    int is_available_b0;

    int xB1, yB1;

    int is_available_b1;

    int xB2, yB2;

    int is_available_b2;

    Mv mvpcand_list[2] = { { 0 } };

    Mv mxA;

    Mv mxB;

    int ref_idx_curr = 0;

    int ref_idx = 0;

    int pred_flag_index_l0;

    int pred_flag_index_l1;

    const int cand_bottom_left = lc->na.cand_bottom_left;

    const int cand_left        = lc->na.cand_left;

    const int cand_up_left     = lc->na.cand_up_left;

    const int cand_up          = lc->na.cand_up;

    const int cand_up_right    = lc->na.cand_up_right_sap;

    ref_idx_curr       = LX;

    ref_idx            = mv->ref_idx[LX];

    pred_flag_index_l0 = LX;

    pred_flag_index_l1 = !LX;

    // left bottom spatial candidate

    xA0 = x0 - 1;

    yA0 = y0 + nPbH;

    is_available_a0 = AVAILABLE(cand_bottom_left, A0) &&

                      yA0 < s->sps->height &&

                      PRED_BLOCK_AVAILABLE(A0);

    //left spatial merge candidate

    xA1    = x0 - 1;

    yA1    = y0 + nPbH - 1;

    is_available_a1 = AVAILABLE(cand_left, A1);

    if (is_available_a0 || is_available_a1)

        isScaledFlag_L0 = 1;

    if (is_available_a0) {

        if (MP_MX(A0, pred_flag_index_l0, mxA)) {

            goto b_candidates;

        }

        if (MP_MX(A0, pred_flag_index_l1, mxA)) {

            goto b_candidates;

        }

    }

    if (is_available_a1) {

        if (MP_MX(A1, pred_flag_index_l0, mxA)) {

            goto b_candidates;

        }

        if (MP_MX(A1, pred_flag_index_l1, mxA)) {

            goto b_candidates;

        }

    }

    if (is_available_a0) {

        if (MP_MX_LT(A0, pred_flag_index_l0, mxA)) {

            goto b_candidates;

        }

        if (MP_MX_LT(A0, pred_flag_index_l1, mxA)) {

            goto b_candidates;

        }

    }

    if (is_available_a1) {

        if (MP_MX_LT(A1, pred_flag_index_l0, mxA)) {

            goto b_candidates;

        }

        if (MP_MX_LT(A1, pred_flag_index_l1, mxA)) {

            goto b_candidates;

        }

    }

    availableFlagLXA0 = 0;

b_candidates:

    // B candidates

    // above right spatial merge candidate

    xB0    = x0 + nPbW;

    yB0    = y0 - 1;

    is_available_b0 =  AVAILABLE(cand_up_right, B0) &&

                       xB0 < s->sps->width &&

                       PRED_BLOCK_AVAILABLE(B0);

    // above spatial merge candidate

    xB1    = x0 + nPbW - 1;

    yB1    = y0 - 1;

    is_available_b1 = AVAILABLE(cand_up, B1);

    // above left spatial merge candidate

    xB2 = x0 - 1;

    yB2 = y0 - 1;

    is_available_b2 = AVAILABLE(cand_up_left, B2);

    // above right spatial merge candidate

    if (is_available_b0) {

        if (MP_MX(B0, pred_flag_index_l0, mxB)) {

            goto scalef;

        }

        if (MP_MX(B0, pred_flag_index_l1, mxB)) {

            goto scalef;

        }

    }

    // above spatial merge candidate

    if (is_available_b1) {

        if (MP_MX(B1, pred_flag_index_l0, mxB)) {

            goto scalef;

        }

        if (MP_MX(B1, pred_flag_index_l1, mxB)) {

            goto scalef;

        }

    }

    // above left spatial merge candidate

    if (is_available_b2) {

        if (MP_MX(B2, pred_flag_index_l0, mxB)) {

            goto scalef;

        }

        if (MP_MX(B2, pred_flag_index_l1, mxB)) {

            goto scalef;

        }

    }

    availableFlagLXB0 = 0;

scalef:

    if (!isScaledFlag_L0) {

        if (availableFlagLXB0) {

            availableFlagLXA0 = 1;

            mxA = mxB;

        }

        availableFlagLXB0 = 0;

        // XB0 and L1

        if (is_available_b0) {

            availableFlagLXB0 = MP_MX_LT(B0, pred_flag_index_l0, mxB);

            if (!availableFlagLXB0)

                availableFlagLXB0 = MP_MX_LT(B0, pred_flag_index_l1, mxB);

        }

        if (is_available_b1 && !availableFlagLXB0) {

            availableFlagLXB0 = MP_MX_LT(B1, pred_flag_index_l0, mxB);

            if (!availableFlagLXB0)

                availableFlagLXB0 = MP_MX_LT(B1, pred_flag_index_l1, mxB);

        }

        if (is_available_b2 && !availableFlagLXB0) {

            availableFlagLXB0 = MP_MX_LT(B2, pred_flag_index_l0, mxB);

            if (!availableFlagLXB0)

                availableFlagLXB0 = MP_MX_LT(B2, pred_flag_index_l1, mxB);

        }

    }

    if (availableFlagLXA0)

        mvpcand_list[numMVPCandLX++] = mxA;

    if (availableFlagLXB0 && (!availableFlagLXA0 || mxA.x != mxB.x || mxA.y != mxB.y))

        mvpcand_list[numMVPCandLX++] = mxB;

    //temporal motion vector prediction candidate

    if (numMVPCandLX < 2 && s->sh.slice_temporal_mvp_enabled_flag &&

        mvp_lx_flag == numMVPCandLX) {

        Mv mv_col;

        int available_col = temporal_luma_motion_vector(s, x0, y0, nPbW,

                                                        nPbH, ref_idx,

                                                        &mv_col, LX);

        if (available_col)

            mvpcand_list[numMVPCandLX++] = mv_col;

    }

    mv->mv[LX] = mvpcand_list[mvp_lx_flag];

}


static void pc_compat_2_0(MachineState *machine)

{

    smbios_legacy_mode = true;

    has_reserved_memory = false;

}


static CharDriverState *qemu_chr_open_msmouse(const char *id,

                                              ChardevBackend *backend,

                                              ChardevReturn *ret,

                                              Error **errp)

{

    ChardevCommon *common = backend->u.msmouse.data;

    MouseState *mouse;

    CharDriverState *chr;

    chr = qemu_chr_alloc(common, errp);

    chr->chr_write = msmouse_chr_write;

    chr->chr_close = msmouse_chr_close;

    chr->chr_accept_input = msmouse_chr_accept_input;

    chr->explicit_be_open = true;

    mouse = g_new0(MouseState, 1);

    mouse->hs = qemu_input_handler_register((DeviceState *)mouse,

                                            &msmouse_handler);

    mouse->chr = chr;

    chr->opaque = mouse;

    return chr;


int kvm_arch_on_sigbus_vcpu(CPUState *env, int code, void *addr)

{

#ifdef KVM_CAP_MCE

    ram_addr_t ram_addr;

    target_phys_addr_t paddr;

    if ((env->mcg_cap & MCG_SER_P) && addr

        && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {

        if (qemu_ram_addr_from_host(addr, &ram_addr) ||

            !kvm_physical_memory_addr_from_ram(env->kvm_state, ram_addr,

                                               &paddr)) {

            fprintf(stderr, "Hardware memory error for memory used by "

                    "QEMU itself instead of guest system!\n");

            /* Hope we are lucky for AO MCE */

            if (code == BUS_MCEERR_AO) {

                return 0;

            } else {

                hardware_memory_error();

            }

        }

        kvm_mce_inject(env, paddr, code);

    } else

#endif /* KVM_CAP_MCE */

    {

        if (code == BUS_MCEERR_AO) {

            return 0;

        } else if (code == BUS_MCEERR_AR) {

            hardware_memory_error();

        } else {

            return 1;

        }

    }

    return 0;

}


static int vc1_decode_intra_block(VC1Context *v, DCTELEM block[64], int n, int coded, int mquant, int codingset)

{

    GetBitContext *gb = &v->s.gb;

    MpegEncContext *s = &v->s;

    int dc_pred_dir = 0; /* Direction of the DC prediction used */

    int run_diff, i;

    int16_t *dc_val;

    int16_t *ac_val, *ac_val2;

    int dcdiff;

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

    int a_avail = v->a_avail, c_avail = v->c_avail;

    int use_pred = s->ac_pred;

    int scale;

    int q1, q2 = 0;

    /* XXX: Guard against dumb values of mquant */

    mquant = (mquant < 1) ? 0 : ( (mquant>31) ? 31 : mquant );

    /* Set DC scale - y and c use the same */

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

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

    /* Get DC differential */

    if (n < 4) {

        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);

    } else {

        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);

    }

    if (dcdiff < 0){

        av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n");

        return -1;

    }

    if (dcdiff)

    {

        if (dcdiff == 119 /* ESC index value */)

        {

            /* TODO: Optimize */

            if (mquant == 1) dcdiff = get_bits(gb, 10);

            else if (mquant == 2) dcdiff = get_bits(gb, 9);

            else dcdiff = get_bits(gb, 8);

        }

        else

        {

            if (mquant == 1)

                dcdiff = (dcdiff<<2) + get_bits(gb, 2) - 3;

            else if (mquant == 2)

                dcdiff = (dcdiff<<1) + get_bits(gb, 1) - 1;

        }

        if (get_bits(gb, 1))

            dcdiff = -dcdiff;

    }

    /* Prediction */

    dcdiff += vc1_pred_dc(&v->s, v->overlap, mquant, n, a_avail, c_avail, &dc_val, &dc_pred_dir);

    *dc_val = dcdiff;

    /* Store the quantized DC coeff, used for prediction */

    if (n < 4) {

        block[0] = dcdiff * s->y_dc_scale;

    } else {

        block[0] = dcdiff * s->c_dc_scale;

    }

    /* Skip ? */

    run_diff = 0;

    i = 0;

    //AC Decoding

    i = 1;

    /* check if AC is needed at all and adjust direction if needed */

    if(!a_avail) dc_pred_dir = 1;

    if(!c_avail) dc_pred_dir = 0;

    if(!a_avail && !c_avail) use_pred = 0;

    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;

    ac_val2 = ac_val;

    scale = mquant * 2 + v->halfpq;

    if(dc_pred_dir) //left

        ac_val -= 16;

    else //top

        ac_val -= 16 * s->block_wrap[n];

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

    if(dc_pred_dir && c_avail) q2 = s->current_picture.qscale_table[mb_pos - 1];

    if(!dc_pred_dir && a_avail) q2 = s->current_picture.qscale_table[mb_pos - s->mb_stride];

    if(n && n<4) q2 = q1;

    if(coded) {

        int last = 0, skip, value;

        const int8_t *zz_table;

        int k;

        zz_table = vc1_simple_progressive_8x8_zz;

        while (!last) {

            vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);

            i += skip;

            if(i > 63)

                break;

            block[zz_table[i++]] = value;

        }

        /* apply AC prediction if needed */

        if(use_pred) {

            /* scale predictors if needed*/

            if(q2 && q1!=q2) {

                q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;

                q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;

                if(dc_pred_dir) { //left

                    for(k = 1; k < 8; k++)

                        block[k << 3] += (ac_val[k] * q2 * vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                } else { //top

                    for(k = 1; k < 8; k++)

                        block[k] += (ac_val[k + 8] * q2 * vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                }

            } else {

                if(dc_pred_dir) { //left

                    for(k = 1; k < 8; k++)

                        block[k << 3] += ac_val[k];

                } else { //top

                    for(k = 1; k < 8; k++)

                        block[k] += ac_val[k + 8];

                }

            }

        }

        /* save AC coeffs for further prediction */

        for(k = 1; k < 8; k++) {

            ac_val2[k] = block[k << 3];

            ac_val2[k + 8] = block[k];

        }

        /* scale AC coeffs */

        for(k = 1; k < 64; k++)

            if(block[k]) {

                block[k] *= scale;

                if(!v->pquantizer)

                    block[k] += (block[k] < 0) ? -mquant : mquant;

            }

        if(use_pred) i = 63;

    } else { // no AC coeffs

        int k;

        memset(ac_val2, 0, 16 * 2);

        if(dc_pred_dir) {//left

            if(use_pred) {

                memcpy(ac_val2, ac_val, 8 * 2);

                if(q2 && q1!=q2) {

                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;

                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;

                    for(k = 1; k < 8; k++)

                        ac_val2[k] = (ac_val2[k] * q2 * vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                }

            }

        } else {//top

            if(use_pred) {

                memcpy(ac_val2 + 8, ac_val + 8, 8 * 2);

                if(q2 && q1!=q2) {

                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;

                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;

                    for(k = 1; k < 8; k++)

                        ac_val2[k + 8] = (ac_val2[k + 8] * q2 * vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                }

            }

        }

        /* apply AC prediction if needed */

        if(use_pred) {

            if(dc_pred_dir) { //left

                for(k = 1; k < 8; k++) {

                    block[k << 3] = ac_val2[k] * scale;

                    if(!v->pquantizer && block[k << 3])

                        block[k << 3] += (block[k << 3] < 0) ? -mquant : mquant;

                }

            } else { //top

                for(k = 1; k < 8; k++) {

                    block[k] = ac_val2[k + 8] * scale;

                    if(!v->pquantizer && block[k])

                        block[k] += (block[k] < 0) ? -mquant : mquant;

                }

            }

            i = 63;

        }

    }

    s->block_last_index[n] = i;

    return 0;

}


static int can_safely_read(GetBitContext* gb, uint64_t bits) {

    return get_bits_left(gb) >= bits;

}


static int tta_probe(AVProbeData *p)

{

    const uint8_t *d = p->buf;

    if (p->buf_size < 4)

        return 0;

    if (d[0] == 'T' && d[1] == 'T' && d[2] == 'A' && d[3] == '1')

        return 80;

    return 0;

}


static void qcow2_cache_table_release(BlockDriverState *bs, Qcow2Cache *c,

                                      int i, int num_tables)

{

/* Using MADV_DONTNEED to discard memory is a Linux-specific feature */

#ifdef CONFIG_LINUX

    BDRVQcow2State *s = bs->opaque;

    void *t = qcow2_cache_get_table_addr(bs, c, i);

    int align = getpagesize();

    size_t mem_size = (size_t) s->cluster_size * num_tables;

    size_t offset = QEMU_ALIGN_UP((uintptr_t) t, align) - (uintptr_t) t;

    size_t length = QEMU_ALIGN_DOWN(mem_size - offset, align);

    if (length > 0) {

        madvise((uint8_t *) t + offset, length, MADV_DONTNEED);

    }

#endif

}


static void qpi_init(void)

{

    kqemu_comm_base = 0xff000000 | 1;

    qpi_io_memory = cpu_register_io_memory(

                                           qpi_mem_read,

                                           qpi_mem_write, NULL);

    cpu_register_physical_memory(kqemu_comm_base & ~0xfff,

                                 0x1000, qpi_io_memory);

}


tight_detect_smooth_image(VncState *vs, int w, int h)

{

    uint errors;

    int compression = vs->tight.compression;

    int quality = vs->tight.quality;

    if (!vs->vd->lossy) {

        return 0;

    }

    if (ds_get_bytes_per_pixel(vs->ds) == 1 ||

        vs->clientds.pf.bytes_per_pixel == 1 ||

        w < VNC_TIGHT_DETECT_MIN_WIDTH || h < VNC_TIGHT_DETECT_MIN_HEIGHT) {

        return 0;

    }

    if (vs->tight.quality != -1) {

        if (w * h < VNC_TIGHT_JPEG_MIN_RECT_SIZE) {

            return 0;

        }

    } else {

        if (w * h < tight_conf[compression].gradient_min_rect_size) {

            return 0;

        }

    }

    if (vs->clientds.pf.bytes_per_pixel == 4) {

        if (vs->tight.pixel24) {

            errors = tight_detect_smooth_image24(vs, w, h);

            if (vs->tight.quality != -1) {

                return (errors < tight_conf[quality].jpeg_threshold24);

            }

            return (errors < tight_conf[compression].gradient_threshold24);

        } else {

            errors = tight_detect_smooth_image32(vs, w, h);

        }

    } else {

        errors = tight_detect_smooth_image16(vs, w, h);

    }

    if (quality != -1) {

        return (errors < tight_conf[quality].jpeg_threshold);

    }

    return (errors < tight_conf[compression].gradient_threshold);

}


static void list_formats(AVFormatContext *ctx, int type)

{

    const struct video_data *s = ctx->priv_data;

    struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };

    while(!v4l2_ioctl(s->fd, VIDIOC_ENUM_FMT, &vfd)) {

        enum AVCodecID codec_id = avpriv_fmt_v4l2codec(vfd.pixelformat);

        enum AVPixelFormat pix_fmt = avpriv_fmt_v4l2ff(vfd.pixelformat, codec_id);

        vfd.index++;

        if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&

            type & V4L_RAWFORMATS) {

            const char *fmt_name = av_get_pix_fmt_name(pix_fmt);

            av_log(ctx, AV_LOG_INFO, "Raw       : %9s : %20s :",

                   fmt_name ? fmt_name : "Unsupported",

                   vfd.description);

        } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&

                   type & V4L_COMPFORMATS) {

            AVCodec *codec = avcodec_find_decoder(codec_id);

            av_log(ctx, AV_LOG_INFO, "Compressed: %9s : %20s :",

                   codec ? codec->name : "Unsupported",

                   vfd.description);

        } else {

            continue;

        }

#ifdef V4L2_FMT_FLAG_EMULATED

        if (vfd.flags & V4L2_FMT_FLAG_EMULATED)

            av_log(ctx, AV_LOG_INFO, " Emulated :");

#endif

#if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE

        list_framesizes(ctx, vfd.pixelformat);

#endif

        av_log(ctx, AV_LOG_INFO, "\n");

    }

}


static CharDriverState *qemu_chr_open_pp_fd(int fd, Error **errp)

{

    CharDriverState *chr;

    ParallelCharDriver *drv;

    if (ioctl(fd, PPCLAIM) < 0) {

        error_setg_errno(errp, errno, "not a parallel port");

        close(fd);

        return NULL;

    }

    drv = g_new0(ParallelCharDriver, 1);

    drv->fd = fd;

    drv->mode = IEEE1284_MODE_COMPAT;

    chr = qemu_chr_alloc();

    chr->chr_write = null_chr_write;

    chr->chr_ioctl = pp_ioctl;

    chr->chr_close = pp_close;

    chr->opaque = drv;

    return chr;

}


static QError *qerror_from_info(const char *fmt, va_list *va)

{

    QError *qerr;

    qerr = qerror_new();

    loc_save(&qerr->loc);

    qerr->error = error_obj_from_fmt_no_fail(fmt, va);

    qerr->err_msg = qerror_format(fmt, qerr->error);

    return qerr;

}


static void unblock_io_signals(void)

{

    sigset_t set;

    sigemptyset(&set);

    sigaddset(&set, SIGUSR2);

    sigaddset(&set, SIGIO);

    sigaddset(&set, SIGALRM);

    pthread_sigmask(SIG_UNBLOCK, &set, NULL);

    sigemptyset(&set);

    sigaddset(&set, SIGUSR1);

    pthread_sigmask(SIG_BLOCK, &set, NULL);

}


float32 helper_fqtos(CPUSPARCState *env)

{

    float32 ret;

    clear_float_exceptions(env);

    ret = float128_to_float32(QT1, &env->fp_status);

    check_ieee_exceptions(env);

    return ret;

}


float32 float32_round_to_int( float32 a STATUS_PARAM)

{

    flag aSign;

    int16 aExp;

    bits32 lastBitMask, roundBitsMask;

    int8 roundingMode;

    float32 z;

    aExp = extractFloat32Exp( a );

    if ( 0x96 <= aExp ) {

        if ( ( aExp == 0xFF ) && extractFloat32Frac( a ) ) {

            return propagateFloat32NaN( a, a STATUS_VAR );

        }

        return a;

    }

    if ( aExp <= 0x7E ) {

        if ( (bits32) ( a<<1 ) == 0 ) return a;

        STATUS(float_exception_flags) |= float_flag_inexact;

        aSign = extractFloat32Sign( a );

        switch ( STATUS(float_rounding_mode) ) {

         case float_round_nearest_even:

            if ( ( aExp == 0x7E ) && extractFloat32Frac( a ) ) {

                return packFloat32( aSign, 0x7F, 0 );

            }

            break;

         case float_round_down:

            return aSign ? 0xBF800000 : 0;

         case float_round_up:

            return aSign ? 0x80000000 : 0x3F800000;

        }

        return packFloat32( aSign, 0, 0 );

    }

    lastBitMask = 1;

    lastBitMask <<= 0x96 - aExp;

    roundBitsMask = lastBitMask - 1;

    z = a;

    roundingMode = STATUS(float_rounding_mode);

    if ( roundingMode == float_round_nearest_even ) {

        z += lastBitMask>>1;

        if ( ( z & roundBitsMask ) == 0 ) z &= ~ lastBitMask;

    }

    else if ( roundingMode != float_round_to_zero ) {

        if ( extractFloat32Sign( z ) ^ ( roundingMode == float_round_up ) ) {

            z += roundBitsMask;

        }

    }

    z &= ~ roundBitsMask;

    if ( z != a ) STATUS(float_exception_flags) |= float_flag_inexact;

    return z;

}


static void do_drive_backup(DriveBackup *backup, BlockJobTxn *txn, Error **errp)

{

    BlockDriverState *bs;

    BlockDriverState *target_bs;

    BlockDriverState *source = NULL;

    BdrvDirtyBitmap *bmap = NULL;

    AioContext *aio_context;

    QDict *options = NULL;

    Error *local_err = NULL;

    int flags;

    int64_t size;

    if (!backup->has_speed) {

        backup->speed = 0;

    }

    if (!backup->has_on_source_error) {

        backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!backup->has_on_target_error) {

        backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!backup->has_mode) {

        backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;

    }

    if (!backup->has_job_id) {

        backup->job_id = NULL;

    }

    bs = qmp_get_root_bs(backup->device, errp);

    if (!bs) {

        return;

    }

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    if (!backup->has_format) {

        backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?

                         NULL : (char*) bs->drv->format_name;

    }

    /* Early check to avoid creating target */

    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {

        goto out;

    }

    flags = bs->open_flags | BDRV_O_RDWR;

    /* See if we have a backing HD we can use to create our new image

     * on top of. */

    if (backup->sync == MIRROR_SYNC_MODE_TOP) {

        source = backing_bs(bs);

        if (!source) {

            backup->sync = MIRROR_SYNC_MODE_FULL;

        }

    }

    if (backup->sync == MIRROR_SYNC_MODE_NONE) {

        source = bs;

    }

    size = bdrv_getlength(bs);

    if (size < 0) {

        error_setg_errno(errp, -size, "bdrv_getlength failed");

        goto out;

    }

    if (backup->mode != NEW_IMAGE_MODE_EXISTING) {

        assert(backup->format);

        if (source) {

            bdrv_img_create(backup->target, backup->format, source->filename,

                            source->drv->format_name, NULL,

                            size, flags, &local_err, false);

        } else {

            bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,

                            size, flags, &local_err, false);

        }

    }

    if (local_err) {

        error_propagate(errp, local_err);

        goto out;

    }

    if (backup->format) {

        options = qdict_new();

        qdict_put(options, "driver", qstring_from_str(backup->format));

    }

    target_bs = bdrv_open(backup->target, NULL, options, flags, errp);

    if (!target_bs) {

        goto out;

    }

    bdrv_set_aio_context(target_bs, aio_context);

    if (backup->has_bitmap) {

        bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);

        if (!bmap) {

            error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);

            bdrv_unref(target_bs);

            goto out;

        }

    }

    backup_start(backup->job_id, bs, target_bs, backup->speed, backup->sync,

                 bmap, backup->on_source_error, backup->on_target_error,

                 block_job_cb, bs, txn, &local_err);

    bdrv_unref(target_bs);

    if (local_err != NULL) {

        error_propagate(errp, local_err);

        goto out;

    }

out:

    aio_context_release(aio_context);

}


static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num,

                           uint8_t *buf, int nb_sectors, bool enc,

                           Error **errp)

{

    union {

        uint64_t ll[2];

        uint8_t b[16];

    } ivec;

    int i;

    int ret;

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

        ivec.ll[0] = cpu_to_le64(sector_num);

        ivec.ll[1] = 0;

        if (qcrypto_cipher_setiv(s->cipher,

                                 ivec.b, G_N_ELEMENTS(ivec.b),

                                 errp) < 0) {

            return -1;

        }

        if (enc) {

            ret = qcrypto_cipher_encrypt(s->cipher,

                                         buf, buf,

                                         512,

                                         errp);

        } else {

            ret = qcrypto_cipher_decrypt(s->cipher,

                                         buf, buf,

                                         512,

                                         errp);

        }

        if (ret < 0) {

            return -1;

        }

        sector_num++;

        buf += 512;

    }

    return 0;

}


static void nbd_teardown_connection(BlockDriverState *bs)

{

    NBDClientSession *client = nbd_get_client_session(bs);

    if (!client->ioc) { /* Already closed */

        return;

    }

    /* finish any pending coroutines */

    qio_channel_shutdown(client->ioc,

                         QIO_CHANNEL_SHUTDOWN_BOTH,

                         NULL);

    nbd_recv_coroutines_enter_all(bs);

    nbd_client_detach_aio_context(bs);

    object_unref(OBJECT(client->sioc));

    client->sioc = NULL;

    object_unref(OBJECT(client->ioc));

    client->ioc = NULL;

}


static int cinepak_decode_strip (CinepakContext *s,

                                 cvid_strip *strip, const uint8_t *data, int size)

{

    const uint8_t *eod = (data + size);

    int      chunk_id, chunk_size;

    /* coordinate sanity checks */

    if (strip->x1 >= s->width  || strip->x2 > s->width  ||

        strip->y1 >= s->height || strip->y2 > s->height ||

        strip->x1 >= strip->x2 || strip->y1 >= strip->y2)

        return -1;

    while ((data + 4) <= eod) {

        chunk_id   = data[0];

        chunk_size = AV_RB24 (&data[1]) - 4;

        if(chunk_size < 0)

            return -1;

        data      += 4;

        chunk_size = ((data + chunk_size) > eod) ? (eod - data) : chunk_size;

        switch (chunk_id) {

        case 0x20:

        case 0x21:

        case 0x24:

        case 0x25:

            cinepak_decode_codebook (strip->v4_codebook, chunk_id,

                chunk_size, data);

            break;

        case 0x22:

        case 0x23:

        case 0x26:

        case 0x27:

            cinepak_decode_codebook (strip->v1_codebook, chunk_id,

                chunk_size, data);

            break;

        case 0x30:

        case 0x31:

        case 0x32:

            return cinepak_decode_vectors (s, strip, chunk_id,

                chunk_size, data);

        }

        data += chunk_size;

    }

    return -1;

}


static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,

                                            uint64_t offset, uint64_t bytes,

                                            QEMUIOVector *qiov, int flags)

{

    BlockDriver *drv = bs->drv;

    int64_t sector_num = offset >> BDRV_SECTOR_BITS;

    unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;

    int ret;

    assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);

    assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);

    assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);

    if (drv->bdrv_co_writev_flags) {

        ret = drv->bdrv_co_writev_flags(bs, sector_num, nb_sectors, qiov,

                                        flags);

    } else {

        assert(drv->supported_write_flags == 0);

        ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);

    }

    if (ret == 0 && (flags & BDRV_REQ_FUA) &&

        !(drv->supported_write_flags & BDRV_REQ_FUA))

    {

        ret = bdrv_co_flush(bs);

    }

    return ret;

}


static void ss10_init(int ram_size, int vga_ram_size, int boot_device,

                            DisplayState *ds, const char **fd_filename, int snapshot,

                            const char *kernel_filename, const char *kernel_cmdline,

                            const char *initrd_filename, const char *cpu_model)

{

    if (cpu_model == NULL)

        cpu_model = "TI SuperSparc II";

    sun4m_common_init(ram_size, boot_device, ds, kernel_filename,

                      kernel_cmdline, initrd_filename, cpu_model,

                      1, PROM_ADDR); // XXX prom overlap, actually first 4GB ok

}


static uint64_t bonito_readl(void *opaque, target_phys_addr_t addr,

                             unsigned size)

{

    PCIBonitoState *s = opaque;

    uint32_t saddr;

    saddr = (addr - BONITO_REGBASE) >> 2;

    DPRINTF("bonito_readl "TARGET_FMT_plx"\n", addr);

    switch (saddr) {

    case BONITO_INTISR:

        return s->regs[saddr];

    default:

        return s->regs[saddr];

    }

}


static int ast_write_header(AVFormatContext *s)

{

    ASTMuxContext *ast = s->priv_data;

    AVIOContext *pb = s->pb;

    AVCodecContext *enc;

    unsigned int codec_tag;

    if (s->nb_streams == 1) {

        enc = s->streams[0]->codec;

    } else {

        av_log(s, AV_LOG_ERROR, "only one stream is supported\n");

        return AVERROR(EINVAL);

    }

    if (enc->codec_id == AV_CODEC_ID_ADPCM_AFC) {

        av_log(s, AV_LOG_ERROR, "muxing ADPCM AFC is not implemented\n");

        return AVERROR_PATCHWELCOME;

    }

    codec_tag = ff_codec_get_tag(ff_codec_ast_tags, enc->codec_id);

    if (!codec_tag) {

        av_log(s, AV_LOG_ERROR, "unsupported codec\n");

        return AVERROR(EINVAL);

    }

    if (ast->loopstart && ast->loopend && ast->loopstart >= ast->loopend) {

        av_log(s, AV_LOG_ERROR, "loopend can't be less or equal to loopstart\n");

        return AVERROR(EINVAL);

    }

    /* Convert milliseconds to samples */

    CHECK_LOOP(start)

    CHECK_LOOP(end)

    ffio_wfourcc(pb, "STRM");

    ast->size = avio_tell(pb);

    avio_wb32(pb, 0); /* File size minus header */

    avio_wb16(pb, codec_tag);

    avio_wb16(pb, 16); /* Bit depth */

    avio_wb16(pb, enc->channels);

    avio_wb16(pb, 0xFFFF);

    avio_wb32(pb, enc->sample_rate);

    ast->samples = avio_tell(pb);

    avio_wb32(pb, 0); /* Number of samples */

    avio_wb32(pb, 0); /* Loopstart */

    avio_wb32(pb, 0); /* Loopend */

    avio_wb32(pb, 0); /* Size of first block */

    /* Unknown */

    avio_wb32(pb, 0);

    avio_wl32(pb, 0x7F);

    avio_wb64(pb, 0);

    avio_wb64(pb, 0);

    avio_wb32(pb, 0);

    avio_flush(pb);

    return 0;

}


static int read_old_huffman_tables(HYuvContext *s)

{

    GetBitContext gb;

    int i;

    init_get_bits(&gb, classic_shift_luma,

                  classic_shift_luma_table_size * 8);

    if (read_len_table(s->len[0], &gb) < 0)

        return -1;

    init_get_bits(&gb, classic_shift_chroma,

                  classic_shift_chroma_table_size * 8);

    if (read_len_table(s->len[1], &gb) < 0)

        return -1;

    for(i=0; i<256; i++) s->bits[0][i] = classic_add_luma  [i];

    for(i=0; i<256; i++) s->bits[1][i] = classic_add_chroma[i];

    if (s->bitstream_bpp >= 24) {

        memcpy(s->bits[1], s->bits[0], 256 * sizeof(uint32_t));

        memcpy(s->len[1] , s->len [0], 256 * sizeof(uint8_t));

    }

    memcpy(s->bits[2], s->bits[1], 256 * sizeof(uint32_t));

    memcpy(s->len[2] , s->len [1], 256 * sizeof(uint8_t));

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

        ff_free_vlc(&s->vlc[i]);

        init_vlc(&s->vlc[i], VLC_BITS, 256, s->len[i], 1, 1,

                 s->bits[i], 4, 4, 0);

    }

    generate_joint_tables(s);

    return 0;

}


static void pc_init_isa(MachineState *machine)

{

    has_pci_info = false;

    has_acpi_build = false;

    smbios_defaults = false;

    if (!machine->cpu_model) {

        machine->cpu_model = "486";

    }

    x86_cpu_compat_disable_kvm_features(FEAT_KVM, KVM_FEATURE_PV_EOI);

    enable_compat_apic_id_mode();

    pc_init1(machine, 0, 1);

}


static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,

                           GetBitContext *gb)

{

    const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;

    const int aot = m4ac->object_type;

    const int sampling_index = m4ac->sampling_index;

    if (aot != AOT_ER_AAC_ELD) {

        if (get_bits1(gb)) {

            av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");

            return AVERROR_INVALIDDATA;

        }

        ics->window_sequence[1] = ics->window_sequence[0];

        ics->window_sequence[0] = get_bits(gb, 2);

        if (aot == AOT_ER_AAC_LD &&

            ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {

            av_log(ac->avctx, AV_LOG_ERROR,

                   "AAC LD is only defined for ONLY_LONG_SEQUENCE but "

                   "window sequence %d found.\n", ics->window_sequence[0]);

            ics->window_sequence[0] = ONLY_LONG_SEQUENCE;

            return AVERROR_INVALIDDATA;

        }

        ics->use_kb_window[1]   = ics->use_kb_window[0];

        ics->use_kb_window[0]   = get_bits1(gb);

    }

    ics->num_window_groups  = 1;

    ics->group_len[0]       = 1;

    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {

        int i;

        ics->max_sfb = get_bits(gb, 4);

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

            if (get_bits1(gb)) {

                ics->group_len[ics->num_window_groups - 1]++;

            } else {

                ics->num_window_groups++;

                ics->group_len[ics->num_window_groups - 1] = 1;

            }

        }

        ics->num_windows       = 8;

        ics->swb_offset        =    ff_swb_offset_128[sampling_index];

        ics->num_swb           =   ff_aac_num_swb_128[sampling_index];

        ics->tns_max_bands     = ff_tns_max_bands_128[sampling_index];

        ics->predictor_present = 0;

    } else {

        ics->max_sfb           = get_bits(gb, 6);

        ics->num_windows       = 1;

        if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {

            if (m4ac->frame_length_short) {

                ics->swb_offset    =     ff_swb_offset_480[sampling_index];

                ics->num_swb       =    ff_aac_num_swb_480[sampling_index];

                ics->tns_max_bands =  ff_tns_max_bands_480[sampling_index];

            } else {

                ics->swb_offset    =     ff_swb_offset_512[sampling_index];

                ics->num_swb       =    ff_aac_num_swb_512[sampling_index];

                ics->tns_max_bands =  ff_tns_max_bands_512[sampling_index];

            }

            if (!ics->num_swb || !ics->swb_offset)

                return AVERROR_BUG;

        } else {

            ics->swb_offset    =    ff_swb_offset_1024[sampling_index];

            ics->num_swb       =   ff_aac_num_swb_1024[sampling_index];

            ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];

        }

        if (aot != AOT_ER_AAC_ELD) {

            ics->predictor_present     = get_bits1(gb);

            ics->predictor_reset_group = 0;

        }

        if (ics->predictor_present) {

            if (aot == AOT_AAC_MAIN) {

                if (decode_prediction(ac, ics, gb)) {

                    return AVERROR_INVALIDDATA;

                }

            } else if (aot == AOT_AAC_LC ||

                       aot == AOT_ER_AAC_LC) {

                av_log(ac->avctx, AV_LOG_ERROR,

                       "Prediction is not allowed in AAC-LC.\n");

                return AVERROR_INVALIDDATA;

            } else {

                if (aot == AOT_ER_AAC_LD) {

                    av_log(ac->avctx, AV_LOG_ERROR,

                           "LTP in ER AAC LD not yet implemented.\n");

                    return AVERROR_PATCHWELCOME;

                }

                if ((ics->ltp.present = get_bits(gb, 1)))

                    decode_ltp(&ics->ltp, gb, ics->max_sfb);

            }

        }

    }

    if (ics->max_sfb > ics->num_swb) {

        av_log(ac->avctx, AV_LOG_ERROR,

               "Number of scalefactor bands in group (%d) "

               "exceeds limit (%d).\n",

               ics->max_sfb, ics->num_swb);

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


static void dvbsub_parse_region_segment(AVCodecContext *avctx,

                                        uint8_t *buf, int buf_size)

{

    DVBSubContext *ctx = (DVBSubContext*) avctx->priv_data;

    uint8_t *buf_end = buf + buf_size;

    int region_id, object_id;

    DVBSubRegion *region;

    DVBSubObject *object;

    DVBSubObjectDisplay *display;

    int fill;

    if (buf_size < 10)

        return;

    region_id = *buf++;

    region = get_region(ctx, region_id);

    if (region == NULL)

    {

        region = av_mallocz(sizeof(DVBSubRegion));

        region->id = region_id;

        region->next = ctx->region_list;

        ctx->region_list = region;

    fill = ((*buf++) >> 3) & 1;

    region->width = AV_RB16(buf);

    buf += 2;

    region->height = AV_RB16(buf);

    buf += 2;

    if (region->width * region->height != region->buf_size) {

        if (region->pbuf != 0)

            av_free(region->pbuf);

        region->buf_size = region->width * region->height;

        region->pbuf = av_malloc(region->buf_size);

        fill = 1;

    region->depth = 1 << (((*buf++) >> 2) & 7);

    region->clut = *buf++;

    if (region->depth == 8)

        region->bgcolour = *buf++;

    else {

        buf += 1;

        if (region->depth == 4)

            region->bgcolour = (((*buf++) >> 4) & 15);

        else

            region->bgcolour = (((*buf++) >> 2) & 3);

#ifdef DEBUG

    av_log(avctx, AV_LOG_INFO, "Region %d, (%dx%d)\n", region_id, region->width, region->height);

#endif

    if (fill) {

        memset(region->pbuf, region->bgcolour, region->buf_size);

#ifdef DEBUG

        av_log(avctx, AV_LOG_INFO, "Fill region (%d)\n", region->bgcolour);

#endif

    delete_region_display_list(ctx, region);

    while (buf + 5 < buf_end) {

        object_id = AV_RB16(buf);

        buf += 2;

        object = get_object(ctx, object_id);

        if (object == NULL) {

            object = av_mallocz(sizeof(DVBSubObject));

            object->id = object_id;

            object->next = ctx->object_list;

            ctx->object_list = object;

        object->type = (*buf) >> 6;

        display = av_mallocz(sizeof(DVBSubObjectDisplay));

        display->object_id = object_id;

        display->region_id = region_id;

        display->x_pos = AV_RB16(buf) & 0xfff;

        buf += 2;

        display->y_pos = AV_RB16(buf) & 0xfff;

        buf += 2;

        if ((object->type == 1 || object->type == 2) && buf+1 < buf_end) {

            display->fgcolour = *buf++;

            display->bgcolour = *buf++;

        display->region_list_next = region->display_list;

        region->display_list = display;

        display->object_list_next = object->display_list;

        object->display_list = display;


int ff_unlock_avcodec(const AVCodec *codec)

{

    if (codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE || !codec->init)

        return 0;

    av_assert0(ff_avcodec_locked);

    ff_avcodec_locked = 0;

    atomic_fetch_add(&entangled_thread_counter, -1);

    if (lockmgr_cb) {

        if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE))

            return -1;

    }

    return 0;

}


static inline void copy(LZOContext *c, int cnt)

{

    register const uint8_t *src = c->in;

    register uint8_t *dst       = c->out;

    if (cnt > c->in_end - src) {

        cnt       = FFMAX(c->in_end - src, 0);

        c->error |= AV_LZO_INPUT_DEPLETED;

    }

    if (cnt > c->out_end - dst) {

        cnt       = FFMAX(c->out_end - dst, 0);

        c->error |= AV_LZO_OUTPUT_FULL;

    }

#if defined(INBUF_PADDED) && defined(OUTBUF_PADDED)

    AV_COPY32U(dst, src);

    src += 4;

    dst += 4;

    cnt -= 4;

    if (cnt > 0)

#endif

    memcpy(dst, src, cnt);

    c->in  = src + cnt;

    c->out = dst + cnt;

}


static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid)

{

    MXFDescriptor *descriptor = arg;

    switch(tag) {

    case 0x3F01:

        descriptor->sub_descriptors_count = avio_rb32(pb);

        if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))

            return -1;

        descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));

        if (!descriptor->sub_descriptors_refs)

            return -1;

        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */

        avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));

        break;

    case 0x3004:

        avio_read(pb, descriptor->essence_container_ul, 16);

        break;

    case 0x3006:

        descriptor->linked_track_id = avio_rb32(pb);

        break;

    case 0x3201: /* PictureEssenceCoding */

        avio_read(pb, descriptor->essence_codec_ul, 16);

        break;

    case 0x3203:

        descriptor->width = avio_rb32(pb);

        break;

    case 0x3202:

        descriptor->height = avio_rb32(pb);

        break;

    case 0x320E:

        descriptor->aspect_ratio.num = avio_rb32(pb);

        descriptor->aspect_ratio.den = avio_rb32(pb);

        break;

    case 0x3D03:

        descriptor->sample_rate.num = avio_rb32(pb);

        descriptor->sample_rate.den = avio_rb32(pb);

        break;

    case 0x3D06: /* SoundEssenceCompression */

        avio_read(pb, descriptor->essence_codec_ul, 16);

        break;

    case 0x3D07:

        descriptor->channels = avio_rb32(pb);

        break;

    case 0x3D01:

        descriptor->bits_per_sample = avio_rb32(pb);

        break;

    case 0x3401:

        mxf_read_pixel_layout(pb, descriptor);

        break;

    default:

        /* Private uid used by SONY C0023S01.mxf */

        if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {

            descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!descriptor->extradata)

                return -1;

            descriptor->extradata_size = size;

            avio_read(pb, descriptor->extradata, size);

        }

        break;

    }

    return 0;

}


static int fir_channel(AVFilterContext *ctx, void *arg, int ch, int nb_jobs)

{

    AudioFIRContext *s = ctx->priv;

    const float *src = (const float *)s->in[0]->extended_data[ch];

    int index1 = (s->index + 1) % 3;

    int index2 = (s->index + 2) % 3;

    float *sum = s->sum[ch];

    AVFrame *out = arg;

    float *block;

    float *dst;

    int n, i, j;

    memset(sum, 0, sizeof(*sum) * s->fft_length);

    block = s->block[ch] + s->part_index * s->block_size;

    memset(block, 0, sizeof(*block) * s->fft_length);

    s->fdsp->vector_fmul_scalar(block + s->part_size, src, s->dry_gain, s->nb_samples);

    emms_c();

    av_rdft_calc(s->rdft[ch], block);

    block[2 * s->part_size] = block[1];

    block[1] = 0;

    j = s->part_index;

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

        const int coffset = i * s->coeff_size;

        const FFTComplex *coeff = s->coeff[ch * !s->one2many] + coffset;

        block = s->block[ch] + j * s->block_size;

        s->fcmul_add(sum, block, (const float *)coeff, s->part_size);

        if (j == 0)

            j = s->nb_partitions;

        j--;

    }

    sum[1] = sum[2 * s->part_size];

    av_rdft_calc(s->irdft[ch], sum);

    dst = (float *)s->buffer->extended_data[ch] + index1 * s->part_size;

    for (n = 0; n < s->part_size; n++) {

        dst[n] += sum[n];

    }

    dst = (float *)s->buffer->extended_data[ch] + index2 * s->part_size;

    memcpy(dst, sum + s->part_size, s->part_size * sizeof(*dst));

    dst = (float *)s->buffer->extended_data[ch] + s->index * s->part_size;

    if (out) {

        float *ptr = (float *)out->extended_data[ch];

        s->fdsp->vector_fmul_scalar(ptr, dst, s->gain * s->wet_gain, out->nb_samples);

        emms_c();

    }

    return 0;

}


static int aiff_read_packet(AVFormatContext *s,

                            AVPacket *pkt)

{

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

    AIFFInputContext *aiff = s->priv_data;

    int64_t max_size;

    int res, size;

    /* calculate size of remaining data */

    max_size = aiff->data_end - avio_tell(s->pb);

    if (max_size <= 0)

        return AVERROR_EOF;

    /* Now for that packet */

    if (st->codec->block_align >= 17) // GSM, QCLP, IMA4

        size = st->codec->block_align;

    else

        size = (MAX_SIZE / st->codec->block_align) * st->codec->block_align;

    size = FFMIN(max_size, size);

    res = av_get_packet(s->pb, pkt, size);

    if (res < 0)

        return res;

    if (size >= st->codec->block_align)

        pkt->flags &= ~AV_PKT_FLAG_CORRUPT;

    /* Only one stream in an AIFF file */

    pkt->stream_index = 0;

    pkt->duration     = (res / st->codec->block_align) * aiff->block_duration;

    return 0;

}


static int get_riff(AVFormatContext *s, AVIOContext *pb)

{

    AVIContext *avi = s->priv_data;

    char header[8];

    int i;

    /* check RIFF header */

    avio_read(pb, header, 4);

    avi->riff_end  = avio_rl32(pb); /* RIFF chunk size */

    avi->riff_end += avio_tell(pb); /* RIFF chunk end */

    avio_read(pb, header + 4, 4);

    for (i = 0; avi_headers[i][0]; i++)

        if (!memcmp(header, avi_headers[i], 8))

            break;

    if (!avi_headers[i][0])

        return AVERROR_INVALIDDATA;

    if (header[7] == 0x19)

        av_log(s, AV_LOG_INFO,

               "This file has been generated by a totally broken muxer.\n");

    return 0;

}


static int decode_segment(TAKDecContext *s, int8_t mode, int32_t *decoded, int len)

{

    struct CParam code;

    GetBitContext *gb = &s->gb;

    int i;

    if (!mode) {

        memset(decoded, 0, len * sizeof(*decoded));

        return 0;

    }

    if (mode > FF_ARRAY_ELEMS(xcodes))

        return AVERROR_INVALIDDATA;

    code = xcodes[mode - 1];

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

        int x = get_bits_long(gb, code.init);

        if (x >= code.escape && get_bits1(gb)) {

            x |= 1 << code.init;

            if (x >= code.aescape) {

                int scale = get_unary(gb, 1, 9);

                if (scale == 9) {

                    int scale_bits = get_bits(gb, 3);

                    if (scale_bits > 0) {

                        if (scale_bits == 7) {

                            scale_bits += get_bits(gb, 5);

                            if (scale_bits > 29)

                                return AVERROR_INVALIDDATA;

                        }

                        scale = get_bits_long(gb, scale_bits) + 1;

                        x    += code.scale * scale;

                    }

                    x += code.bias;

                } else

                    x += code.scale * scale - code.escape;

            } else

                x -= code.escape;

        }

        decoded[i] = (x >> 1) ^ -(x & 1);

    }

    return 0;

}


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

                            int *got_frame, AVPacket *pkt)

{

    PAFVideoDecContext *c = avctx->priv_data;

    uint8_t code, *dst, *end;

    int i, frame, ret;

    if (pkt->size < 2)

        return AVERROR_INVALIDDATA;

    bytestream2_init(&c->gb, pkt->data, pkt->size);

    code = bytestream2_get_byte(&c->gb);

    if ((code & 0xF) > 4) {

        avpriv_request_sample(avctx, "unknown/invalid code");

        return AVERROR_INVALIDDATA;

    }

    if ((ret = ff_reget_buffer(avctx, c->pic)) < 0)

        return ret;

    if (code & 0x20) {  // frame is keyframe

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

            memset(c->frame[i], 0, c->frame_size);

        memset(c->pic->data[1], 0, AVPALETTE_SIZE);

        c->current_frame  = 0;

        c->pic->key_frame = 1;

        c->pic->pict_type = AV_PICTURE_TYPE_I;

    } else {

        c->pic->key_frame = 0;

        c->pic->pict_type = AV_PICTURE_TYPE_P;

    }

    if (code & 0x40) {  // palette update

        uint32_t *out = (uint32_t *)c->pic->data[1];

        int index, count;

        index = bytestream2_get_byte(&c->gb);

        count = bytestream2_get_byte(&c->gb) + 1;

        if (index + count > 256)

            return AVERROR_INVALIDDATA;

        if (bytestream2_get_bytes_left(&c->gb) < 3 * count)

            return AVERROR_INVALIDDATA;

        out += index;

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

            unsigned r, g, b;

            r = bytestream2_get_byteu(&c->gb);

            r = r << 2 | r >> 4;

            g = bytestream2_get_byteu(&c->gb);

            g = g << 2 | g >> 4;

            b = bytestream2_get_byteu(&c->gb);

            b = b << 2 | b >> 4;

            *out++ = (0xFFU << 24) | (r << 16) | (g << 8) | b;

        }

        c->pic->palette_has_changed = 1;

    }

    switch (code & 0x0F) {

    case 0:

        /* Block-based motion compensation using 4x4 blocks with either

         * horizontal or vertical vectors; might incorporate VQ as well. */

        if ((ret = decode_0(c, pkt->data, code)) < 0)

            return ret;

        break;

    case 1:

        /* Uncompressed data. This mode specifies that (width * height) bytes

         * should be copied directly from the encoded buffer into the output. */

        dst = c->frame[c->current_frame];

        // possibly chunk length data

        bytestream2_skip(&c->gb, 2);

        if (bytestream2_get_bytes_left(&c->gb) < c->video_size)

            return AVERROR_INVALIDDATA;

        bytestream2_get_bufferu(&c->gb, dst, c->video_size);

        break;

    case 2:

        /* Copy reference frame: Consume the next byte in the stream as the

         * reference frame (which should be 0, 1, 2, or 3, and should not be

         * the same as the current frame number). */

        frame = bytestream2_get_byte(&c->gb);

        if (frame > 3)

            return AVERROR_INVALIDDATA;

        if (frame != c->current_frame)

            memcpy(c->frame[c->current_frame], c->frame[frame], c->frame_size);

        break;

    case 4:

        /* Run length encoding.*/

        dst = c->frame[c->current_frame];

        end = dst + c->video_size;

        bytestream2_skip(&c->gb, 2);

        while (dst < end) {

            int8_t code;

            int count;

            if (bytestream2_get_bytes_left(&c->gb) < 2)

                return AVERROR_INVALIDDATA;

            code  = bytestream2_get_byteu(&c->gb);

            count = FFABS(code) + 1;

            if (dst + count > end)

                return AVERROR_INVALIDDATA;

            if (code < 0)

                memset(dst, bytestream2_get_byteu(&c->gb), count);

            else

                bytestream2_get_buffer(&c->gb, dst, count);

            dst += count;

        }

        break;

    default:

        av_assert0(0);

    }

    av_image_copy_plane(c->pic->data[0], c->pic->linesize[0],

                        c->frame[c->current_frame], c->width,

                        c->width, c->height);

    c->current_frame = (c->current_frame + 1) & 3;

    if ((ret = av_frame_ref(data, c->pic)) < 0)

        return ret;

    *got_frame = 1;

    return pkt->size;

}


int avresample_get_matrix(AVAudioResampleContext *avr, double *matrix,

                          int stride)

{

    int in_channels, out_channels, i, o;

    in_channels  = av_get_channel_layout_nb_channels(avr->in_channel_layout);

    out_channels = av_get_channel_layout_nb_channels(avr->out_channel_layout);

    if ( in_channels < 0 ||  in_channels > AVRESAMPLE_MAX_CHANNELS ||

        out_channels < 0 || out_channels > AVRESAMPLE_MAX_CHANNELS) {

        av_log(avr, AV_LOG_ERROR, "Invalid channel layouts\n");

        return AVERROR(EINVAL);

    }

    switch (avr->mix_coeff_type) {

    case AV_MIX_COEFF_TYPE_Q8:

        if (!avr->am->matrix_q8[0]) {

            av_log(avr, AV_LOG_ERROR, "matrix is not set\n");

            return AVERROR(EINVAL);

        }

        for (o = 0; o < out_channels; o++)

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

                matrix[o * stride + i] = avr->am->matrix_q8[o][i] / 256.0;

        break;

    case AV_MIX_COEFF_TYPE_Q15:

        if (!avr->am->matrix_q15[0]) {

            av_log(avr, AV_LOG_ERROR, "matrix is not set\n");

            return AVERROR(EINVAL);

        }

        for (o = 0; o < out_channels; o++)

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

                matrix[o * stride + i] = avr->am->matrix_q15[o][i] / 32768.0;

        break;

    case AV_MIX_COEFF_TYPE_FLT:

        if (!avr->am->matrix_flt[0]) {

            av_log(avr, AV_LOG_ERROR, "matrix is not set\n");

            return AVERROR(EINVAL);

        }

        for (o = 0; o < out_channels; o++)

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

                matrix[o * stride + i] = avr->am->matrix_flt[o][i];

        break;

    default:

        av_log(avr, AV_LOG_ERROR, "Invalid mix coeff type\n");

        return AVERROR(EINVAL);

    }

    return 0;

}


static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)

{

    AVPacket out_pkt = { 0 }, flush_pkt = { 0 };

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

    uint8_t *data = pkt ? pkt->data : NULL;

    int size      = pkt ? pkt->size : 0;

    int ret = 0, got_output = 0;

    if (!pkt) {

        av_init_packet(&flush_pkt);

        pkt        = &flush_pkt;

        got_output = 1;

    }

    while (size > 0 || (pkt == &flush_pkt && got_output)) {

        int len;

        av_init_packet(&out_pkt);

        len = av_parser_parse2(st->parser, st->codec,

                               &out_pkt.data, &out_pkt.size, data, size,

                               pkt->pts, pkt->dts, pkt->pos);

        pkt->pts = pkt->dts = AV_NOPTS_VALUE;

        /* increment read pointer */

        data += len;

        size -= len;

        got_output = !!out_pkt.size;

        if (!out_pkt.size)

            continue;

        if (pkt->side_data) {

            out_pkt.side_data       = pkt->side_data;

            out_pkt.side_data_elems = pkt->side_data_elems;

            pkt->side_data          = NULL;

            pkt->side_data_elems    = 0;

        }

        /* set the duration */

        out_pkt.duration = 0;

        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (st->codec->sample_rate > 0) {

                out_pkt.duration =

                    av_rescale_q_rnd(st->parser->duration,

                                     (AVRational) { 1, st->codec->sample_rate },

                                     st->time_base,

                                     AV_ROUND_DOWN);

            }

        }

        out_pkt.stream_index = st->index;

        out_pkt.pts          = st->parser->pts;

        out_pkt.dts          = st->parser->dts;

        out_pkt.pos          = st->parser->pos;

        if (st->parser->key_frame == 1 ||

            (st->parser->key_frame == -1 &&

             st->parser->pict_type == AV_PICTURE_TYPE_I))

            out_pkt.flags |= AV_PKT_FLAG_KEY;

        compute_pkt_fields(s, st, st->parser, &out_pkt);

        if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&

            out_pkt.flags & AV_PKT_FLAG_KEY) {

            ff_reduce_index(s, st->index);

            av_add_index_entry(st, st->parser->frame_offset, out_pkt.dts,

                               0, 0, AVINDEX_KEYFRAME);

        }

        if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {

            out_pkt.buf = pkt->buf;

            pkt->buf    = NULL;

        }

        if ((ret = av_dup_packet(&out_pkt)) < 0)

            goto fail;

        if (!add_to_pktbuf(&s->internal->parse_queue, &out_pkt, &s->internal->parse_queue_end)) {

            av_packet_unref(&out_pkt);

            ret = AVERROR(ENOMEM);

            goto fail;

        }

    }

    /* end of the stream => close and free the parser */

    if (pkt == &flush_pkt) {

        av_parser_close(st->parser);

        st->parser = NULL;

    }

fail:

    av_packet_unref(pkt);

    return ret;

}


int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt,

                      uint8_t* buf, int buf_size, int64_t pos)

{

    int size, i;

    uint8_t *ppcm[4] = {0};

    if (buf_size < DV_PROFILE_BYTES ||

        !(c->sys = avpriv_dv_frame_profile(c->sys, buf, buf_size)) ||

        buf_size < c->sys->frame_size) {

          return -1;   /* Broken frame, or not enough data */

    }

    /* Queueing audio packet */

    /* FIXME: in case of no audio/bad audio we have to do something */

    size = dv_extract_audio_info(c, buf);

    for (i = 0; i < c->ach; i++) {

       c->audio_pkt[i].pos  = pos;

       c->audio_pkt[i].size = size;

       c->audio_pkt[i].pts  = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate;

       ppcm[i] = c->audio_buf[i];

    }

    dv_extract_audio(buf, ppcm, c->sys);

    /* We work with 720p frames split in half, thus even frames have

     * channels 0,1 and odd 2,3. */

    if (c->sys->height == 720) {

        if (buf[1] & 0x0C) {

            c->audio_pkt[2].size = c->audio_pkt[3].size = 0;

        } else {

            c->audio_pkt[0].size = c->audio_pkt[1].size = 0;

            c->abytes += size;

        }

    } else {

        c->abytes += size;

    }

    /* Now it's time to return video packet */

    size = dv_extract_video_info(c, buf);

    av_init_packet(pkt);

    pkt->data         = buf;

    pkt->pos          = pos;

    pkt->size         = size;

    pkt->flags       |= AV_PKT_FLAG_KEY;

    pkt->stream_index = c->vst->id;

    pkt->pts          = c->frames;

    c->frames++;

    return size;

}


int mmu40x_get_physical_address (CPUState *env, mmu_ctx_t *ctx,

                                 target_ulong address, int rw, int access_type)

{

    ppcemb_tlb_t *tlb;

    target_phys_addr_t raddr;

    int i, ret, zsel, zpr, pr;

    ret = -1;

    raddr = -1;

    pr = msr_pr;

    for (i = 0; i < env->nb_tlb; i++) {

        tlb = &env->tlb[i].tlbe;

        if (ppcemb_tlb_check(env, tlb, &raddr, address,

                             env->spr[SPR_40x_PID], 0, i) < 0)

            continue;

        zsel = (tlb->attr >> 4) & 0xF;

        zpr = (env->spr[SPR_40x_ZPR] >> (28 - (2 * zsel))) & 0x3;

#if defined (DEBUG_SOFTWARE_TLB)

        if (loglevel != 0) {

            fprintf(logfile, "%s: TLB %d zsel %d zpr %d rw %d attr %08x\n",

                    __func__, i, zsel, zpr, rw, tlb->attr);

        }

#endif

        /* Check execute enable bit */

        switch (zpr) {

        case 0x2:

            if (pr != 0)

                goto check_perms;

            /* No break here */

        case 0x3:

            /* All accesses granted */

            ctx->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

            ret = 0;

            break;

        case 0x0:

            if (pr != 0) {

                ctx->prot = 0;

                ret = -2;

                break;

            }

            /* No break here */

        case 0x1:

        check_perms:

            /* Check from TLB entry */

            /* XXX: there is a problem here or in the TLB fill code... */

            ctx->prot = tlb->prot;

            ctx->prot |= PAGE_EXEC;

            ret = check_prot(ctx->prot, rw, access_type);

            break;

        }

        if (ret >= 0) {

            ctx->raddr = raddr;

#if defined (DEBUG_SOFTWARE_TLB)

            if (loglevel != 0) {

                fprintf(logfile, "%s: access granted " ADDRX " => " REGX

                        " %d %d\n", __func__, address, ctx->raddr, ctx->prot,

                        ret);

            }

#endif

            return 0;

        }

    }

#if defined (DEBUG_SOFTWARE_TLB)

    if (loglevel != 0) {

        fprintf(logfile, "%s: access refused " ADDRX " => " REGX

                " %d %d\n", __func__, address, raddr, ctx->prot,

                ret);

    }

#endif

    return ret;

}


int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)

{

    int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;

    if (bs->dirty_bitmap != NULL &&

        (sector << BDRV_SECTOR_BITS) <= bdrv_getlength(bs)) {

        return bs->dirty_bitmap[chunk];

    } else {

        return 0;

    }

}


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

                            int *got_frame, AVPacket *avpkt)

{

    GDVContext *gdv = avctx->priv_data;

    GetByteContext *gb = &gdv->gb;

    PutByteContext *pb = &gdv->pb;

    AVFrame *frame = data;

    int ret, i, pal_size;

    const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &pal_size);

    int compression;

    unsigned flags;

    uint8_t *dst;

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

        return ret;

    if (pal && pal_size == AVPALETTE_SIZE)

        memcpy(gdv->pal, pal, AVPALETTE_SIZE);

    bytestream2_init(gb, avpkt->data, avpkt->size);

    bytestream2_init_writer(pb, gdv->frame, gdv->frame_size);

    flags = bytestream2_get_le32(gb);

    compression = flags & 0xF;

    rescale(gdv, gdv->frame, avctx->width, avctx->height,

            !!(flags & 0x10), !!(flags & 0x20));

    switch (compression) {

    case 1:

        memset(gdv->frame + PREAMBLE_SIZE, 0, gdv->frame_size - PREAMBLE_SIZE);

    case 0:

        if (bytestream2_get_bytes_left(gb) < 256*3)

            return AVERROR_INVALIDDATA;

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

            unsigned r = bytestream2_get_byte(gb);

            unsigned g = bytestream2_get_byte(gb);

            unsigned b = bytestream2_get_byte(gb);

            gdv->pal[i] = 0xFFU << 24 | r << 18 | g << 10 | b << 2;

        }

        break;

    case 2:

        ret = decompress_2(avctx);

        break;

    case 3:

        break;

    case 5:

        ret = decompress_5(avctx, flags >> 8);

        break;

    case 6:

        ret = decompress_68(avctx, flags >> 8, 0);

        break;

    case 8:

        ret = decompress_68(avctx, flags >> 8, 1);

        break;

    default:

        return AVERROR_INVALIDDATA;

    }

    memcpy(frame->data[1], gdv->pal, AVPALETTE_SIZE);

    dst = frame->data[0];

    if (!gdv->scale_v && !gdv->scale_h) {

        int sidx = PREAMBLE_SIZE, didx = 0;

        int y, x;

        for (y = 0; y < avctx->height; y++) {

            for (x = 0; x < avctx->width; x++) {

                dst[x+didx] = gdv->frame[x+sidx];

            }

            sidx += avctx->width;

            didx += frame->linesize[0];

        }

    } else {

        int sidx = PREAMBLE_SIZE, didx = 0;

        int y, x;

        for (y = 0; y < avctx->height; y++) {

            if (!gdv->scale_v) {

                for (x = 0; x < avctx->width; x++) {

                    dst[didx + x] = gdv->frame[sidx + x];

                }

            } else {

                for (x = 0; x < avctx->width; x++) {

                    dst[didx + x] = gdv->frame[sidx + x/2];

                }

            }

            if (!gdv->scale_h || ((y & 1) == 1)) {

                sidx += !gdv->scale_v ? avctx->width : avctx->width/2;

            }

            didx += frame->linesize[0];

        }

    }

    *got_frame = 1;

    return ret < 0 ? ret : avpkt->size;

}


int ff_rle_encode(uint8_t *outbuf, int out_size, const uint8_t *ptr , int bpp, int w,

                  int add_rep, int xor_rep, int add_raw, int xor_raw)

{

    int count, x;

    uint8_t *out = outbuf;

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

        /* see if we can encode the next set of pixels with RLE */

        if((count = count_pixels(ptr, w-x, bpp, 1)) > 1) {

            if(out + bpp + 1 > outbuf + out_size) return -1;

            *out++ = (count ^ xor_rep) + add_rep;

            memcpy(out, ptr, bpp);

            out += bpp;

        } else {

            /* fall back on uncompressed */

            count = count_pixels(ptr, w-x, bpp, 0);

            *out++ = (count ^ xor_raw) + add_raw;

            if(out + bpp*count > outbuf + out_size) return -1;

            memcpy(out, ptr, bpp * count);

            out += bpp * count;

        }

        ptr += count * bpp;

    }

    return out - outbuf;

}


static void stream_component_close(VideoState *is, int stream_index)

{

    AVFormatContext *ic = is->ic;

    AVCodecContext *avctx;

    if (stream_index < 0 || stream_index >= ic->nb_streams)

        return;

    avctx = ic->streams[stream_index]->codec;

    switch (avctx->codec_type) {

    case AVMEDIA_TYPE_AUDIO:

        packet_queue_abort(&is->audioq);

        SDL_CloseAudio();

        packet_queue_flush(&is->audioq);

        av_free_packet(&is->audio_pkt);

        if (is->swr_ctx)

            swr_free(&is->swr_ctx);

        av_freep(&is->audio_buf1);

        is->audio_buf = NULL;

        av_freep(&is->frame);

        if (is->rdft) {

            av_rdft_end(is->rdft);

            av_freep(&is->rdft_data);

            is->rdft = NULL;

            is->rdft_bits = 0;

        }

        break;

    case AVMEDIA_TYPE_VIDEO:

        packet_queue_abort(&is->videoq);

        /* note: we also signal this mutex to make sure we deblock the

           video thread in all cases */

        SDL_LockMutex(is->pictq_mutex);

        SDL_CondSignal(is->pictq_cond);

        SDL_UnlockMutex(is->pictq_mutex);

        SDL_WaitThread(is->video_tid, NULL);

        packet_queue_flush(&is->videoq);

        break;

    case AVMEDIA_TYPE_SUBTITLE:

        packet_queue_abort(&is->subtitleq);

        /* note: we also signal this mutex to make sure we deblock the

           video thread in all cases */

        SDL_LockMutex(is->subpq_mutex);

        is->subtitle_stream_changed = 1;

        SDL_CondSignal(is->subpq_cond);

        SDL_UnlockMutex(is->subpq_mutex);

        SDL_WaitThread(is->subtitle_tid, NULL);

        packet_queue_flush(&is->subtitleq);

        break;

    default:

        break;

    }

    ic->streams[stream_index]->discard = AVDISCARD_ALL;

    avcodec_close(avctx);

#if CONFIG_AVFILTER

    free_buffer_pool(&is->buffer_pool);

#endif

    switch (avctx->codec_type) {

    case AVMEDIA_TYPE_AUDIO:

        is->audio_st = NULL;

        is->audio_stream = -1;

        break;

    case AVMEDIA_TYPE_VIDEO:

        is->video_st = NULL;

        is->video_stream = -1;

        break;

    case AVMEDIA_TYPE_SUBTITLE:

        is->subtitle_st = NULL;

        is->subtitle_stream = -1;

        break;

    default:

        break;

    }

}


static inline int mpeg1_decode_block_inter(MpegEncContext *s, int16_t *block, int n)

{

    int level, i, j, run;

    RLTable *rl = &ff_rl_mpeg1;

    uint8_t * const scantable    = s->intra_scantable.permutated;

    const uint16_t *quant_matrix = s->inter_matrix;

    const int qscale             = s->qscale;

    {

        OPEN_READER(re, &s->gb);

        i = -1;

        // special case for first coefficient, no need to add second VLC table

        UPDATE_CACHE(re, &s->gb);

        if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {

            level = (3 * qscale * quant_matrix[0]) >> 5;

            level = (level - 1) | 1;

            if (GET_CACHE(re, &s->gb) & 0x40000000)

                level = -level;

            block[0] = level;

            i++;

            SKIP_BITS(re, &s->gb, 2);

            if (((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)

                goto end;

        }

        /* now quantify & encode AC coefficients */

        for (;;) {

            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);

            if (level != 0) {

                i += run;

                j = scantable[i];

                level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;

                level = (level - 1) | 1;

                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                SKIP_BITS(re, &s->gb, 1);

            } else {

                /* escape */

                run = SHOW_UBITS(re, &s->gb, 6) + 1; LAST_SKIP_BITS(re, &s->gb, 6);

                UPDATE_CACHE(re, &s->gb);

                level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);

                if (level == -128) {

                    level = SHOW_UBITS(re, &s->gb, 8) - 256; SKIP_BITS(re, &s->gb, 8);

                } else if (level == 0) {

                    level = SHOW_UBITS(re, &s->gb, 8)      ; SKIP_BITS(re, &s->gb, 8);

                }

                i += run;

                j = scantable[i];

                if (level < 0) {

                    level = -level;

                    level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;

                    level = (level - 1) | 1;

                    level = -level;

                } else {

                    level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;

                    level = (level - 1) | 1;

                }

            }

            if (i > 63) {

                av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);

                return -1;

            }

            block[j] = level;

            if (((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)

                break;

            UPDATE_CACHE(re, &s->gb);

        }

end:

        LAST_SKIP_BITS(re, &s->gb, 2);

        CLOSE_READER(re, &s->gb);

    }

    s->block_last_index[n] = i;

    return 0;

}


static void vp8_decode_mv_mb_modes(AVCodecContext *avctx, VP8Frame *curframe,

                                   VP8Frame *prev_frame)

{

    VP8Context *s = avctx->priv_data;

    int mb_x, mb_y;

    s->mv_min.y = -MARGIN;

    s->mv_max.y = ((s->mb_height - 1) << 6) + MARGIN;

    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {

        VP8Macroblock *mb = s->macroblocks_base +

                            ((s->mb_width + 1) * (mb_y + 1) + 1);

        int mb_xy = mb_y * s->mb_width;

        AV_WN32A(s->intra4x4_pred_mode_left, DC_PRED * 0x01010101);

        s->mv_min.x = -MARGIN;

        s->mv_max.x = ((s->mb_width - 1) << 6) + MARGIN;

        for (mb_x = 0; mb_x < s->mb_width; mb_x++, mb_xy++, mb++) {

            if (mb_y == 0)

                AV_WN32A((mb - s->mb_width - 1)->intra4x4_pred_mode_top,

                         DC_PRED * 0x01010101);

            decode_mb_mode(s, mb, mb_x, mb_y, curframe->seg_map->data + mb_xy,

                           prev_frame && prev_frame->seg_map ?

                           prev_frame->seg_map->data + mb_xy : NULL, 1);

            s->mv_min.x -= 64;

            s->mv_max.x -= 64;

        }

        s->mv_min.y -= 64;

        s->mv_max.y -= 64;

    }

}


static struct omap_eac_s *omap_eac_init(struct omap_target_agent_s *ta,

                qemu_irq irq, qemu_irq *drq, omap_clk fclk, omap_clk iclk)

{

    struct omap_eac_s *s = (struct omap_eac_s *)

            g_malloc0(sizeof(struct omap_eac_s));

    s->irq = irq;

    s->codec.rxdrq = *drq ++;

    s->codec.txdrq = *drq;

    omap_eac_reset(s);

    AUD_register_card("OMAP EAC", &s->codec.card);

    memory_region_init_io(&s->iomem, NULL, &omap_eac_ops, s, "omap.eac",

                          omap_l4_region_size(ta, 0));

    omap_l4_attach(ta, 0, &s->iomem);

    return s;

}


bool runstate_needs_reset(void)

{

    return runstate_check(RUN_STATE_INTERNAL_ERROR) ||

        runstate_check(RUN_STATE_SHUTDOWN) ||

        runstate_check(RUN_STATE_GUEST_PANICKED);

}


int64_t bdrv_getlength(BlockDriverState *bs)

{

    int64_t ret = bdrv_nb_sectors(bs);

    return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;

}