int ff_jpegls_decode_picture(MJpegDecodeContext *s, int near,
                             int point_transform, int ilv)
{
    int i, t = 0;
    uint8_t *zero, *last, *cur;
    JLSState *state;
    int off = 0, stride = 1, width, shift, ret = 0;
    zero = av_mallocz(s->picture_ptr->linesize[0]);
    if (!zero)
        return AVERROR(ENOMEM);
    last = zero;
    cur  = s->picture_ptr->data[0];
    state = av_mallocz(sizeof(JLSState));
    if (!state) {
        av_free(zero);
        return AVERROR(ENOMEM);
    /* initialize JPEG-LS state from JPEG parameters */
    state->near   = near;
    state->bpp    = (s->bits < 2) ? 2 : s->bits;
    state->maxval = s->maxval;
    state->T1     = s->t1;
    state->T2     = s->t2;
    state->T3     = s->t3;
    state->reset  = s->reset;
    ff_jpegls_reset_coding_parameters(state, 0);
    ff_jpegls_init_state(state);
    if (s->bits <= 8)
        shift = point_transform + (8 - s->bits);
    else
        shift = point_transform + (16 - s->bits);
    if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
        av_log(s->avctx, AV_LOG_DEBUG,
               "JPEG-LS params: %ix%i NEAR=%i MV=%i T(%i,%i,%i) "
               "RESET=%i, LIMIT=%i, qbpp=%i, RANGE=%i\n",
                s->width, s->height, state->near, state->maxval,
                state->T1, state->T2, state->T3,
                state->reset, state->limit, state->qbpp, state->range);
        av_log(s->avctx, AV_LOG_DEBUG, "JPEG params: ILV=%i Pt=%i BPP=%i, scan = %i\n",
                ilv, point_transform, s->bits, s->cur_scan);
    if (ilv == 0) { /* separate planes */
        if (s->cur_scan > s->nb_components) {
        stride = (s->nb_components > 1) ? 3 : 1;
        off    = av_clip(s->cur_scan - 1, 0, stride - 1);
        width  = s->width * stride;
        cur   += off;
        for (i = 0; i < s->height; i++) {
            if (s->bits <= 8) {
                ls_decode_line(state, s, last, cur, t, width, stride, off, 8);
                t = last[0];
            } else {
                ls_decode_line(state, s, last, cur, t, width, stride, off, 16);
                t = *((uint16_t *)last);
            last = cur;
            cur += s->picture_ptr->linesize[0];
            if (s->restart_interval && !--s->restart_count) {
                align_get_bits(&s->gb);
                skip_bits(&s->gb, 16); /* skip RSTn */
    } else if (ilv == 1) { /* line interleaving */
        int j;
        int Rc[3] = { 0, 0, 0 };
        stride = (s->nb_components > 1) ? 3 : 1;
        memset(cur, 0, s->picture_ptr->linesize[0]);
        width = s->width * stride;
        for (i = 0; i < s->height; i++) {
            for (j = 0; j < stride; j++) {
                ls_decode_line(state, s, last + j, cur + j,
                               Rc[j], width, stride, j, 8);
                Rc[j] = last[j];
                if (s->restart_interval && !--s->restart_count) {
                    align_get_bits(&s->gb);
                    skip_bits(&s->gb, 16); /* skip RSTn */
            last = cur;
            cur += s->picture_ptr->linesize[0];
    } else if (ilv == 2) { /* sample interleaving */
        avpriv_report_missing_feature(s->avctx, "Sample interleaved images");
        ret = AVERROR_PATCHWELCOME;
    if (s->xfrm && s->nb_components == 3) {
        int x, w;
        w = s->width * s->nb_components;
        if (s->bits <= 8) {
            uint8_t *src = s->picture_ptr->data[0];
            for (i = 0; i < s->height; i++) {
                switch(s->xfrm) {
                case 1:
                    for (x = off; x < w; x += 3) {
                        src[x  ] += src[x+1] + 128;
                        src[x+2] += src[x+1] + 128;
                    break;
                case 2:
                    for (x = off; x < w; x += 3) {
                        src[x  ] += src[x+1] + 128;
                        src[x+2] += ((src[x  ] + src[x+1])>>1) + 128;
                    break;
                case 3:
                    for (x = off; x < w; x += 3) {
                        int g = src[x+0] - ((src[x+2]+src[x+1])>>2) + 64;
                        src[x+0] = src[x+2] + g + 128;
                        src[x+2] = src[x+1] + g + 128;
                        src[x+1] = g;
                    break;
                case 4:
                    for (x = off; x < w; x += 3) {
                        int r    = src[x+0] - ((                       359 * (src[x+2]-128) + 490) >> 8);
                        int g    = src[x+0] - (( 88 * (src[x+1]-128) - 183 * (src[x+2]-128) +  30) >> 8);
                        int b    = src[x+0] + ((454 * (src[x+1]-128)                        + 574) >> 8);
                        src[x+0] = av_clip_uint8(r);
                        src[x+1] = av_clip_uint8(g);
                        src[x+2] = av_clip_uint8(b);
                    break;
                src += s->picture_ptr->linesize[0];
        }else
            avpriv_report_missing_feature(s->avctx, "16bit xfrm");
    if (shift) { /* we need to do point transform or normalize samples */
        int x, w;
        w = s->width * s->nb_components;
        if (s->bits <= 8) {
            uint8_t *src = s->picture_ptr->data[0];
            for (i = 0; i < s->height; i++) {
                for (x = off; x < w; x += stride)
                    src[x] <<= shift;
                src += s->picture_ptr->linesize[0];
        } else {
            uint16_t *src = (uint16_t *)s->picture_ptr->data[0];
            for (i = 0; i < s->height; i++) {
                for (x = 0; x < w; x++)
                    src[x] <<= shift;
                src += s->picture_ptr->linesize[0] / 2;
end:
    av_free(state);
    av_free(zero);
    return ret;


void FUNCC(ff_h264_chroma_dc_dequant_idct)(int16_t *_block, int qmul){

    const int stride= 16*2;

    const int xStride= 16;

    int a,b,c,d,e;

    dctcoef *block = (dctcoef*)_block;

    a= block[stride*0 + xStride*0];

    b= block[stride*0 + xStride*1];

    c= block[stride*1 + xStride*0];

    d= block[stride*1 + xStride*1];

    e= a-b;

    a= a+b;

    b= c-d;

    c= c+d;

    block[stride*0 + xStride*0]= ((a+c)*qmul) >> 7;

    block[stride*0 + xStride*1]= ((e+b)*qmul) >> 7;

    block[stride*1 + xStride*0]= ((a-c)*qmul) >> 7;

    block[stride*1 + xStride*1]= ((e-b)*qmul) >> 7;

}


static inline int mpeg2_decode_block_intra(MpegEncContext *s,

                                           int16_t *block, int n)

{

    int level, dc, diff, i, j, run;

    int component;

    RLTable *rl;

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

    const uint16_t *quant_matrix;

    const int qscale = s->qscale;

    int mismatch;

    /* DC coefficient */

    if (n < 4) {

        quant_matrix = s->intra_matrix;

        component    = 0;

    } else {

        quant_matrix = s->chroma_intra_matrix;

        component    = (n & 1) + 1;

    }

    diff = decode_dc(&s->gb, component);

    if (diff >= 0xffff)

        return AVERROR_INVALIDDATA;

    dc  = s->last_dc[component];

    dc += diff;

    s->last_dc[component] = dc;

    block[0] = dc << (3 - s->intra_dc_precision);

    ff_tlog(s->avctx, "dc=%d\n", block[0]);

    mismatch = block[0] ^ 1;

    i = 0;

    if (s->intra_vlc_format)

        rl = &ff_rl_mpeg2;

    else

        rl = &ff_rl_mpeg1;

    {

        OPEN_READER(re, &s->gb);

        /* now quantify & encode AC coefficients */

        for (;;) {

            UPDATE_CACHE(re, &s->gb);

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

                       TEX_VLC_BITS, 2, 0);

            if (level == 127) {

                break;

            } else if (level != 0) {

                i += run;

                if (i > MAX_INDEX)

                    break;

                j = scantable[i];

                level = (level * qscale * quant_matrix[j]) >> 4;

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

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

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

            } else {

                /* escape */

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

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

                UPDATE_CACHE(re, &s->gb);

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

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

                i += run;

                if (i > MAX_INDEX)

                    break;

                j = scantable[i];

                if (level < 0) {

                    level = (-level * qscale * quant_matrix[j]) >> 4;

                    level = -level;

                } else {

                    level = (level * qscale * quant_matrix[j]) >> 4;

                }

            }

            mismatch ^= level;

            block[j]  = level;

        }

        CLOSE_READER(re, &s->gb);

    }

    block[63] ^= mismatch & 1;

    check_scantable_index(s, i);

    s->block_last_index[n] = i;

    return 0;

}


static void vc1_draw_sprites(VC1Context *v, SpriteData* sd)

{

    int i, plane, row, sprite;

    int sr_cache[2][2] = { { -1, -1 }, { -1, -1 } };

    uint8_t* src_h[2][2];

    int xoff[2], xadv[2], yoff[2], yadv[2], alpha;

    int ysub[2];

    MpegEncContext *s = &v->s;

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

        xoff[i] = av_clip(sd->coefs[i][2], 0, v->sprite_width-1 << 16);

        xadv[i] = sd->coefs[i][0];

        if (xadv[i] != 1<<16 || (v->sprite_width << 16) - (v->output_width << 16) - xoff[i])

            xadv[i] = av_clip(xadv[i], 0, ((v->sprite_width<<16) - xoff[i] - 1) / v->output_width);

        yoff[i] = av_clip(sd->coefs[i][5], 0, v->sprite_height-1 << 16);

        yadv[i] = av_clip(sd->coefs[i][4], 0, ((v->sprite_height << 16) - yoff[i]) / v->output_height);

    }

    alpha = av_clip(sd->coefs[1][6], 0, (1<<16) - 1);

    for (plane = 0; plane < (s->flags&CODEC_FLAG_GRAY ? 1 : 3); plane++) {

        int width = v->output_width>>!!plane;

        for (row = 0; row < v->output_height>>!!plane; row++) {

            uint8_t *dst = v->sprite_output_frame.data[plane] +

                           v->sprite_output_frame.linesize[plane] * row;

            for (sprite = 0; sprite <= v->two_sprites; sprite++) {

                uint8_t *iplane = s->current_picture.f.data[plane];

                int      iline  = s->current_picture.f.linesize[plane];

                int      ycoord = yoff[sprite] + yadv[sprite] * row;

                int      yline  = ycoord >> 16;

                ysub[sprite] = ycoord & 0xFFFF;

                if (sprite) {

                    iplane = s->last_picture.f.data[plane];

                    iline  = s->last_picture.f.linesize[plane];

                }

                if (!(xoff[sprite] & 0xFFFF) && xadv[sprite] == 1 << 16) {

                        src_h[sprite][0] = iplane + (xoff[sprite] >> 16) +  yline      * iline;

                    if (ysub[sprite])

                        src_h[sprite][1] = iplane + (xoff[sprite] >> 16) + (yline + 1) * iline;

                } else {

                    if (sr_cache[sprite][0] != yline) {

                        if (sr_cache[sprite][1] == yline) {

                            FFSWAP(uint8_t*, v->sr_rows[sprite][0], v->sr_rows[sprite][1]);

                            FFSWAP(int,        sr_cache[sprite][0],   sr_cache[sprite][1]);

                        } else {

                            v->vc1dsp.sprite_h(v->sr_rows[sprite][0], iplane + yline * iline, xoff[sprite], xadv[sprite], width);

                            sr_cache[sprite][0] = yline;

                        }

                    }

                    if (ysub[sprite] && sr_cache[sprite][1] != yline + 1) {

                        v->vc1dsp.sprite_h(v->sr_rows[sprite][1], iplane + (yline + 1) * iline, xoff[sprite], xadv[sprite], width);

                        sr_cache[sprite][1] = yline + 1;

                    }

                    src_h[sprite][0] = v->sr_rows[sprite][0];

                    src_h[sprite][1] = v->sr_rows[sprite][1];

                }

            }

            if (!v->two_sprites) {

                if (ysub[0]) {

                    v->vc1dsp.sprite_v_single(dst, src_h[0][0], src_h[0][1], ysub[0], width);

                } else {

                    memcpy(dst, src_h[0][0], width);

                }

            } else {

                if (ysub[0] && ysub[1]) {

                    v->vc1dsp.sprite_v_double_twoscale(dst, src_h[0][0], src_h[0][1], ysub[0],

                                                       src_h[1][0], src_h[1][1], ysub[1], alpha, width);

                } else if (ysub[0]) {

                    v->vc1dsp.sprite_v_double_onescale(dst, src_h[0][0], src_h[0][1], ysub[0],

                                                       src_h[1][0], alpha, width);

                } else if (ysub[1]) {

                    v->vc1dsp.sprite_v_double_onescale(dst, src_h[1][0], src_h[1][1], ysub[1],

                                                       src_h[0][0], (1<<16)-1-alpha, width);

                } else {

                    v->vc1dsp.sprite_v_double_noscale(dst, src_h[0][0], src_h[1][0], alpha, width);

                }

            }

        }

        if (!plane) {

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

                xoff[i] >>= 1;

                yoff[i] >>= 1;

            }

        }

    }

}


static int vhdx_log_flush(BlockDriverState *bs, BDRVVHDXState *s,

                          VHDXLogSequence *logs)

{

    int ret = 0;

    int i;

    uint32_t cnt, sectors_read;

    uint64_t new_file_size;

    void *data = NULL;

    VHDXLogDescEntries *desc_entries = NULL;

    VHDXLogEntryHeader hdr_tmp = { 0 };

    cnt = logs->count;

    data = qemu_blockalign(bs, VHDX_LOG_SECTOR_SIZE);

    ret = vhdx_user_visible_write(bs, s);

    if (ret < 0) {

        goto exit;

    }

    /* each iteration represents one log sequence, which may span multiple

     * sectors */

    while (cnt--) {

        ret = vhdx_log_peek_hdr(bs, &logs->log, &hdr_tmp);

        if (ret < 0) {

            goto exit;

        }

        /* if the log shows a FlushedFileOffset larger than our current file

         * size, then that means the file has been truncated / corrupted, and

         * we must refused to open it / use it */

        if (hdr_tmp.flushed_file_offset > bdrv_getlength(bs->file->bs)) {

            ret = -EINVAL;

            goto exit;

        }

        ret = vhdx_log_read_desc(bs, s, &logs->log, &desc_entries, true);

        if (ret < 0) {

            goto exit;

        }

        for (i = 0; i < desc_entries->hdr.descriptor_count; i++) {

            if (desc_entries->desc[i].signature == VHDX_LOG_DESC_SIGNATURE) {

                /* data sector, so read a sector to flush */

                ret = vhdx_log_read_sectors(bs, &logs->log, &sectors_read,

                                            data, 1, false);

                if (ret < 0) {

                    goto exit;

                }

                if (sectors_read != 1) {

                    ret = -EINVAL;

                    goto exit;

                }

                vhdx_log_data_le_import(data);

            }

            ret = vhdx_log_flush_desc(bs, &desc_entries->desc[i], data);

            if (ret < 0) {

                goto exit;

            }

        }

        if (bdrv_getlength(bs->file->bs) < desc_entries->hdr.last_file_offset) {

            new_file_size = desc_entries->hdr.last_file_offset;

            if (new_file_size % (1024*1024)) {

                /* round up to nearest 1MB boundary */

                new_file_size = ((new_file_size >> 20) + 1) << 20;

                bdrv_truncate(bs->file, new_file_size, PREALLOC_MODE_OFF, NULL);

            }

        }

        qemu_vfree(desc_entries);

        desc_entries = NULL;

    }

    bdrv_flush(bs);

    /* once the log is fully flushed, indicate that we have an empty log

     * now.  This also sets the log guid to 0, to indicate an empty log */

    vhdx_log_reset(bs, s);

exit:

    qemu_vfree(data);

    qemu_vfree(desc_entries);

    return ret;

}


static void unterminated_array(void)

{

    QObject *obj = qobject_from_json("[32", NULL);

    g_assert(obj == NULL);

}


static av_cold int xan_decode_init(AVCodecContext *avctx)

{

    XanContext *s = avctx->priv_data;

    s->avctx = avctx;

    s->frame_size = 0;

    if ((avctx->codec->id == CODEC_ID_XAN_WC3) &&

        (s->avctx->palctrl == NULL)) {

        av_log(avctx, AV_LOG_ERROR, "palette expected\n");

        return AVERROR(EINVAL);

    }

    avctx->pix_fmt = PIX_FMT_PAL8;

    s->buffer1_size = avctx->width * avctx->height;

    s->buffer1 = av_malloc(s->buffer1_size);

    if (!s->buffer1)

        return AVERROR(ENOMEM);

    s->buffer2_size = avctx->width * avctx->height;

    s->buffer2 = av_malloc(s->buffer2_size + 130);

    if (!s->buffer2) {

        av_freep(&s->buffer1);

        return AVERROR(ENOMEM);

    }

    return 0;

}


static void init_uni_ac_vlc(RLTable *rl, uint8_t *uni_ac_vlc_len){

    int i;

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

        int level= i-64;

        int run;

        for(run=0; run<64; run++){

            int len, bits, code;

            int alevel= FFABS(level);

            int sign= (level>>31)&1;

            if (alevel > rl->max_level[0][run])

                code= 111; /*rl->n*/

            else

                code= rl->index_run[0][run] + alevel - 1;

            if (code < 111 /* rl->n */) {

                /* store the vlc & sign at once */

                len=   rl->table_vlc[code][1]+1;

                bits= (rl->table_vlc[code][0]<<1) + sign;

            } else {

                len=  rl->table_vlc[111/*rl->n*/][1]+6;

                bits= rl->table_vlc[111/*rl->n*/][0]<<6;

                bits|= run;

                if (alevel < 128) {

                    bits<<=8; len+=8;

                    bits|= level & 0xff;

                } else {

                    bits<<=16; len+=16;

                    bits|= level & 0xff;

                    if (level < 0) {

                        bits|= 0x8001 + level + 255;

                    } else {

                        bits|= level & 0xffff;

                    }

                }

            }

            uni_ac_vlc_len [UNI_AC_ENC_INDEX(run, i)]= len;

        }

    }

}


int virtqueue_pop(VirtQueue *vq, VirtQueueElement *elem)

{

    unsigned int i, head, max;

    target_phys_addr_t desc_pa = vq->vring.desc;

    if (!virtqueue_num_heads(vq, vq->last_avail_idx))

        return 0;

    /* When we start there are none of either input nor output. */

    elem->out_num = elem->in_num = 0;

    max = vq->vring.num;

    i = head = virtqueue_get_head(vq, vq->last_avail_idx++);

    if (vq->vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) {

        vring_avail_event(vq, vring_avail_idx(vq));

    if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) {

        if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) {

            error_report("Invalid size for indirect buffer table");

        /* loop over the indirect descriptor table */

        max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc);

        desc_pa = vring_desc_addr(desc_pa, i);

        i = 0;

    /* Collect all the descriptors */

    do {

        struct iovec *sg;

        if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) {

            elem->in_addr[elem->in_num] = vring_desc_addr(desc_pa, i);

            sg = &elem->in_sg[elem->in_num++];

        } else {

            elem->out_addr[elem->out_num] = vring_desc_addr(desc_pa, i);

            sg = &elem->out_sg[elem->out_num++];

        sg->iov_len = vring_desc_len(desc_pa, i);

        /* If we've got too many, that implies a descriptor loop. */

        if ((elem->in_num + elem->out_num) > max) {

            error_report("Looped descriptor");

    } while ((i = virtqueue_next_desc(desc_pa, i, max)) != max);

    /* Now map what we have collected */

    virtqueue_map_sg(elem->in_sg, elem->in_addr, elem->in_num, 1);

    virtqueue_map_sg(elem->out_sg, elem->out_addr, elem->out_num, 0);

    elem->index = head;

    vq->inuse++;

    trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);

    return elem->in_num + elem->out_num;


void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)

{

    RAMBlock *block;

    ram_addr_t offset;

    int flags;

    void *area, *vaddr;

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

        offset = addr - block->offset;

        if (offset < block->length) {

            vaddr = block->host + offset;

            if (block->flags & RAM_PREALLOC_MASK) {

                ;

            } else {

                flags = MAP_FIXED;

                munmap(vaddr, length);

                if (mem_path) {

#if defined(__linux__) && !defined(TARGET_S390X)

                    if (block->fd) {

#ifdef MAP_POPULATE

                        flags |= mem_prealloc ? MAP_POPULATE | MAP_SHARED :

                            MAP_PRIVATE;

                        flags |= MAP_PRIVATE;

#endif

                        area = mmap(vaddr, length, PROT_READ | PROT_WRITE,

                                    flags, block->fd, offset);

                    } else {

                        flags |= MAP_PRIVATE | MAP_ANONYMOUS;

                        area = mmap(vaddr, length, PROT_READ | PROT_WRITE,

                                    flags, -1, 0);

                    }

#endif

                } else {

#if defined(TARGET_S390X) && defined(CONFIG_KVM)

                    flags |= MAP_SHARED | MAP_ANONYMOUS;

                    area = mmap(vaddr, length, PROT_EXEC|PROT_READ|PROT_WRITE,

                                flags, -1, 0);

                    flags |= MAP_PRIVATE | MAP_ANONYMOUS;

                    area = mmap(vaddr, length, PROT_READ | PROT_WRITE,

                                flags, -1, 0);

#endif

                }

                if (area != vaddr) {

                    fprintf(stderr, "Could not remap addr: %lx@%lx\n",

                            length, addr);

                    exit(1);

                }

                qemu_madvise(vaddr, length, QEMU_MADV_MERGEABLE);

            }

            return;

        }

    }

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PnvChipClass *k = PNV_CHIP_CLASS(klass);

    k->cpu_model = "POWER8";

    k->chip_type = PNV_CHIP_POWER8;

    k->chip_cfam_id = 0x220ea04980000000ull; /* P8 Venice DD2.0 */

    k->cores_mask = POWER8_CORE_MASK;

    k->core_pir = pnv_chip_core_pir_p8;

    dc->desc = "PowerNV Chip POWER8";

}


static void multiwrite_user_cb(MultiwriteCB *mcb)

{

    int i;

    for (i = 0; i < mcb->num_callbacks; i++) {

        mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);

        qemu_free(mcb->callbacks[i].free_qiov);

        qemu_free(mcb->callbacks[i].free_buf);

    }

}


static void pflash_cfi02_realize(DeviceState *dev, Error **errp)
{
    pflash_t *pfl = CFI_PFLASH02(dev);
    uint32_t chip_len;
    int ret;
    Error *local_err = NULL;
    chip_len = pfl->sector_len * pfl->nb_blocs;
    /* XXX: to be fixed */
#if 0
    if (total_len != (8 * 1024 * 1024) && total_len != (16 * 1024 * 1024) &&
        total_len != (32 * 1024 * 1024) && total_len != (64 * 1024 * 1024))
        return NULL;
#endif
    memory_region_init_rom_device(&pfl->orig_mem, OBJECT(pfl), pfl->be ?
                                  &pflash_cfi02_ops_be : &pflash_cfi02_ops_le,
                                  pfl, pfl->name, chip_len, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
    vmstate_register_ram(&pfl->orig_mem, DEVICE(pfl));
    pfl->storage = memory_region_get_ram_ptr(&pfl->orig_mem);
    pfl->chip_len = chip_len;
    if (pfl->blk) {
        /* read the initial flash content */
        ret = blk_pread(pfl->blk, 0, pfl->storage, chip_len);
        if (ret < 0) {
            vmstate_unregister_ram(&pfl->orig_mem, DEVICE(pfl));
            error_setg(errp, "failed to read the initial flash content");
    pflash_setup_mappings(pfl);
    pfl->rom_mode = 1;
    sysbus_init_mmio(SYS_BUS_DEVICE(dev), &pfl->mem);
    if (pfl->blk) {
        pfl->ro = blk_is_read_only(pfl->blk);
    } else {
        pfl->ro = 0;
    pfl->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, pflash_timer, pfl);
    pfl->wcycle = 0;
    pfl->cmd = 0;
    pfl->status = 0;
    /* Hardcoded CFI table (mostly from SG29 Spansion flash) */
    pfl->cfi_len = 0x52;
    /* Standard "QRY" string */
    pfl->cfi_table[0x10] = 'Q';
    pfl->cfi_table[0x11] = 'R';
    pfl->cfi_table[0x12] = 'Y';
    /* Command set (AMD/Fujitsu) */
    pfl->cfi_table[0x13] = 0x02;
    pfl->cfi_table[0x14] = 0x00;
    /* Primary extended table address */
    pfl->cfi_table[0x15] = 0x31;
    pfl->cfi_table[0x16] = 0x00;
    /* Alternate command set (none) */
    pfl->cfi_table[0x17] = 0x00;
    pfl->cfi_table[0x18] = 0x00;
    /* Alternate extended table (none) */
    pfl->cfi_table[0x19] = 0x00;
    pfl->cfi_table[0x1A] = 0x00;
    /* Vcc min */
    pfl->cfi_table[0x1B] = 0x27;
    /* Vcc max */
    pfl->cfi_table[0x1C] = 0x36;
    /* Vpp min (no Vpp pin) */
    pfl->cfi_table[0x1D] = 0x00;
    /* Vpp max (no Vpp pin) */
    pfl->cfi_table[0x1E] = 0x00;
    /* Reserved */
    pfl->cfi_table[0x1F] = 0x07;
    /* Timeout for min size buffer write (NA) */
    pfl->cfi_table[0x20] = 0x00;
    /* Typical timeout for block erase (512 ms) */
    pfl->cfi_table[0x21] = 0x09;
    /* Typical timeout for full chip erase (4096 ms) */
    pfl->cfi_table[0x22] = 0x0C;
    /* Reserved */
    pfl->cfi_table[0x23] = 0x01;
    /* Max timeout for buffer write (NA) */
    pfl->cfi_table[0x24] = 0x00;
    /* Max timeout for block erase */
    pfl->cfi_table[0x25] = 0x0A;
    /* Max timeout for chip erase */
    pfl->cfi_table[0x26] = 0x0D;
    /* Device size */
    pfl->cfi_table[0x27] = ctz32(chip_len);
    /* Flash device interface (8 & 16 bits) */
    pfl->cfi_table[0x28] = 0x02;
    pfl->cfi_table[0x29] = 0x00;
    /* Max number of bytes in multi-bytes write */
    /* XXX: disable buffered write as it's not supported */
    //    pfl->cfi_table[0x2A] = 0x05;
    pfl->cfi_table[0x2A] = 0x00;
    pfl->cfi_table[0x2B] = 0x00;
    /* Number of erase block regions (uniform) */
    pfl->cfi_table[0x2C] = 0x01;
    /* Erase block region 1 */
    pfl->cfi_table[0x2D] = pfl->nb_blocs - 1;
    pfl->cfi_table[0x2E] = (pfl->nb_blocs - 1) >> 8;
    pfl->cfi_table[0x2F] = pfl->sector_len >> 8;
    pfl->cfi_table[0x30] = pfl->sector_len >> 16;
    /* Extended */
    pfl->cfi_table[0x31] = 'P';
    pfl->cfi_table[0x32] = 'R';
    pfl->cfi_table[0x33] = 'I';
    pfl->cfi_table[0x34] = '1';
    pfl->cfi_table[0x35] = '0';
    pfl->cfi_table[0x36] = 0x00;
    pfl->cfi_table[0x37] = 0x00;
    pfl->cfi_table[0x38] = 0x00;
    pfl->cfi_table[0x39] = 0x00;
    pfl->cfi_table[0x3a] = 0x00;
    pfl->cfi_table[0x3b] = 0x00;
    pfl->cfi_table[0x3c] = 0x00;


float ff_rate_estimate_qscale(MpegEncContext *s, int dry_run)

{

    float q;

    int qmin, qmax;

    float br_compensation;

    double diff;

    double short_term_q;

    double fps;

    int picture_number = s->picture_number;

    int64_t wanted_bits;

    RateControlContext *rcc = &s->rc_context;

    AVCodecContext *a       = s->avctx;

    RateControlEntry local_rce, *rce;

    double bits;

    double rate_factor;

    int var;

    const int pict_type = s->pict_type;

    Picture * const pic = &s->current_picture;

    emms_c();

#if CONFIG_LIBXVID

    if ((s->flags & CODEC_FLAG_PASS2) &&

        s->avctx->rc_strategy == FF_RC_STRATEGY_XVID)

        return ff_xvid_rate_estimate_qscale(s, dry_run);

#endif

    get_qminmax(&qmin, &qmax, s, pict_type);

    fps = get_fps(s->avctx);

    /* update predictors */

    if (picture_number > 2 && !dry_run) {

        const int last_var = s->last_pict_type == AV_PICTURE_TYPE_I ? rcc->last_mb_var_sum

                                                                    : rcc->last_mc_mb_var_sum;

        av_assert1(s->frame_bits >= s->stuffing_bits);

        update_predictor(&rcc->pred[s->last_pict_type],

                         rcc->last_qscale,

                         sqrt(last_var),

                         s->frame_bits - s->stuffing_bits);

    }

    if (s->flags & CODEC_FLAG_PASS2) {

        assert(picture_number >= 0);

        if (picture_number >= rcc->num_entries) {

            av_log(s, AV_LOG_ERROR, "Input is longer than 2-pass log file\n");

            return -1;

        }

        rce         = &rcc->entry[picture_number];

        wanted_bits = rce->expected_bits;

    } else {

        Picture *dts_pic;

        rce = &local_rce;

        /* FIXME add a dts field to AVFrame and ensure it is set and use it

         * here instead of reordering but the reordering is simpler for now

         * until H.264 B-pyramid must be handled. */

        if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay)

            dts_pic = s->current_picture_ptr;

        else

            dts_pic = s->last_picture_ptr;

        if (!dts_pic || dts_pic->f.pts == AV_NOPTS_VALUE)

            wanted_bits = (uint64_t)(s->bit_rate * (double)picture_number / fps);

        else

            wanted_bits = (uint64_t)(s->bit_rate * (double)dts_pic->f.pts / fps);

    }

    diff = s->total_bits - wanted_bits;

    br_compensation = (a->bit_rate_tolerance - diff) / a->bit_rate_tolerance;

    if (br_compensation <= 0.0)

        br_compensation = 0.001;

    var = pict_type == AV_PICTURE_TYPE_I ? pic->mb_var_sum : pic->mc_mb_var_sum;

    short_term_q = 0; /* avoid warning */

    if (s->flags & CODEC_FLAG_PASS2) {

        if (pict_type != AV_PICTURE_TYPE_I)

            assert(pict_type == rce->new_pict_type);

        q = rce->new_qscale / br_compensation;

        av_dlog(s, "%f %f %f last:%d var:%d type:%d//\n", q, rce->new_qscale,

                br_compensation, s->frame_bits, var, pict_type);

    } else {

        rce->pict_type     =

        rce->new_pict_type = pict_type;

        rce->mc_mb_var_sum = pic->mc_mb_var_sum;

        rce->mb_var_sum    = pic->mb_var_sum;

        rce->qscale        = FF_QP2LAMBDA * 2;

        rce->f_code        = s->f_code;

        rce->b_code        = s->b_code;

        rce->misc_bits     = 1;

        bits = predict_size(&rcc->pred[pict_type], rce->qscale, sqrt(var));

        if (pict_type == AV_PICTURE_TYPE_I) {

            rce->i_count    = s->mb_num;

            rce->i_tex_bits = bits;

            rce->p_tex_bits = 0;

            rce->mv_bits    = 0;

        } else {

            rce->i_count    = 0;    // FIXME we do know this approx

            rce->i_tex_bits = 0;

            rce->p_tex_bits = bits * 0.9;

            rce->mv_bits    = bits * 0.1;

        }

        rcc->i_cplx_sum[pict_type]  += rce->i_tex_bits * rce->qscale;

        rcc->p_cplx_sum[pict_type]  += rce->p_tex_bits * rce->qscale;

        rcc->mv_bits_sum[pict_type] += rce->mv_bits;

        rcc->frame_count[pict_type]++;

        bits        = rce->i_tex_bits + rce->p_tex_bits;

        rate_factor = rcc->pass1_wanted_bits /

                      rcc->pass1_rc_eq_output_sum * br_compensation;

        q = get_qscale(s, rce, rate_factor, picture_number);

        if (q < 0)

            return -1;

        assert(q > 0.0);

        q = get_diff_limited_q(s, rce, q);

        assert(q > 0.0);

        // FIXME type dependent blur like in 2-pass

        if (pict_type == AV_PICTURE_TYPE_P || s->intra_only) {

            rcc->short_term_qsum   *= a->qblur;

            rcc->short_term_qcount *= a->qblur;

            rcc->short_term_qsum += q;

            rcc->short_term_qcount++;

            q = short_term_q = rcc->short_term_qsum / rcc->short_term_qcount;

        }

        assert(q > 0.0);

        q = modify_qscale(s, rce, q, picture_number);

        rcc->pass1_wanted_bits += s->bit_rate / fps;

        assert(q > 0.0);

    }

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

        av_log(s->avctx, AV_LOG_DEBUG,

               "%c qp:%d<%2.1f<%d %d want:%d total:%d comp:%f st_q:%2.2f "

               "size:%d var:%"PRId64"/%"PRId64" br:%d fps:%d\n",

               av_get_picture_type_char(pict_type),

               qmin, q, qmax, picture_number,

               (int)wanted_bits / 1000, (int)s->total_bits / 1000,

               br_compensation, short_term_q, s->frame_bits,

               pic->mb_var_sum, pic->mc_mb_var_sum,

               s->bit_rate / 1000, (int)fps);

    }

    if (q < qmin)

        q = qmin;

    else if (q > qmax)

        q = qmax;

    if (s->adaptive_quant)

        adaptive_quantization(s, q);

    else

        q = (int)(q + 0.5);

    if (!dry_run) {

        rcc->last_qscale        = q;

        rcc->last_mc_mb_var_sum = pic->mc_mb_var_sum;

        rcc->last_mb_var_sum    = pic->mb_var_sum;

    }

    return q;

}


static void pred_spatial_direct_motion(H264Context * const h, int *mb_type){

    MpegEncContext * const s = &h->s;

    int b8_stride = 2;

    int b4_stride = h->b_stride;

    int mb_xy = h->mb_xy, mb_y = s->mb_y;

    int mb_type_col[2];

    const int16_t (*l1mv0)[2], (*l1mv1)[2];

    const int8_t *l1ref0, *l1ref1;

    const int is_b8x8 = IS_8X8(*mb_type);

    unsigned int sub_mb_type= MB_TYPE_L0L1;

    int i8, i4;

    int ref[2];

    int mv[2];

    int list;

    assert(h->ref_list[1][0].f.reference & 3);

    await_reference_mb_row(h, &h->ref_list[1][0], s->mb_y + !!IS_INTERLACED(*mb_type));

#define MB_TYPE_16x16_OR_INTRA (MB_TYPE_16x16|MB_TYPE_INTRA4x4|MB_TYPE_INTRA16x16|MB_TYPE_INTRA_PCM)

    /* ref = min(neighbors) */

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

        int left_ref = h->ref_cache[list][scan8[0] - 1];

        int top_ref  = h->ref_cache[list][scan8[0] - 8];

        int refc = h->ref_cache[list][scan8[0] - 8 + 4];

        const int16_t *C= h->mv_cache[list][ scan8[0] - 8 + 4];

        if(refc == PART_NOT_AVAILABLE){

            refc = h->ref_cache[list][scan8[0] - 8 - 1];

            C    = h-> mv_cache[list][scan8[0] - 8 - 1];

        ref[list] = FFMIN3((unsigned)left_ref, (unsigned)top_ref, (unsigned)refc);

        if(ref[list] >= 0){

            //this is just pred_motion() but with the cases removed that cannot happen for direct blocks

            const int16_t * const A= h->mv_cache[list][ scan8[0] - 1 ];

            const int16_t * const B= h->mv_cache[list][ scan8[0] - 8 ];

            int match_count= (left_ref==ref[list]) + (top_ref==ref[list]) + (refc==ref[list]);

            if(match_count > 1){ //most common

                mv[list]= pack16to32(mid_pred(A[0], B[0], C[0]),

                                     mid_pred(A[1], B[1], C[1]) );

            }else {

                assert(match_count==1);

                if(left_ref==ref[list]){

                    mv[list]= AV_RN32A(A);

                }else if(top_ref==ref[list]){

                    mv[list]= AV_RN32A(B);

                }else{

                    mv[list]= AV_RN32A(C);

        }else{

            int mask= ~(MB_TYPE_L0 << (2*list));

            mv[list] = 0;

            ref[list] = -1;

            if(!is_b8x8)

                *mb_type &= mask;

            sub_mb_type &= mask;

    if(ref[0] < 0 && ref[1] < 0){

        ref[0] = ref[1] = 0;

        if(!is_b8x8)

            *mb_type |= MB_TYPE_L0L1;

        sub_mb_type |= MB_TYPE_L0L1;

    if(!(is_b8x8|mv[0]|mv[1])){

        fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);

        fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);

        fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, 0, 4);

        fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, 0, 4);

        *mb_type= (*mb_type & ~(MB_TYPE_8x8|MB_TYPE_16x8|MB_TYPE_8x16|MB_TYPE_P1L0|MB_TYPE_P1L1))|MB_TYPE_16x16|MB_TYPE_DIRECT2;

        return;

    if (IS_INTERLACED(h->ref_list[1][0].f.mb_type[mb_xy])) { // AFL/AFR/FR/FL -> AFL/FL

        if (!IS_INTERLACED(*mb_type)) {                          //     AFR/FR    -> AFL/FL

            mb_y = (s->mb_y&~1) + h->col_parity;

            mb_xy= s->mb_x + ((s->mb_y&~1) + h->col_parity)*s->mb_stride;

            b8_stride = 0;

        }else{

            mb_y  += h->col_fieldoff;

            mb_xy += s->mb_stride*h->col_fieldoff; // non zero for FL -> FL & differ parity

        goto single_col;

    }else{                                               // AFL/AFR/FR/FL -> AFR/FR

        if(IS_INTERLACED(*mb_type)){                     // AFL       /FL -> AFR/FR

            mb_y = s->mb_y&~1;

            mb_xy= s->mb_x + (s->mb_y&~1)*s->mb_stride;

            mb_type_col[0] = h->ref_list[1][0].f.mb_type[mb_xy];

            mb_type_col[1] = h->ref_list[1][0].f.mb_type[mb_xy + s->mb_stride];

            b8_stride = 2+4*s->mb_stride;

            b4_stride *= 6;

            sub_mb_type |= MB_TYPE_16x16|MB_TYPE_DIRECT2; /* B_SUB_8x8 */

            if(    (mb_type_col[0] & MB_TYPE_16x16_OR_INTRA)

                && (mb_type_col[1] & MB_TYPE_16x16_OR_INTRA)

                && !is_b8x8){

                *mb_type   |= MB_TYPE_16x8 |MB_TYPE_DIRECT2; /* B_16x8 */

            }else{

                *mb_type   |= MB_TYPE_8x8;

        }else{                                           //     AFR/FR    -> AFR/FR

single_col:

            mb_type_col[0] =

            mb_type_col[1] = h->ref_list[1][0].f.mb_type[mb_xy];

            sub_mb_type |= MB_TYPE_16x16|MB_TYPE_DIRECT2; /* B_SUB_8x8 */

            if(!is_b8x8 && (mb_type_col[0] & MB_TYPE_16x16_OR_INTRA)){

                *mb_type   |= MB_TYPE_16x16|MB_TYPE_DIRECT2; /* B_16x16 */

            }else if(!is_b8x8 && (mb_type_col[0] & (MB_TYPE_16x8|MB_TYPE_8x16))){

                *mb_type   |= MB_TYPE_DIRECT2 | (mb_type_col[0] & (MB_TYPE_16x8|MB_TYPE_8x16));

            }else{

                if(!h->sps.direct_8x8_inference_flag){

                    /* FIXME save sub mb types from previous frames (or derive from MVs)

                    * so we know exactly what block size to use */

                    sub_mb_type += (MB_TYPE_8x8-MB_TYPE_16x16); /* B_SUB_4x4 */

                *mb_type   |= MB_TYPE_8x8;

    await_reference_mb_row(h, &h->ref_list[1][0], mb_y);

    l1mv0  = &h->ref_list[1][0].f.motion_val[0][h->mb2b_xy [mb_xy]];

    l1mv1  = &h->ref_list[1][0].f.motion_val[1][h->mb2b_xy [mb_xy]];

    l1ref0 = &h->ref_list[1][0].f.ref_index [0][4 * mb_xy];

    l1ref1 = &h->ref_list[1][0].f.ref_index [1][4 * mb_xy];

    if(!b8_stride){

        if(s->mb_y&1){

            l1ref0 += 2;

            l1ref1 += 2;

            l1mv0  +=  2*b4_stride;

            l1mv1  +=  2*b4_stride;

        if(IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col[0])){

            int n=0;

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

                int x8 = i8&1;

                int y8 = i8>>1;

                int xy8 = x8+y8*b8_stride;

                int xy4 = 3*x8+y8*b4_stride;

                int a,b;

                if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))

                    continue;

                h->sub_mb_type[i8] = sub_mb_type;

                fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[0], 1);

                fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[1], 1);

                if(!IS_INTRA(mb_type_col[y8]) && !h->ref_list[1][0].long_ref

                   && (   (l1ref0[xy8] == 0 && FFABS(l1mv0[xy4][0]) <= 1 && FFABS(l1mv0[xy4][1]) <= 1)

                       || (l1ref0[xy8]  < 0 && l1ref1[xy8] == 0 && FFABS(l1mv1[xy4][0]) <= 1 && FFABS(l1mv1[xy4][1]) <= 1))){

                    a=b=0;

                    if(ref[0] > 0)

                        a= mv[0];

                    if(ref[1] > 0)

                        b= mv[1];

                    n++;

                }else{

                    a= mv[0];

                    b= mv[1];

                fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, a, 4);

                fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, b, 4);

            if(!is_b8x8 && !(n&3))

                *mb_type= (*mb_type & ~(MB_TYPE_8x8|MB_TYPE_16x8|MB_TYPE_8x16|MB_TYPE_P1L0|MB_TYPE_P1L1))|MB_TYPE_16x16|MB_TYPE_DIRECT2;

        }else if(IS_16X16(*mb_type)){

            int a,b;

            fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);

            fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);

            if(!IS_INTRA(mb_type_col[0]) && !h->ref_list[1][0].long_ref

               && (   (l1ref0[0] == 0 && FFABS(l1mv0[0][0]) <= 1 && FFABS(l1mv0[0][1]) <= 1)

                   || (l1ref0[0]  < 0 && l1ref1[0] == 0 && FFABS(l1mv1[0][0]) <= 1 && FFABS(l1mv1[0][1]) <= 1

                       && h->x264_build>33U))){

                a=b=0;

                if(ref[0] > 0)

                    a= mv[0];

                if(ref[1] > 0)

                    b= mv[1];

            }else{

                a= mv[0];

                b= mv[1];

            fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, a, 4);

            fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, b, 4);

        }else{

            int n=0;

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

                const int x8 = i8&1;

                const int y8 = i8>>1;

                if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))

                    continue;

                h->sub_mb_type[i8] = sub_mb_type;

                fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, mv[0], 4);

                fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, mv[1], 4);

                fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[0], 1);

                fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[1], 1);

                assert(b8_stride==2);

                /* col_zero_flag */

                if(!IS_INTRA(mb_type_col[0]) && !h->ref_list[1][0].long_ref && (   l1ref0[i8] == 0

                                              || (l1ref0[i8] < 0 && l1ref1[i8] == 0

                                                  && h->x264_build>33U))){

                    const int16_t (*l1mv)[2]= l1ref0[i8] == 0 ? l1mv0 : l1mv1;

                    if(IS_SUB_8X8(sub_mb_type)){

                        const int16_t *mv_col = l1mv[x8*3 + y8*3*b4_stride];

                        if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){

                            if(ref[0] == 0)

                                fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);

                            if(ref[1] == 0)

                                fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);

                            n+=4;

                    }else{

                        int m=0;

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

                        const int16_t *mv_col = l1mv[x8*2 + (i4&1) + (y8*2 + (i4>>1))*b4_stride];

                        if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){

                            if(ref[0] == 0)

                                AV_ZERO32(h->mv_cache[0][scan8[i8*4+i4]]);

                            if(ref[1] == 0)

                                AV_ZERO32(h->mv_cache[1][scan8[i8*4+i4]]);

                            m++;

                    if(!(m&3))

                        h->sub_mb_type[i8]+= MB_TYPE_16x16 - MB_TYPE_8x8;

                    n+=m;

            if(!is_b8x8 && !(n&15))

                *mb_type= (*mb_type & ~(MB_TYPE_8x8|MB_TYPE_16x8|MB_TYPE_8x16|MB_TYPE_P1L0|MB_TYPE_P1L1))|MB_TYPE_16x16|MB_TYPE_DIRECT2;


int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)

{

    if(min_ts > ts || max_ts < ts)

        return -1;

    if (s->iformat->read_seek2) {

        int ret;

        ff_read_frame_flush(s);

        if (stream_index == -1 && s->nb_streams == 1) {

            AVRational time_base = s->streams[0]->time_base;

            ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);

            min_ts = av_rescale_rnd(min_ts, time_base.den,

                                    time_base.num * (int64_t)AV_TIME_BASE,

                                    AV_ROUND_UP);

            max_ts = av_rescale_rnd(max_ts, time_base.den,

                                    time_base.num * (int64_t)AV_TIME_BASE,

                                    AV_ROUND_DOWN);

        }

        ret = s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);

        if (ret >= 0)

            avformat_queue_attached_pictures(s);

        return ret;

    }

    if(s->iformat->read_timestamp){

        //try to seek via read_timestamp()

    }

    //Fallback to old API if new is not implemented but old is

    //Note the old has somewhat different semantics

    if (s->iformat->read_seek || 1) {

        int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);

        int ret = av_seek_frame(s, stream_index, ts, flags | dir);

        if (ret<0 && ts != min_ts && max_ts != ts) {

            ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);

            if (ret >= 0)

                ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));

        }

        return ret;

    }

    // try some generic seek like seek_frame_generic() but with new ts semantics

}


static inline void render_line_unrolled(intptr_t x, uint8_t y, int x1,

                                        intptr_t sy, int ady, int adx,

                                        float *buf)

{

    int err = -adx;

    x -= x1 - 1;

    buf += x1 - 1;

    while (++x < 0) {

        err += ady;

        if (err >= 0) {

            err += ady - adx;

            y   += sy;

            buf[x++] = ff_vorbis_floor1_inverse_db_table[y];

        }

        buf[x] = ff_vorbis_floor1_inverse_db_table[y];

    }

    if (x <= 0) {

        if (err + ady >= 0)

            y += sy;

        buf[x] = ff_vorbis_floor1_inverse_db_table[y];

    }

}


iscsi_connect_cb(struct iscsi_context *iscsi, int status, void *command_data,

                 void *opaque)

{

    struct IscsiTask *itask = opaque;

    struct scsi_task *task;

    if (status != 0) {

        itask->status   = 1;

        itask->complete = 1;

        return;

    }

    task = iscsi_inquiry_task(iscsi, itask->iscsilun->lun,

                              0, 0, 36,

                              iscsi_inquiry_cb, opaque);

    if (task == NULL) {

        error_report("iSCSI: failed to send inquiry command.");

        itask->status   = 1;

        itask->complete = 1;

        return;

    }

}


static inline void s_zero(int cur_diff, struct G722Band *band)

{

    int s_zero = 0;

    #define ACCUM(k, x, d) do { \

            int tmp = x; \

            band->zero_mem[k] = ((band->zero_mem[k] * 255) >> 8) + \

               d*((band->diff_mem[k]^cur_diff) < 0 ? -128 : 128); \

            band->diff_mem[k] = tmp; \

            s_zero += (tmp * band->zero_mem[k]) >> 15; \

        } while (0)

    if (cur_diff) {

        ACCUM(5, band->diff_mem[4], 1);

        ACCUM(4, band->diff_mem[3], 1);

        ACCUM(3, band->diff_mem[2], 1);

        ACCUM(2, band->diff_mem[1], 1);

        ACCUM(1, band->diff_mem[0], 1);

        ACCUM(0, cur_diff << 1, 1);

    } else {

        ACCUM(5, band->diff_mem[4], 0);

        ACCUM(4, band->diff_mem[3], 0);

        ACCUM(3, band->diff_mem[2], 0);

        ACCUM(2, band->diff_mem[1], 0);

        ACCUM(1, band->diff_mem[0], 0);

        ACCUM(0, cur_diff << 1, 0);

    }

    #undef ACCUM

    band->s_zero = s_zero;

}


static uint32_t qvirtio_pci_get_features(QVirtioDevice *d)

{

    QVirtioPCIDevice *dev = (QVirtioPCIDevice *)d;

    return qpci_io_readl(dev->pdev, dev->addr + VIRTIO_PCI_HOST_FEATURES);

}


static av_cold int decode_init(AVCodecContext * avctx)

{

    KmvcContext *const c = avctx->priv_data;

    int i;

    c->avctx = avctx;

    if (avctx->width > 320 || avctx->height > 200) {

        av_log(avctx, AV_LOG_ERROR, "KMVC supports frames <= 320x200\n");

        return -1;

    }

    c->frm0 = av_mallocz(320 * 200);

    c->frm1 = av_mallocz(320 * 200);

    c->cur = c->frm0;

    c->prev = c->frm1;

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

        c->pal[i] = 0xFF << 24 | i * 0x10101;

    }

    if (avctx->extradata_size < 12) {

        av_log(avctx, AV_LOG_WARNING,

               "Extradata missing, decoding may not work properly...\n");

        c->palsize = 127;

    } else {

        c->palsize = AV_RL16(avctx->extradata + 10);

        if (c->palsize >= (unsigned)MAX_PALSIZE) {

            c->palsize = 127;

            av_log(avctx, AV_LOG_ERROR, "KMVC palette too large\n");

            return AVERROR_INVALIDDATA;

        }

    }

    if (avctx->extradata_size == 1036) {        // palette in extradata

        uint8_t *src = avctx->extradata + 12;

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

            c->pal[i] = AV_RL32(src);

            src += 4;

        }

        c->setpal = 1;

    }

    avcodec_get_frame_defaults(&c->pic);

    avctx->pix_fmt = AV_PIX_FMT_PAL8;

    return 0;

}


static uint8_t lag_calc_zero_run(int8_t x)

{

    return (x << 1) ^ (x >> 7);

}


static void patch_reloc(uint8_t *code_ptr, int type,

                        intptr_t value, intptr_t addend)

{

    value += addend;

    switch(type) {

    case R_386_PC32:

        value -= (uintptr_t)code_ptr;

        if (value != (int32_t)value) {

            tcg_abort();

        }

        *(uint32_t *)code_ptr = value;

        break;

    case R_386_PC8:

        value -= (uintptr_t)code_ptr;

        if (value != (int8_t)value) {

            tcg_abort();

        }

        *(uint8_t *)code_ptr = value;

        break;

    default:

        tcg_abort();

    }

}


static int nut_write_trailer(AVFormatContext *s)

{

    NUTContext *nut = s->priv_data;

    ByteIOContext *bc = &s->pb;

    update_packetheader(nut, bc, 0);

#if 0

    int i;

    /* WRITE INDEX */

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

    {

	put_be64(bc, INDEX_STARTCODE);

	put_packetheader(nut, bc, 64);

	put_v(bc, s->streams[i]->id);

	put_v(bc, ...);

	put_be32(bc, 0); /* FIXME: checksum */

        update_packetheader(nut, bc, 0);

    }

#endif

    put_flush_packet(bc);

    av_freep(&nut->stream);

    return 0;

}


static void noise(uint8_t *dst, const uint8_t *src,

                  int dst_linesize, int src_linesize,

                  int width, int start, int end, NoiseContext *n, int comp)

{

    FilterParams *p = &n->param[comp];

    int8_t *noise = p->noise;

    const int flags = p->flags;

    AVLFG *lfg = &p->lfg;

    int shift, y;

    if (!noise) {

        if (dst != src)

            av_image_copy_plane(dst, dst_linesize, src, src_linesize, width, end - start);

        return;

    }

    for (y = start; y < end; y++) {

        if (flags & NOISE_TEMPORAL)

            shift = av_lfg_get(lfg) & (MAX_SHIFT - 1);

        else

            shift = n->rand_shift[y];

        if (flags & NOISE_AVERAGED) {

            n->line_noise_avg(dst, src, width, p->prev_shift[y]);

            p->prev_shift[y][shift & 3] = noise + shift;

        } else {

            n->line_noise(dst, src, noise, width, shift);

        }

        dst += dst_linesize;

        src += src_linesize;

    }

}


void ff_generate_sliding_window_mmcos(H264Context *h) {

    MpegEncContext * const s = &h->s;

    assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);

    h->mmco_index= 0;

    if(h->short_ref_count && h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&

            !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {

        h->mmco[0].opcode= MMCO_SHORT2UNUSED;

        h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;

        h->mmco_index= 1;

        if (FIELD_PICTURE) {

            h->mmco[0].short_pic_num *= 2;

            h->mmco[1].opcode= MMCO_SHORT2UNUSED;

            h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;

            h->mmco_index= 2;

        }

    }

}


static av_cold int X264_init(AVCodecContext *avctx)

{

    X264Context *x4 = avctx->priv_data;

    AVCPBProperties *cpb_props;

#if CONFIG_LIBX262_ENCODER

    if (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

        x4->params.b_mpeg2 = 1;

        x264_param_default_mpeg2(&x4->params);

    } else

#else

    x264_param_default(&x4->params);

#endif

    x4->params.b_deblocking_filter         = avctx->flags & AV_CODEC_FLAG_LOOP_FILTER;

    if (x4->preset || x4->tune)

        if (x264_param_default_preset(&x4->params, x4->preset, x4->tune) < 0) {

            av_log(avctx, AV_LOG_ERROR, "Error setting preset/tune %s/%s.\n", x4->preset, x4->tune);

            return AVERROR(EINVAL);

        }

    if (avctx->level > 0)

        x4->params.i_level_idc = avctx->level;

    x4->params.pf_log               = X264_log;

    x4->params.p_log_private        = avctx;

    x4->params.i_log_level          = X264_LOG_DEBUG;

    x4->params.i_csp                = convert_pix_fmt(avctx->pix_fmt);

    if (avctx->bit_rate) {

        x4->params.rc.i_bitrate   = avctx->bit_rate / 1000;

        x4->params.rc.i_rc_method = X264_RC_ABR;

    }

    x4->params.rc.i_vbv_buffer_size = avctx->rc_buffer_size / 1000;

    x4->params.rc.i_vbv_max_bitrate = avctx->rc_max_rate    / 1000;

    x4->params.rc.b_stat_write      = avctx->flags & AV_CODEC_FLAG_PASS1;

    if (avctx->flags & AV_CODEC_FLAG_PASS2) {

        x4->params.rc.b_stat_read = 1;

    } else {

        if (x4->crf >= 0) {

            x4->params.rc.i_rc_method   = X264_RC_CRF;

            x4->params.rc.f_rf_constant = x4->crf;

        } else if (x4->cqp >= 0) {

            x4->params.rc.i_rc_method   = X264_RC_CQP;

            x4->params.rc.i_qp_constant = x4->cqp;

        }

        if (x4->crf_max >= 0)

            x4->params.rc.f_rf_constant_max = x4->crf_max;

    }

    if (avctx->rc_buffer_size && avctx->rc_initial_buffer_occupancy > 0 &&

        (avctx->rc_initial_buffer_occupancy <= avctx->rc_buffer_size)) {

        x4->params.rc.f_vbv_buffer_init =

            (float)avctx->rc_initial_buffer_occupancy / avctx->rc_buffer_size;

    }

    if (avctx->i_quant_factor > 0)

        x4->params.rc.f_ip_factor         = 1 / fabs(avctx->i_quant_factor);

    x4->params.rc.f_pb_factor             = avctx->b_quant_factor;

    x4->params.analyse.i_chroma_qp_offset = avctx->chromaoffset;

    if (avctx->gop_size >= 0)

        x4->params.i_keyint_max         = avctx->gop_size;

    if (avctx->max_b_frames >= 0)

        x4->params.i_bframe             = avctx->max_b_frames;

    if (avctx->scenechange_threshold >= 0)

        x4->params.i_scenecut_threshold = avctx->scenechange_threshold;

    if (avctx->qmin >= 0)

        x4->params.rc.i_qp_min          = avctx->qmin;

    if (avctx->qmax >= 0)

        x4->params.rc.i_qp_max          = avctx->qmax;

    if (avctx->max_qdiff >= 0)

        x4->params.rc.i_qp_step         = avctx->max_qdiff;

    if (avctx->qblur >= 0)

        x4->params.rc.f_qblur           = avctx->qblur;     /* temporally blur quants */

    if (avctx->qcompress >= 0)

        x4->params.rc.f_qcompress       = avctx->qcompress; /* 0.0 => cbr, 1.0 => constant qp */

    if (avctx->refs >= 0)

        x4->params.i_frame_reference    = avctx->refs;

    if (avctx->trellis >= 0)

        x4->params.analyse.i_trellis    = avctx->trellis;

    if (avctx->me_range >= 0)

        x4->params.analyse.i_me_range   = avctx->me_range;

    if (avctx->noise_reduction >= 0)

        x4->params.analyse.i_noise_reduction = avctx->noise_reduction;

    if (avctx->me_subpel_quality >= 0)

        x4->params.analyse.i_subpel_refine   = avctx->me_subpel_quality;

    if (avctx->b_frame_strategy >= 0)

        x4->params.i_bframe_adaptive = avctx->b_frame_strategy;

    if (avctx->keyint_min >= 0)

        x4->params.i_keyint_min = avctx->keyint_min;

#if FF_API_CODER_TYPE

FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->coder_type >= 0)

        x4->coder = avctx->coder_type == FF_CODER_TYPE_AC;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    if (avctx->me_cmp >= 0)

        x4->params.analyse.b_chroma_me = avctx->me_cmp & FF_CMP_CHROMA;

    if (x4->aq_mode >= 0)

        x4->params.rc.i_aq_mode = x4->aq_mode;

    if (x4->aq_strength >= 0)

        x4->params.rc.f_aq_strength = x4->aq_strength;

    PARSE_X264_OPT("psy-rd", psy_rd);

    PARSE_X264_OPT("deblock", deblock);

    PARSE_X264_OPT("partitions", partitions);

    PARSE_X264_OPT("stats", stats);

    if (x4->psy >= 0)

        x4->params.analyse.b_psy  = x4->psy;

    if (x4->rc_lookahead >= 0)

        x4->params.rc.i_lookahead = x4->rc_lookahead;

    if (x4->weightp >= 0)

        x4->params.analyse.i_weighted_pred = x4->weightp;

    if (x4->weightb >= 0)

        x4->params.analyse.b_weighted_bipred = x4->weightb;

    if (x4->cplxblur >= 0)

        x4->params.rc.f_complexity_blur = x4->cplxblur;

    if (x4->ssim >= 0)

        x4->params.analyse.b_ssim = x4->ssim;

    if (x4->intra_refresh >= 0)

        x4->params.b_intra_refresh = x4->intra_refresh;

    if (x4->bluray_compat >= 0) {

        x4->params.b_bluray_compat = x4->bluray_compat;

        x4->params.b_vfr_input = 0;

    }

    if (x4->b_bias != INT_MIN)

        x4->params.i_bframe_bias              = x4->b_bias;

    if (x4->b_pyramid >= 0)

        x4->params.i_bframe_pyramid = x4->b_pyramid;

    if (x4->mixed_refs >= 0)

        x4->params.analyse.b_mixed_references = x4->mixed_refs;

    if (x4->dct8x8 >= 0)

        x4->params.analyse.b_transform_8x8    = x4->dct8x8;

    if (x4->fast_pskip >= 0)

        x4->params.analyse.b_fast_pskip       = x4->fast_pskip;

    if (x4->aud >= 0)

        x4->params.b_aud                      = x4->aud;

    if (x4->mbtree >= 0)

        x4->params.rc.b_mb_tree               = x4->mbtree;

    if (x4->direct_pred >= 0)

        x4->params.analyse.i_direct_mv_pred   = x4->direct_pred;

    if (x4->slice_max_size >= 0)

        x4->params.i_slice_max_size =  x4->slice_max_size;

    if (x4->fastfirstpass)

        x264_param_apply_fastfirstpass(&x4->params);

    if (x4->nal_hrd >= 0)

        x4->params.i_nal_hrd = x4->nal_hrd;

    if (x4->motion_est >= 0) {

        x4->params.analyse.i_me_method = x4->motion_est;

#if FF_API_MOTION_EST

FF_DISABLE_DEPRECATION_WARNINGS

    } else {

        if (avctx->me_method == ME_EPZS)

            x4->params.analyse.i_me_method = X264_ME_DIA;

        else if (avctx->me_method == ME_HEX)

            x4->params.analyse.i_me_method = X264_ME_HEX;

        else if (avctx->me_method == ME_UMH)

            x4->params.analyse.i_me_method = X264_ME_UMH;

        else if (avctx->me_method == ME_FULL)

            x4->params.analyse.i_me_method = X264_ME_ESA;

        else if (avctx->me_method == ME_TESA)

            x4->params.analyse.i_me_method = X264_ME_TESA;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    }

    if (x4->coder >= 0)

        x4->params.b_cabac = x4->coder;

    if (x4->profile)

        if (x264_param_apply_profile(&x4->params, x4->profile) < 0) {

            av_log(avctx, AV_LOG_ERROR, "Error setting profile %s.\n", x4->profile);

            return AVERROR(EINVAL);

        }

    x4->params.i_width          = avctx->width;

    x4->params.i_height         = avctx->height;

    x4->params.vui.i_sar_width  = avctx->sample_aspect_ratio.num;

    x4->params.vui.i_sar_height = avctx->sample_aspect_ratio.den;

    x4->params.i_fps_num = x4->params.i_timebase_den = avctx->time_base.den;

    x4->params.i_fps_den = x4->params.i_timebase_num = avctx->time_base.num;

    x4->params.analyse.b_psnr = avctx->flags & AV_CODEC_FLAG_PSNR;

    x4->params.i_threads      = avctx->thread_count;

    if (avctx->thread_type)

        x4->params.b_sliced_threads = avctx->thread_type == FF_THREAD_SLICE;

    x4->params.b_interlaced   = avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT;

    x4->params.b_open_gop     = !(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);

    x4->params.i_slice_count  = avctx->slices;

    x4->params.vui.b_fullrange = avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||

                                 avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||

                                 avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||

                                 avctx->color_range == AVCOL_RANGE_JPEG;

    // x264 validates the values internally

    x4->params.vui.i_colorprim = avctx->color_primaries;

    x4->params.vui.i_transfer  = avctx->color_trc;

    x4->params.vui.i_colmatrix = avctx->colorspace;

    if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)

        x4->params.b_repeat_headers = 0;

    if (x4->x264_params) {

        AVDictionary *dict    = NULL;

        AVDictionaryEntry *en = NULL;

        if (!av_dict_parse_string(&dict, x4->x264_params, "=", ":", 0)) {

            while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {

                if (x264_param_parse(&x4->params, en->key, en->value) < 0)

                    av_log(avctx, AV_LOG_WARNING,

                           "Error parsing option '%s = %s'.\n",

                            en->key, en->value);

            }

            av_dict_free(&dict);

        }

    }

    // update AVCodecContext with x264 parameters

    avctx->has_b_frames = x4->params.i_bframe ?

        x4->params.i_bframe_pyramid ? 2 : 1 : 0;

    if (avctx->max_b_frames < 0)

        avctx->max_b_frames = 0;

    avctx->bit_rate = x4->params.rc.i_bitrate*1000;

    x4->enc = x264_encoder_open(&x4->params);

    if (!x4->enc)

        return AVERROR_UNKNOWN;

    if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {

        x264_nal_t *nal;

        uint8_t *p;

        int nnal, s, i;

        s = x264_encoder_headers(x4->enc, &nal, &nnal);

        avctx->extradata = p = av_mallocz(s + AV_INPUT_BUFFER_PADDING_SIZE);

        if (!p)

            return AVERROR(ENOMEM);

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

            /* Don't put the SEI in extradata. */

            if (nal[i].i_type == NAL_SEI) {

                av_log(avctx, AV_LOG_INFO, "%s\n", nal[i].p_payload+25);

                x4->sei_size = nal[i].i_payload;

                x4->sei      = av_malloc(x4->sei_size);

                if (!x4->sei)

                    return AVERROR(ENOMEM);

                memcpy(x4->sei, nal[i].p_payload, nal[i].i_payload);

                continue;

            }

            memcpy(p, nal[i].p_payload, nal[i].i_payload);

            p += nal[i].i_payload;

        }

        avctx->extradata_size = p - avctx->extradata;

    }

    cpb_props = ff_add_cpb_side_data(avctx);

    if (!cpb_props)

        return AVERROR(ENOMEM);

    cpb_props->buffer_size = x4->params.rc.i_vbv_buffer_size * 1000;

    cpb_props->max_bitrate = x4->params.rc.i_vbv_max_bitrate * 1000;

    cpb_props->avg_bitrate = x4->params.rc.i_bitrate         * 1000;

    return 0;

}


static void blend_image_rgba_pm(AVFilterContext *ctx, AVFrame *dst, const AVFrame *src, int x, int y)

{

    blend_image_packed_rgb(ctx, dst, src, 1, x, y, 1);

}


int ff_h264_frame_start(H264Context *h)

{

    Picture *pic;

    int i, ret;

    const int pixel_shift = h->pixel_shift;

    int c[4] = {

        1<<(h->sps.bit_depth_luma-1),

        1<<(h->sps.bit_depth_chroma-1),

        1<<(h->sps.bit_depth_chroma-1),

        -1

    };

    if (!ff_thread_can_start_frame(h->avctx)) {

        av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");

        return -1;

    }

    release_unused_pictures(h, 1);

    h->cur_pic_ptr = NULL;

    i = find_unused_picture(h);

    if (i < 0) {

        av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");

        return i;

    }

    pic = &h->DPB[i];

    pic->f.reference            = h->droppable ? 0 : h->picture_structure;

    pic->f.coded_picture_number = h->coded_picture_number++;

    pic->field_picture          = h->picture_structure != PICT_FRAME;

    /*

     * Zero key_frame here; IDR markings per slice in frame or fields are ORed

     * in later.

     * See decode_nal_units().

     */

    pic->f.key_frame = 0;

    pic->sync        = 0;

    pic->mmco_reset  = 0;

    if ((ret = alloc_picture(h, pic)) < 0)

        return ret;

    if(!h->sync && !h->avctx->hwaccel &&

       !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))

        avpriv_color_frame(&pic->f, c);

    h->cur_pic_ptr = pic;

    h->cur_pic     = *h->cur_pic_ptr;

    h->cur_pic.f.extended_data = h->cur_pic.f.data;

    ff_er_frame_start(&h->er);

    assert(h->linesize && h->uvlinesize);

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

        h->block_offset[i]           = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);

        h->block_offset[48 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);

    }

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

        h->block_offset[16 + i]      =

        h->block_offset[32 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);

        h->block_offset[48 + 16 + i] =

        h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);

    }

    /* can't be in alloc_tables because linesize isn't known there.

     * FIXME: redo bipred weight to not require extra buffer? */

    for (i = 0; i < h->slice_context_count; i++)

        if (h->thread_context[i]) {

            ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);

            if (ret < 0)

                return ret;

        }

    /* Some macroblocks can be accessed before they're available in case

     * of lost slices, MBAFF or threading. */

    memset(h->slice_table, -1,

           (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));

    // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||

    //             h->cur_pic.f.reference /* || h->contains_intra */ || 1;

    /* We mark the current picture as non-reference after allocating it, so

     * that if we break out due to an error it can be released automatically

     * in the next ff_MPV_frame_start().

     * SVQ3 as well as most other codecs have only last/next/current and thus

     * get released even with set reference, besides SVQ3 and others do not

     * mark frames as reference later "naturally". */

    if (h->avctx->codec_id != AV_CODEC_ID_SVQ3)

        h->cur_pic_ptr->f.reference = 0;

    h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;

    h->next_output_pic = NULL;

    assert(h->cur_pic_ptr->long_ref == 0);

    return 0;

}


static int probe(AVProbeData *p)

{

    if (p->buf_size < 13)

        return 0;

    if (p->buf[0] == 0x01 && p->buf[1] == 0x00 &&

        p->buf[4] == 0x01 + p->buf[2] &&

        p->buf[8] == p->buf[4] + p->buf[6] &&

        p->buf[12] == p->buf[8] + p->buf[10])

        return AVPROBE_SCORE_MAX;

    return 0;

}


void ff_weight_h264_pixels8_8_msa(uint8_t *src, int stride,

                                  int height, int log2_denom,

                                  int weight_src, int offset)

{

    avc_wgt_8width_msa(src, stride,

                       height, log2_denom, weight_src, offset);

}


void ff_fetch_timestamp(AVCodecParserContext *s, int off, int remove){

    int i;

    s->dts= s->pts= AV_NOPTS_VALUE;

    s->offset= 0;

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

        if (   s->next_frame_offset + off >= s->cur_frame_offset[i]

            &&(s->     frame_offset       <  s->cur_frame_offset[i] || !s->frame_offset)

            //check is disabled  becausue mpeg-ts doesnt send complete PES packets

            && /*s->next_frame_offset + off <*/  s->cur_frame_end[i]){

            s->dts= s->cur_frame_dts[i];

            s->pts= s->cur_frame_pts[i];

            s->offset = s->next_frame_offset - s->cur_frame_offset[i];

            if(remove)

                s->cur_frame_offset[i]= INT64_MAX;

        }

    }

}


static void new_video_stream(AVFormatContext *oc)

{

    AVStream *st;

    AVCodecContext *video_enc;

    enum CodecID codec_id;

    st = av_new_stream(oc, oc->nb_streams);

    if (!st) {

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

        av_exit(1);

    }

    avcodec_get_context_defaults2(st->codec, AVMEDIA_TYPE_VIDEO);

    bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;

    video_bitstream_filters= NULL;

    avcodec_thread_init(st->codec, thread_count);

    video_enc = st->codec;

    if(video_codec_tag)

        video_enc->codec_tag= video_codec_tag;

    if(   (video_global_header&1)

       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){

        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;

        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;

    }

    if(video_global_header&2){

        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;

        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags2|= CODEC_FLAG2_LOCAL_HEADER;

    }

    if (video_stream_copy) {

        st->stream_copy = 1;

        video_enc->codec_type = AVMEDIA_TYPE_VIDEO;

        video_enc->sample_aspect_ratio =

        st->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);

    } else {

        const char *p;

        int i;

        AVCodec *codec;

        AVRational fps= frame_rate.num ? frame_rate : (AVRational){25,1};

        if (video_codec_name) {

            codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1);

            codec = avcodec_find_encoder_by_name(video_codec_name);

            output_codecs[nb_ocodecs] = codec;

        } else {

            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);

            codec = avcodec_find_encoder(codec_id);

        }

        video_enc->codec_id = codec_id;

        set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM);

        if (codec && codec->supported_framerates && !force_fps)

            fps = codec->supported_framerates[av_find_nearest_q_idx(fps, codec->supported_framerates)];

        video_enc->time_base.den = fps.num;

        video_enc->time_base.num = fps.den;

        video_enc->width = frame_width + frame_padright + frame_padleft;

        video_enc->height = frame_height + frame_padtop + frame_padbottom;

        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);

        video_enc->pix_fmt = frame_pix_fmt;

        st->sample_aspect_ratio = video_enc->sample_aspect_ratio;

        choose_pixel_fmt(st, codec);

        if (intra_only)

            video_enc->gop_size = 0;

        if (video_qscale || same_quality) {

            video_enc->flags |= CODEC_FLAG_QSCALE;

            video_enc->global_quality=

                st->quality = FF_QP2LAMBDA * video_qscale;

        }

        if(intra_matrix)

            video_enc->intra_matrix = intra_matrix;

        if(inter_matrix)

            video_enc->inter_matrix = inter_matrix;

        p= video_rc_override_string;

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

            int start, end, q;

            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);

            if(e!=3){

                fprintf(stderr, "error parsing rc_override\n");

                av_exit(1);

            }

            video_enc->rc_override=

                av_realloc(video_enc->rc_override,

                           sizeof(RcOverride)*(i+1));

            video_enc->rc_override[i].start_frame= start;

            video_enc->rc_override[i].end_frame  = end;

            if(q>0){

                video_enc->rc_override[i].qscale= q;

                video_enc->rc_override[i].quality_factor= 1.0;

            }

            else{

                video_enc->rc_override[i].qscale= 0;

                video_enc->rc_override[i].quality_factor= -q/100.0;

            }

            p= strchr(p, '/');

            if(p) p++;

        }

        video_enc->rc_override_count=i;

        if (!video_enc->rc_initial_buffer_occupancy)

            video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;

        video_enc->me_threshold= me_threshold;

        video_enc->intra_dc_precision= intra_dc_precision - 8;

        if (do_psnr)

            video_enc->flags|= CODEC_FLAG_PSNR;

        /* two pass mode */

        if (do_pass) {

            if (do_pass == 1) {

                video_enc->flags |= CODEC_FLAG_PASS1;

            } else {

                video_enc->flags |= CODEC_FLAG_PASS2;

            }

        }

    }

    nb_ocodecs++;

    if (video_language) {

        av_metadata_set2(&st->metadata, "language", video_language, 0);

        av_freep(&video_language);

    }

    /* reset some key parameters */

    video_disable = 0;

    av_freep(&video_codec_name);

    video_stream_copy = 0;

    frame_pix_fmt = PIX_FMT_NONE;

}


static int opt_debug(void *optctx, const char *opt, const char *arg)

{

    av_log_set_level(99);

    debug = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);

    return 0;

}


static int pulse_set_volume(PulseData *s, double volume)

{

    pa_operation *op;

    pa_cvolume cvol;

    pa_volume_t vol;

    const pa_sample_spec *ss = pa_stream_get_sample_spec(s->stream);

    vol = pa_sw_volume_multiply(lround(volume * PA_VOLUME_NORM), s->base_volume);

    pa_cvolume_set(&cvol, ss->channels, PA_VOLUME_NORM);

    pa_sw_cvolume_multiply_scalar(&cvol, &cvol, vol);

    pa_threaded_mainloop_lock(s->mainloop);

    op = pa_context_set_sink_input_volume(s->ctx, pa_stream_get_index(s->stream),

                                          &cvol, pulse_context_result, s);

    return pulse_finish_context_operation(s, op, "pa_context_set_sink_input_volume");

}


static void handle_port_status_write(EHCIState *s, int port, uint32_t val)

{

    uint32_t *portsc = &s->portsc[port];

    USBDevice *dev = s->ports[port].dev;

    /* Clear rwc bits */

    *portsc &= ~(val & PORTSC_RWC_MASK);

    /* The guest may clear, but not set the PED bit */

    *portsc &= val | ~PORTSC_PED;

    /* POWNER is masked out by RO_MASK as it is RO when we've no companion */

    handle_port_owner_write(s, port, val);

    /* And finally apply RO_MASK */

    val &= PORTSC_RO_MASK;

    if ((val & PORTSC_PRESET) && !(*portsc & PORTSC_PRESET)) {

        trace_usb_ehci_port_reset(port, 1);

    }

    if (!(val & PORTSC_PRESET) &&(*portsc & PORTSC_PRESET)) {

        trace_usb_ehci_port_reset(port, 0);

        if (dev && dev->attached) {

            usb_port_reset(&s->ports[port]);

            *portsc &= ~PORTSC_CSC;

        }

        /*

         *  Table 2.16 Set the enable bit(and enable bit change) to indicate

         *  to SW that this port has a high speed device attached

         */

        if (dev && dev->attached && (dev->speedmask & USB_SPEED_MASK_HIGH)) {

            val |= PORTSC_PED;

        }

    }

    *portsc &= ~PORTSC_RO_MASK;

    *portsc |= val;

}


static void vp6_build_huff_tree(VP56Context *s, uint8_t coeff_model[],

                                const uint8_t *map, unsigned size, VLC *vlc)

{

    Node nodes[2*size], *tmp = &nodes[size];

    int a, b, i;

    /* first compute probabilities from model */

    tmp[0].count = 256;

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

        a = tmp[i].count *        coeff_model[i]  >> 8;

        b = tmp[i].count * (255 - coeff_model[i]) >> 8;

        nodes[map[2*i  ]].count = a + !a;

        nodes[map[2*i+1]].count = b + !b;

    }

    /* then build the huffman tree accodring to probabilities */

    ff_huff_build_tree(s->avctx, vlc, size, nodes, vp6_huff_cmp,

                       FF_HUFFMAN_FLAG_HNODE_FIRST);

}


static void vga_putcharxy(DisplayState *ds, int x, int y, int ch,

                          TextAttributes *t_attrib)

{

    uint8_t *d;

    const uint8_t *font_ptr;

    unsigned int font_data, linesize, xorcol, bpp;

    int i;

    unsigned int fgcol, bgcol;

#ifdef DEBUG_CONSOLE

    printf("x: %2i y: %2i", x, y);

    console_print_text_attributes(t_attrib, ch);

#endif

    if (t_attrib->invers) {

        bgcol = color_table[t_attrib->bold][t_attrib->fgcol];

        fgcol = color_table[t_attrib->bold][t_attrib->bgcol];

    } else {

        fgcol = color_table[t_attrib->bold][t_attrib->fgcol];

        bgcol = color_table[t_attrib->bold][t_attrib->bgcol];

    }

    bpp = (ds_get_bits_per_pixel(ds) + 7) >> 3;

    d = ds_get_data(ds) +

        ds_get_linesize(ds) * y * FONT_HEIGHT + bpp * x * FONT_WIDTH;

    linesize = ds_get_linesize(ds);

    font_ptr = vgafont16 + FONT_HEIGHT * ch;

    xorcol = bgcol ^ fgcol;

    switch(ds_get_bits_per_pixel(ds)) {

    case 8:

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

            font_data = *font_ptr++;

            if (t_attrib->uline

                && ((i == FONT_HEIGHT - 2) || (i == FONT_HEIGHT - 3))) {

                font_data = 0xFFFF;

            }

            ((uint32_t *)d)[0] = (dmask16[(font_data >> 4)] & xorcol) ^ bgcol;

            ((uint32_t *)d)[1] = (dmask16[(font_data >> 0) & 0xf] & xorcol) ^ bgcol;

            d += linesize;

        }

        break;

    case 16:

    case 15:

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

            font_data = *font_ptr++;

            if (t_attrib->uline

                && ((i == FONT_HEIGHT - 2) || (i == FONT_HEIGHT - 3))) {

                font_data = 0xFFFF;

            }

            ((uint32_t *)d)[0] = (dmask4[(font_data >> 6)] & xorcol) ^ bgcol;

            ((uint32_t *)d)[1] = (dmask4[(font_data >> 4) & 3] & xorcol) ^ bgcol;

            ((uint32_t *)d)[2] = (dmask4[(font_data >> 2) & 3] & xorcol) ^ bgcol;

            ((uint32_t *)d)[3] = (dmask4[(font_data >> 0) & 3] & xorcol) ^ bgcol;

            d += linesize;

        }

        break;

    case 32:

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

            font_data = *font_ptr++;

            if (t_attrib->uline && ((i == FONT_HEIGHT - 2) || (i == FONT_HEIGHT - 3))) {

                font_data = 0xFFFF;

            }

            ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol;

            ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol;

            ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol;

            ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol;

            ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol;

            ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol;

            ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol;

            ((uint32_t *)d)[7] = (-((font_data >> 0) & 1) & xorcol) ^ bgcol;

            d += linesize;

        }

        break;

    }

}


static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)

{

    int ret = 0;

    int64_t total_size = 0;

    BlockDriverState *bs;

    IscsiLun *iscsilun = NULL;

    QDict *bs_options;

    bs = bdrv_new("", &error_abort);

    /* Read out options */

    total_size =

        qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0) / BDRV_SECTOR_SIZE;

    bs->opaque = g_malloc0(sizeof(struct IscsiLun));

    iscsilun = bs->opaque;

    bs_options = qdict_new();

    qdict_put(bs_options, "filename", qstring_from_str(filename));

    ret = iscsi_open(bs, bs_options, 0, NULL);

    QDECREF(bs_options);

    if (ret != 0) {

        goto out;

    }

    iscsi_detach_aio_context(bs);

    if (iscsilun->type != TYPE_DISK) {

        ret = -ENODEV;

        goto out;

    }

    if (bs->total_sectors < total_size) {

        ret = -ENOSPC;

        goto out;

    }

    ret = 0;

out:

    if (iscsilun->iscsi != NULL) {

        iscsi_destroy_context(iscsilun->iscsi);

    }

    g_free(bs->opaque);

    bs->opaque = NULL;

    bdrv_unref(bs);

    return ret;

}


static int dvbsub_parse_clut_segment(AVCodecContext *avctx,

                                        const uint8_t *buf, int buf_size)

{

    DVBSubContext *ctx = avctx->priv_data;

    const uint8_t *buf_end = buf + buf_size;

    int i, clut_id;

    int version;

    DVBSubCLUT *clut;

    int entry_id, depth , full_range;

    int y, cr, cb, alpha;

    int r, g, b, r_add, g_add, b_add;

    av_dlog(avctx, "DVB clut packet:\n");

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

        av_dlog(avctx, "%02x ", buf[i]);

        if (i % 16 == 15)

            av_dlog(avctx, "\n");

    }

    if (i % 16)

        av_dlog(avctx, "\n");

    clut_id = *buf++;

    version = ((*buf)>>4)&15;

    buf += 1;

    clut = get_clut(ctx, clut_id);

    if (!clut) {

        clut = av_malloc(sizeof(DVBSubCLUT));

        memcpy(clut, &default_clut, sizeof(DVBSubCLUT));

        clut->id = clut_id;

        clut->version = -1;

        clut->next = ctx->clut_list;

        ctx->clut_list = clut;

    }

    if (clut->version != version) {

    clut->version = version;

    while (buf + 4 < buf_end) {

        entry_id = *buf++;

        depth = (*buf) & 0xe0;

        if (depth == 0) {

            av_log(avctx, AV_LOG_ERROR, "Invalid clut depth 0x%x!\n", *buf);

            return 0;

        }

        full_range = (*buf++) & 1;

        if (full_range) {

            y = *buf++;

            cr = *buf++;

            cb = *buf++;

            alpha = *buf++;

        } else {

            y = buf[0] & 0xfc;

            cr = (((buf[0] & 3) << 2) | ((buf[1] >> 6) & 3)) << 4;

            cb = (buf[1] << 2) & 0xf0;

            alpha = (buf[1] << 6) & 0xc0;

            buf += 2;

        }

        if (y == 0)

            alpha = 0xff;

        YUV_TO_RGB1_CCIR(cb, cr);

        YUV_TO_RGB2_CCIR(r, g, b, y);

        av_dlog(avctx, "clut %d := (%d,%d,%d,%d)\n", entry_id, r, g, b, alpha);

        if (!!(depth & 0x80) + !!(depth & 0x40) + !!(depth & 0x20) > 1) {

            av_dlog(avctx, "More than one bit level marked: %x\n", depth);

            if (avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL)

                return AVERROR_INVALIDDATA;

        }

        if (depth & 0x80)

            clut->clut4[entry_id] = RGBA(r,g,b,255 - alpha);

        else if (depth & 0x40)

            clut->clut16[entry_id] = RGBA(r,g,b,255 - alpha);

        else if (depth & 0x20)

            clut->clut256[entry_id] = RGBA(r,g,b,255 - alpha);

    }

    }

    return 0;

}


static void scsi_write_request(SCSIDiskReq *r)

{

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

    uint32_t n;

    /* No data transfer may already be in progress */

    assert(r->req.aiocb == NULL);

    n = r->iov.iov_len / 512;

    if (n) {

        qemu_iovec_init_external(&r->qiov, &r->iov, 1);

        r->req.aiocb = bdrv_aio_writev(s->bs, r->sector, &r->qiov, n,

                                   scsi_write_complete, r);

        if (r->req.aiocb == NULL) {

            scsi_write_complete(r, -EIO);

        }

    } else {

        /* Invoke completion routine to fetch data from host.  */

        scsi_write_complete(r, 0);

    }

}


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

{

    DXAContext *c = s->priv_data;

    int ret;

    uint32_t size;

    uint8_t buf[DXA_EXTRA_SIZE], pal[768+4];

    int pal_size = 0;

    if(!c->readvid && c->has_sound && c->bytes_left){

        c->readvid = 1;

        avio_seek(s->pb, c->wavpos, SEEK_SET);

        size = FFMIN(c->bytes_left, c->bpc);

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

        pkt->stream_index = 1;

        if(ret != size)

            return AVERROR(EIO);

        c->bytes_left -= size;

        c->wavpos = avio_tell(s->pb);

        return 0;

    }

    avio_seek(s->pb, c->vidpos, SEEK_SET);

    while(!url_feof(s->pb) && c->frames){

        avio_read(s->pb, buf, 4);

        switch(AV_RL32(buf)){

        case MKTAG('N', 'U', 'L', 'L'):

            if(av_new_packet(pkt, 4 + pal_size) < 0)

                return AVERROR(ENOMEM);

            pkt->stream_index = 0;

            if(pal_size) memcpy(pkt->data, pal, pal_size);

            memcpy(pkt->data + pal_size, buf, 4);

            c->frames--;

            c->vidpos = avio_tell(s->pb);

            c->readvid = 0;

            return 0;

        case MKTAG('C', 'M', 'A', 'P'):

            pal_size = 768+4;

            memcpy(pal, buf, 4);

            avio_read(s->pb, pal + 4, 768);

            break;

        case MKTAG('F', 'R', 'A', 'M'):

            avio_read(s->pb, buf + 4, DXA_EXTRA_SIZE - 4);

            size = AV_RB32(buf + 5);

            if(size > 0xFFFFFF){

                av_log(s, AV_LOG_ERROR, "Frame size is too big: %d\n", size);

                return AVERROR_INVALIDDATA;

            }

            if(av_new_packet(pkt, size + DXA_EXTRA_SIZE + pal_size) < 0)

                return AVERROR(ENOMEM);

            memcpy(pkt->data + pal_size, buf, DXA_EXTRA_SIZE);

            ret = avio_read(s->pb, pkt->data + DXA_EXTRA_SIZE + pal_size, size);

            if(ret != size){

                av_free_packet(pkt);

                return AVERROR(EIO);

            }

            if(pal_size) memcpy(pkt->data, pal, pal_size);

            pkt->stream_index = 0;

            c->frames--;

            c->vidpos = avio_tell(s->pb);

            c->readvid = 0;

            return 0;

        default:

            av_log(s, AV_LOG_ERROR, "Unknown tag %c%c%c%c\n", buf[0], buf[1], buf[2], buf[3]);

            return AVERROR_INVALIDDATA;

        }

    }

    return AVERROR_EOF;

}


static int qemu_rdma_post_recv_control(RDMAContext *rdma, int idx)

{

    struct ibv_recv_wr *bad_wr;

    struct ibv_sge sge = {

                            .addr = (uint64_t)(rdma->wr_data[idx].control),

                            .length = RDMA_CONTROL_MAX_BUFFER,

                            .lkey = rdma->wr_data[idx].control_mr->lkey,

                         };

    struct ibv_recv_wr recv_wr = {

                                    .wr_id = RDMA_WRID_RECV_CONTROL + idx,

                                    .sg_list = &sge,

                                    .num_sge = 1,

                                 };

    if (ibv_post_recv(rdma->qp, &recv_wr, &bad_wr)) {

        return -1;

    }

    return 0;

}


static void adx_encode(unsigned char *adx,const short *wav,PREV *prev)

{

	int scale;

	int i;

	int s0,s1,s2,d;

	int max=0;

	int min=0;

	int data[32];

	s1 = prev->s1;

	s2 = prev->s2;

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

		s0 = wav[i];

		d = ((s0<<14) - SCALE1*s1 + SCALE2*s2)/BASEVOL;

		data[i]=d;

		if (max<d) max=d;

		if (min>d) min=d;

		s2 = s1;

		s1 = s0;

	}

	prev->s1 = s1;

	prev->s2 = s2;

	/* -8..+7 */

	if (max==0 && min==0) {

		memset(adx,0,18);

		return;

	}

	if (max/7>-min/8) scale = max/7;

	else scale = -min/8;

	if (scale==0) scale=1;

	adx[0] = scale>>8;

	adx[1] = scale;

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

		adx[i+2] = ((data[i*2]/scale)<<4) | ((data[i*2+1]/scale)&0xf);

	}

}


void virtqueue_fill(VirtQueue *vq, const VirtQueueElement *elem,
                    unsigned int len, unsigned int idx)
{
    VRingUsedElem uelem;
    trace_virtqueue_fill(vq, elem, len, idx);
    virtqueue_unmap_sg(vq, elem, len);
    idx = (idx + vq->used_idx) % vq->vring.num;
    uelem.id = elem->index;
    uelem.len = len;
    vring_used_write(vq, &uelem, idx);


void rtsp_close_streams(AVFormatContext *s)

{

    RTSPState *rt = s->priv_data;

    int i;

    RTSPStream *rtsp_st;

    for (i = 0; i < rt->nb_rtsp_streams; i++) {

        rtsp_st = rt->rtsp_streams[i];

        if (rtsp_st) {

            if (rtsp_st->transport_priv) {

                if (s->oformat) {

                    AVFormatContext *rtpctx = rtsp_st->transport_priv;

                    av_write_trailer(rtpctx);

                    url_fclose(rtpctx->pb);

                    av_free(rtpctx->streams[0]);

                    av_free(rtpctx);

                } else if (rt->transport == RTSP_TRANSPORT_RDT)

                    ff_rdt_parse_close(rtsp_st->transport_priv);

                else

                    rtp_parse_close(rtsp_st->transport_priv);

            }

            if (rtsp_st->rtp_handle)

                url_close(rtsp_st->rtp_handle);

            if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)

                rtsp_st->dynamic_handler->close(

                    rtsp_st->dynamic_protocol_context);

        }

    }

    av_free(rt->rtsp_streams);

    if (rt->asf_ctx) {

        av_close_input_stream (rt->asf_ctx);

        rt->asf_ctx = NULL;

    }

    av_freep(&rt->auth_b64);

}


void replay_save_instructions(void)
{
    if (replay_file && replay_mode == REPLAY_MODE_RECORD) {
        replay_mutex_lock();
        int diff = (int)(replay_get_current_step() - replay_state.current_step);
        if (diff > 0) {
            replay_put_event(EVENT_INSTRUCTION);
            replay_put_dword(diff);
            replay_state.current_step += diff;
        }
        replay_mutex_unlock();
    }
}


int load_vmstate(const char *name)

{

    BlockDriverState *bs, *bs1;

    QEMUSnapshotInfo sn;

    QEMUFile *f;

    int ret;

    /* Verify if there is a device that doesn't support snapshots and is writable */

    bs = NULL;

    while ((bs = bdrv_next(bs))) {

        if (bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {

            continue;

        }

        if (!bdrv_can_snapshot(bs)) {

            error_report("Device '%s' is writable but does not support snapshots.",

                               bdrv_get_device_name(bs));

            return -ENOTSUP;

        }

    }

    bs = bdrv_snapshots();

    if (!bs) {

        error_report("No block device supports snapshots");

        return -EINVAL;

    }

    /* Flush all IO requests so they don't interfere with the new state.  */

    qemu_aio_flush();

    bs1 = NULL;

    while ((bs1 = bdrv_next(bs1))) {

        if (bdrv_can_snapshot(bs1)) {

            ret = bdrv_snapshot_goto(bs1, name);

            if (ret < 0) {

                switch(ret) {

                case -ENOTSUP:

                    error_report("%sSnapshots not supported on device '%s'",

                                 bs != bs1 ? "Warning: " : "",

                                 bdrv_get_device_name(bs1));

                    break;

                case -ENOENT:

                    error_report("%sCould not find snapshot '%s' on device '%s'",

                                 bs != bs1 ? "Warning: " : "",

                                 name, bdrv_get_device_name(bs1));

                    break;

                default:

                    error_report("%sError %d while activating snapshot on '%s'",

                                 bs != bs1 ? "Warning: " : "",

                                 ret, bdrv_get_device_name(bs1));

                    break;

                }

                /* fatal on snapshot block device */

                if (bs == bs1)

                    return 0;

            }

        }

    }

    /* Don't even try to load empty VM states */

    ret = bdrv_snapshot_find(bs, &sn, name);

    if ((ret >= 0) && (sn.vm_state_size == 0))

        return -EINVAL;

    /* restore the VM state */

    f = qemu_fopen_bdrv(bs, 0);

    if (!f) {

        error_report("Could not open VM state file");

        return -EINVAL;

    }

    ret = qemu_loadvm_state(f);

    qemu_fclose(f);

    if (ret < 0) {

        error_report("Error %d while loading VM state", ret);

        return ret;

    }

    return 0;

}


static int flv_write_header(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    FLVContext *flv = s->priv_data;

    AVCodecContext *audio_enc = NULL, *video_enc = NULL, *data_enc = NULL;

    int i, metadata_count = 0;

    double framerate = 0.0;

    int64_t metadata_size_pos, data_size, metadata_count_pos;

    AVDictionaryEntry *tag = NULL;

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

        AVCodecContext *enc = s->streams[i]->codec;

        FLVStreamContext *sc;

        switch (enc->codec_type) {

        case AVMEDIA_TYPE_VIDEO:

            if (s->streams[i]->r_frame_rate.den &&

                s->streams[i]->r_frame_rate.num) {

                framerate = av_q2d(s->streams[i]->r_frame_rate);

            } else {

                framerate = 1 / av_q2d(s->streams[i]->codec->time_base);

            }

            video_enc = enc;

            if (enc->codec_tag == 0) {

                av_log(s, AV_LOG_ERROR, "video codec not compatible with flv\n");

                return -1;

            }

            break;

        case AVMEDIA_TYPE_AUDIO:

            audio_enc = enc;

            if (get_audio_flags(s, enc) < 0)

                return AVERROR_INVALIDDATA;

            break;

        case AVMEDIA_TYPE_DATA:

            if (enc->codec_id != CODEC_ID_TEXT) {

                av_log(s, AV_LOG_ERROR, "codec not compatible with flv\n");

                return AVERROR_INVALIDDATA;

            }

            data_enc = enc;

            break;

        default:

            av_log(s, AV_LOG_ERROR, "codec not compatible with flv\n");

            return -1;

        }

        avpriv_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */

        sc = av_mallocz(sizeof(FLVStreamContext));

        if (!sc)

            return AVERROR(ENOMEM);

        s->streams[i]->priv_data = sc;

        sc->last_ts = -1;

    }

    flv->delay = AV_NOPTS_VALUE;

    avio_write(pb, "FLV", 3);

    avio_w8(pb, 1);

    avio_w8(pb, FLV_HEADER_FLAG_HASAUDIO * !!audio_enc +

                FLV_HEADER_FLAG_HASVIDEO * !!video_enc);

    avio_wb32(pb, 9);

    avio_wb32(pb, 0);

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

        if (s->streams[i]->codec->codec_tag == 5) {

            avio_w8(pb, 8);     // message type

            avio_wb24(pb, 0);   // include flags

            avio_wb24(pb, 0);   // time stamp

            avio_wb32(pb, 0);   // reserved

            avio_wb32(pb, 11);  // size

            flv->reserved = 5;

        }

    /* write meta_tag */

    avio_w8(pb, 18);            // tag type META

    metadata_size_pos = avio_tell(pb);

    avio_wb24(pb, 0);           // size of data part (sum of all parts below)

    avio_wb24(pb, 0);           // timestamp

    avio_wb32(pb, 0);           // reserved

    /* now data of data_size size */

    /* first event name as a string */

    avio_w8(pb, AMF_DATA_TYPE_STRING);

    put_amf_string(pb, "onMetaData"); // 12 bytes

    /* mixed array (hash) with size and string/type/data tuples */

    avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);

    metadata_count_pos = avio_tell(pb);

    metadata_count = 5 * !!video_enc +

                     5 * !!audio_enc +

                     1 * !!data_enc  +

                     2; // +2 for duration and file size

    avio_wb32(pb, metadata_count);

    put_amf_string(pb, "duration");

    flv->duration_offset= avio_tell(pb);

    // fill in the guessed duration, it'll be corrected later if incorrect

    put_amf_double(pb, s->duration / AV_TIME_BASE);

    if (video_enc) {

        put_amf_string(pb, "width");

        put_amf_double(pb, video_enc->width);

        put_amf_string(pb, "height");

        put_amf_double(pb, video_enc->height);

        put_amf_string(pb, "videodatarate");

        put_amf_double(pb, video_enc->bit_rate / 1024.0);

        put_amf_string(pb, "framerate");

        put_amf_double(pb, framerate);

        put_amf_string(pb, "videocodecid");

        put_amf_double(pb, video_enc->codec_tag);

    }

    if (audio_enc) {

        put_amf_string(pb, "audiodatarate");

        put_amf_double(pb, audio_enc->bit_rate / 1024.0);

        put_amf_string(pb, "audiosamplerate");

        put_amf_double(pb, audio_enc->sample_rate);

        put_amf_string(pb, "audiosamplesize");

        put_amf_double(pb, audio_enc->codec_id == CODEC_ID_PCM_U8 ? 8 : 16);

        put_amf_string(pb, "stereo");

        put_amf_bool(pb, audio_enc->channels == 2);

        put_amf_string(pb, "audiocodecid");

        put_amf_double(pb, audio_enc->codec_tag);

    }

    if (data_enc) {

        put_amf_string(pb, "datastream");

        put_amf_double(pb, 0.0);

    }

    while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {

        put_amf_string(pb, tag->key);

        avio_w8(pb, AMF_DATA_TYPE_STRING);

        put_amf_string(pb, tag->value);

        metadata_count++;

    }

    put_amf_string(pb, "filesize");

    flv->filesize_offset = avio_tell(pb);

    put_amf_double(pb, 0); // delayed write

    put_amf_string(pb, "");

    avio_w8(pb, AMF_END_OF_OBJECT);

    /* write total size of tag */

    data_size = avio_tell(pb) - metadata_size_pos - 10;

    avio_seek(pb, metadata_count_pos, SEEK_SET);

    avio_wb32(pb, metadata_count);

    avio_seek(pb, metadata_size_pos, SEEK_SET);

    avio_wb24(pb, data_size);

    avio_skip(pb, data_size + 10 - 3);

    avio_wb32(pb, data_size + 11);

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

        AVCodecContext *enc = s->streams[i]->codec;

        if (enc->codec_id == CODEC_ID_AAC || enc->codec_id == CODEC_ID_H264) {

            int64_t pos;

            avio_w8(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?

                    FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);

            avio_wb24(pb, 0); // size patched later

            avio_wb24(pb, 0); // ts

            avio_w8(pb, 0);   // ts ext

            avio_wb24(pb, 0); // streamid

            pos = avio_tell(pb);

            if (enc->codec_id == CODEC_ID_AAC) {

                avio_w8(pb, get_audio_flags(s, enc));

                avio_w8(pb, 0); // AAC sequence header

                avio_write(pb, enc->extradata, enc->extradata_size);

            } else {

                avio_w8(pb, enc->codec_tag | FLV_FRAME_KEY); // flags

                avio_w8(pb, 0); // AVC sequence header

                avio_wb24(pb, 0); // composition time

                ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);

            }

            data_size = avio_tell(pb) - pos;

            avio_seek(pb, -data_size - 10, SEEK_CUR);

            avio_wb24(pb, data_size);

            avio_skip(pb, data_size + 10 - 3);

            avio_wb32(pb, data_size + 11); // previous tag size

        }

    }

    return 0;

}