static int read_packet(AVFormatContext *s1, AVPacket *pkt)

{

    VideoDemuxData *s = s1->priv_data;

    char filename_bytes[1024];

    char *filename = filename_bytes;

    int i;

    int size[3]={0}, ret[3]={0};

    AVIOContext *f[3] = {NULL};

    AVCodecContext *codec= s1->streams[0]->codec;

    if (!s->is_pipe) {

        /* loop over input */

        if (s->loop && s->img_number > s->img_last) {

            s->img_number = s->img_first;

        }

        if (s->img_number > s->img_last)

            return AVERROR_EOF;

        if (s->use_glob) {

#if HAVE_GLOB

            filename = s->globstate.gl_pathv[s->img_number];

#endif

        } else {

        if (av_get_frame_filename(filename_bytes, sizeof(filename_bytes),

                                  s->path, s->img_number)<0 && s->img_number > 1)

            return AVERROR(EIO);

        }

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

            if (avio_open2(&f[i], filename, AVIO_FLAG_READ,

                           &s1->interrupt_callback, NULL) < 0) {

                if(i>=1)

                    break;

                av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",filename);

                return AVERROR(EIO);

            }

            size[i]= avio_size(f[i]);

            if(!s->split_planes)

                break;

            filename[ strlen(filename) - 1 ]= 'U' + i;

        }

        if(codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->width)

            infer_size(&codec->width, &codec->height, size[0]);

    } else {

        f[0] = s1->pb;

        if (url_feof(f[0]))

            return AVERROR(EIO);

        size[0]= 4096;

    }

    av_new_packet(pkt, size[0] + size[1] + size[2]);

    pkt->stream_index = 0;

    pkt->flags |= AV_PKT_FLAG_KEY;

    pkt->size= 0;

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

        if(f[i]){

            ret[i]= avio_read(f[i], pkt->data + pkt->size, size[i]);

            if (!s->is_pipe)

                avio_close(f[i]);

            if(ret[i]>0)

                pkt->size += ret[i];

        }

    }

    if (ret[0] <= 0 || ret[1]<0 || ret[2]<0) {

        av_free_packet(pkt);

        return AVERROR(EIO); /* signal EOF */

    } else {

        s->img_count++;

        s->img_number++;

        return 0;

    }

}


static int smacker_read_header(AVFormatContext *s)
{
    AVIOContext *pb = s->pb;
    SmackerContext *smk = s->priv_data;
    AVStream *st, *ast[7];
    int i, ret;
    int tbase;
    /* read and check header */
    smk->magic = avio_rl32(pb);
    if (smk->magic != MKTAG('S', 'M', 'K', '2') && smk->magic != MKTAG('S', 'M', 'K', '4'))
    smk->width = avio_rl32(pb);
    smk->height = avio_rl32(pb);
    smk->frames = avio_rl32(pb);
    smk->pts_inc = (int32_t)avio_rl32(pb);
    smk->flags = avio_rl32(pb);
    if(smk->flags & SMACKER_FLAG_RING_FRAME)
        smk->frames++;
    for(i = 0; i < 7; i++)
        smk->audio[i] = avio_rl32(pb);
    smk->treesize = avio_rl32(pb);
    if(smk->treesize >= UINT_MAX/4){ // smk->treesize + 16 must not overflow (this check is probably redundant)
        av_log(s, AV_LOG_ERROR, "treesize too large\n");
//FIXME remove extradata "rebuilding"
    smk->mmap_size = avio_rl32(pb);
    smk->mclr_size = avio_rl32(pb);
    smk->full_size = avio_rl32(pb);
    smk->type_size = avio_rl32(pb);
    for(i = 0; i < 7; i++) {
        smk->rates[i]  = avio_rl24(pb);
        smk->aflags[i] = avio_r8(pb);
    smk->pad = avio_rl32(pb);
    /* setup data */
    if(smk->frames > 0xFFFFFF) {
        av_log(s, AV_LOG_ERROR, "Too many frames: %"PRIu32"\n", smk->frames);
    smk->frm_size = av_malloc_array(smk->frames, sizeof(*smk->frm_size));
    smk->frm_flags = av_malloc(smk->frames);
    if (!smk->frm_size || !smk->frm_flags) {
        av_freep(&smk->frm_size);
        av_freep(&smk->frm_flags);
        return AVERROR(ENOMEM);
    smk->is_ver4 = (smk->magic != MKTAG('S', 'M', 'K', '2'));
    /* read frame info */
    for(i = 0; i < smk->frames; i++) {
        smk->frm_size[i] = avio_rl32(pb);
    for(i = 0; i < smk->frames; i++) {
        smk->frm_flags[i] = avio_r8(pb);
    /* init video codec */
    st = avformat_new_stream(s, NULL);
    if (!st)
        return AVERROR(ENOMEM);
    smk->videoindex = st->index;
    st->codec->width = smk->width;
    st->codec->height = smk->height;
    st->codec->pix_fmt = AV_PIX_FMT_PAL8;
    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
    st->codec->codec_id = AV_CODEC_ID_SMACKVIDEO;
    st->codec->codec_tag = smk->magic;
    /* Smacker uses 100000 as internal timebase */
    if(smk->pts_inc < 0)
        smk->pts_inc = -smk->pts_inc;
    else
        smk->pts_inc *= 100;
    tbase = 100000;
    av_reduce(&tbase, &smk->pts_inc, tbase, smk->pts_inc, (1UL<<31)-1);
    avpriv_set_pts_info(st, 33, smk->pts_inc, tbase);
    st->duration = smk->frames;
    /* handle possible audio streams */
    for(i = 0; i < 7; i++) {
        smk->indexes[i] = -1;
        if (smk->rates[i]) {
            ast[i] = avformat_new_stream(s, NULL);
            if (!ast[i])
                return AVERROR(ENOMEM);
            smk->indexes[i] = ast[i]->index;
            ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO;
            if (smk->aflags[i] & SMK_AUD_BINKAUD) {
                ast[i]->codec->codec_id = AV_CODEC_ID_BINKAUDIO_RDFT;
            } else if (smk->aflags[i] & SMK_AUD_USEDCT) {
                ast[i]->codec->codec_id = AV_CODEC_ID_BINKAUDIO_DCT;
            } else if (smk->aflags[i] & SMK_AUD_PACKED){
                ast[i]->codec->codec_id = AV_CODEC_ID_SMACKAUDIO;
                ast[i]->codec->codec_tag = MKTAG('S', 'M', 'K', 'A');
            } else {
                ast[i]->codec->codec_id = AV_CODEC_ID_PCM_U8;
            if (smk->aflags[i] & SMK_AUD_STEREO) {
                ast[i]->codec->channels       = 2;
                ast[i]->codec->channel_layout = AV_CH_LAYOUT_STEREO;
            } else {
                ast[i]->codec->channels       = 1;
                ast[i]->codec->channel_layout = AV_CH_LAYOUT_MONO;
            ast[i]->codec->sample_rate = smk->rates[i];
            ast[i]->codec->bits_per_coded_sample = (smk->aflags[i] & SMK_AUD_16BITS) ? 16 : 8;
            if(ast[i]->codec->bits_per_coded_sample == 16 && ast[i]->codec->codec_id == AV_CODEC_ID_PCM_U8)
                ast[i]->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
            avpriv_set_pts_info(ast[i], 64, 1, ast[i]->codec->sample_rate
                    * ast[i]->codec->channels * ast[i]->codec->bits_per_coded_sample / 8);
    /* load trees to extradata, they will be unpacked by decoder */
    if(ff_alloc_extradata(st->codec, smk->treesize + 16)){
        av_log(s, AV_LOG_ERROR,
               "Cannot allocate %"PRIu32" bytes of extradata\n",
               smk->treesize + 16);
        av_freep(&smk->frm_size);
        av_freep(&smk->frm_flags);
        return AVERROR(ENOMEM);
    ret = avio_read(pb, st->codec->extradata + 16, st->codec->extradata_size - 16);
    if(ret != st->codec->extradata_size - 16){
        av_freep(&smk->frm_size);
        av_freep(&smk->frm_flags);
        return AVERROR(EIO);
    ((int32_t*)st->codec->extradata)[0] = av_le2ne32(smk->mmap_size);
    ((int32_t*)st->codec->extradata)[1] = av_le2ne32(smk->mclr_size);
    ((int32_t*)st->codec->extradata)[2] = av_le2ne32(smk->full_size);
    ((int32_t*)st->codec->extradata)[3] = av_le2ne32(smk->type_size);
    smk->curstream = -1;
    smk->nextpos = avio_tell(pb);
    return 0;


static int coroutine_fn raw_co_discard(BlockDriverState *bs,

                                       int64_t sector_num, int nb_sectors)

{

    return bdrv_co_discard(bs->file->bs, sector_num, nb_sectors);

}


BlockAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,

        BlockCompletionFunc *cb, void *opaque)

{

    trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);

    return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,

                                 BDRV_REQ_ZERO_WRITE | flags,

                                 cb, opaque, true);

}


static void virtio_pci_reset(DeviceState *d)

{

    VirtIOPCIProxy *proxy = container_of(d, VirtIOPCIProxy, pci_dev.qdev);

    virtio_reset(proxy->vdev);

    msix_reset(&proxy->pci_dev);

    proxy->flags = 0;

}


static void tcg_out_dat_rIK(TCGContext *s, int cond, int opc, int opinv,

                            TCGReg dst, TCGReg lhs, TCGArg rhs,

                            bool rhs_is_const)

{

    /* Emit either the reg,imm or reg,reg form of a data-processing insn.

     * rhs must satisfy the "rIK" constraint.

     */

    if (rhs_is_const) {

        int rot = encode_imm(rhs);

        if (rot < 0) {

            rhs = ~rhs;

            rot = encode_imm(rhs);

            assert(rot >= 0);

            opc = opinv;

        }

        tcg_out_dat_imm(s, cond, opc, dst, lhs, rotl(rhs, rot) | (rot << 7));

    } else {

        tcg_out_dat_reg(s, cond, opc, dst, lhs, rhs, SHIFT_IMM_LSL(0));

    }

}


static int twl92230_init(i2c_slave *i2c)

{

    MenelausState *s = FROM_I2C_SLAVE(MenelausState, i2c);

    s->rtc.hz_tm = qemu_new_timer(rt_clock, menelaus_rtc_hz, s);

    /* Three output pins plus one interrupt pin.  */

    qdev_init_gpio_out(&i2c->qdev, s->out, 4);

    qdev_init_gpio_in(&i2c->qdev, menelaus_gpio_set, 3);

    s->pwrbtn = qemu_allocate_irqs(menelaus_pwrbtn_set, s, 1)[0];

    menelaus_reset(&s->i2c);

    return 0;

}


static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)

{

    MOVContext *mov = s->priv_data;

    ByteIOContext *pb = s->pb;

    MOVTrack *trk = &mov->tracks[pkt->stream_index];

    AVCodecContext *enc = trk->enc;

    unsigned int samplesInChunk = 0;

    int size= pkt->size;

    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */

    if (!size) return 0; /* Discard 0 sized packets */

    if (enc->codec_id == CODEC_ID_AMR_NB) {

        /* We must find out how many AMR blocks there are in one packet */

        static uint16_t packed_size[16] =

            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};

        int len = 0;

        while (len < size && samplesInChunk < 100) {

            len += packed_size[(pkt->data[len] >> 3) & 0x0F];

            samplesInChunk++;

        }

        if(samplesInChunk > 1){

            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");

            return -1;

        }

    } else if (trk->sampleSize)

        samplesInChunk = size/trk->sampleSize;

    else

        samplesInChunk = 1;

    /* copy extradata if it exists */

    if (trk->vosLen == 0 && enc->extradata_size > 0) {

        trk->vosLen = enc->extradata_size;

        trk->vosData = av_malloc(trk->vosLen);

        memcpy(trk->vosData, enc->extradata, trk->vosLen);

    }

    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {

        /* from x264 or from bytestream h264 */

        /* nal reformating needed */

        int ret = ff_avc_parse_nal_units(pkt->data, &pkt->data, &pkt->size);

        if (ret < 0)

            return ret;

        assert(pkt->size);

        size = pkt->size;

    } else if (enc->codec_id == CODEC_ID_DNXHD && !trk->vosLen) {

        /* copy frame to create needed atoms */

        trk->vosLen = size;

        trk->vosData = av_malloc(size);

        memcpy(trk->vosData, pkt->data, size);

    }

    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {

        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));

        if (!trk->cluster)

            return -1;

    }

    trk->cluster[trk->entry].pos = url_ftell(pb);

    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;

    trk->cluster[trk->entry].size = size;

    trk->cluster[trk->entry].entries = samplesInChunk;

    trk->cluster[trk->entry].dts = pkt->dts;

    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;

    if (pkt->pts == AV_NOPTS_VALUE) {

        av_log(s, AV_LOG_WARNING, "pts has no value\n");

        pkt->pts = pkt->dts;

    }

    if (pkt->dts != pkt->pts)

        trk->hasBframes = 1;

    trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;

    trk->cluster[trk->entry].key_frame = !!(pkt->flags & PKT_FLAG_KEY);

    if(trk->cluster[trk->entry].key_frame)

        trk->hasKeyframes++;

    trk->entry++;

    trk->sampleCount += samplesInChunk;

    mov->mdat_size += size;

    put_buffer(pb, pkt->data, size);

    put_flush_packet(pb);

    return 0;

}


static void gen_st_cond (DisasContext *ctx, uint32_t opc, int rt,

                         int base, int16_t offset)

{

    const char *opn = "st_cond";

    TCGv t0, t1;

    t0 = tcg_temp_local_new();

    gen_base_offset_addr(ctx, t0, base, offset);

    /* Don't do NOP if destination is zero: we must perform the actual

       memory access. */

    t1 = tcg_temp_local_new();

    gen_load_gpr(t1, rt);

    switch (opc) {

#if defined(TARGET_MIPS64)

    case OPC_SCD:

        save_cpu_state(ctx, 0);

        op_st_scd(t1, t0, rt, ctx);

        opn = "scd";

        break;

#endif

    case OPC_SC:

        save_cpu_state(ctx, 1);

        op_st_sc(t1, t0, rt, ctx);

        opn = "sc";

        break;

    }

    (void)opn; /* avoid a compiler warning */

    MIPS_DEBUG("%s %s, %d(%s)", opn, regnames[rt], offset, regnames[base]);

    tcg_temp_free(t1);

    tcg_temp_free(t0);

}


static int32_t bmdma_prepare_buf(IDEDMA *dma, int is_write)

{

    BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);

    IDEState *s = bmdma_active_if(bm);

    PCIDevice *pci_dev = PCI_DEVICE(bm->pci_dev);

    struct {

        uint32_t addr;

        uint32_t size;

    } prd;

    int l, len;

    pci_dma_sglist_init(&s->sg, pci_dev,

                        s->nsector / (BMDMA_PAGE_SIZE / 512) + 1);

    s->io_buffer_size = 0;

    for(;;) {

        if (bm->cur_prd_len == 0) {

            /* end of table (with a fail safe of one page) */

            if (bm->cur_prd_last ||

                (bm->cur_addr - bm->addr) >= BMDMA_PAGE_SIZE) {

                return s->io_buffer_size;

            }

            pci_dma_read(pci_dev, bm->cur_addr, &prd, 8);

            bm->cur_addr += 8;

            prd.addr = le32_to_cpu(prd.addr);

            prd.size = le32_to_cpu(prd.size);

            len = prd.size & 0xfffe;

            if (len == 0)

                len = 0x10000;

            bm->cur_prd_len = len;

            bm->cur_prd_addr = prd.addr;

            bm->cur_prd_last = (prd.size & 0x80000000);

        }

        l = bm->cur_prd_len;

        if (l > 0) {

            qemu_sglist_add(&s->sg, bm->cur_prd_addr, l);

            /* Note: We limit the max transfer to be 2GiB.

             * This should accommodate the largest ATA transaction

             * for LBA48 (65,536 sectors) and 32K sector sizes. */

            if (s->sg.size > INT32_MAX) {

                error_report("IDE: sglist describes more than 2GiB.");

                break;

            }

            bm->cur_prd_addr += l;

            bm->cur_prd_len -= l;

            s->io_buffer_size += l;

        }

    }

    qemu_sglist_destroy(&s->sg);

    s->io_buffer_size = 0;

    return -1;

}


static int apply_window_and_mdct(vorbis_enc_context *venc,

                                 float *audio, int samples)

{

    int channel;

    const float * win = venc->win[0];

    int window_len = 1 << (venc->log2_blocksize[0] - 1);

    float n = (float)(1 << venc->log2_blocksize[0]) / 4.0;

    AVFloatDSPContext *fdsp = venc->fdsp;

    if (!venc->have_saved && !samples)

        return 0;

    if (venc->have_saved) {

        for (channel = 0; channel < venc->channels; channel++)

            memcpy(venc->samples + channel * window_len * 2,

                   venc->saved + channel * window_len, sizeof(float) * window_len);

    } else {

        for (channel = 0; channel < venc->channels; channel++)

            memset(venc->samples + channel * window_len * 2, 0,

                   sizeof(float) * window_len);

    }

    if (samples) {

        for (channel = 0; channel < venc->channels; channel++) {

            float *offset = venc->samples + channel * window_len * 2 + window_len;

            fdsp->vector_fmul_reverse(offset, audio + channel * window_len, win, samples);

            fdsp->vector_fmul_scalar(offset, offset, 1/n, samples);

        }

    } else {

        for (channel = 0; channel < venc->channels; channel++)

            memset(venc->samples + channel * window_len * 2 + window_len,

                   0, sizeof(float) * window_len);

    }

    for (channel = 0; channel < venc->channels; channel++)

        venc->mdct[0].mdct_calc(&venc->mdct[0], venc->coeffs + channel * window_len,

                     venc->samples + channel * window_len * 2);

    if (samples) {

        for (channel = 0; channel < venc->channels; channel++) {

            float *offset = venc->saved + channel * window_len;

            fdsp->vector_fmul(offset, audio + channel * window_len, win, samples);

            fdsp->vector_fmul_scalar(offset, offset, 1/n, samples);

        }

        venc->have_saved = 1;

    } else {

        venc->have_saved = 0;

    }

    return 1;

}


static inline int popcountl(unsigned long l)

{

    return BITS_PER_LONG == 32 ? ctpop32(l) : ctpop64(l);

}


static int32_t parse_gain(const char *gain)

{

    char *fraction;

    int  scale = 10000;

    int32_t mb = 0;

    int sign   = 1;

    int db;

    if (!gain)

        return INT32_MIN;

    gain += strspn(gain, " \t");

    if (*gain == '-')

        sign = -1;

    db = strtol(gain, &fraction, 0);

    if (*fraction++ == '.') {

        while (av_isdigit(*fraction) && scale) {

            mb += scale * (*fraction - '0');

            scale /= 10;

            fraction++;

        }

    }

    if (abs(db) > (INT32_MAX - mb) / 100000)

        return INT32_MIN;

    return db * 100000 + sign * mb;

}


static inline void ide_dma_submit_check(IDEState *s,

          BlockDriverCompletionFunc *dma_cb)

{

    if (s->bus->dma->aiocb)

	return;

    dma_cb(s, -1);

}


static BlockStats *bdrv_query_bds_stats(const BlockDriverState *bs,

                                 bool query_backing)

{

    BlockStats *s = NULL;

    s = g_malloc0(sizeof(*s));

    s->stats = g_malloc0(sizeof(*s->stats));

    if (!bs) {

        return s;

    }

    if (bdrv_get_node_name(bs)[0]) {

        s->has_node_name = true;

        s->node_name = g_strdup(bdrv_get_node_name(bs));

    }

    s->stats->wr_highest_offset = stat64_get(&bs->wr_highest_offset);

    if (bs->file) {

        s->has_parent = true;

        s->parent = bdrv_query_bds_stats(bs->file->bs, query_backing);

    }

    if (query_backing && bs->backing) {

        s->has_backing = true;

        s->backing = bdrv_query_bds_stats(bs->backing->bs, query_backing);

    }

    return s;

}


static int lag_decode_zero_run_line(LagarithContext *l, uint8_t *dst,

                                    const uint8_t *src, const uint8_t *src_end,

                                    int width, int esc_count)

{

    int i = 0;

    int count;

    uint8_t zero_run = 0;

    const uint8_t *src_start = src;

    uint8_t mask1 = -(esc_count < 2);

    uint8_t mask2 = -(esc_count < 3);

    uint8_t *end = dst + (width - 2);

    avpriv_request_sample(l->avctx, "zero_run_line");

    return AVERROR_PATCHWELCOME;

output_zeros:

    if (l->zeros_rem) {

        count = FFMIN(l->zeros_rem, width - i);

        if (end - dst < count) {

            av_log(l->avctx, AV_LOG_ERROR, "Too many zeros remaining.\n");

            return AVERROR_INVALIDDATA;

        }

        memset(dst, 0, count);

        l->zeros_rem -= count;

        dst += count;

    }

    while (dst < end) {

        i = 0;

        while (!zero_run && dst + i < end) {

            i++;

            if (i+2 >= src_end - src)

                return AVERROR_INVALIDDATA;

            zero_run =

                !(src[i] | (src[i + 1] & mask1) | (src[i + 2] & mask2));

        }

        if (zero_run) {

            zero_run = 0;

            i += esc_count;

            memcpy(dst, src, i);

            dst += i;

            l->zeros_rem = lag_calc_zero_run(src[i]);

            src += i + 1;

            goto output_zeros;

        } else {

            memcpy(dst, src, i);

            src += i;

            dst += i;

        }

    }

    return  src - src_start;

}


static int ram_init_all(RAMState **rsp)

{

    Error *local_err = NULL;

    if (ram_state_init(rsp)) {

        return -1;

    }

    if (migrate_use_xbzrle()) {

        XBZRLE_cache_lock();

        XBZRLE.zero_target_page = g_malloc0(TARGET_PAGE_SIZE);

        XBZRLE.cache = cache_init(migrate_xbzrle_cache_size(),

                                  TARGET_PAGE_SIZE, &local_err);

        if (!XBZRLE.cache) {

            XBZRLE_cache_unlock();

            error_report_err(local_err);

            g_free(*rsp);

            *rsp = NULL;

            return -1;

        }

        XBZRLE_cache_unlock();

        /* We prefer not to abort if there is no memory */

        XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);

        if (!XBZRLE.encoded_buf) {

            error_report("Error allocating encoded_buf");

            g_free(*rsp);

            *rsp = NULL;

            return -1;

        }

        XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);

        if (!XBZRLE.current_buf) {

            error_report("Error allocating current_buf");

            g_free(XBZRLE.encoded_buf);

            XBZRLE.encoded_buf = NULL;

            g_free(*rsp);

            *rsp = NULL;

            return -1;

        }

    }

    /* For memory_global_dirty_log_start below.  */

    qemu_mutex_lock_iothread();

    qemu_mutex_lock_ramlist();

    rcu_read_lock();

    /* Skip setting bitmap if there is no RAM */

    if (ram_bytes_total()) {

        RAMBlock *block;

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

            unsigned long pages = block->max_length >> TARGET_PAGE_BITS;

            block->bmap = bitmap_new(pages);

            bitmap_set(block->bmap, 0, pages);

            if (migrate_postcopy_ram()) {

                block->unsentmap = bitmap_new(pages);

                bitmap_set(block->unsentmap, 0, pages);

            }

        }

    }

    memory_global_dirty_log_start();

    migration_bitmap_sync(*rsp);

    qemu_mutex_unlock_ramlist();

    qemu_mutex_unlock_iothread();

    rcu_read_unlock();

    return 0;

}


static void av_always_inline filter_mb_edgecv( uint8_t *pix, int stride, int16_t bS[4], unsigned int qp, H264Context *h ) {

    const unsigned int index_a = qp + h->slice_alpha_c0_offset;

    const int alpha = alpha_table[index_a];

    const int beta  = beta_table[qp + h->slice_beta_offset];

    if (alpha ==0 || beta == 0) return;

    if( bS[0] < 4 ) {

        int8_t tc[4];

        tc[0] = tc0_table[index_a][bS[0]]+1;

        tc[1] = tc0_table[index_a][bS[1]]+1;

        tc[2] = tc0_table[index_a][bS[2]]+1;

        tc[3] = tc0_table[index_a][bS[3]]+1;

        h->h264dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc);

    } else {

        h->h264dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta);

    }

}


static int decode_entropy_coded_image(WebPContext *s, enum ImageRole role,

                                      int w, int h)

{

    ImageContext *img;

    HuffReader *hg;

    int i, j, ret, x, y, width;

    img       = &s->image[role];

    img->role = role;

    if (!img->frame) {

        img->frame = av_frame_alloc();

        if (!img->frame)

            return AVERROR(ENOMEM);

    }

    img->frame->format = AV_PIX_FMT_ARGB;

    img->frame->width  = w;

    img->frame->height = h;

    if (role == IMAGE_ROLE_ARGB && !img->is_alpha_primary) {

        ThreadFrame pt = { .f = img->frame };

        ret = ff_thread_get_buffer(s->avctx, &pt, 0);

    } else

        ret = av_frame_get_buffer(img->frame, 1);

    if (ret < 0)

        return ret;

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

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

        if (img->color_cache_bits < 1 || img->color_cache_bits > 11) {

            av_log(s->avctx, AV_LOG_ERROR, "invalid color cache bits: %d\n",

                   img->color_cache_bits);

            return AVERROR_INVALIDDATA;

        }

        img->color_cache = av_mallocz_array(1 << img->color_cache_bits,

                                            sizeof(*img->color_cache));

        if (!img->color_cache)

            return AVERROR(ENOMEM);

    } else {

        img->color_cache_bits = 0;

    }

    img->nb_huffman_groups = 1;

    if (role == IMAGE_ROLE_ARGB && get_bits1(&s->gb)) {

        ret = decode_entropy_image(s);

        if (ret < 0)

            return ret;

        img->nb_huffman_groups = s->nb_huffman_groups;

    }

    img->huffman_groups = av_mallocz_array(img->nb_huffman_groups *

                                           HUFFMAN_CODES_PER_META_CODE,

                                           sizeof(*img->huffman_groups));

    if (!img->huffman_groups)

        return AVERROR(ENOMEM);

    for (i = 0; i < img->nb_huffman_groups; i++) {

        hg = &img->huffman_groups[i * HUFFMAN_CODES_PER_META_CODE];

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

            int alphabet_size = alphabet_sizes[j];

            if (!j && img->color_cache_bits > 0)

                alphabet_size += 1 << img->color_cache_bits;

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

                read_huffman_code_simple(s, &hg[j]);

            } else {

                ret = read_huffman_code_normal(s, &hg[j], alphabet_size);

                if (ret < 0)

                    return ret;

            }

        }

    }

    width = img->frame->width;

    if (role == IMAGE_ROLE_ARGB && s->reduced_width > 0)

        width = s->reduced_width;

    x = 0; y = 0;

    while (y < img->frame->height) {

        int v;

        hg = get_huffman_group(s, img, x, y);

        v = huff_reader_get_symbol(&hg[HUFF_IDX_GREEN], &s->gb);

        if (v < NUM_LITERAL_CODES) {

            /* literal pixel values */

            uint8_t *p = GET_PIXEL(img->frame, x, y);

            p[2] = v;

            p[1] = huff_reader_get_symbol(&hg[HUFF_IDX_RED],   &s->gb);

            p[3] = huff_reader_get_symbol(&hg[HUFF_IDX_BLUE],  &s->gb);

            p[0] = huff_reader_get_symbol(&hg[HUFF_IDX_ALPHA], &s->gb);

            if (img->color_cache_bits)

                color_cache_put(img, AV_RB32(p));

            x++;

            if (x == width) {

                x = 0;

                y++;

            }

        } else if (v < NUM_LITERAL_CODES + NUM_LENGTH_CODES) {

            /* LZ77 backwards mapping */

            int prefix_code, length, distance, ref_x, ref_y;

            /* parse length and distance */

            prefix_code = v - NUM_LITERAL_CODES;

            if (prefix_code < 4) {

                length = prefix_code + 1;

            } else {

                int extra_bits = (prefix_code - 2) >> 1;

                int offset     = 2 + (prefix_code & 1) << extra_bits;

                length = offset + get_bits(&s->gb, extra_bits) + 1;

            }

            prefix_code = huff_reader_get_symbol(&hg[HUFF_IDX_DIST], &s->gb);

            if (prefix_code > 39) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "distance prefix code too large: %d\n", prefix_code);

                return AVERROR_INVALIDDATA;

            }

            if (prefix_code < 4) {

                distance = prefix_code + 1;

            } else {

                int extra_bits = prefix_code - 2 >> 1;

                int offset     = 2 + (prefix_code & 1) << extra_bits;

                distance = offset + get_bits(&s->gb, extra_bits) + 1;

            }

            /* find reference location */

            if (distance <= NUM_SHORT_DISTANCES) {

                int xi = lz77_distance_offsets[distance - 1][0];

                int yi = lz77_distance_offsets[distance - 1][1];

                distance = FFMAX(1, xi + yi * width);

            } else {

                distance -= NUM_SHORT_DISTANCES;

            }

            ref_x = x;

            ref_y = y;

            if (distance <= x) {

                ref_x -= distance;

                distance = 0;

            } else {

                ref_x = 0;

                distance -= x;

            }

            while (distance >= width) {

                ref_y--;

                distance -= width;

            }

            if (distance > 0) {

                ref_x = width - distance;

                ref_y--;

            }

            ref_x = FFMAX(0, ref_x);

            ref_y = FFMAX(0, ref_y);

            /* copy pixels

             * source and dest regions can overlap and wrap lines, so just

             * copy per-pixel */

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

                uint8_t *p_ref = GET_PIXEL(img->frame, ref_x, ref_y);

                uint8_t *p     = GET_PIXEL(img->frame,     x,     y);

                AV_COPY32(p, p_ref);

                if (img->color_cache_bits)

                    color_cache_put(img, AV_RB32(p));

                x++;

                ref_x++;

                if (x == width) {

                    x = 0;

                    y++;

                }

                if (ref_x == width) {

                    ref_x = 0;

                    ref_y++;

                }

                if (y == img->frame->height || ref_y == img->frame->height)

                    break;

            }

        } else {

            /* read from color cache */

            uint8_t *p = GET_PIXEL(img->frame, x, y);

            int cache_idx = v - (NUM_LITERAL_CODES + NUM_LENGTH_CODES);

            if (!img->color_cache_bits) {

                av_log(s->avctx, AV_LOG_ERROR, "color cache not found\n");

                return AVERROR_INVALIDDATA;

            }

            if (cache_idx >= 1 << img->color_cache_bits) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "color cache index out-of-bounds\n");

                return AVERROR_INVALIDDATA;

            }

            AV_WB32(p, img->color_cache[cache_idx]);

            x++;

            if (x == width) {

                x = 0;

                y++;

            }

        }

    }

    return 0;

}


void ff_mspel_motion(MpegEncContext *s,

                               uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,

                               uint8_t **ref_picture, op_pixels_func (*pix_op)[4],

                               int motion_x, int motion_y, int h)

{

    Wmv2Context * const w= (Wmv2Context*)s;

    uint8_t *ptr;

    int dxy, offset, mx, my, src_x, src_y, v_edge_pos, linesize, uvlinesize;

    int emu=0;

    dxy = ((motion_y & 1) << 1) | (motion_x & 1);

    dxy = 2*dxy + w->hshift;

    src_x = s->mb_x * 16 + (motion_x >> 1);

    src_y = s->mb_y * 16 + (motion_y >> 1);

    /* WARNING: do no forget half pels */

    v_edge_pos = s->v_edge_pos;

    src_x = av_clip(src_x, -16, s->width);

    src_y = av_clip(src_y, -16, s->height);

    if(src_x<=-16 || src_x >= s->width)

        dxy &= ~3;

    if(src_y<=-16 || src_y >= s->height)

        dxy &= ~4;

    linesize   = s->linesize;

    uvlinesize = s->uvlinesize;

    ptr = ref_picture[0] + (src_y * linesize) + src_x;

        if(src_x<1 || src_y<1 || src_x + 17  >= s->h_edge_pos

                              || src_y + h+1 >= v_edge_pos){

            s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr - 1 - s->linesize, s->linesize, 19, 19,

                             src_x-1, src_y-1, s->h_edge_pos, s->v_edge_pos);

            ptr= s->edge_emu_buffer + 1 + s->linesize;

            emu=1;

        }

    s->dsp.put_mspel_pixels_tab[dxy](dest_y             , ptr             , linesize);

    s->dsp.put_mspel_pixels_tab[dxy](dest_y+8           , ptr+8           , linesize);

    s->dsp.put_mspel_pixels_tab[dxy](dest_y  +8*linesize, ptr  +8*linesize, linesize);

    s->dsp.put_mspel_pixels_tab[dxy](dest_y+8+8*linesize, ptr+8+8*linesize, linesize);

    if(s->flags&CODEC_FLAG_GRAY) return;

    if (s->out_format == FMT_H263) {

        dxy = 0;

        if ((motion_x & 3) != 0)

            dxy |= 1;

        if ((motion_y & 3) != 0)

            dxy |= 2;

        mx = motion_x >> 2;

        my = motion_y >> 2;

    } else {

        mx = motion_x / 2;

        my = motion_y / 2;

        dxy = ((my & 1) << 1) | (mx & 1);

        mx >>= 1;

        my >>= 1;

    }

    src_x = s->mb_x * 8 + mx;

    src_y = s->mb_y * 8 + my;

    src_x = av_clip(src_x, -8, s->width >> 1);

    if (src_x == (s->width >> 1))

        dxy &= ~1;

    src_y = av_clip(src_y, -8, s->height >> 1);

    if (src_y == (s->height >> 1))

        dxy &= ~2;

    offset = (src_y * uvlinesize) + src_x;

    ptr = ref_picture[1] + offset;

    if(emu){

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9,

                         src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);

        ptr= s->edge_emu_buffer;

    }

    pix_op[1][dxy](dest_cb, ptr, uvlinesize, h >> 1);

    ptr = ref_picture[2] + offset;

    if(emu){

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9,

                         src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);

        ptr= s->edge_emu_buffer;

    }

    pix_op[1][dxy](dest_cr, ptr, uvlinesize, h >> 1);

}


static int svq1_encode_plane(SVQ1Context *s, int plane,

                             unsigned char *src_plane,

                             unsigned char *ref_plane,

                             unsigned char *decoded_plane,

                             int width, int height, int src_stride, int stride)

{

    const AVFrame *f = s->avctx->coded_frame;

    int x, y;

    int i;

    int block_width, block_height;

    int level;

    int threshold[6];

    uint8_t *src     = s->scratchbuf + stride * 16;

    const int lambda = (f->quality * f->quality) >>

                       (2 * FF_LAMBDA_SHIFT);

    /* figure out the acceptable level thresholds in advance */

    threshold[5] = QUALITY_THRESHOLD;

    for (level = 4; level >= 0; level--)

        threshold[level] = threshold[level + 1] * THRESHOLD_MULTIPLIER;

    block_width  = (width  + 15) / 16;

    block_height = (height + 15) / 16;

    if (f->pict_type == AV_PICTURE_TYPE_P) {

        s->m.avctx                         = s->avctx;

        s->m.current_picture_ptr           = &s->m.current_picture;

        s->m.last_picture_ptr              = &s->m.last_picture;

        s->m.last_picture.f.data[0]        = ref_plane;

        s->m.linesize                      =

        s->m.last_picture.f.linesize[0]    =

        s->m.new_picture.f.linesize[0]     =

        s->m.current_picture.f.linesize[0] = stride;

        s->m.width                         = width;

        s->m.height                        = height;

        s->m.mb_width                      = block_width;

        s->m.mb_height                     = block_height;

        s->m.mb_stride                     = s->m.mb_width + 1;

        s->m.b8_stride                     = 2 * s->m.mb_width + 1;

        s->m.f_code                        = 1;

        s->m.pict_type                     = f->pict_type;

        s->m.me_method                     = s->avctx->me_method;

        s->m.me.scene_change_score         = 0;

        s->m.flags                         = s->avctx->flags;

        // s->m.out_format                    = FMT_H263;

        // s->m.unrestricted_mv               = 1;

        s->m.lambda                        = f->quality;

        s->m.qscale                        = s->m.lambda * 139 +

                                             FF_LAMBDA_SCALE * 64 >>

                                             FF_LAMBDA_SHIFT + 7;

        s->m.lambda2                       = s->m.lambda * s->m.lambda +

                                             FF_LAMBDA_SCALE / 2 >>

                                             FF_LAMBDA_SHIFT;

        if (!s->motion_val8[plane]) {

            s->motion_val8[plane]  = av_mallocz((s->m.b8_stride *

                                                 block_height * 2 + 2) *

                                                2 * sizeof(int16_t));

            s->motion_val16[plane] = av_mallocz((s->m.mb_stride *

                                                 (block_height + 2) + 1) *

                                                2 * sizeof(int16_t));

        }

        s->m.mb_type = s->mb_type;

        // dummies, to avoid segfaults

        s->m.current_picture.mb_mean   = (uint8_t *)s->dummy;

        s->m.current_picture.mb_var    = (uint16_t *)s->dummy;

        s->m.current_picture.mc_mb_var = (uint16_t *)s->dummy;

        s->m.current_picture.mb_type = s->dummy;

        s->m.current_picture.motion_val[0]   = s->motion_val8[plane] + 2;

        s->m.p_mv_table                      = s->motion_val16[plane] +

                                               s->m.mb_stride + 1;

        s->m.dsp                             = s->dsp; // move

        ff_init_me(&s->m);

        s->m.me.dia_size      = s->avctx->dia_size;

        s->m.first_slice_line = 1;

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

            s->m.new_picture.f.data[0] = src - y * 16 * stride; // ugly

            s->m.mb_y                  = y;

            for (i = 0; i < 16 && i + 16 * y < height; i++) {

                memcpy(&src[i * stride], &src_plane[(i + 16 * y) * src_stride],

                       width);

                for (x = width; x < 16 * block_width; x++)

                    src[i * stride + x] = src[i * stride + x - 1];

            }

            for (; i < 16 && i + 16 * y < 16 * block_height; i++)

                memcpy(&src[i * stride], &src[(i - 1) * stride],

                       16 * block_width);

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

                s->m.mb_x = x;

                ff_init_block_index(&s->m);

                ff_update_block_index(&s->m);

                ff_estimate_p_frame_motion(&s->m, x, y);

            }

            s->m.first_slice_line = 0;

        }

        ff_fix_long_p_mvs(&s->m);

        ff_fix_long_mvs(&s->m, NULL, 0, s->m.p_mv_table, s->m.f_code,

                        CANDIDATE_MB_TYPE_INTER, 0);

    }

    s->m.first_slice_line = 1;

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

        for (i = 0; i < 16 && i + 16 * y < height; i++) {

            memcpy(&src[i * stride], &src_plane[(i + 16 * y) * src_stride],

                   width);

            for (x = width; x < 16 * block_width; x++)

                src[i * stride + x] = src[i * stride + x - 1];

        }

        for (; i < 16 && i + 16 * y < 16 * block_height; i++)

            memcpy(&src[i * stride], &src[(i - 1) * stride], 16 * block_width);

        s->m.mb_y = y;

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

            uint8_t reorder_buffer[3][6][7 * 32];

            int count[3][6];

            int offset       = y * 16 * stride + x * 16;

            uint8_t *decoded = decoded_plane + offset;

            uint8_t *ref     = ref_plane + offset;

            int score[4]     = { 0, 0, 0, 0 }, best;

            uint8_t *temp    = s->scratchbuf;

            if (s->pb.buf_end - s->pb.buf -

                (put_bits_count(&s->pb) >> 3) < 3000) { // FIXME: check size

                av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");

                return -1;

            }

            s->m.mb_x = x;

            ff_init_block_index(&s->m);

            ff_update_block_index(&s->m);

            if (f->pict_type == AV_PICTURE_TYPE_I ||

                (s->m.mb_type[x + y * s->m.mb_stride] &

                 CANDIDATE_MB_TYPE_INTRA)) {

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

                    init_put_bits(&s->reorder_pb[i], reorder_buffer[0][i],

                                  7 * 32);

                if (f->pict_type == AV_PICTURE_TYPE_P) {

                    const uint8_t *vlc = ff_svq1_block_type_vlc[SVQ1_BLOCK_INTRA];

                    put_bits(&s->reorder_pb[5], vlc[1], vlc[0]);

                    score[0] = vlc[1] * lambda;

                }

                score[0] += encode_block(s, src + 16 * x, NULL, temp, stride,

                                         5, 64, lambda, 1);

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

                    count[0][i] = put_bits_count(&s->reorder_pb[i]);

                    flush_put_bits(&s->reorder_pb[i]);

                }

            } else

                score[0] = INT_MAX;

            best = 0;

            if (f->pict_type == AV_PICTURE_TYPE_P) {

                const uint8_t *vlc = ff_svq1_block_type_vlc[SVQ1_BLOCK_INTER];

                int mx, my, pred_x, pred_y, dxy;

                int16_t *motion_ptr;

                motion_ptr = ff_h263_pred_motion(&s->m, 0, 0, &pred_x, &pred_y);

                if (s->m.mb_type[x + y * s->m.mb_stride] &

                    CANDIDATE_MB_TYPE_INTER) {

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

                        init_put_bits(&s->reorder_pb[i], reorder_buffer[1][i],

                                      7 * 32);

                    put_bits(&s->reorder_pb[5], vlc[1], vlc[0]);

                    s->m.pb = s->reorder_pb[5];

                    mx      = motion_ptr[0];

                    my      = motion_ptr[1];

                    assert(mx     >= -32 && mx     <= 31);

                    assert(my     >= -32 && my     <= 31);

                    assert(pred_x >= -32 && pred_x <= 31);

                    assert(pred_y >= -32 && pred_y <= 31);

                    ff_h263_encode_motion(&s->m, mx - pred_x, 1);

                    ff_h263_encode_motion(&s->m, my - pred_y, 1);

                    s->reorder_pb[5] = s->m.pb;

                    score[1]        += lambda * put_bits_count(&s->reorder_pb[5]);

                    dxy = (mx & 1) + 2 * (my & 1);

                    s->hdsp.put_pixels_tab[0][dxy](temp + 16,

                                                   ref + (mx >> 1) +

                                                   stride * (my >> 1),

                                                   stride, 16);

                    score[1] += encode_block(s, src + 16 * x, temp + 16,

                                             decoded, stride, 5, 64, lambda, 0);

                    best      = score[1] <= score[0];

                    vlc       = ff_svq1_block_type_vlc[SVQ1_BLOCK_SKIP];

                    score[2]  = s->dsp.sse[0](NULL, src + 16 * x, ref,

                                              stride, 16);

                    score[2] += vlc[1] * lambda;

                    if (score[2] < score[best] && mx == 0 && my == 0) {

                        best = 2;

                        s->hdsp.put_pixels_tab[0][0](decoded, ref, stride, 16);

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

                            count[2][i] = 0;

                        put_bits(&s->pb, vlc[1], vlc[0]);

                    }

                }

                if (best == 1) {

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

                        count[1][i] = put_bits_count(&s->reorder_pb[i]);

                        flush_put_bits(&s->reorder_pb[i]);

                    }

                } else {

                    motion_ptr[0]                      =

                    motion_ptr[1]                      =

                    motion_ptr[2]                      =

                    motion_ptr[3]                      =

                    motion_ptr[0 + 2 * s->m.b8_stride] =

                    motion_ptr[1 + 2 * s->m.b8_stride] =

                    motion_ptr[2 + 2 * s->m.b8_stride] =

                    motion_ptr[3 + 2 * s->m.b8_stride] = 0;

                }

            }

            s->rd_total += score[best];

            for (i = 5; i >= 0; i--)

                avpriv_copy_bits(&s->pb, reorder_buffer[best][i],

                                 count[best][i]);

            if (best == 0)

                s->hdsp.put_pixels_tab[0][0](decoded, temp, stride, 16);

        }

        s->m.first_slice_line = 0;

    }

    return 0;

}


static int ffmmal_add_packet(AVCodecContext *avctx, AVPacket *avpkt,

                             int is_extradata)

{

    MMALDecodeContext *ctx = avctx->priv_data;

    AVBufferRef *buf = NULL;

    int size = 0;

    uint8_t *data = (uint8_t *)"";

    uint8_t *start;

    int ret = 0;

    if (avpkt->size) {

        if (avpkt->buf) {

            buf = av_buffer_ref(avpkt->buf);

            size = avpkt->size;

            data = avpkt->data;

        } else {

            buf = av_buffer_alloc(avpkt->size);

            if (buf) {

                memcpy(buf->data, avpkt->data, avpkt->size);

                size = buf->size;

                data = buf->data;

            }

        }

        if (!buf) {

            ret = AVERROR(ENOMEM);

            goto done;

        }

        if (!is_extradata)

            ctx->packets_sent++;

    } else {

        if (!ctx->packets_sent) {

            // Short-cut the flush logic to avoid upsetting MMAL.

            ctx->eos_sent = 1;

            ctx->eos_received = 1;

            goto done;

        }

    }

    start = data;

    do {

        FFBufferEntry *buffer = av_mallocz(sizeof(*buffer));

        if (!buffer) {

            ret = AVERROR(ENOMEM);

            goto done;

        }

        buffer->data = data;

        buffer->length = FFMIN(size, ctx->decoder->input[0]->buffer_size);

        if (is_extradata)

            buffer->flags |= MMAL_BUFFER_HEADER_FLAG_CONFIG;

        if (data == start)

            buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_START;

        data += buffer->length;

        size -= buffer->length;

        buffer->pts = avpkt->pts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->pts;

        buffer->dts = avpkt->dts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->dts;

        if (!size)

            buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_END;

        if (!buffer->length) {

            buffer->flags |= MMAL_BUFFER_HEADER_FLAG_EOS;

            ctx->eos_sent = 1;

        }

        if (buf) {

            buffer->ref = av_buffer_ref(buf);

            if (!buffer->ref) {

                av_free(buffer);

                ret = AVERROR(ENOMEM);

                goto done;

            }

        }

        // Insert at end of the list

        if (!ctx->waiting_buffers)

            ctx->waiting_buffers = buffer;

        if (ctx->waiting_buffers_tail)

            ctx->waiting_buffers_tail->next = buffer;

        ctx->waiting_buffers_tail = buffer;

    } while (size);

done:

    av_buffer_unref(&buf);

    return ret;

}


static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)

{

    AVBitStreamFilterContext *bsfc = ost->bitstream_filters;

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

    int ret;

    if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||

        (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))

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

    if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {

        int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);

        if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE &&  max > pkt->dts) {

            av_log(s, max - pkt->dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt->dts, max);

            pkt->pts = pkt->dts = max;

    /*

     * Audio encoders may split the packets --  #frames in != #packets out.

     * But there is no reordering, so we can limit the number of output packets

     * by simply dropping them here.

     * Counting encoded video frames needs to be done separately because of

     * reordering, see do_video_out()

     */

    if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {

        if (ost->frame_number >= ost->max_frames) {

            av_free_packet(pkt);

            return;

        ost->frame_number++;

    while (bsfc) {

        AVPacket new_pkt = *pkt;

        int a = av_bitstream_filter_filter(bsfc, avctx, NULL,

                                           &new_pkt.data, &new_pkt.size,

                                           pkt->data, pkt->size,

                                           pkt->flags & AV_PKT_FLAG_KEY);

        if (a > 0) {

            av_free_packet(pkt);

            new_pkt.destruct = av_destruct_packet;

        } else if (a < 0) {

            av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",

                   bsfc->filter->name, pkt->stream_index,

                   avctx->codec ? avctx->codec->name : "copy");

            print_error("", a);

            if (exit_on_error)

                exit_program(1);

        *pkt = new_pkt;

        bsfc = bsfc->next;

    pkt->stream_index = ost->index;

    ret = av_interleaved_write_frame(s, pkt);

    if (ret < 0) {

        print_error("av_interleaved_write_frame()", ret);

        exit_program(1);


void qed_commit_l2_cache_entry(L2TableCache *l2_cache, CachedL2Table *l2_table)

{

    CachedL2Table *entry;

    entry = qed_find_l2_cache_entry(l2_cache, l2_table->offset);

    if (entry) {

        qed_unref_l2_cache_entry(entry);

        qed_unref_l2_cache_entry(l2_table);

        return;

    }

    if (l2_cache->n_entries >= MAX_L2_CACHE_SIZE) {

        entry = QTAILQ_FIRST(&l2_cache->entries);

        QTAILQ_REMOVE(&l2_cache->entries, entry, node);

        l2_cache->n_entries--;

        qed_unref_l2_cache_entry(entry);

    }

    l2_cache->n_entries++;

    QTAILQ_INSERT_TAIL(&l2_cache->entries, l2_table, node);

}


av_cold void ff_pixblockdsp_init_x86(PixblockDSPContext *c,

                                     AVCodecContext *avctx,

                                     unsigned high_bit_depth)

{

    int cpu_flags = av_get_cpu_flags();

    if (EXTERNAL_MMX(cpu_flags)) {

        if (!high_bit_depth)

            c->get_pixels = ff_get_pixels_mmx;

        c->diff_pixels = ff_diff_pixels_mmx;

    }

    if (EXTERNAL_SSE2(cpu_flags)) {

        if (!high_bit_depth)

            c->get_pixels = ff_get_pixels_sse2;

        c->diff_pixels = ff_diff_pixels_sse2;

    }

}


static USBDevice *usb_net_init(const char *cmdline)

{

    USBDevice *dev;

    QemuOpts *opts;

    int idx;

    opts = qemu_opts_parse(&qemu_net_opts, cmdline, NULL);

    if (!opts) {

    qemu_opt_set(opts, "type", "nic");

    qemu_opt_set(opts, "model", "usb");

    idx = net_client_init(NULL, opts, 0);

    if (idx == -1) {

    dev = usb_create(NULL /* FIXME */, "usb-net");

    qdev_set_nic_properties(&dev->qdev, &nd_table[idx]);

    qdev_init_nofail(&dev->qdev);

    return dev;


static void pkt_dump_internal(void *avcl, FILE *f, int level, const AVPacket *pkt,

                              int dump_payload, AVRational time_base)

{

    HEXDUMP_PRINT("stream #%d:\n", pkt->stream_index);

    HEXDUMP_PRINT("  keyframe=%d\n", (pkt->flags & AV_PKT_FLAG_KEY) != 0);

    HEXDUMP_PRINT("  duration=%0.3f\n", pkt->duration * av_q2d(time_base));

    /* DTS is _always_ valid after av_read_frame() */

    HEXDUMP_PRINT("  dts=");

    if (pkt->dts == AV_NOPTS_VALUE)

        HEXDUMP_PRINT("N/A");

    else

        HEXDUMP_PRINT("%0.3f", pkt->dts * av_q2d(time_base));

    /* PTS may not be known if B-frames are present. */

    HEXDUMP_PRINT("  pts=");

    if (pkt->pts == AV_NOPTS_VALUE)

        HEXDUMP_PRINT("N/A");

    else

        HEXDUMP_PRINT("%0.3f", pkt->pts * av_q2d(time_base));

    HEXDUMP_PRINT("\n");

    HEXDUMP_PRINT("  size=%d\n", pkt->size);

    if (dump_payload)

        av_hex_dump(f, pkt->data, pkt->size);

}


static void handle_mousewheel(SDL_Event *ev)

{

    struct sdl2_console *scon = get_scon_from_window(ev->key.windowID);

    SDL_MouseWheelEvent *wev = &ev->wheel;

    InputButton btn;

    if (wev->y > 0) {

        btn = INPUT_BUTTON_WHEEL_UP;

    } else if (wev->y < 0) {

        btn = INPUT_BUTTON_WHEEL_DOWN;

    } else {

        return;

    }

    qemu_input_queue_btn(scon->dcl.con, btn, true);

    qemu_input_event_sync();

    qemu_input_queue_btn(scon->dcl.con, btn, false);

    qemu_input_event_sync();

}


static void init_virtio_dev(TestServer *s)

{

    QPCIBus *bus;

    QVirtioPCIDevice *dev;

    uint32_t features;

    bus = qpci_init_pc(NULL);

    g_assert_nonnull(bus);

    dev = qvirtio_pci_device_find(bus, VIRTIO_ID_NET);

    g_assert_nonnull(dev);

    qvirtio_pci_device_enable(dev);

    qvirtio_reset(&dev->vdev);

    qvirtio_set_acknowledge(&dev->vdev);

    qvirtio_set_driver(&dev->vdev);

    features = qvirtio_get_features(&dev->vdev);

    features = features & VIRTIO_NET_F_MAC;

    qvirtio_set_features(&dev->vdev, features);

    qvirtio_set_driver_ok(&dev->vdev);

}


int av_packet_split_side_data(AVPacket *pkt){

    if (!pkt->side_data_elems && pkt->size >12 && AV_RB64(pkt->data + pkt->size - 8) == FF_MERGE_MARKER){

        int i;

        unsigned int size;

        uint8_t *p;

        p = pkt->data + pkt->size - 8 - 5;

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

            size = AV_RB32(p);

            if (size>INT_MAX || p - pkt->data < size)

                return 0;

            if (p[4]&128)

                break;

            p-= size+5;

        }

        pkt->side_data = av_malloc_array(i, sizeof(*pkt->side_data));

        if (!pkt->side_data)

            return AVERROR(ENOMEM);

        p= pkt->data + pkt->size - 8 - 5;

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

            size= AV_RB32(p);

            av_assert0(size<=INT_MAX && p - pkt->data >= size);

            pkt->side_data[i].data = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);

            pkt->side_data[i].size = size;

            pkt->side_data[i].type = p[4]&127;

            if (!pkt->side_data[i].data)

                return AVERROR(ENOMEM);

            memcpy(pkt->side_data[i].data, p-size, size);

            pkt->size -= size + 5;

            if(p[4]&128)

                break;

            p-= size+5;

        }

        pkt->size -= 8;

        pkt->side_data_elems = i+1;

        return 1;

    }

    return 0;

}


static void usb_msd_cancel_io(USBDevice *dev, USBPacket *p)

{

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

    scsi_req_cancel(s->req);

}


ram_addr_t ppc405_set_bootinfo (CPUState *env, ppc4xx_bd_info_t *bd,

                                uint32_t flags)

{

    ram_addr_t bdloc;

    int i, n;

    /* We put the bd structure at the top of memory */

    if (bd->bi_memsize >= 0x01000000UL)

        bdloc = 0x01000000UL - sizeof(struct ppc4xx_bd_info_t);

    else

        bdloc = bd->bi_memsize - sizeof(struct ppc4xx_bd_info_t);

    stl_phys(bdloc + 0x00, bd->bi_memstart);

    stl_phys(bdloc + 0x04, bd->bi_memsize);

    stl_phys(bdloc + 0x08, bd->bi_flashstart);

    stl_phys(bdloc + 0x0C, bd->bi_flashsize);

    stl_phys(bdloc + 0x10, bd->bi_flashoffset);

    stl_phys(bdloc + 0x14, bd->bi_sramstart);

    stl_phys(bdloc + 0x18, bd->bi_sramsize);

    stl_phys(bdloc + 0x1C, bd->bi_bootflags);

    stl_phys(bdloc + 0x20, bd->bi_ipaddr);

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

        stb_phys(bdloc + 0x24 + i, bd->bi_enetaddr[i]);

    stw_phys(bdloc + 0x2A, bd->bi_ethspeed);

    stl_phys(bdloc + 0x2C, bd->bi_intfreq);

    stl_phys(bdloc + 0x30, bd->bi_busfreq);

    stl_phys(bdloc + 0x34, bd->bi_baudrate);

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

        stb_phys(bdloc + 0x38 + i, bd->bi_s_version[i]);

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

        stb_phys(bdloc + 0x3C + i, bd->bi_s_version[i]);

    stl_phys(bdloc + 0x5C, bd->bi_plb_busfreq);

    stl_phys(bdloc + 0x60, bd->bi_pci_busfreq);

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

        stb_phys(bdloc + 0x64 + i, bd->bi_pci_enetaddr[i]);

    n = 0x6A;

    if (flags & 0x00000001) {

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

            stb_phys(bdloc + n++, bd->bi_pci_enetaddr2[i]);

    }

    stl_phys(bdloc + n, bd->bi_opbfreq);

    n += 4;

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

        stl_phys(bdloc + n, bd->bi_iic_fast[i]);

        n += 4;

    }

    return bdloc;

}


bool virtio_ipl_disk_is_valid(void)

{

    return blk_cfg.blk_size && (virtio_disk_is_scsi() || virtio_disk_is_eckd());

}


static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)

{

    BlockDriverState *bs = opaque;

    int ret = 0;

    if (bdrv_set_key(bs, password) != 0) {

        monitor_printf(mon, "invalid password\n");

        ret = -EPERM;

    }

    if (mon->password_completion_cb)

        mon->password_completion_cb(mon->password_opaque, ret);

    monitor_read_command(mon, 1);

}


dshow_cycle_devices(AVFormatContext *avctx, ICreateDevEnum *devenum,

                    enum dshowDeviceType devtype, IBaseFilter **pfilter)

{

    struct dshow_ctx *ctx = avctx->priv_data;

    IBaseFilter *device_filter = NULL;

    IEnumMoniker *classenum = NULL;

    IMoniker *m = NULL;

    const char *device_name = ctx->device_name[devtype];

    int skip = (devtype == VideoDevice) ? ctx->video_device_number

                                        : ctx->audio_device_number;

    int r;

    const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory,

                                   &CLSID_AudioInputDeviceCategory };

    const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";

    r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[devtype],

                                             (IEnumMoniker **) &classenum, 0);

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices.\n",

               devtypename);

        return AVERROR(EIO);

    }

    while (!device_filter && IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK) {

        IPropertyBag *bag = NULL;

        char *buf = NULL;

        VARIANT var;

        r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag);

        if (r != S_OK)

            goto fail1;

        var.vt = VT_BSTR;

        r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL);

        if (r != S_OK)

            goto fail1;

        buf = dup_wchar_to_utf8(var.bstrVal);

        if (pfilter) {

            if (strcmp(device_name, buf))

                goto fail1;

            if (!skip--)

                IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter);

        } else {

            av_log(avctx, AV_LOG_INFO, " \"%s\"\n", buf);

        }

fail1:

        if (buf)

            av_free(buf);

        if (bag)

            IPropertyBag_Release(bag);

        IMoniker_Release(m);

    }

    IEnumMoniker_Release(classenum);

    if (pfilter) {

        if (!device_filter) {

            av_log(avctx, AV_LOG_ERROR, "Could not find %s device.\n",

                   devtypename);

            return AVERROR(EIO);

        }

        *pfilter = device_filter;

    }

    return 0;

}


static int do_decode(AVCodecContext *avctx, AVPacket *pkt)

{

    int got_frame;

    int ret;

    av_assert0(!avctx->internal->buffer_frame->buf[0]);

    if (!pkt)

        pkt = avctx->internal->buffer_pkt;

    // This is the lesser evil. The field is for compatibility with legacy users

    // of the legacy API, and users using the new API should not be forced to

    // even know about this field.

    avctx->refcounted_frames = 1;

    // Some codecs (at least wma lossless) will crash when feeding drain packets

    // after EOF was signaled.

    if (avctx->internal->draining_done)

        return AVERROR_EOF;

    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {

        ret = avcodec_decode_video2(avctx, avctx->internal->buffer_frame,

                                    &got_frame, pkt);

        if (ret >= 0 && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))

            ret = pkt->size;

    } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {

        ret = avcodec_decode_audio4(avctx, avctx->internal->buffer_frame,

                                    &got_frame, pkt);

    } else {

        ret = AVERROR(EINVAL);

    }

    if (ret == AVERROR(EAGAIN))

        ret = pkt->size;

    if (ret < 0)

        return ret;

    if (avctx->internal->draining && !got_frame)

        avctx->internal->draining_done = 1;

    if (ret >= pkt->size) {

        av_packet_unref(avctx->internal->buffer_pkt);

    } else {

        int consumed = ret;

        if (pkt != avctx->internal->buffer_pkt) {

            av_packet_unref(avctx->internal->buffer_pkt);

            if ((ret = av_packet_ref(avctx->internal->buffer_pkt, pkt)) < 0)

                return ret;

        }

        avctx->internal->buffer_pkt->data += consumed;

        avctx->internal->buffer_pkt->size -= consumed;

        avctx->internal->buffer_pkt->pts   = AV_NOPTS_VALUE;

        avctx->internal->buffer_pkt->dts   = AV_NOPTS_VALUE;

    }

    if (got_frame)

        av_assert0(avctx->internal->buffer_frame->buf[0]);

    return 0;

}


void net_host_device_remove(Monitor *mon, int vlan_id, const char *device)

{

    VLANState *vlan;

    VLANClientState *vc;

    vlan = qemu_find_vlan(vlan_id);

   for(vc = vlan->first_client; vc != NULL; vc = vc->next)

        if (!strcmp(vc->name, device))

            break;

    if (!vc) {

        monitor_printf(mon, "can't find device %s\n", device);

        return;

    }

    qemu_del_vlan_client(vc);

}


static void vfio_bar_write(void *opaque, hwaddr addr,

                           uint64_t data, unsigned size)

{

    VFIOBAR *bar = opaque;

    union {

        uint8_t byte;

        uint16_t word;

        uint32_t dword;

        uint64_t qword;

    } buf;

    switch (size) {

    case 1:

        buf.byte = data;

        break;

    case 2:

        buf.word = cpu_to_le16(data);

        break;

    case 4:

        buf.dword = cpu_to_le32(data);

        break;

    default:

        hw_error("vfio: unsupported write size, %d bytes\n", size);

        break;

    }

    if (pwrite(bar->fd, &buf, size, bar->fd_offset + addr) != size) {

        error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m",

                     __func__, addr, data, size);

    }

    DPRINTF("%s(BAR%d+0x%"HWADDR_PRIx", 0x%"PRIx64", %d)\n",

            __func__, bar->nr, addr, data, size);

    /*

     * A read or write to a BAR always signals an INTx EOI.  This will

     * do nothing if not pending (including not in INTx mode).  We assume

     * that a BAR access is in response to an interrupt and that BAR

     * accesses will service the interrupt.  Unfortunately, we don't know

     * which access will service the interrupt, so we're potentially

     * getting quite a few host interrupts per guest interrupt.

     */

    vfio_eoi(container_of(bar, VFIODevice, bars[bar->nr]));

}


static void mcf5208evb_init(QEMUMachineInitArgs *args)

{

    ram_addr_t ram_size = args->ram_size;

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    CPUM68KState *env;

    int kernel_size;

    uint64_t elf_entry;

    target_phys_addr_t entry;

    qemu_irq *pic;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *sram = g_new(MemoryRegion, 1);

    if (!cpu_model)

        cpu_model = "m5208";

    env = cpu_init(cpu_model);

    if (!env) {

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

        exit(1);

    }

    /* Initialize CPU registers.  */

    env->vbr = 0;

    /* TODO: Configure BARs.  */

    /* DRAM at 0x40000000 */

    memory_region_init_ram(ram, "mcf5208.ram", ram_size);

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(address_space_mem, 0x40000000, ram);

    /* Internal SRAM.  */

    memory_region_init_ram(sram, "mcf5208.sram", 16384);

    vmstate_register_ram_global(sram);

    memory_region_add_subregion(address_space_mem, 0x80000000, sram);

    /* Internal peripherals.  */

    pic = mcf_intc_init(address_space_mem, 0xfc048000, env);

    mcf_uart_mm_init(address_space_mem, 0xfc060000, pic[26], serial_hds[0]);

    mcf_uart_mm_init(address_space_mem, 0xfc064000, pic[27], serial_hds[1]);

    mcf_uart_mm_init(address_space_mem, 0xfc068000, pic[28], serial_hds[2]);

    mcf5208_sys_init(address_space_mem, pic);

    if (nb_nics > 1) {

        fprintf(stderr, "Too many NICs\n");

        exit(1);

    }

    if (nd_table[0].used)

        mcf_fec_init(address_space_mem, &nd_table[0],

                     0xfc030000, pic + 36);

    /*  0xfc000000 SCM.  */

    /*  0xfc004000 XBS.  */

    /*  0xfc008000 FlexBus CS.  */

    /* 0xfc030000 FEC.  */

    /*  0xfc040000 SCM + Power management.  */

    /*  0xfc044000 eDMA.  */

    /* 0xfc048000 INTC.  */

    /*  0xfc058000 I2C.  */

    /*  0xfc05c000 QSPI.  */

    /* 0xfc060000 UART0.  */

    /* 0xfc064000 UART0.  */

    /* 0xfc068000 UART0.  */

    /*  0xfc070000 DMA timers.  */

    /* 0xfc080000 PIT0.  */

    /* 0xfc084000 PIT1.  */

    /*  0xfc088000 EPORT.  */

    /*  0xfc08c000 Watchdog.  */

    /*  0xfc090000 clock module.  */

    /*  0xfc0a0000 CCM + reset.  */

    /*  0xfc0a4000 GPIO.  */

    /* 0xfc0a8000 SDRAM controller.  */

    /* Load kernel.  */

    if (!kernel_filename) {

        fprintf(stderr, "Kernel image must be specified\n");

        exit(1);

    }

    kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,

                           NULL, NULL, 1, ELF_MACHINE, 0);

    entry = elf_entry;

    if (kernel_size < 0) {

        kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL);

    }

    if (kernel_size < 0) {

        kernel_size = load_image_targphys(kernel_filename, 0x40000000,

                                          ram_size);

        entry = 0x40000000;

    }

    if (kernel_size < 0) {

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

        exit(1);

    }

    env->pc = entry;

}


static QObject *parse_escape(JSONParserContext *ctxt, va_list *ap)

{

    QObject *token;

    const char *val;

    if (ap == NULL) {

        return NULL;

    }

    token = parser_context_pop_token(ctxt);

    assert(token && token_get_type(token) == JSON_ESCAPE);

    val = token_get_value(token);

    if (!strcmp(val, "%p")) {

        return va_arg(*ap, QObject *);

    } else if (!strcmp(val, "%i")) {

        return QOBJECT(qbool_from_bool(va_arg(*ap, int)));

    } else if (!strcmp(val, "%d")) {

        return QOBJECT(qint_from_int(va_arg(*ap, int)));

    } else if (!strcmp(val, "%ld")) {

        return QOBJECT(qint_from_int(va_arg(*ap, long)));

    } else if (!strcmp(val, "%lld") ||

               !strcmp(val, "%I64d")) {

        return QOBJECT(qint_from_int(va_arg(*ap, long long)));

    } else if (!strcmp(val, "%s")) {

        return QOBJECT(qstring_from_str(va_arg(*ap, const char *)));

    } else if (!strcmp(val, "%f")) {

        return QOBJECT(qfloat_from_double(va_arg(*ap, double)));

    }

    return NULL;

}


static inline uint64_t ldq_phys_internal(hwaddr addr,

                                         enum device_endian endian)

{

    uint8_t *ptr;

    uint64_t val;

    MemoryRegionSection *section;

    section = phys_page_find(address_space_memory.dispatch, addr >> TARGET_PAGE_BITS);

    if (!(memory_region_is_ram(section->mr) ||

          memory_region_is_romd(section->mr))) {

        /* I/O case */

        addr = memory_region_section_addr(section, addr);

        /* XXX This is broken when device endian != cpu endian.

               Fix and add "endian" variable check */

#ifdef TARGET_WORDS_BIGENDIAN

        val = io_mem_read(section->mr, addr, 4) << 32;

        val |= io_mem_read(section->mr, addr + 4, 4);

#else

        val = io_mem_read(section->mr, addr, 4);

        val |= io_mem_read(section->mr, addr + 4, 4) << 32;

#endif

    } else {

        /* RAM case */

        ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(section->mr)

                                & TARGET_PAGE_MASK)

                               + memory_region_section_addr(section, addr));

        switch (endian) {

        case DEVICE_LITTLE_ENDIAN:

            val = ldq_le_p(ptr);

            break;

        case DEVICE_BIG_ENDIAN:

            val = ldq_be_p(ptr);

            break;

        default:

            val = ldq_p(ptr);

            break;

        }

    }

    return val;

}


void main_loop_wait(int nonblocking)

{

    fd_set rfds, wfds, xfds;

    int ret, nfds;

    struct timeval tv;

    int timeout;

    if (nonblocking)

        timeout = 0;

    else {

        timeout = qemu_calculate_timeout();

        qemu_bh_update_timeout(&timeout);

    }

    os_host_main_loop_wait(&timeout);

    tv.tv_sec = timeout / 1000;

    tv.tv_usec = (timeout % 1000) * 1000;

    /* poll any events */

    /* XXX: separate device handlers from system ones */

    nfds = -1;

    FD_ZERO(&rfds);

    FD_ZERO(&wfds);

    FD_ZERO(&xfds);

    qemu_iohandler_fill(&nfds, &rfds, &wfds, &xfds);

    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);

    qemu_mutex_unlock_iothread();

    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);

    qemu_mutex_lock_iothread();

    qemu_iohandler_poll(&rfds, &wfds, &xfds, ret);

    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));

    qemu_run_all_timers();

    /* Check bottom-halves last in case any of the earlier events triggered

       them.  */

    qemu_bh_poll();

}


void bdrv_invalidate_cache_all(Error **errp)

{

    BlockDriverState *bs;

    Error *local_err = NULL;

    BdrvNextIterator *it = NULL;

    while ((it = bdrv_next(it, &bs)) != NULL) {

        AioContext *aio_context = bdrv_get_aio_context(bs);

        aio_context_acquire(aio_context);

        bdrv_invalidate_cache(bs, &local_err);

        aio_context_release(aio_context);

        if (local_err) {

            error_propagate(errp, local_err);

            return;

        }

    }

}


static int parse_adaptation_sets(AVFormatContext *s)

{

    WebMDashMuxContext *w = s->priv_data;

    char *p = w->adaptation_sets;

    char *q;

    enum { new_set, parsed_id, parsing_streams } state;

    if (!w->adaptation_sets) {

        av_log(s, AV_LOG_ERROR, "The 'adaptation_sets' option must be set.\n");

        return AVERROR(EINVAL);

    }

    // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on

    state = new_set;

    while (p < w->adaptation_sets + strlen(w->adaptation_sets)) {

        if (*p == ' ')

            continue;

        else if (state == new_set && !strncmp(p, "id=", 3)) {

            void *mem = av_realloc(w->as, sizeof(*w->as) * (w->nb_as + 1));

            if (mem == NULL)

                return AVERROR(ENOMEM);

            w->as = mem;

            ++w->nb_as;

            w->as[w->nb_as - 1].nb_streams = 0;

            w->as[w->nb_as - 1].streams = NULL;

            p += 3; // consume "id="

            q = w->as[w->nb_as - 1].id;

            while (*p != ',') *q++ = *p++;

            *q = 0;

            p++;

            state = parsed_id;

        } else if (state == parsed_id && !strncmp(p, "streams=", 8)) {

            p += 8; // consume "streams="

            state = parsing_streams;

        } else if (state == parsing_streams) {

            struct AdaptationSet *as = &w->as[w->nb_as - 1];

            q = p;

            while (*q != '\0' && *q != ',' && *q != ' ') q++;

            as->streams = av_realloc(as->streams, sizeof(*as->streams) * ++as->nb_streams);

            if (as->streams == NULL)

                return AVERROR(ENOMEM);

            as->streams[as->nb_streams - 1] = to_integer(p, q - p + 1);

            if (as->streams[as->nb_streams - 1] < 0) return -1;

            if (*q == '\0') break;

            if (*q == ' ') state = new_set;

            p = ++q;

        } else {

            return -1;

        }

    }

    return 0;

}


static QObject *parse_keyword(JSONParserContext *ctxt)

{

    QObject *token, *ret;

    JSONParserContext saved_ctxt = parser_context_save(ctxt);

    token = parser_context_pop_token(ctxt);

    if (token == NULL) {

        goto out;

    }

    if (token_get_type(token) != JSON_KEYWORD) {

        goto out;

    }

    if (token_is_keyword(token, "true")) {

        ret = QOBJECT(qbool_from_int(true));

    } else if (token_is_keyword(token, "false")) {

        ret = QOBJECT(qbool_from_int(false));

    } else {

        parse_error(ctxt, token, "invalid keyword `%s'", token_get_value(token));

        goto out;

    }

    return ret;

out:

    parser_context_restore(ctxt, saved_ctxt);

    return NULL;

}


static int aac_encode_frame(AVCodecContext *avctx,

                            uint8_t *frame, int buf_size, void *data)

{

    AACEncContext *s = avctx->priv_data;

    int16_t *samples = s->samples, *samples2, *la;

    ChannelElement *cpe;

    int i, j, chans, tag, start_ch;

    const uint8_t *chan_map = aac_chan_configs[avctx->channels-1];

    int chan_el_counter[4];

    FFPsyWindowInfo windows[AAC_MAX_CHANNELS];

    if (s->last_frame)

        return 0;

    if (data) {

        if (!s->psypp) {

            memcpy(s->samples + 1024 * avctx->channels, data,

                   1024 * avctx->channels * sizeof(s->samples[0]));

        } else {

            start_ch = 0;

            samples2 = s->samples + 1024 * avctx->channels;

            for (i = 0; i < chan_map[0]; i++) {

                tag = chan_map[i+1];

                chans = tag == TYPE_CPE ? 2 : 1;

                ff_psy_preprocess(s->psypp, (uint16_t*)data + start_ch,

                                  samples2 + start_ch, start_ch, chans);

                start_ch += chans;

            }

        }

    }

    if (!avctx->frame_number) {

        memcpy(s->samples, s->samples + 1024 * avctx->channels,

               1024 * avctx->channels * sizeof(s->samples[0]));

        return 0;

    }

    start_ch = 0;

    for (i = 0; i < chan_map[0]; i++) {

        FFPsyWindowInfo* wi = windows + start_ch;

        tag      = chan_map[i+1];

        chans    = tag == TYPE_CPE ? 2 : 1;

        cpe      = &s->cpe[i];

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

            IndividualChannelStream *ics = &cpe->ch[j].ics;

            int k;

            int cur_channel = start_ch + j;

            samples2 = samples + cur_channel;

            la       = samples2 + (448+64) * avctx->channels;

            if (!data)

                la = NULL;

            if (tag == TYPE_LFE) {

                wi[j].window_type[0] = ONLY_LONG_SEQUENCE;

                wi[j].window_shape   = 0;

                wi[j].num_windows    = 1;

                wi[j].grouping[0]    = 1;

            } else {

                wi[j] = ff_psy_suggest_window(&s->psy, samples2, la, cur_channel,

                                              ics->window_sequence[0]);

            }

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

            ics->window_sequence[0] = wi[j].window_type[0];

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

            ics->use_kb_window[0]   = wi[j].window_shape;

            ics->num_windows        = wi[j].num_windows;

            ics->swb_sizes          = s->psy.bands    [ics->num_windows == 8];

            ics->num_swb            = tag == TYPE_LFE ? 12 : s->psy.num_bands[ics->num_windows == 8];

            for (k = 0; k < ics->num_windows; k++)

                ics->group_len[k] = wi[j].grouping[k];

            apply_window_and_mdct(avctx, s, &cpe->ch[j], samples2);

        }

        start_ch += chans;

    }

    do {

        int frame_bits;

        init_put_bits(&s->pb, frame, buf_size*8);

        if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT))

            put_bitstream_info(avctx, s, LIBAVCODEC_IDENT);

        start_ch = 0;

        memset(chan_el_counter, 0, sizeof(chan_el_counter));

        for (i = 0; i < chan_map[0]; i++) {

            FFPsyWindowInfo* wi = windows + start_ch;

            tag      = chan_map[i+1];

            chans    = tag == TYPE_CPE ? 2 : 1;

            cpe      = &s->cpe[i];

            put_bits(&s->pb, 3, tag);

            put_bits(&s->pb, 4, chan_el_counter[tag]++);

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

                s->cur_channel = start_ch + j;

                ff_psy_set_band_info(&s->psy, s->cur_channel, cpe->ch[j].coeffs, &wi[j]);

                s->coder->search_for_quantizers(avctx, s, &cpe->ch[j], s->lambda);

            }

            cpe->common_window = 0;

            if (chans > 1

                && wi[0].window_type[0] == wi[1].window_type[0]

                && wi[0].window_shape   == wi[1].window_shape) {

                cpe->common_window = 1;

                for (j = 0; j < wi[0].num_windows; j++) {

                    if (wi[0].grouping[j] != wi[1].grouping[j]) {

                        cpe->common_window = 0;

                        break;

                    }

                }

            }

            s->cur_channel = start_ch;

            if (cpe->common_window && s->coder->search_for_ms)

                s->coder->search_for_ms(s, cpe, s->lambda);

            adjust_frame_information(s, cpe, chans);

            if (chans == 2) {

                put_bits(&s->pb, 1, cpe->common_window);

                if (cpe->common_window) {

                    put_ics_info(s, &cpe->ch[0].ics);

                    encode_ms_info(&s->pb, cpe);

                }

            }

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

                s->cur_channel = start_ch + j;

                encode_individual_channel(avctx, s, &cpe->ch[j], cpe->common_window);

            }

            start_ch += chans;

        }

        frame_bits = put_bits_count(&s->pb);

        if (frame_bits <= 6144 * avctx->channels - 3) {

            s->psy.bitres.bits = frame_bits / avctx->channels;

            break;

        }

        s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;

    } while (1);

    put_bits(&s->pb, 3, TYPE_END);

    flush_put_bits(&s->pb);

    avctx->frame_bits = put_bits_count(&s->pb);

    // rate control stuff

    if (!(avctx->flags & CODEC_FLAG_QSCALE)) {

        float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits;

        s->lambda *= ratio;

        s->lambda = FFMIN(s->lambda, 65536.f);

    }

    if (!data)

        s->last_frame = 1;

    memcpy(s->samples, s->samples + 1024 * avctx->channels,

           1024 * avctx->channels * sizeof(s->samples[0]));

    return put_bits_count(&s->pb)>>3;

}


static int dxtory_decode_v2_420(AVCodecContext *avctx, AVFrame *pic,

                                const uint8_t *src, int src_size)

{

    GetByteContext gb;

    GetBitContext  gb2;

    int nslices, slice, slice_height, ref_slice_height;

    int cur_y, next_y;

    uint32_t off, slice_size;

    uint8_t *Y, *U, *V;

    int ret;

    bytestream2_init(&gb, src, src_size);

    nslices = bytestream2_get_le16(&gb);

    off = FFALIGN(nslices * 4 + 2, 16);

    if (src_size < off) {

        av_log(avctx, AV_LOG_ERROR, "no slice data\n");

        return AVERROR_INVALIDDATA;

    }

    if (!nslices || avctx->height % nslices) {

        avpriv_request_sample(avctx, "%d slices for %dx%d", nslices,

                              avctx->width, avctx->height);

        return AVERROR_PATCHWELCOME;

    }

    ref_slice_height = avctx->height / nslices;

    if ((avctx->width & 1) || (avctx->height & 1)) {

        avpriv_request_sample(avctx, "Frame dimensions %dx%d",

                              avctx->width, avctx->height);

    }

    avctx->pix_fmt = AV_PIX_FMT_YUV420P;

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

        return ret;

    Y = pic->data[0];

    U = pic->data[1];

    V = pic->data[2];

    cur_y  = 0;

    next_y = ref_slice_height;

    for (slice = 0; slice < nslices; slice++) {

        slice_size   = bytestream2_get_le32(&gb);

        slice_height = (next_y & ~1) - (cur_y & ~1);

        if (slice_size > src_size - off) {

            av_log(avctx, AV_LOG_ERROR,

                   "invalid slice size %"PRIu32" (only %"PRIu32" bytes left)\n",

                   slice_size, src_size - off);

            return AVERROR_INVALIDDATA;

        }

        if (slice_size <= 16) {

            av_log(avctx, AV_LOG_ERROR, "invalid slice size %"PRIu32"\n", slice_size);

            return AVERROR_INVALIDDATA;

        }

        if (AV_RL32(src + off) != slice_size - 16) {

            av_log(avctx, AV_LOG_ERROR,

                   "Slice sizes mismatch: got %"PRIu32" instead of %"PRIu32"\n",

                   AV_RL32(src + off), slice_size - 16);

        }

        init_get_bits(&gb2, src + off + 16, (slice_size - 16) * 8);

        dx2_decode_slice_420(&gb2, avctx->width, slice_height, Y, U, V,

                             pic->linesize[0], pic->linesize[1],

                             pic->linesize[2]);

        Y += pic->linesize[0] *  slice_height;

        U += pic->linesize[1] * (slice_height >> 1);

        V += pic->linesize[2] * (slice_height >> 1);

        off += slice_size;

        cur_y   = next_y;

        next_y += ref_slice_height;

    }

    return 0;

}


static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,

                         GetBitContext *gb, SBRData *ch_data)

{

    int i;

    unsigned bs_pointer = 0;

    // frameLengthFlag ? 15 : 16; 960 sample length frames unsupported; this value is numTimeSlots

    int abs_bord_trail = 16;

    int num_rel_lead, num_rel_trail;

    unsigned bs_num_env_old = ch_data->bs_num_env;

    ch_data->bs_freq_res[0] = ch_data->bs_freq_res[ch_data->bs_num_env];

    ch_data->bs_amp_res = sbr->bs_amp_res_header;

    ch_data->t_env_num_env_old = ch_data->t_env[bs_num_env_old];

    switch (ch_data->bs_frame_class = get_bits(gb, 2)) {

    case FIXFIX:

        ch_data->bs_num_env                 = 1 << get_bits(gb, 2);

        num_rel_lead                        = ch_data->bs_num_env - 1;

        if (ch_data->bs_num_env == 1)

            ch_data->bs_amp_res = 0;

        if (ch_data->bs_num_env > 4) {

            av_log(ac->avccontext, AV_LOG_ERROR,

                   "Invalid bitstream, too many SBR envelopes in FIXFIX type SBR frame: %d\n",

                   ch_data->bs_num_env);

            return -1;

        }

        ch_data->t_env[0]                   = 0;

        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;

        abs_bord_trail = (abs_bord_trail + (ch_data->bs_num_env >> 1)) /

                   ch_data->bs_num_env;

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

            ch_data->t_env[i + 1] = ch_data->t_env[i] + abs_bord_trail;

        ch_data->bs_freq_res[1] = get_bits1(gb);

        for (i = 1; i < ch_data->bs_num_env; i++)

            ch_data->bs_freq_res[i + 1] = ch_data->bs_freq_res[1];

        break;

    case FIXVAR:

        abs_bord_trail                     += get_bits(gb, 2);

        num_rel_trail                       = get_bits(gb, 2);

        ch_data->bs_num_env                 = num_rel_trail + 1;

        ch_data->t_env[0]                   = 0;

        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;

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

            ch_data->t_env[ch_data->bs_num_env - 1 - i] =

                ch_data->t_env[ch_data->bs_num_env - i] - 2 * get_bits(gb, 2) - 2;

        bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);

        for (i = 0; i < ch_data->bs_num_env; i++)

            ch_data->bs_freq_res[ch_data->bs_num_env - i] = get_bits1(gb);

        break;

    case VARFIX:

        ch_data->t_env[0]                   = get_bits(gb, 2);

        num_rel_lead                        = get_bits(gb, 2);

        ch_data->bs_num_env                 = num_rel_lead + 1;

        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;

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

            ch_data->t_env[i + 1] = ch_data->t_env[i] + 2 * get_bits(gb, 2) + 2;

        bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);

        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env);

        break;

    case VARVAR:

        ch_data->t_env[0]                   = get_bits(gb, 2);

        abs_bord_trail                     += get_bits(gb, 2);

        num_rel_lead                        = get_bits(gb, 2);

        num_rel_trail                       = get_bits(gb, 2);

        ch_data->bs_num_env                 = num_rel_lead + num_rel_trail + 1;

        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;

        if (ch_data->bs_num_env > 5) {

            av_log(ac->avccontext, AV_LOG_ERROR,

                   "Invalid bitstream, too many SBR envelopes in VARVAR type SBR frame: %d\n",

                   ch_data->bs_num_env);

            return -1;

        }

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

            ch_data->t_env[i + 1] = ch_data->t_env[i] + 2 * get_bits(gb, 2) + 2;

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

            ch_data->t_env[ch_data->bs_num_env - 1 - i] =

                ch_data->t_env[ch_data->bs_num_env - i] - 2 * get_bits(gb, 2) - 2;

        bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);

        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env);

        break;

    }

    if (bs_pointer > ch_data->bs_num_env + 1) {

        av_log(ac->avccontext, AV_LOG_ERROR,

               "Invalid bitstream, bs_pointer points to a middle noise border outside the time borders table: %d\n",

               bs_pointer);

        return -1;

    }

    ch_data->bs_num_noise = (ch_data->bs_num_env > 1) + 1;

    ch_data->t_q[0]                     = ch_data->t_env[0];

    ch_data->t_q[ch_data->bs_num_noise] = ch_data->t_env[ch_data->bs_num_env];

    if (ch_data->bs_num_noise > 1) {

        unsigned int idx;

        if (ch_data->bs_frame_class == FIXFIX) {

            idx = ch_data->bs_num_env >> 1;

        } else if (ch_data->bs_frame_class & 1) { // FIXVAR or VARVAR

            idx = ch_data->bs_num_env - FFMAX(bs_pointer - 1, 1);

        } else { // VARFIX

            if (!bs_pointer)

                idx = 1;

            else if (bs_pointer == 1)

                idx = ch_data->bs_num_env - 1;

            else // bs_pointer > 1

                idx = bs_pointer - 1;

        }

        ch_data->t_q[1] = ch_data->t_env[idx];

    }

    ch_data->e_a[0] = -(ch_data->e_a[1] != bs_num_env_old); // l_APrev

    ch_data->e_a[1] = -1;

    if ((ch_data->bs_frame_class & 1) && bs_pointer) { // FIXVAR or VARVAR and bs_pointer != 0

        ch_data->e_a[1] = ch_data->bs_num_env + 1 - bs_pointer;

    } else if ((ch_data->bs_frame_class == 2) && (bs_pointer > 1)) // VARFIX and bs_pointer > 1

        ch_data->e_a[1] = bs_pointer - 1;

    return 0;

}


static int uhci_complete_td(UHCIState *s, UHCI_TD *td, UHCIAsync *async, uint32_t *int_mask)

{

    int len = 0, max_len, err, ret;

    uint8_t pid;

    max_len = ((td->token >> 21) + 1) & 0x7ff;

    pid = td->token & 0xff;

    ret = async->packet.result;

    if (td->ctrl & TD_CTRL_IOS)

        td->ctrl &= ~TD_CTRL_ACTIVE;

    if (ret < 0)

        goto out;

    len = async->packet.result;

    td->ctrl = (td->ctrl & ~0x7ff) | ((len - 1) & 0x7ff);

    /* The NAK bit may have been set by a previous frame, so clear it

       here.  The docs are somewhat unclear, but win2k relies on this

       behavior.  */

    td->ctrl &= ~(TD_CTRL_ACTIVE | TD_CTRL_NAK);

    if (td->ctrl & TD_CTRL_IOC)

        *int_mask |= 0x01;

    if (pid == USB_TOKEN_IN) {

        if (len > max_len) {

            ret = USB_RET_BABBLE;

            goto out;

        }

        if ((td->ctrl & TD_CTRL_SPD) && len < max_len) {

            *int_mask |= 0x02;

            /* short packet: do not update QH */

            trace_usb_uhci_packet_complete_shortxfer(async->queue->token,

                                                    async->td);

            return TD_RESULT_NEXT_QH;

        }

    }

    /* success */

    trace_usb_uhci_packet_complete_success(async->queue->token, async->td);

    return TD_RESULT_COMPLETE;

out:

    /*

     * We should not do any further processing on a queue with errors!

     * This is esp. important for bulk endpoints with pipelining enabled

     * (redirection to a real USB device), where we must cancel all the

     * transfers after this one so that:

     * 1) If they've completed already, they are not processed further

     *    causing more stalls, originating from the same failed transfer

     * 2) If still in flight, they are cancelled before the guest does

     *    a clear stall, otherwise the guest and device can loose sync!

     */

    while (!QTAILQ_EMPTY(&async->queue->asyncs)) {

        UHCIAsync *as = QTAILQ_FIRST(&async->queue->asyncs);

        uhci_async_unlink(as);

        uhci_async_cancel(as);

    }

    switch(ret) {

    case USB_RET_STALL:

        td->ctrl |= TD_CTRL_STALL;

        td->ctrl &= ~TD_CTRL_ACTIVE;

        s->status |= UHCI_STS_USBERR;

        if (td->ctrl & TD_CTRL_IOC) {

            *int_mask |= 0x01;

        }

        uhci_update_irq(s);

        trace_usb_uhci_packet_complete_stall(async->queue->token, async->td);

        return TD_RESULT_NEXT_QH;

    case USB_RET_BABBLE:

        td->ctrl |= TD_CTRL_BABBLE | TD_CTRL_STALL;

        td->ctrl &= ~TD_CTRL_ACTIVE;

        s->status |= UHCI_STS_USBERR;

        if (td->ctrl & TD_CTRL_IOC) {

            *int_mask |= 0x01;

        }

        uhci_update_irq(s);

        /* frame interrupted */

        trace_usb_uhci_packet_complete_babble(async->queue->token, async->td);

        return TD_RESULT_STOP_FRAME;

    case USB_RET_NAK:

        td->ctrl |= TD_CTRL_NAK;

        if (pid == USB_TOKEN_SETUP)

            break;

        return TD_RESULT_NEXT_QH;

    case USB_RET_IOERROR:

    case USB_RET_NODEV:

    default:

	break;

    }

    /* Retry the TD if error count is not zero */

    td->ctrl |= TD_CTRL_TIMEOUT;

    err = (td->ctrl >> TD_CTRL_ERROR_SHIFT) & 3;

    if (err != 0) {

        err--;

        if (err == 0) {

            td->ctrl &= ~TD_CTRL_ACTIVE;

            s->status |= UHCI_STS_USBERR;

            if (td->ctrl & TD_CTRL_IOC)

                *int_mask |= 0x01;

            uhci_update_irq(s);

            trace_usb_uhci_packet_complete_error(async->queue->token,

                                                 async->td);

        }

    }

    td->ctrl = (td->ctrl & ~(3 << TD_CTRL_ERROR_SHIFT)) |

        (err << TD_CTRL_ERROR_SHIFT);

    return TD_RESULT_NEXT_QH;

}


static void cpu_x86_dump_state(FILE *f)

{

    int eflags;

    char cc_op_name[32];

    eflags = cc_table[CC_OP].compute_all();

    eflags |= (DF & DF_MASK);

    if ((unsigned)env->cc_op < CC_OP_NB)

        strcpy(cc_op_name, cc_op_str[env->cc_op]);

    else

        snprintf(cc_op_name, sizeof(cc_op_name), "[%d]", env->cc_op);

    fprintf(f,

            "EAX=%08x EBX=%08X ECX=%08x EDX=%08x\n"

            "ESI=%08x EDI=%08X EBP=%08x ESP=%08x\n"

            "CCS=%08x CCD=%08x CCO=%-8s EFL=%c%c%c%c%c%c%c\n"

            "EIP=%08x\n",

            env->regs[R_EAX], env->regs[R_EBX], env->regs[R_ECX], env->regs[R_EDX],

            env->regs[R_ESI], env->regs[R_EDI], env->regs[R_EBP], env->regs[R_ESP],

            env->cc_src, env->cc_dst, cc_op_name,

            eflags & DF_MASK ? 'D' : '-',

            eflags & CC_O ? 'O' : '-',

            eflags & CC_S ? 'S' : '-',

            eflags & CC_Z ? 'Z' : '-',

            eflags & CC_A ? 'A' : '-',

            eflags & CC_P ? 'P' : '-',

            eflags & CC_C ? 'C' : '-',

            env->eip);

#if 1

    fprintf(f, "ST0=%f ST1=%f ST2=%f ST3=%f\n",

            (double)ST0, (double)ST1, (double)ST(2), (double)ST(3));

#endif

}


static int gif_read_image(GifState *s)

{

    int left, top, width, height, bits_per_pixel, code_size, flags;

    int is_interleaved, has_local_palette, y, pass, y1, linesize, n, i;

    uint8_t *ptr, *spal, *palette, *ptr1;

    left = bytestream_get_le16(&s->bytestream);

    top = bytestream_get_le16(&s->bytestream);

    width = bytestream_get_le16(&s->bytestream);

    height = bytestream_get_le16(&s->bytestream);

    flags = bytestream_get_byte(&s->bytestream);

    is_interleaved = flags & 0x40;

    has_local_palette = flags & 0x80;

    bits_per_pixel = (flags & 0x07) + 1;

    av_dlog(s->avctx, "image x=%d y=%d w=%d h=%d\n", left, top, width, height);

    if (has_local_palette) {

        bytestream_get_buffer(&s->bytestream, s->local_palette, 3 * (1 << bits_per_pixel));

        palette = s->local_palette;

    } else {

        palette = s->global_palette;

        bits_per_pixel = s->bits_per_pixel;

    }

    /* verify that all the image is inside the screen dimensions */

    if (left + width > s->screen_width ||

        top + height > s->screen_height)

        return AVERROR(EINVAL);

    /* build the palette */

    n = (1 << bits_per_pixel);

    spal = palette;

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

        s->image_palette[i] = (0xffu << 24) | AV_RB24(spal);

        spal += 3;

    }

    for(; i < 256; i++)

        s->image_palette[i] = (0xffu << 24);

    /* handle transparency */

    if (s->transparent_color_index >= 0)

        s->image_palette[s->transparent_color_index] = 0;

    /* now get the image data */

    code_size = bytestream_get_byte(&s->bytestream);

    ff_lzw_decode_init(s->lzw, code_size, s->bytestream,

                       s->bytestream_end - s->bytestream, FF_LZW_GIF);

    /* read all the image */

    linesize = s->picture.linesize[0];

    ptr1 = s->picture.data[0] + top * linesize + left;

    ptr = ptr1;

    pass = 0;

    y1 = 0;

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

        ff_lzw_decode(s->lzw, ptr, width);

        if (is_interleaved) {

            switch(pass) {

            default:

            case 0:

            case 1:

                y1 += 8;

                ptr += linesize * 8;

                if (y1 >= height) {

                    y1 = pass ? 2 : 4;

                    ptr = ptr1 + linesize * y1;

                    pass++;

                }

                break;

            case 2:

                y1 += 4;

                ptr += linesize * 4;

                if (y1 >= height) {

                    y1 = 1;

                    ptr = ptr1 + linesize;

                    pass++;

                }

                break;

            case 3:

                y1 += 2;

                ptr += linesize * 2;

                break;

            }

        } else {

            ptr += linesize;

        }

    }

    /* read the garbage data until end marker is found */

    ff_lzw_decode_tail(s->lzw);

    s->bytestream = ff_lzw_cur_ptr(s->lzw);

    return 0;

}


static int alac_encode_frame(AVCodecContext *avctx, uint8_t *frame,

                             int buf_size, void *data)

{

    AlacEncodeContext *s = avctx->priv_data;

    PutBitContext *pb = &s->pbctx;

    int i, out_bytes, verbatim_flag = 0;

    if (avctx->frame_size > DEFAULT_FRAME_SIZE) {

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

        return -1;

    }

    if (buf_size < 2 * s->max_coded_frame_size) {

        av_log(avctx, AV_LOG_ERROR, "buffer size is too small\n");

        return -1;

    }

verbatim:

    init_put_bits(pb, frame, buf_size);

    if (s->compression_level == 0 || verbatim_flag) {

        // Verbatim mode

        const int16_t *samples = data;

        write_frame_header(s, 1);

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

            put_sbits(pb, 16, *samples++);

        }

    } else {

        init_sample_buffers(s, data);

        write_frame_header(s, 0);

        write_compressed_frame(s);

    }

    put_bits(pb, 3, 7);

    flush_put_bits(pb);

    out_bytes = put_bits_count(pb) >> 3;

    if (out_bytes > s->max_coded_frame_size) {

        /* frame too large. use verbatim mode */

        if (verbatim_flag || s->compression_level == 0) {

            /* still too large. must be an error. */

            av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");

            return -1;

        }

        verbatim_flag = 1;

        goto verbatim;

    }

    return out_bytes;

}


static void i440fx_update_memory_mappings(PCII440FXState *d)

{

    int i, r;

    uint32_t smram;

    bool smram_enabled;

    memory_region_transaction_begin();

    update_pam(d, 0xf0000, 0x100000, (d->dev.config[I440FX_PAM] >> 4) & 3,

               &d->pam_regions[0]);

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

        r = (d->dev.config[(i >> 1) + (I440FX_PAM + 1)] >> ((i & 1) * 4)) & 3;

        update_pam(d, 0xc0000 + 0x4000 * i, 0xc0000 + 0x4000 * (i + 1), r,

                   &d->pam_regions[i+1]);

    }

    smram = d->dev.config[I440FX_SMRAM];

    smram_enabled = (d->smm_enabled && (smram & 0x08)) || (smram & 0x40);

    memory_region_set_enabled(&d->smram_region, !smram_enabled);

    memory_region_transaction_commit();

}