static unsigned int dec_addi_r(DisasContext *dc)

{

	TCGv t0;

	DIS(fprintf (logfile, "addi.%c $r%u, $r%u\n",

		    memsize_char(memsize_zz(dc)), dc->op2, dc->op1));

	cris_cc_mask(dc, 0);

	t0 = tcg_temp_new(TCG_TYPE_TL);

	tcg_gen_shl_tl(t0, cpu_R[dc->op2], tcg_const_tl(dc->zzsize));

	tcg_gen_add_tl(cpu_R[dc->op1], cpu_R[dc->op1], t0);

	tcg_temp_free(t0);

	return 2;

}


static void gen_trap (DisasContext *ctx, uint32_t opc,

                      int rs, int rt, int16_t imm)

{

    int cond;

    TCGv t0 = tcg_temp_new();

    TCGv t1 = tcg_temp_new();

    cond = 0;

    /* Load needed operands */

    switch (opc) {

    case OPC_TEQ:

    case OPC_TGE:

    case OPC_TGEU:

    case OPC_TLT:

    case OPC_TLTU:

    case OPC_TNE:

        /* Compare two registers */

        if (rs != rt) {

            gen_load_gpr(t0, rs);

            gen_load_gpr(t1, rt);

            cond = 1;

        }

        break;

    case OPC_TEQI:

    case OPC_TGEI:

    case OPC_TGEIU:

    case OPC_TLTI:

    case OPC_TLTIU:

    case OPC_TNEI:

        /* Compare register to immediate */

        if (rs != 0 || imm != 0) {

            gen_load_gpr(t0, rs);

            tcg_gen_movi_tl(t1, (int32_t)imm);

            cond = 1;

        }

        break;

    }

    if (cond == 0) {

        switch (opc) {

        case OPC_TEQ:   /* rs == rs */

        case OPC_TEQI:  /* r0 == 0  */

        case OPC_TGE:   /* rs >= rs */

        case OPC_TGEI:  /* r0 >= 0  */

        case OPC_TGEU:  /* rs >= rs unsigned */

        case OPC_TGEIU: /* r0 >= 0  unsigned */

            /* Always trap */

            generate_exception(ctx, EXCP_TRAP);

            break;

        case OPC_TLT:   /* rs < rs           */

        case OPC_TLTI:  /* r0 < 0            */

        case OPC_TLTU:  /* rs < rs unsigned  */

        case OPC_TLTIU: /* r0 < 0  unsigned  */

        case OPC_TNE:   /* rs != rs          */

        case OPC_TNEI:  /* r0 != 0           */

            /* Never trap: treat as NOP. */

            break;

        }

    } else {

        int l1 = gen_new_label();

        switch (opc) {

        case OPC_TEQ:

        case OPC_TEQI:

            tcg_gen_brcond_tl(TCG_COND_NE, t0, t1, l1);

            break;

        case OPC_TGE:

        case OPC_TGEI:

            tcg_gen_brcond_tl(TCG_COND_LT, t0, t1, l1);

            break;

        case OPC_TGEU:

        case OPC_TGEIU:

            tcg_gen_brcond_tl(TCG_COND_LTU, t0, t1, l1);

            break;

        case OPC_TLT:

        case OPC_TLTI:

            tcg_gen_brcond_tl(TCG_COND_GE, t0, t1, l1);

            break;

        case OPC_TLTU:

        case OPC_TLTIU:

            tcg_gen_brcond_tl(TCG_COND_GEU, t0, t1, l1);

            break;

        case OPC_TNE:

        case OPC_TNEI:

            tcg_gen_brcond_tl(TCG_COND_EQ, t0, t1, l1);

            break;

        }

        generate_exception(ctx, EXCP_TRAP);

        gen_set_label(l1);

    }

    tcg_temp_free(t0);

    tcg_temp_free(t1);

}


static uint64_t pxa2xx_gpio_read(void *opaque, hwaddr offset,

                                 unsigned size)

{

    PXA2xxGPIOInfo *s = (PXA2xxGPIOInfo *) opaque;

    uint32_t ret;

    int bank;

    if (offset >= 0x200)

        return 0;

    bank = pxa2xx_gpio_regs[offset].bank;

    switch (pxa2xx_gpio_regs[offset].reg) {

    case GPDR:		/* GPIO Pin-Direction registers */

        return s->dir[bank];

    case GPSR:		/* GPIO Pin-Output Set registers */

        qemu_log_mask(LOG_GUEST_ERROR,

                      "pxa2xx GPIO: read from write only register GPSR\n");

        return 0;

    case GPCR:		/* GPIO Pin-Output Clear registers */

        qemu_log_mask(LOG_GUEST_ERROR,

                      "pxa2xx GPIO: read from write only register GPCR\n");

        return 0;

    case GRER:		/* GPIO Rising-Edge Detect Enable registers */

        return s->rising[bank];

    case GFER:		/* GPIO Falling-Edge Detect Enable registers */

        return s->falling[bank];

    case GAFR_L:	/* GPIO Alternate Function registers */

        return s->gafr[bank * 2];

    case GAFR_U:	/* GPIO Alternate Function registers */

        return s->gafr[bank * 2 + 1];

    case GPLR:		/* GPIO Pin-Level registers */

        ret = (s->olevel[bank] & s->dir[bank]) |

                (s->ilevel[bank] & ~s->dir[bank]);

        qemu_irq_raise(s->read_notify);

        return ret;

    case GEDR:		/* GPIO Edge Detect Status registers */

        return s->status[bank];

    default:

        hw_error("%s: Bad offset " REG_FMT "\n", __FUNCTION__, offset);

    }

    return 0;

}


static int ipvideo_decode_block_opcode_0xD(IpvideoContext *s, AVFrame *frame)
{
    int y;
    unsigned char P[2];
    /* 4-color block encoding: each 4x4 block is a different color */
    for (y = 0; y < 8; y++) {
        if (!(y & 3)) {
            P[0] = bytestream2_get_byte(&s->stream_ptr);
            P[1] = bytestream2_get_byte(&s->stream_ptr);
        memset(s->pixel_ptr,     P[0], 4);
        memset(s->pixel_ptr + 4, P[1], 4);
        s->pixel_ptr += s->stride;
    /* report success */
    return 0;


static int64_t migration_set_rate_limit(void *opaque, int64_t new_rate)

{

    MigrationState *s = opaque;

    if (qemu_file_get_error(s->file)) {

        goto out;

    }

    s->xfer_limit = new_rate;

out:

    return s->xfer_limit;

}


static void reverse_matrixing(float *su1, float *su2, int *prev_code,

                              int *curr_code)

{

    int i, nsample, band;

    float mc1_l, mc1_r, mc2_l, mc2_r;

    for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {

        int s1 = prev_code[i];

        int s2 = curr_code[i];

        nsample = 0;

        if (s1 != s2) {

            /* Selector value changed, interpolation needed. */

            mc1_l = matrix_coeffs[s1 * 2    ];

            mc1_r = matrix_coeffs[s1 * 2 + 1];

            mc2_l = matrix_coeffs[s2 * 2    ];

            mc2_r = matrix_coeffs[s2 * 2 + 1];

            /* Interpolation is done over the first eight samples. */

            for (; nsample < 8; nsample++) {

                float c1 = su1[band + nsample];

                float c2 = su2[band + nsample];

                c2 = c1 * INTERPOLATE(mc1_l, mc2_l, nsample) +

                     c2 * INTERPOLATE(mc1_r, mc2_r, nsample);

                su1[band + nsample] = c2;

                su2[band + nsample] = c1 * 2.0 - c2;

            }

        }

        /* Apply the matrix without interpolation. */

        switch (s2) {

        case 0:     /* M/S decoding */

            for (; nsample < 256; nsample++) {

                float c1 = su1[band + nsample];

                float c2 = su2[band + nsample];

                su1[band + nsample] =  c2       * 2.0;

                su2[band + nsample] = (c1 - c2) * 2.0;

            }

            break;

        case 1:

            for (; nsample < 256; nsample++) {

                float c1 = su1[band + nsample];

                float c2 = su2[band + nsample];

                su1[band + nsample] = (c1 + c2) *  2.0;

                su2[band + nsample] =  c2       * -2.0;

            }

            break;

        case 2:

        case 3:

            for (; nsample < 256; nsample++) {

                float c1 = su1[band + nsample];

                float c2 = su2[band + nsample];

                su1[band + nsample] = c1 + c2;

                su2[band + nsample] = c1 - c2;

            }

            break;

        default:

            assert(0);

        }

    }

}


static void scsi_disk_reset(DeviceState *dev)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev.qdev, dev);

    uint64_t nb_sectors;

    scsi_device_purge_requests(&s->qdev, SENSE_CODE(RESET));

    bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);

    nb_sectors /= s->qdev.blocksize / 512;

    if (nb_sectors) {

        nb_sectors--;

    }

    s->qdev.max_lba = nb_sectors;

    /* reset tray statuses */

    s->tray_locked = 0;

    s->tray_open = 0;

}


static int read_part_of_packet(AVFormatContext *s, int64_t *pts,

                               int *len, int *strid, int read_packet) {

    AVIOContext *pb = s->pb;

    PVAContext *pvactx = s->priv_data;

    int syncword, streamid, reserved, flags, length, pts_flag;

    int64_t pva_pts = AV_NOPTS_VALUE, startpos;

    int ret;

recover:

    startpos = avio_tell(pb);

    syncword = avio_rb16(pb);

    streamid = avio_r8(pb);

    avio_r8(pb);               /* counter not used */

    reserved = avio_r8(pb);

    flags    = avio_r8(pb);

    length   = avio_rb16(pb);

    pts_flag = flags & 0x10;

    if (syncword != PVA_MAGIC) {

        pva_log(s, AV_LOG_ERROR, "invalid syncword\n");

        return AVERROR(EIO);

    }

    if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) {

        pva_log(s, AV_LOG_ERROR, "invalid streamid\n");

        return AVERROR(EIO);

    }

    if (reserved != 0x55) {

        pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n");

    }

    if (length > PVA_MAX_PAYLOAD_LENGTH) {

        pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length);

        return AVERROR(EIO);

    }

    if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {

        pva_pts = avio_rb32(pb);

        length -= 4;

    } else if (streamid == PVA_AUDIO_PAYLOAD) {

        /* PVA Audio Packets either start with a signaled PES packet or

         * are a continuation of the previous PES packet. New PES packets

         * always start at the beginning of a PVA Packet, never somewhere in

         * the middle. */

        if (!pvactx->continue_pes) {

            int pes_signal, pes_header_data_length, pes_packet_length,

                pes_flags;

            unsigned char pes_header_data[256];

            pes_signal             = avio_rb24(pb);

            avio_r8(pb);

            pes_packet_length      = avio_rb16(pb);

            pes_flags              = avio_rb16(pb);

            pes_header_data_length = avio_r8(pb);

            if (pes_signal != 1 || pes_header_data_length == 0) {

                pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, "

                                          "trying to recover\n");

                avio_skip(pb, length - 9);

                if (!read_packet)

                    return AVERROR(EIO);

                goto recover;

            }

            ret = avio_read(pb, pes_header_data, pes_header_data_length);

            if (ret != pes_header_data_length)

                return ret < 0 ? ret : AVERROR_INVALIDDATA;

            length -= 9 + pes_header_data_length;

            pes_packet_length -= 3 + pes_header_data_length;

            pvactx->continue_pes = pes_packet_length;

            if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20)

                pva_pts = ff_parse_pes_pts(pes_header_data);

        }

        pvactx->continue_pes -= length;

        if (pvactx->continue_pes < 0) {

            pva_log(s, AV_LOG_WARNING, "audio data corruption\n");

            pvactx->continue_pes = 0;

        }

    }

    if (pva_pts != AV_NOPTS_VALUE)

        av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME);

    *pts   = pva_pts;

    *len   = length;

    *strid = streamid;

    return 0;

}


static void pred8x8_top_dc_rv40_c(uint8_t *src, int stride){

    int i;

    int dc0;

    dc0=0;

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

        dc0+= src[i-stride];

    dc0= 0x01010101*((dc0 + 4)>>3);

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

        ((uint32_t*)(src+i*stride))[0]=

        ((uint32_t*)(src+i*stride))[1]= dc0;

    }

}


static int virtio_ccw_set_vqs(SubchDev *sch, uint64_t addr, uint32_t align,

                              uint16_t index, uint16_t num)

{

    VirtIODevice *vdev = virtio_ccw_get_vdev(sch);

    if (index >= VIRTIO_PCI_QUEUE_MAX) {

        return -EINVAL;

    }

    /* Current code in virtio.c relies on 4K alignment. */

    if (addr && (align != 4096)) {

        return -EINVAL;

    }

    if (!vdev) {

        return -EINVAL;

    }

    virtio_queue_set_addr(vdev, index, addr);

    if (!addr) {

        virtio_queue_set_vector(vdev, index, 0);

    } else {

        /* Fail if we don't have a big enough queue. */

        /* TODO: Add interface to handle vring.num changing */

        if (virtio_queue_get_num(vdev, index) > num) {

            return -EINVAL;

        }

        virtio_queue_set_vector(vdev, index, index);

    }

    /* tell notify handler in case of config change */

    vdev->config_vector = VIRTIO_PCI_QUEUE_MAX;

    return 0;

}


static void rtl8139_receive(void *opaque, const uint8_t *buf, size_t size)

{

    rtl8139_do_receive(opaque, buf, size, 1);

}


static int local_chown(FsContext *fs_ctx, V9fsPath *fs_path, FsCred *credp)

{

    char buffer[PATH_MAX];

    char *path = fs_path->data;

    if ((credp->fc_uid == -1 && credp->fc_gid == -1) ||

        (fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) ||

        (fs_ctx->export_flags & V9FS_SM_NONE)) {

        return lchown(rpath(fs_ctx, path, buffer),

                      credp->fc_uid, credp->fc_gid);

    } else if (fs_ctx->export_flags & V9FS_SM_MAPPED) {

        return local_set_xattr(rpath(fs_ctx, path, buffer), credp);

    } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) {

        return local_set_mapped_file_attr(fs_ctx, path, credp);

    }

    return -1;

}


static void qdict_crumple_test_recursive(void)

{

    QDict *src, *dst, *rule, *vnc, *acl, *listen;

    QObject *child, *res;

    QList *rules;

    src = qdict_new();

    qdict_put(src, "vnc.listen.addr", qstring_from_str("127.0.0.1"));

    qdict_put(src, "vnc.listen.port", qstring_from_str("5901"));

    qdict_put(src, "vnc.acl.rules.0.match", qstring_from_str("fred"));

    qdict_put(src, "vnc.acl.rules.0.policy", qstring_from_str("allow"));

    qdict_put(src, "vnc.acl.rules.1.match", qstring_from_str("bob"));

    qdict_put(src, "vnc.acl.rules.1.policy", qstring_from_str("deny"));

    qdict_put(src, "vnc.acl.default", qstring_from_str("deny"));

    qdict_put(src, "vnc.acl..name", qstring_from_str("acl0"));

    qdict_put(src, "vnc.acl.rule..name", qstring_from_str("acl0"));

    res = qdict_crumple(src, &error_abort);

    g_assert_cmpint(qobject_type(res), ==, QTYPE_QDICT);

    dst = qobject_to_qdict(res);

    g_assert_cmpint(qdict_size(dst), ==, 1);

    child = qdict_get(dst, "vnc");

    g_assert_cmpint(qobject_type(child), ==, QTYPE_QDICT);

    vnc = qobject_to_qdict(child);

    child = qdict_get(vnc, "listen");

    g_assert_cmpint(qobject_type(child), ==, QTYPE_QDICT);

    listen = qobject_to_qdict(child);

    g_assert_cmpstr("127.0.0.1", ==, qdict_get_str(listen, "addr"));

    g_assert_cmpstr("5901", ==, qdict_get_str(listen, "port"));

    child = qdict_get(vnc, "acl");

    g_assert_cmpint(qobject_type(child), ==, QTYPE_QDICT);

    acl = qobject_to_qdict(child);

    child = qdict_get(acl, "rules");

    g_assert_cmpint(qobject_type(child), ==, QTYPE_QLIST);

    rules = qobject_to_qlist(child);

    g_assert_cmpint(qlist_size(rules), ==, 2);

    rule = qobject_to_qdict(qlist_pop(rules));

    g_assert_cmpint(qdict_size(rule), ==, 2);

    g_assert_cmpstr("fred", ==, qdict_get_str(rule, "match"));

    g_assert_cmpstr("allow", ==, qdict_get_str(rule, "policy"));

    QDECREF(rule);

    rule = qobject_to_qdict(qlist_pop(rules));

    g_assert_cmpint(qdict_size(rule), ==, 2);

    g_assert_cmpstr("bob", ==, qdict_get_str(rule, "match"));

    g_assert_cmpstr("deny", ==, qdict_get_str(rule, "policy"));

    QDECREF(rule);

    /* With recursive crumpling, we should see all names unescaped */

    g_assert_cmpstr("acl0", ==, qdict_get_str(vnc, "acl.name"));

    child = qdict_get(vnc, "acl");

    g_assert_cmpint(qobject_type(child), ==, QTYPE_QDICT);

    acl = qdict_get_qdict(vnc, "acl");

    g_assert_cmpstr("acl0", ==, qdict_get_str(acl, "rule.name"));

    QDECREF(src);

    QDECREF(dst);

}


static void test_validate_fail_alternate(TestInputVisitorData *data,

                                         const void *unused)

{

    UserDefAlternate *tmp;

    Visitor *v;

    Error *err = NULL;

    v = validate_test_init(data, "3.14");

    visit_type_UserDefAlternate(v, NULL, &tmp, &err);

    error_free_or_abort(&err);

    qapi_free_UserDefAlternate(tmp);

}


static int qcow2_co_flush(BlockDriverState *bs)

{

    BDRVQcowState *s = bs->opaque;

    int ret;

    qemu_co_mutex_lock(&s->lock);

    ret = qcow2_cache_flush(bs, s->l2_table_cache);

    if (ret < 0) {

        return ret;

    }

    ret = qcow2_cache_flush(bs, s->refcount_block_cache);

    if (ret < 0) {

        return ret;

    }

    return bdrv_co_flush(bs->file);

}


static int vc1_init_common(VC1Context *v)

{

    static int done = 0;

    int i = 0;

    v->hrd_rate = v->hrd_buffer = NULL;

    /* VLC tables */

    if(!done)

    {

        done = 1;

        init_vlc(&ff_vc1_bfraction_vlc, VC1_BFRACTION_VLC_BITS, 23,

                 ff_vc1_bfraction_bits, 1, 1,

                 ff_vc1_bfraction_codes, 1, 1, INIT_VLC_USE_STATIC);

        init_vlc(&ff_vc1_norm2_vlc, VC1_NORM2_VLC_BITS, 4,

                 ff_vc1_norm2_bits, 1, 1,

                 ff_vc1_norm2_codes, 1, 1, INIT_VLC_USE_STATIC);

        init_vlc(&ff_vc1_norm6_vlc, VC1_NORM6_VLC_BITS, 64,

                 ff_vc1_norm6_bits, 1, 1,

                 ff_vc1_norm6_codes, 2, 2, INIT_VLC_USE_STATIC);

        init_vlc(&ff_vc1_imode_vlc, VC1_IMODE_VLC_BITS, 7,

                 ff_vc1_imode_bits, 1, 1,

                 ff_vc1_imode_codes, 1, 1, INIT_VLC_USE_STATIC);

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

        {

            init_vlc(&ff_vc1_ttmb_vlc[i], VC1_TTMB_VLC_BITS, 16,

                     ff_vc1_ttmb_bits[i], 1, 1,

                     ff_vc1_ttmb_codes[i], 2, 2, INIT_VLC_USE_STATIC);

            init_vlc(&ff_vc1_ttblk_vlc[i], VC1_TTBLK_VLC_BITS, 8,

                     ff_vc1_ttblk_bits[i], 1, 1,

                     ff_vc1_ttblk_codes[i], 1, 1, INIT_VLC_USE_STATIC);

            init_vlc(&ff_vc1_subblkpat_vlc[i], VC1_SUBBLKPAT_VLC_BITS, 15,

                     ff_vc1_subblkpat_bits[i], 1, 1,

                     ff_vc1_subblkpat_codes[i], 1, 1, INIT_VLC_USE_STATIC);

        }

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

        {

            init_vlc(&ff_vc1_4mv_block_pattern_vlc[i], VC1_4MV_BLOCK_PATTERN_VLC_BITS, 16,

                     ff_vc1_4mv_block_pattern_bits[i], 1, 1,

                     ff_vc1_4mv_block_pattern_codes[i], 1, 1, INIT_VLC_USE_STATIC);

            init_vlc(&ff_vc1_cbpcy_p_vlc[i], VC1_CBPCY_P_VLC_BITS, 64,

                     ff_vc1_cbpcy_p_bits[i], 1, 1,

                     ff_vc1_cbpcy_p_codes[i], 2, 2, INIT_VLC_USE_STATIC);

            init_vlc(&ff_vc1_mv_diff_vlc[i], VC1_MV_DIFF_VLC_BITS, 73,

                     ff_vc1_mv_diff_bits[i], 1, 1,

                     ff_vc1_mv_diff_codes[i], 2, 2, INIT_VLC_USE_STATIC);

        }

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

            init_vlc(&ff_vc1_ac_coeff_table[i], AC_VLC_BITS, vc1_ac_sizes[i],

                     &vc1_ac_tables[i][0][1], 8, 4,

                     &vc1_ac_tables[i][0][0], 8, 4, INIT_VLC_USE_STATIC);

        init_vlc(&ff_msmp4_mb_i_vlc, MB_INTRA_VLC_BITS, 64,

                 &ff_msmp4_mb_i_table[0][1], 4, 2,

                 &ff_msmp4_mb_i_table[0][0], 4, 2, INIT_VLC_USE_STATIC);

    }

    /* Other defaults */

    v->pq = -1;

    v->mvrange = 0; /* 7.1.1.18, p80 */

    return 0;

}


int av_read_packet(AVFormatContext *s, AVPacket *pkt)
{
    int ret, i;
    AVStream *st;
    for(;;){
        AVPacketList *pktl = s->raw_packet_buffer;
        if (pktl) {
            *pkt = pktl->pkt;
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
               !s->streams[pkt->stream_index]->probe_packets ||
               s->raw_packet_buffer_remaining_size < pkt->size){
                AVProbeData *pd = &s->streams[pkt->stream_index]->probe_data;
                av_freep(&pd->buf);
                pd->buf_size = 0;
                s->raw_packet_buffer = pktl->next;
                s->raw_packet_buffer_remaining_size += pkt->size;
                av_free(pktl);
                return 0;
        av_init_packet(pkt);
        ret= s->iformat->read_packet(s, pkt);
        if (ret < 0) {
            if (!pktl || ret == AVERROR(EAGAIN))
                return ret;
            for (i = 0; i < s->nb_streams; i++)
                s->streams[i]->probe_packets = 0;
        st= s->streams[pkt->stream_index];
        switch(st->codec->codec_type){
        case AVMEDIA_TYPE_VIDEO:
            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
            break;
        case AVMEDIA_TYPE_AUDIO:
            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
            break;
        case AVMEDIA_TYPE_SUBTITLE:
            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
            break;
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
                     !st->probe_packets))
            return ret;
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
        s->raw_packet_buffer_remaining_size -= pkt->size;
        if(st->codec->codec_id == CODEC_ID_PROBE){
            AVProbeData *pd = &st->probe_data;
            av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
            --st->probe_packets;
            pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
            memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
            pd->buf_size += pkt->size;
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
                //FIXME we dont reduce score to 0 for the case of running out of buffer space in bytes
                set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
                if(st->codec->codec_id != CODEC_ID_PROBE){
                    pd->buf_size=0;
                    av_freep(&pd->buf);
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);


static int nbd_can_accept(void)

{

    return nb_fds < shared;

}


static int net_connect(struct XenDevice *xendev)

{

    struct XenNetDev *netdev = container_of(xendev, struct XenNetDev, xendev);

    int rx_copy;

    if (xenstore_read_fe_int(&netdev->xendev, "tx-ring-ref",

                             &netdev->tx_ring_ref) == -1) {

        return -1;

    }

    if (xenstore_read_fe_int(&netdev->xendev, "rx-ring-ref",

                             &netdev->rx_ring_ref) == -1) {

        return 1;

    }

    if (xenstore_read_fe_int(&netdev->xendev, "event-channel",

                             &netdev->xendev.remote_port) == -1) {

        return -1;

    }

    if (xenstore_read_fe_int(&netdev->xendev, "request-rx-copy", &rx_copy) == -1) {

        rx_copy = 0;

    }

    if (rx_copy == 0) {

        xen_be_printf(&netdev->xendev, 0, "frontend doesn't support rx-copy.\n");

        return -1;

    }

    netdev->txs = xc_gnttab_map_grant_ref(netdev->xendev.gnttabdev,

                                          netdev->xendev.dom,

                                          netdev->tx_ring_ref,

                                          PROT_READ | PROT_WRITE);

    netdev->rxs = xc_gnttab_map_grant_ref(netdev->xendev.gnttabdev,

                                          netdev->xendev.dom,

                                          netdev->rx_ring_ref,

                                          PROT_READ | PROT_WRITE);

    if (!netdev->txs || !netdev->rxs) {

        return -1;

    }

    BACK_RING_INIT(&netdev->tx_ring, netdev->txs, XC_PAGE_SIZE);

    BACK_RING_INIT(&netdev->rx_ring, netdev->rxs, XC_PAGE_SIZE);

    xen_be_bind_evtchn(&netdev->xendev);

    xen_be_printf(&netdev->xendev, 1, "ok: tx-ring-ref %d, rx-ring-ref %d, "

                  "remote port %d, local port %d\n",

                  netdev->tx_ring_ref, netdev->rx_ring_ref,

                  netdev->xendev.remote_port, netdev->xendev.local_port);

    net_tx_packets(netdev);

    return 0;

}


static bool do_modify_softint(CPUSPARCState *env, uint32_t value)

{

    if (env->softint != value) {

        env->softint = value;

#if !defined(CONFIG_USER_ONLY)

        if (cpu_interrupts_enabled(env)) {

            cpu_check_irqs(env);

        }

#endif

        return true;

    }

    return false;

}


static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent, int numBands)

{

    int i,j,k,cnt;

    int   components, coding_mode_selector, coding_mode, coded_values_per_component;

    int   sfIndx, coded_values, max_coded_values, quant_step_index, coded_components;

    int   band_flags[4], mantissa[8];

    float  *pCoef;

    float  scalefactor;

    int   component_count = 0;

    components = get_bits(gb,5);

    /* no tonal components */

    if (components == 0)

        return 0;

    coding_mode_selector = get_bits(gb,2);

    if (coding_mode_selector == 2)

    coding_mode = coding_mode_selector & 1;

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

        for (cnt = 0; cnt <= numBands; cnt++)

            band_flags[cnt] = get_bits1(gb);

        coded_values_per_component = get_bits(gb,3);

        quant_step_index = get_bits(gb,3);

        if (quant_step_index <= 1)

        if (coding_mode_selector == 3)

            coding_mode = get_bits1(gb);

        for (j = 0; j < (numBands + 1) * 4; j++) {

            if (band_flags[j >> 2] == 0)

                continue;

            coded_components = get_bits(gb,3);

            for (k=0; k<coded_components; k++) {

                sfIndx = get_bits(gb,6);

                pComponent[component_count].pos = j * 64 + (get_bits(gb,6));

                max_coded_values = SAMPLES_PER_FRAME - pComponent[component_count].pos;

                coded_values = coded_values_per_component + 1;

                coded_values = FFMIN(max_coded_values,coded_values);

                scalefactor = ff_atrac_sf_table[sfIndx] * iMaxQuant[quant_step_index];

                readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);

                pComponent[component_count].numCoefs = coded_values;

                /* inverse quant */

                pCoef = pComponent[component_count].coef;

                for (cnt = 0; cnt < coded_values; cnt++)

                    pCoef[cnt] = mantissa[cnt] * scalefactor;

                component_count++;

            }

        }

    }

    return component_count;

}


static void do_send_key(const char *string)

{

    char keybuf[16], *q;

    uint8_t keycodes[16];

    const char *p;

    int nb_keycodes, keycode, i;

    nb_keycodes = 0;

    p = string;

    while (*p != '\0') {

        q = keybuf;

        while (*p != '\0' && *p != '-') {

            if ((q - keybuf) < sizeof(keybuf) - 1) {

                *q++ = *p;

            }

            p++;

        }

        *q = '\0';

        keycode = get_keycode(keybuf);

        if (keycode < 0) {

            term_printf("unknown key: '%s'\n", keybuf);

            return;

        }

        keycodes[nb_keycodes++] = keycode;

        if (*p == '\0')

            break;

        p++;

    }

    /* key down events */

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

        keycode = keycodes[i];

        if (keycode & 0x80)

            kbd_put_keycode(0xe0);

        kbd_put_keycode(keycode & 0x7f);

    }

    /* key up events */

    for(i = nb_keycodes - 1; i >= 0; i--) {

        keycode = keycodes[i];

        if (keycode & 0x80)

            kbd_put_keycode(0xe0);

        kbd_put_keycode(keycode | 0x80);

    }

}


void do_migrate_set_speed(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

    double d;

    char *ptr;

    FdMigrationState *s;

    const char *value = qdict_get_str(qdict, "value");

    d = strtod(value, &ptr);

    switch (*ptr) {

    case 'G': case 'g':

        d *= 1024;

    case 'M': case 'm':

        d *= 1024;

    case 'K': case 'k':

        d *= 1024;

    default:

        break;

    }

    max_throttle = (uint32_t)d;

    s = migrate_to_fms(current_migration);

    if (s) {

        qemu_file_set_rate_limit(s->file, max_throttle);

    }

}


static inline void gen_efdneg(DisasContext *ctx)

{

    if (unlikely(!ctx->spe_enabled)) {

        gen_exception(ctx, POWERPC_EXCP_APU);

        return;

    }

#if defined(TARGET_PPC64)

    tcg_gen_xori_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], 0x8000000000000000LL);

#else

    tcg_gen_mov_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);

    tcg_gen_xori_tl(cpu_gprh[rD(ctx->opcode)], cpu_gprh[rA(ctx->opcode)], 0x80000000);

#endif

}


static void gen_srlq(DisasContext *ctx)

{

    int l1 = gen_new_label();

    int l2 = gen_new_label();

    TCGv t0 = tcg_temp_local_new();

    TCGv t1 = tcg_temp_local_new();

    TCGv t2 = tcg_temp_local_new();

    tcg_gen_andi_tl(t2, cpu_gpr[rB(ctx->opcode)], 0x1F);

    tcg_gen_movi_tl(t1, 0xFFFFFFFF);

    tcg_gen_shr_tl(t2, t1, t2);

    tcg_gen_andi_tl(t0, cpu_gpr[rB(ctx->opcode)], 0x20);

    tcg_gen_brcondi_tl(TCG_COND_EQ, t0, 0, l1);

    gen_load_spr(t0, SPR_MQ);

    tcg_gen_and_tl(cpu_gpr[rA(ctx->opcode)], t0, t2);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_shr_tl(t0, cpu_gpr[rS(ctx->opcode)], t2);

    tcg_gen_and_tl(t0, t0, t2);

    gen_load_spr(t1, SPR_MQ);

    tcg_gen_andc_tl(t1, t1, t2);

    tcg_gen_or_tl(cpu_gpr[rA(ctx->opcode)], t0, t1);

    gen_set_label(l2);

    tcg_temp_free(t0);

    tcg_temp_free(t1);

    tcg_temp_free(t2);

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, cpu_gpr[rA(ctx->opcode)]);

}


static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len)

{

    VirtQueueElement elem;

    VirtQueue *vq;

    vq = vser->c_ivq;

    if (!virtio_queue_ready(vq)) {

        return 0;

    }

    if (!virtqueue_pop(vq, &elem)) {

        return 0;

    }

    /* TODO: detect a buffer that's too short, set NEEDS_RESET */

    iov_from_buf(elem.in_sg, elem.in_num, 0, buf, len);

    virtqueue_push(vq, &elem, len);

    virtio_notify(VIRTIO_DEVICE(vser), vq);

    return len;

}


void ich9_pm_init(PCIDevice *lpc_pci, ICH9LPCPMRegs *pm,

                  qemu_irq sci_irq)

{

    memory_region_init(&pm->io, OBJECT(lpc_pci), "ich9-pm", ICH9_PMIO_SIZE);

    memory_region_set_enabled(&pm->io, false);

    memory_region_add_subregion(pci_address_space_io(lpc_pci),

                                0, &pm->io);

    acpi_pm_tmr_init(&pm->acpi_regs, ich9_pm_update_sci_fn, &pm->io);

    acpi_pm1_evt_init(&pm->acpi_regs, ich9_pm_update_sci_fn, &pm->io);

    acpi_pm1_cnt_init(&pm->acpi_regs, &pm->io, pm->s4_val);

    acpi_gpe_init(&pm->acpi_regs, ICH9_PMIO_GPE0_LEN);

    memory_region_init_io(&pm->io_gpe, OBJECT(lpc_pci), &ich9_gpe_ops, pm,

                          "acpi-gpe0", ICH9_PMIO_GPE0_LEN);

    memory_region_add_subregion(&pm->io, ICH9_PMIO_GPE0_STS, &pm->io_gpe);

    memory_region_init_io(&pm->io_smi, OBJECT(lpc_pci), &ich9_smi_ops, pm,

                          "acpi-smi", 8);

    memory_region_add_subregion(&pm->io, ICH9_PMIO_SMI_EN, &pm->io_smi);

    pm->irq = sci_irq;

    qemu_register_reset(pm_reset, pm);

    pm->powerdown_notifier.notify = pm_powerdown_req;

    qemu_register_powerdown_notifier(&pm->powerdown_notifier);

    acpi_cpu_hotplug_init(pci_address_space_io(lpc_pci), OBJECT(lpc_pci),

                          &pm->gpe_cpu, ICH9_CPU_HOTPLUG_IO_BASE);

    if (pm->acpi_memory_hotplug.is_enabled) {

        acpi_memory_hotplug_init(pci_address_space_io(lpc_pci), OBJECT(lpc_pci),

                                 &pm->acpi_memory_hotplug);

    }

}


uint32_t omap_badwidth_read8(void *opaque, target_phys_addr_t addr)

{

    uint8_t ret;

    OMAP_8B_REG(addr);

    cpu_physical_memory_read(addr, (void *) &ret, 1);

    return ret;

}


static inline void IRQ_setbit(IRQ_queue_t *q, int n_IRQ)

{

    q->pending++;

    set_bit(q->queue, n_IRQ);

}


static int matroska_decode_buffer(uint8_t** buf, int* buf_size,

                                  MatroskaTrack *track)

{

    MatroskaTrackEncoding *encodings = track->encodings.elem;

    uint8_t* data = *buf;

    int isize = *buf_size;

    uint8_t* pkt_data = NULL;

    int pkt_size = isize;

    int result = 0;

    int olen;

    if (pkt_size >= 10000000)

        return -1;

    switch (encodings[0].compression.algo) {

    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:

        return encodings[0].compression.settings.size;

    case MATROSKA_TRACK_ENCODING_COMP_LZO:

        do {

            olen = pkt_size *= 3;

            pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);

            result = av_lzo1x_decode(pkt_data, &olen, data, &isize);

        } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);

        if (result)

            goto failed;

        pkt_size -= olen;

        break;

#if CONFIG_ZLIB

    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {

        z_stream zstream = {0};

        if (inflateInit(&zstream) != Z_OK)

            return -1;

        zstream.next_in = data;

        zstream.avail_in = isize;

        do {

            pkt_size *= 3;

            pkt_data = av_realloc(pkt_data, pkt_size);

            zstream.avail_out = pkt_size - zstream.total_out;

            zstream.next_out = pkt_data + zstream.total_out;

            result = inflate(&zstream, Z_NO_FLUSH);

        } while (result==Z_OK && pkt_size<10000000);

        pkt_size = zstream.total_out;

        inflateEnd(&zstream);

        if (result != Z_STREAM_END)

            goto failed;

        break;

    }

#endif

#if CONFIG_BZLIB

    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {

        bz_stream bzstream = {0};

        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)

            return -1;

        bzstream.next_in = data;

        bzstream.avail_in = isize;

        do {

            pkt_size *= 3;

            pkt_data = av_realloc(pkt_data, pkt_size);

            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;

            bzstream.next_out = pkt_data + bzstream.total_out_lo32;

            result = BZ2_bzDecompress(&bzstream);

        } while (result==BZ_OK && pkt_size<10000000);

        pkt_size = bzstream.total_out_lo32;

        BZ2_bzDecompressEnd(&bzstream);

        if (result != BZ_STREAM_END)

            goto failed;

        break;

    }

#endif

    default:

        return -1;

    }

    *buf = pkt_data;

    *buf_size = pkt_size;

    return 0;

 failed:

    av_free(pkt_data);

    return -1;

}


static void ac3_extract_exponents_c(uint8_t *exp, int32_t *coef, int nb_coefs)

{

    int i;

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

        int e;

        int v = abs(coef[i]);

        if (v == 0)

            e = 24;

        else {

            e = 23 - av_log2(v);

            if (e >= 24) {

                e = 24;

                coef[i] = 0;

            }

            av_assert2(e >= 0);

        }

        exp[i] = e;

    }

}


static void vhost_log_stop(MemoryListener *listener,

                           MemoryRegionSection *section)

{

    /* FIXME: implement */

}


static void spapr_hotplug_req_event(sPAPRDRConnector *drc, uint8_t hp_action)

{

    struct hp_log_full *new_hp;

    struct rtas_error_log *hdr;

    struct rtas_event_log_v6 *v6hdr;

    struct rtas_event_log_v6_maina *maina;

    struct rtas_event_log_v6_mainb *mainb;

    struct rtas_event_log_v6_hp *hp;

    sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

    sPAPRDRConnectorType drc_type = drck->get_type(drc);

    new_hp = g_malloc0(sizeof(struct hp_log_full));

    hdr = &new_hp->hdr;

    v6hdr = &new_hp->v6hdr;

    maina = &new_hp->maina;

    mainb = &new_hp->mainb;

    hp = &new_hp->hp;

    hdr->summary = cpu_to_be32(RTAS_LOG_VERSION_6

                               | RTAS_LOG_SEVERITY_EVENT

                               | RTAS_LOG_DISPOSITION_NOT_RECOVERED

                               | RTAS_LOG_OPTIONAL_PART_PRESENT

                               | RTAS_LOG_INITIATOR_HOTPLUG

                               | RTAS_LOG_TYPE_HOTPLUG);

    hdr->extended_length = cpu_to_be32(sizeof(*new_hp)

                                       - sizeof(new_hp->hdr));

    spapr_init_v6hdr(v6hdr);

    spapr_init_maina(maina, 3 /* Main-A, Main-B, HP */);

    mainb->hdr.section_id = cpu_to_be16(RTAS_LOG_V6_SECTION_ID_MAINB);

    mainb->hdr.section_length = cpu_to_be16(sizeof(*mainb));

    mainb->subsystem_id = 0x80; /* External environment */

    mainb->event_severity = 0x00; /* Informational / non-error */

    mainb->event_subtype = 0x00; /* Normal shutdown */

    hp->hdr.section_id = cpu_to_be16(RTAS_LOG_V6_SECTION_ID_HOTPLUG);

    hp->hdr.section_length = cpu_to_be16(sizeof(*hp));

    hp->hdr.section_version = 1; /* includes extended modifier */

    hp->hotplug_action = hp_action;

    switch (drc_type) {

    case SPAPR_DR_CONNECTOR_TYPE_PCI:

        hp->drc.index = cpu_to_be32(drck->get_index(drc));

        hp->hotplug_identifier = RTAS_LOG_V6_HP_ID_DRC_INDEX;

        hp->hotplug_type = RTAS_LOG_V6_HP_TYPE_PCI;

        break;

    default:

        /* we shouldn't be signaling hotplug events for resources

         * that don't support them

         */

        g_assert(false);

        return;

    }

    rtas_event_log_queue(RTAS_LOG_TYPE_HOTPLUG, new_hp);

    qemu_irq_pulse(xics_get_qirq(spapr->icp, spapr->check_exception_irq));

}


static TCGReg tcg_out_tlb_load(TCGContext *s, TCGReg addr, int mem_index,

                               TCGMemOp s_bits, int which)

{

    const TCGReg r0 = TCG_REG_O0;

    const TCGReg r1 = TCG_REG_O1;

    const TCGReg r2 = TCG_REG_O2;

    int tlb_ofs;

    /* Shift the page number down.  */

    tcg_out_arithi(s, r1, addr, TARGET_PAGE_BITS, SHIFT_SRL);

    /* Mask out the page offset, except for the required alignment.  */

    tcg_out_movi(s, TCG_TYPE_TL, TCG_REG_T1,

                 TARGET_PAGE_MASK | ((1 << s_bits) - 1));

    /* Mask the tlb index.  */

    tcg_out_arithi(s, r1, r1, CPU_TLB_SIZE - 1, ARITH_AND);

    /* Mask page, part 2.  */

    tcg_out_arith(s, r0, addr, TCG_REG_T1, ARITH_AND);

    /* Shift the tlb index into place.  */

    tcg_out_arithi(s, r1, r1, CPU_TLB_ENTRY_BITS, SHIFT_SLL);

    /* Relative to the current ENV.  */

    tcg_out_arith(s, r1, TCG_AREG0, r1, ARITH_ADD);

    /* Find a base address that can load both tlb comparator and addend.  */

    tlb_ofs = offsetof(CPUArchState, tlb_table[mem_index][0]);

    if (!check_fit_tl(tlb_ofs + sizeof(CPUTLBEntry), 13)) {

        tcg_out_addi(s, r1, tlb_ofs & ~0x3ff);

        tlb_ofs &= 0x3ff;

    }

    /* Load the tlb comparator and the addend.  */

    tcg_out_ld(s, TCG_TYPE_TL, r2, r1, tlb_ofs + which);

    tcg_out_ld(s, TCG_TYPE_PTR, r1, r1, tlb_ofs+offsetof(CPUTLBEntry, addend));

    /* subcc arg0, arg2, %g0 */

    tcg_out_cmp(s, r0, r2, 0);

    /* If the guest address must be zero-extended, do so now.  */

    if (SPARC64 && TARGET_LONG_BITS == 32) {

        tcg_out_arithi(s, r0, addr, 0, SHIFT_SRL);

        return r0;

    }

    return addr;

}


static int curl_sock_cb(CURL *curl, curl_socket_t fd, int action,

                        void *s, void *sp)

{

    DPRINTF("CURL (AIO): Sock action %d on fd %d\n", action, fd);

    switch (action) {

        case CURL_POLL_IN:

            qemu_aio_set_fd_handler(fd, curl_multi_do, NULL, s);

            break;

        case CURL_POLL_OUT:

            qemu_aio_set_fd_handler(fd, NULL, curl_multi_do, s);

            break;

        case CURL_POLL_INOUT:

            qemu_aio_set_fd_handler(fd, curl_multi_do, curl_multi_do, s);

            break;

        case CURL_POLL_REMOVE:

            qemu_aio_set_fd_handler(fd, NULL, NULL, NULL);

            break;

    }

    return 0;

}


SwsFunc yuv2rgb_get_func_ptr (SwsContext *c)

{

#if defined(HAVE_MMX2) || defined(HAVE_MMX)

    if(c->flags & SWS_CPU_CAPS_MMX2){

	switch(c->dstFormat){

	case PIX_FMT_RGB32: return yuv420_rgb32_MMX2;

	case PIX_FMT_BGR24: return yuv420_rgb24_MMX2;

	case PIX_FMT_BGR565: return yuv420_rgb16_MMX2;

	case PIX_FMT_BGR555: return yuv420_rgb15_MMX2;

	}

    }

    if(c->flags & SWS_CPU_CAPS_MMX){

	switch(c->dstFormat){

	case PIX_FMT_RGB32: return yuv420_rgb32_MMX;

	case PIX_FMT_BGR24: return yuv420_rgb24_MMX;

	case PIX_FMT_BGR565: return yuv420_rgb16_MMX;

	case PIX_FMT_BGR555: return yuv420_rgb15_MMX;

	}

    }

#endif

#ifdef HAVE_MLIB

    {

	SwsFunc t= yuv2rgb_init_mlib(c);

	if(t) return t;

    }

#endif

#ifdef HAVE_ALTIVEC

    if (c->flags & SWS_CPU_CAPS_ALTIVEC)

    {

	SwsFunc t = yuv2rgb_init_altivec(c);

	if(t) return t;

    }

#endif

    av_log(c, AV_LOG_WARNING, "No accelerated colorspace conversion found\n");

    switch(c->dstFormat){

    case PIX_FMT_BGR32:

    case PIX_FMT_RGB32: return yuv2rgb_c_32;

    case PIX_FMT_RGB24: return yuv2rgb_c_24_rgb;

    case PIX_FMT_BGR24: return yuv2rgb_c_24_bgr;

    case PIX_FMT_RGB565:

    case PIX_FMT_BGR565:

    case PIX_FMT_RGB555:

    case PIX_FMT_BGR555: return yuv2rgb_c_16;

    case PIX_FMT_RGB8:

    case PIX_FMT_BGR8:  return yuv2rgb_c_8_ordered_dither;

    case PIX_FMT_RGB4:

    case PIX_FMT_BGR4:  return yuv2rgb_c_4_ordered_dither;

    case PIX_FMT_RGB4_BYTE:

    case PIX_FMT_BGR4_BYTE:  return yuv2rgb_c_4b_ordered_dither;

    case PIX_FMT_MONOBLACK:  return yuv2rgb_c_1_ordered_dither;

    default:

    	assert(0);

    }

    return NULL;

}


static void vnc_set_share_mode(VncState *vs, VncShareMode mode)

{

#ifdef _VNC_DEBUG

    static const char *mn[] = {

        [0]                           = "undefined",

        [VNC_SHARE_MODE_CONNECTING]   = "connecting",

        [VNC_SHARE_MODE_SHARED]       = "shared",

        [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",

        [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",

    };

    fprintf(stderr, "%s/%d: %s -> %s\n", __func__,

            vs->csock, mn[vs->share_mode], mn[mode]);

#endif

    if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {

        vs->vd->num_exclusive--;

    }

    vs->share_mode = mode;

    if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {

        vs->vd->num_exclusive++;

    }

}


uint8_t ff_mlp_calculate_parity(const uint8_t *buf, unsigned int buf_size)

{

    uint32_t scratch = 0;

    const uint8_t *buf_end = buf + buf_size;

    for (; buf < buf_end - 3; buf += 4)

        scratch ^= *((const uint32_t*)buf);

    scratch = xor_32_to_8(scratch);

    for (; buf < buf_end; buf++)

    return scratch;

}


void ff_er_frame_start(ERContext *s)

{

    if (!s->avctx->err_recognition)

        return;

    memset(s->error_status_table, ER_MB_ERROR | VP_START | ER_MB_END,

           s->mb_stride * s->mb_height * sizeof(uint8_t));

    s->error_count    = 3 * s->mb_num;

    s->error_occurred = 0;

}


av_cold int MPV_common_init(MpegEncContext *s)

{

    int y_size, c_size, yc_size, i, mb_array_size, mv_table_size, x, y, threads;

    if(s->codec_id == CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)

        s->mb_height = (s->height + 31) / 32 * 2;

    else if (s->codec_id != CODEC_ID_H264)

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

    if(s->avctx->pix_fmt == PIX_FMT_NONE){

        av_log(s->avctx, AV_LOG_ERROR, "decoding to PIX_FMT_NONE is not supported.\n");

        return -1;

    }

    if((s->encoding || (s->avctx->active_thread_type & FF_THREAD_SLICE)) &&

       (s->avctx->thread_count > MAX_THREADS || (s->avctx->thread_count > s->mb_height && s->mb_height))){

        av_log(s->avctx, AV_LOG_ERROR, "too many threads\n");

        return -1;

    }

    if((s->width || s->height) && av_image_check_size(s->width, s->height, 0, s->avctx))

        return -1;

    dsputil_init(&s->dsp, s->avctx);

    ff_dct_common_init(s);

    s->flags= s->avctx->flags;

    s->flags2= s->avctx->flags2;

    if (s->width && s->height) {

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

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

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

        s->b4_stride = s->mb_width*4 + 1;

        mb_array_size= s->mb_height * s->mb_stride;

        mv_table_size= (s->mb_height+2) * s->mb_stride + 1;

        /* set chroma shifts */

        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt,&(s->chroma_x_shift),

                                      &(s->chroma_y_shift) );

        /* set default edge pos, will be overriden in decode_header if needed */

        s->h_edge_pos= s->mb_width*16;

        s->v_edge_pos= s->mb_height*16;

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

        s->block_wrap[0]=

        s->block_wrap[1]=

        s->block_wrap[2]=

        s->block_wrap[3]= s->b8_stride;

        s->block_wrap[4]=

        s->block_wrap[5]= s->mb_stride;

        y_size = s->b8_stride * (2 * s->mb_height + 1);

        c_size = s->mb_stride * (s->mb_height + 1);

        yc_size = y_size + 2 * c_size;

        /* convert fourcc to upper case */

        s->codec_tag = ff_toupper4(s->avctx->codec_tag);

        s->stream_codec_tag = ff_toupper4(s->avctx->stream_codec_tag);

        s->avctx->coded_frame= (AVFrame*)&s->current_picture;

        FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_index2xy, (s->mb_num+1)*sizeof(int), fail) //error ressilience code looks cleaner with this

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

            for(x=0; x<s->mb_width; x++){

                s->mb_index2xy[ x + y*s->mb_width ] = x + y*s->mb_stride;

            }

        }

        s->mb_index2xy[ s->mb_height*s->mb_width ] = (s->mb_height-1)*s->mb_stride + s->mb_width; //FIXME really needed?

        if (s->encoding) {

            /* Allocate MV tables */

            FF_ALLOCZ_OR_GOTO(s->avctx, s->p_mv_table_base            , mv_table_size * 2 * sizeof(int16_t), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->b_forw_mv_table_base       , mv_table_size * 2 * sizeof(int16_t), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->b_back_mv_table_base       , mv_table_size * 2 * sizeof(int16_t), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_forw_mv_table_base , mv_table_size * 2 * sizeof(int16_t), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_back_mv_table_base , mv_table_size * 2 * sizeof(int16_t), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->b_direct_mv_table_base     , mv_table_size * 2 * sizeof(int16_t), fail)

            s->p_mv_table           = s->p_mv_table_base            + s->mb_stride + 1;

            s->b_forw_mv_table      = s->b_forw_mv_table_base       + s->mb_stride + 1;

            s->b_back_mv_table      = s->b_back_mv_table_base       + s->mb_stride + 1;

            s->b_bidir_forw_mv_table= s->b_bidir_forw_mv_table_base + s->mb_stride + 1;

            s->b_bidir_back_mv_table= s->b_bidir_back_mv_table_base + s->mb_stride + 1;

            s->b_direct_mv_table    = s->b_direct_mv_table_base     + s->mb_stride + 1;

            if(s->msmpeg4_version){

                FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_stats, 2*2*(MAX_LEVEL+1)*(MAX_RUN+1)*2*sizeof(int), fail);

            }

            FF_ALLOCZ_OR_GOTO(s->avctx, s->avctx->stats_out, 256, fail);

            /* Allocate MB type table */

            FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_type  , mb_array_size * sizeof(uint16_t), fail) //needed for encoding

            FF_ALLOCZ_OR_GOTO(s->avctx, s->lambda_table, mb_array_size * sizeof(int), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix  , 64*32   * sizeof(int), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix  , 64*32   * sizeof(int), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix16, 64*32*2 * sizeof(uint16_t), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix16, 64*32*2 * sizeof(uint16_t), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->input_picture, MAX_PICTURE_COUNT * sizeof(Picture*), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->reordered_input_picture, MAX_PICTURE_COUNT * sizeof(Picture*), fail)

            if(s->avctx->noise_reduction){

                FF_ALLOCZ_OR_GOTO(s->avctx, s->dct_offset, 2 * 64 * sizeof(uint16_t), fail)

            }

        }

    }

    s->picture_count = MAX_PICTURE_COUNT * FFMAX(1, s->avctx->thread_count);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->picture, s->picture_count * sizeof(Picture), fail)

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

        avcodec_get_frame_defaults((AVFrame *)&s->picture[i]);

    }

    if (s->width && s->height) {

        FF_ALLOCZ_OR_GOTO(s->avctx, s->error_status_table, mb_array_size*sizeof(uint8_t), fail)

        if(s->codec_id==CODEC_ID_MPEG4 || (s->flags & CODEC_FLAG_INTERLACED_ME)){

            /* interlaced direct mode decoding tables */

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

                int j, k;

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

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

                        FF_ALLOCZ_OR_GOTO(s->avctx,    s->b_field_mv_table_base[i][j][k], mv_table_size * 2 * sizeof(int16_t), fail)

                        s->b_field_mv_table[i][j][k] = s->b_field_mv_table_base[i][j][k] + s->mb_stride + 1;

                    }

                    FF_ALLOCZ_OR_GOTO(s->avctx, s->b_field_select_table [i][j], mb_array_size * 2 * sizeof(uint8_t), fail)

                    FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_mv_table_base[i][j], mv_table_size * 2 * sizeof(int16_t), fail)

                    s->p_field_mv_table[i][j] = s->p_field_mv_table_base[i][j]+ s->mb_stride + 1;

                }

                FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_select_table[i], mb_array_size * 2 * sizeof(uint8_t), fail)

            }

        }

        if (s->out_format == FMT_H263) {

            /* cbp values */

            FF_ALLOCZ_OR_GOTO(s->avctx, s->coded_block_base, y_size, fail);

            s->coded_block= s->coded_block_base + s->b8_stride + 1;

            /* cbp, ac_pred, pred_dir */

            FF_ALLOCZ_OR_GOTO(s->avctx, s->cbp_table     , mb_array_size * sizeof(uint8_t), fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, s->pred_dir_table, mb_array_size * sizeof(uint8_t), fail)

        }

        if (s->h263_pred || s->h263_plus || !s->encoding) {

            /* dc values */

            //MN: we need these for error resilience of intra-frames

            FF_ALLOCZ_OR_GOTO(s->avctx, s->dc_val_base, yc_size * sizeof(int16_t), fail);

            s->dc_val[0] = s->dc_val_base + s->b8_stride + 1;

            s->dc_val[1] = s->dc_val_base + y_size + s->mb_stride + 1;

            s->dc_val[2] = s->dc_val[1] + c_size;

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

                s->dc_val_base[i] = 1024;

        }

        /* which mb is a intra block */

        FF_ALLOCZ_OR_GOTO(s->avctx, s->mbintra_table, mb_array_size, fail);

        memset(s->mbintra_table, 1, mb_array_size);

        /* init macroblock skip table */

        FF_ALLOCZ_OR_GOTO(s->avctx, s->mbskip_table, mb_array_size+2, fail);

        //Note the +1 is for a quicker mpeg4 slice_end detection

        FF_ALLOCZ_OR_GOTO(s->avctx, s->prev_pict_types, PREV_PICT_TYPES_BUFFER_SIZE, fail);

        s->parse_context.state= -1;

        if((s->avctx->debug&(FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) || (s->avctx->debug_mv)){

            s->visualization_buffer[0] = av_malloc((s->mb_width*16 + 2*EDGE_WIDTH) * s->mb_height*16 + 2*EDGE_WIDTH);

            s->visualization_buffer[1] = av_malloc((s->mb_width*16 + 2*EDGE_WIDTH) * s->mb_height*16 + 2*EDGE_WIDTH);

            s->visualization_buffer[2] = av_malloc((s->mb_width*16 + 2*EDGE_WIDTH) * s->mb_height*16 + 2*EDGE_WIDTH);

        }

    }

    s->context_initialized = 1;

    s->thread_context[0]= s;

    if (s->width && s->height) {

    if (s->encoding || (HAVE_THREADS && s->avctx->active_thread_type&FF_THREAD_SLICE)) {

        threads = s->avctx->thread_count;

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

            s->thread_context[i]= av_malloc(sizeof(MpegEncContext));

            memcpy(s->thread_context[i], s, sizeof(MpegEncContext));

        }

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

            if(init_duplicate_context(s->thread_context[i], s) < 0)

                goto fail;

            s->thread_context[i]->start_mb_y= (s->mb_height*(i  ) + s->avctx->thread_count/2) / s->avctx->thread_count;

            s->thread_context[i]->end_mb_y  = (s->mb_height*(i+1) + s->avctx->thread_count/2) / s->avctx->thread_count;

        }

    } else {

        if(init_duplicate_context(s, s) < 0) goto fail;

        s->start_mb_y = 0;

        s->end_mb_y   = s->mb_height;

    }

    }

    return 0;

 fail:

    MPV_common_end(s);

    return -1;

}


int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,

                          const char *filename, void *logctx,

                          unsigned int offset, unsigned int max_probe_size)

{

    AVProbeData pd = { filename ? filename : "", NULL, -offset };

    unsigned char *buf = NULL;

    int ret = 0, probe_size;

    if (!max_probe_size) {

        max_probe_size = PROBE_BUF_MAX;

    } else if (max_probe_size > PROBE_BUF_MAX) {

        max_probe_size = PROBE_BUF_MAX;

    } else if (max_probe_size < PROBE_BUF_MIN) {

        return AVERROR(EINVAL);

    }

    if (offset >= max_probe_size) {

        return AVERROR(EINVAL);

    }

    for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;

        probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {

        int score = probe_size < max_probe_size ? AVPROBE_SCORE_RETRY : 0;

        int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;

        void *buftmp;

        if (probe_size < offset) {

            continue;

        }

        /* read probe data */

        buftmp = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);

        if(!buftmp){

            av_free(buf);

            return AVERROR(ENOMEM);

        }

        buf=buftmp;

        if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {

            /* fail if error was not end of file, otherwise, lower score */

            if (ret != AVERROR_EOF) {

                av_free(buf);

                return ret;

            }

            score = 0;

            ret = 0;            /* error was end of file, nothing read */

        }

        pd.buf_size += ret;

        pd.buf = &buf[offset];

        memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);

        /* guess file format */

        *fmt = av_probe_input_format2(&pd, 1, &score);

        if(*fmt){

            if(score <= AVPROBE_SCORE_RETRY){ //this can only be true in the last iteration

                av_log(logctx, AV_LOG_WARNING, "Format %s detected only with low score of %d, misdetection possible!\n", (*fmt)->name, score);

            }else

                av_log(logctx, AV_LOG_DEBUG, "Format %s probed with size=%d and score=%d\n", (*fmt)->name, probe_size, score);

        }

    }

    if (!*fmt) {

        av_free(buf);

        return AVERROR_INVALIDDATA;

    }

    /* rewind. reuse probe buffer to avoid seeking */

    ret = ffio_rewind_with_probe_data(pb, &buf, pd.buf_size);

    return ret;

}


static void slirp_smb(SlirpState* s, Monitor *mon, const char *exported_dir,

                      struct in_addr vserver_addr)

{

    static int instance;

    char smb_conf[128];

    char smb_cmdline[128];

    FILE *f;

    snprintf(s->smb_dir, sizeof(s->smb_dir), "/tmp/qemu-smb.%ld-%d",

             (long)getpid(), instance++);

    if (mkdir(s->smb_dir, 0700) < 0) {

        config_error(mon, "could not create samba server dir '%s'\n",

                     s->smb_dir);

        return;

    }

    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", s->smb_dir, "smb.conf");

    f = fopen(smb_conf, "w");

    if (!f) {

        slirp_smb_cleanup(s);

        config_error(mon, "could not create samba server "

                     "configuration file '%s'\n", smb_conf);

        return;

    }

    fprintf(f,

            "[global]\n"

            "private dir=%s\n"

            "smb ports=0\n"

            "socket address=127.0.0.1\n"

            "pid directory=%s\n"

            "lock directory=%s\n"

            "log file=%s/log.smbd\n"

            "smb passwd file=%s/smbpasswd\n"

            "security = share\n"

            "[qemu]\n"

            "path=%s\n"

            "read only=no\n"

            "guest ok=yes\n",

            s->smb_dir,

            s->smb_dir,

            s->smb_dir,

            s->smb_dir,

            s->smb_dir,

            exported_dir

            );

    fclose(f);

    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",

             SMBD_COMMAND, smb_conf);

    if (slirp_add_exec(s->slirp, 0, smb_cmdline, &vserver_addr, 139) < 0) {

        slirp_smb_cleanup(s);

        config_error(mon, "conflicting/invalid smbserver address\n");

    }

}


void tlb_set_page(CPUState *env, target_ulong vaddr,

                  target_phys_addr_t paddr, int prot,

                  int mmu_idx, target_ulong size)

{

    PhysPageDesc *p;

    unsigned long pd;

    unsigned int index;

    target_ulong address;

    target_ulong code_address;

    unsigned long addend;

    CPUTLBEntry *te;

    CPUWatchpoint *wp;

    target_phys_addr_t iotlb;

    assert(size >= TARGET_PAGE_SIZE);

    if (size != TARGET_PAGE_SIZE) {

        tlb_add_large_page(env, vaddr, size);

    }

    p = phys_page_find(paddr >> TARGET_PAGE_BITS);

    if (!p) {

        pd = IO_MEM_UNASSIGNED;

    } else {

        pd = p->phys_offset;

    }

#if defined(DEBUG_TLB)

    printf("tlb_set_page: vaddr=" TARGET_FMT_lx " paddr=0x%08x prot=%x idx=%d smmu=%d pd=0x%08lx\n",

           vaddr, (int)paddr, prot, mmu_idx, is_softmmu, pd);

#endif

    address = vaddr;

    if ((pd & ~TARGET_PAGE_MASK) > IO_MEM_ROM && !(pd & IO_MEM_ROMD)) {

        /* IO memory case (romd handled later) */

        address |= TLB_MMIO;

    }

    addend = (unsigned long)qemu_get_ram_ptr(pd & TARGET_PAGE_MASK);

    if ((pd & ~TARGET_PAGE_MASK) <= IO_MEM_ROM) {

        /* Normal RAM.  */

        iotlb = pd & TARGET_PAGE_MASK;

        if ((pd & ~TARGET_PAGE_MASK) == IO_MEM_RAM)

            iotlb |= IO_MEM_NOTDIRTY;

        else

            iotlb |= IO_MEM_ROM;

    } else {

        /* IO handlers are currently passed a physical address.

           It would be nice to pass an offset from the base address

           of that region.  This would avoid having to special case RAM,

           and avoid full address decoding in every device.

           We can't use the high bits of pd for this because

           IO_MEM_ROMD uses these as a ram address.  */

        iotlb = (pd & ~TARGET_PAGE_MASK);

        if (p) {

            iotlb += p->region_offset;

        } else {

            iotlb += paddr;

        }

    }

    code_address = address;

    /* Make accesses to pages with watchpoints go via the

       watchpoint trap routines.  */

    QTAILQ_FOREACH(wp, &env->watchpoints, entry) {

        if (vaddr == (wp->vaddr & TARGET_PAGE_MASK)) {

            iotlb = io_mem_watch + paddr;

            /* TODO: The memory case can be optimized by not trapping

               reads of pages with a write breakpoint.  */

            address |= TLB_MMIO;

        }

    }

    index = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);

    env->iotlb[mmu_idx][index] = iotlb - vaddr;

    te = &env->tlb_table[mmu_idx][index];

    te->addend = addend - vaddr;

    if (prot & PAGE_READ) {

        te->addr_read = address;

    } else {

        te->addr_read = -1;

    }

    if (prot & PAGE_EXEC) {

        te->addr_code = code_address;

    } else {

        te->addr_code = -1;

    }

    if (prot & PAGE_WRITE) {

        if ((pd & ~TARGET_PAGE_MASK) == IO_MEM_ROM ||

            (pd & IO_MEM_ROMD)) {

            /* Write access calls the I/O callback.  */

            te->addr_write = address | TLB_MMIO;

        } else if ((pd & ~TARGET_PAGE_MASK) == IO_MEM_RAM &&

                   !cpu_physical_memory_is_dirty(pd)) {

            te->addr_write = address | TLB_NOTDIRTY;

        } else {

            te->addr_write = address;

        }

    } else {

        te->addr_write = -1;

    }

}


void *slavio_intctl_init(target_phys_addr_t addr, target_phys_addr_t addrg,

                         const uint32_t *intbit_to_level,

                         qemu_irq **irq, qemu_irq **cpu_irq,

                         unsigned int cputimer)

{

    int slavio_intctl_io_memory, slavio_intctlm_io_memory, i;

    SLAVIO_INTCTLState *s;

    s = qemu_mallocz(sizeof(SLAVIO_INTCTLState));

    if (!s)

        return NULL;

    s->intbit_to_level = intbit_to_level;

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

	slavio_intctl_io_memory = cpu_register_io_memory(0, slavio_intctl_mem_read, slavio_intctl_mem_write, s);

	cpu_register_physical_memory(addr + i * TARGET_PAGE_SIZE, INTCTL_SIZE,

                                     slavio_intctl_io_memory);

    }

    slavio_intctlm_io_memory = cpu_register_io_memory(0, slavio_intctlm_mem_read, slavio_intctlm_mem_write, s);

    cpu_register_physical_memory(addrg, INTCTLM_SIZE, slavio_intctlm_io_memory);

    register_savevm("slavio_intctl", addr, 1, slavio_intctl_save, slavio_intctl_load, s);

    qemu_register_reset(slavio_intctl_reset, s);

    *irq = qemu_allocate_irqs(slavio_set_irq, s, 32);

    *cpu_irq = qemu_allocate_irqs(slavio_set_timer_irq_cpu, s, MAX_CPUS);

    s->cputimer_bit = 1 << s->intbit_to_level[cputimer];

    slavio_intctl_reset(s);

    return s;

}


void helper_frndint(void)

{

    ST0 = rint(ST0);

}


static void start_children(FFStream *feed)

{

    if (no_launch)

        return;

    for (; feed; feed = feed->next) {

        if (feed->child_argv && !feed->pid) {

            feed->pid_start = time(0);

            feed->pid = fork();

            if (feed->pid < 0) {

                http_log("Unable to create children\n");

                exit(1);

            }

            if (!feed->pid) {

                /* In child */

                char pathname[1024];

                char *slash;

                int i;

                av_strlcpy(pathname, my_program_name, sizeof(pathname));

                slash = strrchr(pathname, '/');

                if (!slash)

                    slash = pathname;

                else

                    slash++;

                strcpy(slash, "ffmpeg");

                http_log("Launch command line: ");

                http_log("%s ", pathname);

                for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)

                    http_log("%s ", feed->child_argv[i]);

                http_log("\n");

                for (i = 3; i < 256; i++)

                    close(i);

                if (!ffserver_debug) {

                    i = open("/dev/null", O_RDWR);

                    if (i != -1) {

                        dup2(i, 0);

                        dup2(i, 1);

                        dup2(i, 2);

                        close(i);

                    }

                }

                /* This is needed to make relative pathnames work */

                chdir(my_program_dir);

                signal(SIGPIPE, SIG_DFL);

                execvp(pathname, feed->child_argv);

                _exit(1);

            }

        }

    }

}


static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)

{

    MOVContext *mov = s->priv_data;

    int i, j;

    if (!mov->fragment_index_complete)

        return 0;

    for (i = 0; i < mov->fragment_index_count; i++) {

        if (mov->fragment_index_data[i]->track_id == st->id) {

            MOVFragmentIndex *index = index = mov->fragment_index_data[i];

            for (j = index->item_count - 1; j >= 0; j--) {

                if (index->items[j].time <= timestamp) {

                    if (index->items[j].headers_read)

                        return 0;

                    return mov_switch_root(s, index->items[j].moof_offset);

                }

            }

        }

    }

    return 0;

}


static int mxf_read_track(MXFTrack *track, ByteIOContext *pb, int tag)

{

    switch(tag) {

    case 0x4801:

        track->track_id = get_be32(pb);

        break;

    case 0x4804:

        get_buffer(pb, track->track_number, 4);

        break;

    case 0x4B01:

        track->edit_rate.den = get_be32(pb);

        track->edit_rate.num = get_be32(pb);

        break;

    case 0x4803:

        get_buffer(pb, track->sequence_ref, 16);

        break;

    }

    return 0;

}


int ff_wms_parse_sdp_a_line(AVFormatContext *s, const char *p)

{

    int ret = 0;

    if (av_strstart(p, "pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,", &p)) {

        AVIOContext pb;

        RTSPState *rt = s->priv_data;

        AVDictionary *opts = NULL;

        int len = strlen(p) * 6 / 8;

        char *buf = av_mallocz(len);

        AVInputFormat *iformat;

        if (!buf)

            return AVERROR(ENOMEM);

        av_base64_decode(buf, p, len);

        if (rtp_asf_fix_header(buf, len) < 0)

            av_log(s, AV_LOG_ERROR,

                   "Failed to fix invalid RTSP-MS/ASF min_pktsize\n");

        init_packetizer(&pb, buf, len);

        if (rt->asf_ctx) {

            avformat_close_input(&rt->asf_ctx);

        }

        if (!(iformat = av_find_input_format("asf")))

            return AVERROR_DEMUXER_NOT_FOUND;

        rt->asf_ctx = avformat_alloc_context();

        if (!rt->asf_ctx) {

            av_free(buf);

            return AVERROR(ENOMEM);

        }

        rt->asf_ctx->pb      = &pb;

        av_dict_set(&opts, "no_resync_search", "1", 0);

        if ((ret = ff_copy_whiteblacklists(rt->asf_ctx, s)) < 0) {

            av_dict_free(&opts);

            return ret;

        }

        ret = avformat_open_input(&rt->asf_ctx, "", iformat, &opts);

        av_dict_free(&opts);

        if (ret < 0) {

            av_free(buf);

            return ret;

        }

        av_dict_copy(&s->metadata, rt->asf_ctx->metadata, 0);

        rt->asf_pb_pos = avio_tell(&pb);

        av_free(buf);

        rt->asf_ctx->pb = NULL;

    }

    return ret;

}


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

                              int buf_size, void *data)

{

    static const uint8_t sizes[LPC_ORDER] = {64, 32, 32, 16, 16, 8, 8, 8, 8, 4};

    static const uint8_t bit_sizes[LPC_ORDER] = {6, 5, 5, 4, 4, 3, 3, 3, 3, 2};

    RA144Context *ractx;

    PutBitContext pb;

    int32_t lpc_data[NBLOCKS * BLOCKSIZE];

    int32_t lpc_coefs[LPC_ORDER][MAX_LPC_ORDER];

    int shift[LPC_ORDER];

    int16_t block_coefs[NBLOCKS][LPC_ORDER];

    int lpc_refl[LPC_ORDER];    /**< reflection coefficients of the frame */

    unsigned int refl_rms[NBLOCKS]; /**< RMS of the reflection coefficients */

    int energy = 0;

    int i, idx;

    if (buf_size < FRAMESIZE) {

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

        return 0;

    }

    ractx = avctx->priv_data;

    /**

     * Since the LPC coefficients are calculated on a frame centered over the

     * fourth subframe, to encode a given frame, data from the next frame is

     * needed. In each call to this function, the previous frame (whose data are

     * saved in the encoder context) is encoded, and data from the current frame

     * are saved in the encoder context to be used in the next function call.

     */

    for (i = 0; i < (2 * BLOCKSIZE + BLOCKSIZE / 2); i++) {

        lpc_data[i] = ractx->curr_block[BLOCKSIZE + BLOCKSIZE / 2 + i];

        energy += (lpc_data[i] * lpc_data[i]) >> 4;

    }

    for (i = 2 * BLOCKSIZE + BLOCKSIZE / 2; i < NBLOCKS * BLOCKSIZE; i++) {

        lpc_data[i] = *((int16_t *)data + i - 2 * BLOCKSIZE - BLOCKSIZE / 2) >>

                      2;

        energy += (lpc_data[i] * lpc_data[i]) >> 4;

    }

    energy = ff_energy_tab[quantize(ff_t_sqrt(energy >> 5) >> 10, ff_energy_tab,

                                    32)];

    ff_lpc_calc_coefs(&ractx->lpc_ctx, lpc_data, NBLOCKS * BLOCKSIZE, LPC_ORDER,

                      LPC_ORDER, 16, lpc_coefs, shift, FF_LPC_TYPE_LEVINSON,

                      0, ORDER_METHOD_EST, 12, 0);

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

        block_coefs[NBLOCKS - 1][i] = -(lpc_coefs[LPC_ORDER - 1][i] <<

                                        (12 - shift[LPC_ORDER - 1]));

    /**

     * TODO: apply perceptual weighting of the input speech through bandwidth

     * expansion of the LPC filter.

     */

    if (ff_eval_refl(lpc_refl, block_coefs[NBLOCKS - 1], avctx)) {

        /**

         * The filter is unstable: use the coefficients of the previous frame.

         */

        ff_int_to_int16(block_coefs[NBLOCKS - 1], ractx->lpc_coef[1]);

        ff_eval_refl(lpc_refl, block_coefs[NBLOCKS - 1], avctx);

    }

    init_put_bits(&pb, frame, buf_size);

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

        idx = quantize(lpc_refl[i], ff_lpc_refl_cb[i], sizes[i]);

        put_bits(&pb, bit_sizes[i], idx);

        lpc_refl[i] = ff_lpc_refl_cb[i][idx];

    }

    ractx->lpc_refl_rms[0] = ff_rms(lpc_refl);

    ff_eval_coefs(ractx->lpc_coef[0], lpc_refl);

    refl_rms[0] = ff_interp(ractx, block_coefs[0], 1, 1, ractx->old_energy);

    refl_rms[1] = ff_interp(ractx, block_coefs[1], 2,

                            energy <= ractx->old_energy,

                            ff_t_sqrt(energy * ractx->old_energy) >> 12);

    refl_rms[2] = ff_interp(ractx, block_coefs[2], 3, 0, energy);

    refl_rms[3] = ff_rescale_rms(ractx->lpc_refl_rms[0], energy);

    ff_int_to_int16(block_coefs[NBLOCKS - 1], ractx->lpc_coef[0]);

    put_bits(&pb, 5, quantize(energy, ff_energy_tab, 32));

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

        ra144_encode_subblock(ractx, ractx->curr_block + i * BLOCKSIZE,

                              block_coefs[i], refl_rms[i], &pb);

    flush_put_bits(&pb);

    ractx->old_energy = energy;

    ractx->lpc_refl_rms[1] = ractx->lpc_refl_rms[0];

    FFSWAP(unsigned int *, ractx->lpc_coef[0], ractx->lpc_coef[1]);

    for (i = 0; i < NBLOCKS * BLOCKSIZE; i++)

        ractx->curr_block[i] = *((int16_t *)data + i) >> 2;

    return FRAMESIZE;

}


static void decode0(GetByteContext *gb, RangeCoder *rc, unsigned cumFreq, unsigned freq, unsigned total_freq)

{

    int t = rc->range * (uint64_t)cumFreq / total_freq;

    rc->code1 += t + 1;

    rc->range = rc->range * (uint64_t)(freq + cumFreq) / total_freq - (t + 1);

    while (rc->range < TOP && bytestream2_get_bytes_left(gb) > 0) {

        unsigned byte = bytestream2_get_byte(gb);

        rc->code = (rc->code << 8) | byte;

        rc->code1 <<= 8;

        rc->range <<= 8;

    }

}


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

{

    BDRVDMGState *s = bs->opaque;

    off_t info_begin,info_end,last_in_offset,last_out_offset;

    uint32_t count;

    uint32_t max_compressed_size=1,max_sectors_per_chunk=1,i;

    int64_t offset;

    s->fd = open(filename, O_RDONLY | O_BINARY);

    if (s->fd < 0)

        return -errno;

    bs->read_only = 1;

    s->n_chunks = 0;

    s->offsets = s->lengths = s->sectors = s->sectorcounts = NULL;

    /* read offset of info blocks */

    offset = lseek(s->fd, -0x1d8, SEEK_END);

    if (offset < 0) {

        goto fail;

    }

    info_begin = read_off(s->fd, offset);

    if (info_begin == 0) {

	goto fail;

    }

    if (read_uint32(s->fd, info_begin) != 0x100) {

        goto fail;

    }

    count = read_uint32(s->fd, info_begin + 4);

    if (count == 0) {

        goto fail;

    }

    info_end = info_begin + count;

    offset = info_begin + 0x100;

    /* read offsets */

    last_in_offset = last_out_offset = 0;

    while (offset < info_end) {

        uint32_t type;

	count = read_uint32(s->fd, offset);

	if(count==0)

	    goto fail;

        offset += 4;

	type = read_uint32(s->fd, offset);

	if (type == 0x6d697368 && count >= 244) {

	    int new_size, chunk_count;

            offset += 4;

            offset += 200;

	    chunk_count = (count-204)/40;

	    new_size = sizeof(uint64_t) * (s->n_chunks + chunk_count);

	    s->types = qemu_realloc(s->types, new_size/2);

	    s->offsets = qemu_realloc(s->offsets, new_size);

	    s->lengths = qemu_realloc(s->lengths, new_size);

	    s->sectors = qemu_realloc(s->sectors, new_size);

	    s->sectorcounts = qemu_realloc(s->sectorcounts, new_size);

	    for(i=s->n_chunks;i<s->n_chunks+chunk_count;i++) {

		s->types[i] = read_uint32(s->fd, offset);

		offset += 4;

		if(s->types[i]!=0x80000005 && s->types[i]!=1 && s->types[i]!=2) {

		    if(s->types[i]==0xffffffff) {

			last_in_offset = s->offsets[i-1]+s->lengths[i-1];

			last_out_offset = s->sectors[i-1]+s->sectorcounts[i-1];

		    }

		    chunk_count--;

		    i--;

		    offset += 36;

		    continue;

		}

		offset += 4;

		s->sectors[i] = last_out_offset+read_off(s->fd, offset);

		offset += 8;

		s->sectorcounts[i] = read_off(s->fd, offset);

		offset += 8;

		s->offsets[i] = last_in_offset+read_off(s->fd, offset);

		offset += 8;

		s->lengths[i] = read_off(s->fd, offset);

		offset += 8;

		if(s->lengths[i]>max_compressed_size)

		    max_compressed_size = s->lengths[i];

		if(s->sectorcounts[i]>max_sectors_per_chunk)

		    max_sectors_per_chunk = s->sectorcounts[i];

	    }

	    s->n_chunks+=chunk_count;

	}

    }

    /* initialize zlib engine */

    s->compressed_chunk = qemu_malloc(max_compressed_size+1);

    s->uncompressed_chunk = qemu_malloc(512*max_sectors_per_chunk);

    if(inflateInit(&s->zstream) != Z_OK)

	goto fail;

    s->current_chunk = s->n_chunks;

    return 0;

fail:

    close(s->fd);

    return -1;

}


bool net_rx_pkt_is_vlan_stripped(struct NetRxPkt *pkt)

{

    assert(pkt);

    return pkt->vlan_stripped;

}


static Visitor *validate_test_init_raw(TestInputVisitorData *data,

                                       const char *json_string)

{

    Visitor *v;

    data->obj = qobject_from_json(json_string);

    g_assert(data->obj != NULL);

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

    g_assert(data->qiv != NULL);

    v = qmp_input_get_visitor(data->qiv);

    g_assert(v != NULL);

    return v;

}


static int connect_namedsocket(const char *path)

{

    int sockfd, size;

    struct sockaddr_un helper;

    sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

    if (sockfd < 0) {

        fprintf(stderr, "socket %s\n", strerror(errno));

        return -1;

    }

    strcpy(helper.sun_path, path);

    helper.sun_family = AF_UNIX;

    size = strlen(helper.sun_path) + sizeof(helper.sun_family);

    if (connect(sockfd, (struct sockaddr *)&helper, size) < 0) {

        fprintf(stderr, "socket error\n");

        return -1;

    }

    /* remove the socket for security reasons */

    unlink(path);

    return sockfd;

}


static void ehci_mem_writel(void *ptr, target_phys_addr_t addr, uint32_t val)
{
    EHCIState *s = ptr;
    uint32_t *mmio = (uint32_t *)(&s->mmio[addr]);
    uint32_t old = *mmio;
    int i;
    trace_usb_ehci_mmio_writel(addr, addr2str(addr), val);
    /* Only aligned reads are allowed on OHCI */
    if (addr & 3) {
        fprintf(stderr, "usb-ehci: Mis-aligned write to addr 0x"
                TARGET_FMT_plx "\n", addr);
        return;
    if (addr >= PORTSC && addr < PORTSC + 4 * NB_PORTS) {
        handle_port_status_write(s, (addr-PORTSC)/4, val);
        trace_usb_ehci_mmio_change(addr, addr2str(addr), *mmio, old);
        return;
    if (addr < OPREGBASE) {
        fprintf(stderr, "usb-ehci: write attempt to read-only register"
                TARGET_FMT_plx "\n", addr);
        return;
    /* Do any register specific pre-write processing here.  */
    switch(addr) {
    case USBCMD:
        if (val & USBCMD_HCRESET) {
            ehci_reset(s);
            val = s->usbcmd;
            break;
        /* not supporting dynamic frame list size at the moment */
        if ((val & USBCMD_FLS) && !(s->usbcmd & USBCMD_FLS)) {
            fprintf(stderr, "attempt to set frame list size -- value %d\n",
                    val & USBCMD_FLS);
            val &= ~USBCMD_FLS;
        if (((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & val) !=
            ((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & s->usbcmd)) {
            if (s->pstate == EST_INACTIVE) {
                SET_LAST_RUN_CLOCK(s);
            s->usbcmd = val; /* Set usbcmd for ehci_update_halt() */
            ehci_update_halt(s);
            qemu_mod_timer(s->frame_timer, qemu_get_clock_ns(vm_clock));
        break;
    case USBSTS:
        val &= USBSTS_RO_MASK;              // bits 6 through 31 are RO
        ehci_clear_usbsts(s, val);          // bits 0 through 5 are R/WC
        val = s->usbsts;
        ehci_update_irq(s);
        break;
    case USBINTR:
        val &= USBINTR_MASK;
        break;
    case FRINDEX:
        val &= 0x00003ff8; /* frindex is 14bits and always a multiple of 8 */
        break;
    case CONFIGFLAG:
        val &= 0x1;
        if (val) {
            for(i = 0; i < NB_PORTS; i++)
                handle_port_owner_write(s, i, 0);
        break;
    case PERIODICLISTBASE:
        if (ehci_periodic_enabled(s)) {
            fprintf(stderr,
              "ehci: PERIODIC list base register set while periodic schedule\n"
              "      is enabled and HC is enabled\n");
        break;
    case ASYNCLISTADDR:
        if (ehci_async_enabled(s)) {
            fprintf(stderr,
              "ehci: ASYNC list address register set while async schedule\n"
              "      is enabled and HC is enabled\n");
        break;
    *mmio = val;
    trace_usb_ehci_mmio_change(addr, addr2str(addr), *mmio, old);


static av_cold int dnxhd_encode_init(AVCodecContext *avctx)

{

    DNXHDEncContext *ctx = avctx->priv_data;

    int i, index, bit_depth, ret;

    switch (avctx->pix_fmt) {

    case AV_PIX_FMT_YUV422P:

        bit_depth = 8;

        break;

    case AV_PIX_FMT_YUV422P10:

        bit_depth = 10;

        break;

    default:

        av_log(avctx, AV_LOG_ERROR,

               "pixel format is incompatible with DNxHD\n");

        return AVERROR(EINVAL);

    }

    ctx->cid = ff_dnxhd_find_cid(avctx, bit_depth);

    if (!ctx->cid) {

        av_log(avctx, AV_LOG_ERROR,

               "video parameters incompatible with DNxHD\n");

        return AVERROR(EINVAL);

    }

    av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);

    index = ff_dnxhd_get_cid_table(ctx->cid);

    if (index < 0)

        return index;

    ctx->cid_table = &ff_dnxhd_cid_table[index];

    ctx->m.avctx    = avctx;

    ctx->m.mb_intra = 1;

    ctx->m.h263_aic = 1;

    avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;

    ff_blockdsp_init(&ctx->bdsp, avctx);

    ff_fdctdsp_init(&ctx->m.fdsp, avctx);

    ff_mpv_idct_init(&ctx->m);

    ff_mpegvideoencdsp_init(&ctx->m.mpvencdsp, avctx);

    ff_pixblockdsp_init(&ctx->m.pdsp, avctx);

    if (!ctx->m.dct_quantize)

        ctx->m.dct_quantize = ff_dct_quantize_c;

    if (ctx->cid_table->bit_depth == 10) {

        ctx->m.dct_quantize     = dnxhd_10bit_dct_quantize;

        ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;

        ctx->block_width_l2     = 4;

    } else {

        ctx->get_pixels_8x4_sym = dnxhd_8bit_get_pixels_8x4_sym;

        ctx->block_width_l2     = 3;

    }

    if (ARCH_X86)

        ff_dnxhdenc_init_x86(ctx);

    ctx->m.mb_height = (avctx->height + 15) / 16;

    ctx->m.mb_width  = (avctx->width  + 15) / 16;

    if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {

        ctx->interlaced   = 1;

        ctx->m.mb_height /= 2;

    }

    ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;

#if FF_API_QUANT_BIAS

FF_DISABLE_DEPRECATION_WARNINGS

    if (ctx->intra_quant_bias == FF_DEFAULT_QUANT_BIAS &&

        avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)

        ctx->intra_quant_bias = avctx->intra_quant_bias;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    // XXX tune lbias/cbias

    if ((ret = dnxhd_init_qmat(ctx, ctx->intra_quant_bias, 0)) < 0)

        return ret;

    /* Avid Nitris hardware decoder requires a minimum amount of padding

     * in the coding unit payload */

    if (ctx->nitris_compat)

        ctx->min_padding = 1600;

    if ((ret = dnxhd_init_vlc(ctx)) < 0)

        return ret;

    if ((ret = dnxhd_init_rc(ctx)) < 0)

        return ret;

    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_size,

                      ctx->m.mb_height * sizeof(uint32_t), fail);

    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_offs,

                      ctx->m.mb_height * sizeof(uint32_t), fail);

    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_bits,

                      ctx->m.mb_num * sizeof(uint16_t), fail);

    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_qscale,

                      ctx->m.mb_num * sizeof(uint8_t), fail);

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    avctx->coded_frame->key_frame = 1;

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    if (avctx->thread_count > MAX_THREADS) {

        av_log(avctx, AV_LOG_ERROR, "too many threads\n");

        return AVERROR(EINVAL);

    }

    ctx->thread[0] = ctx;

    for (i = 1; i < avctx->thread_count; i++) {

        ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));

        memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));

    }

    return 0;

fail:  // for FF_ALLOCZ_OR_GOTO

    return AVERROR(ENOMEM);

}


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

                            int *data_size, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size, n_slices = 0, i;

    VC1Context *v = avctx->priv_data;

    MpegEncContext *s = &v->s;

    AVFrame *pict = data;

    uint8_t *buf2 = NULL;

    const uint8_t *buf_start = buf, *buf_start_second_field = NULL;

    int mb_height, n_slices1=-1;

    struct {

        uint8_t *buf;

        GetBitContext gb;

        int mby_start;

    } *slices = NULL, *tmp;

    v->second_field = 0;

    if(s->flags & CODEC_FLAG_LOW_DELAY)

        s->low_delay = 1;

    /* no supplementary picture */

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

        /* special case for last picture */

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

            *pict = s->next_picture_ptr->f;

            s->next_picture_ptr = NULL;

            *data_size = sizeof(AVFrame);

        }

        return buf_size;

    }

    if (s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU) {

        if (v->profile < PROFILE_ADVANCED)

            avctx->pix_fmt = AV_PIX_FMT_VDPAU_WMV3;

        else

            avctx->pix_fmt = AV_PIX_FMT_VDPAU_VC1;

    }

    //for advanced profile we may need to parse and unescape data

    if (avctx->codec_id == AV_CODEC_ID_VC1 || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {

        int buf_size2 = 0;

        buf2 = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

        if (IS_MARKER(AV_RB32(buf))) { /* frame starts with marker and needs to be parsed */

            const uint8_t *start, *end, *next;

            int size;

            next = buf;

            for (start = buf, end = buf + buf_size; next < end; start = next) {

                next = find_next_marker(start + 4, end);

                size = next - start - 4;

                if (size <= 0) continue;

                switch (AV_RB32(start)) {

                case VC1_CODE_FRAME:

                    if (avctx->hwaccel ||

                        s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)

                        buf_start = start;

                    buf_size2 = vc1_unescape_buffer(start + 4, size, buf2);

                    break;

                case VC1_CODE_FIELD: {

                    int buf_size3;

                    if (avctx->hwaccel ||

                        s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)

                        buf_start_second_field = start;

                    tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));

                    if (!tmp)

                        goto err;

                    slices = tmp;

                    slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

                    if (!slices[n_slices].buf)

                        goto err;

                    buf_size3 = vc1_unescape_buffer(start + 4, size,

                                                    slices[n_slices].buf);

                    init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,

                                  buf_size3 << 3);

                    /* assuming that the field marker is at the exact middle,

                       hope it's correct */

                    slices[n_slices].mby_start = s->mb_height >> 1;

                    n_slices1 = n_slices - 1; // index of the last slice of the first field

                    n_slices++;

                    break;

                }

                case VC1_CODE_ENTRYPOINT: /* it should be before frame data */

                    buf_size2 = vc1_unescape_buffer(start + 4, size, buf2);

                    init_get_bits(&s->gb, buf2, buf_size2 * 8);

                    ff_vc1_decode_entry_point(avctx, v, &s->gb);

                    break;

                case VC1_CODE_SLICE: {

                    int buf_size3;

                    tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));

                    if (!tmp)

                        goto err;

                    slices = tmp;

                    slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

                    if (!slices[n_slices].buf)

                        goto err;

                    buf_size3 = vc1_unescape_buffer(start + 4, size,

                                                    slices[n_slices].buf);

                    init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,

                                  buf_size3 << 3);

                    slices[n_slices].mby_start = get_bits(&slices[n_slices].gb, 9);

                    n_slices++;

                    break;

                }

                }

            }

        } else if (v->interlace && ((buf[0] & 0xC0) == 0xC0)) { /* WVC1 interlaced stores both fields divided by marker */

            const uint8_t *divider;

            int buf_size3;

            divider = find_next_marker(buf, buf + buf_size);

            if ((divider == (buf + buf_size)) || AV_RB32(divider) != VC1_CODE_FIELD) {

                av_log(avctx, AV_LOG_ERROR, "Error in WVC1 interlaced frame\n");

                goto err;

            } else { // found field marker, unescape second field

                if (avctx->hwaccel ||

                    s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)

                    buf_start_second_field = divider;

                tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));

                if (!tmp)

                    goto err;

                slices = tmp;

                slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

                if (!slices[n_slices].buf)

                    goto err;

                buf_size3 = vc1_unescape_buffer(divider + 4, buf + buf_size - divider - 4, slices[n_slices].buf);

                init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,

                              buf_size3 << 3);

                slices[n_slices].mby_start = s->mb_height >> 1;

                n_slices1 = n_slices - 1;

                n_slices++;

            }

            buf_size2 = vc1_unescape_buffer(buf, divider - buf, buf2);

        } else {

            buf_size2 = vc1_unescape_buffer(buf, buf_size, buf2);

        }

        init_get_bits(&s->gb, buf2, buf_size2*8);

    } else

        init_get_bits(&s->gb, buf, buf_size*8);

    if (v->res_sprite) {

        v->new_sprite  = !get_bits1(&s->gb);

        v->two_sprites =  get_bits1(&s->gb);

        /* res_sprite means a Windows Media Image stream, AV_CODEC_ID_*IMAGE means

           we're using the sprite compositor. These are intentionally kept separate

           so you can get the raw sprites by using the wmv3 decoder for WMVP or

           the vc1 one for WVP2 */

        if (avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {

            if (v->new_sprite) {

                // switch AVCodecContext parameters to those of the sprites

                avctx->width  = avctx->coded_width  = v->sprite_width;

                avctx->height = avctx->coded_height = v->sprite_height;

            } else {

                goto image;

            }

        }

    }

    if (s->context_initialized &&

        (s->width  != avctx->coded_width ||

         s->height != avctx->coded_height)) {

        ff_vc1_decode_end(avctx);

    }

    if (!s->context_initialized) {

        if (ff_msmpeg4_decode_init(avctx) < 0 || ff_vc1_decode_init_alloc_tables(v) < 0)

            goto err;

        s->low_delay = !avctx->has_b_frames || v->res_sprite;

        if (v->profile == PROFILE_ADVANCED) {

            s->h_edge_pos = avctx->coded_width;

            s->v_edge_pos = avctx->coded_height;

        }

    }

    /* We need to set current_picture_ptr before reading the header,

     * otherwise we cannot store anything in there. */

    if (s->current_picture_ptr == NULL || s->current_picture_ptr->f.data[0]) {

        int i = ff_find_unused_picture(s, 0);

        if (i < 0)

            goto err;

        s->current_picture_ptr = &s->picture[i];

    }

    // do parse frame header

    v->pic_header_flag = 0;

    if (v->profile < PROFILE_ADVANCED) {

        if (ff_vc1_parse_frame_header(v, &s->gb) < 0) {

            goto err;

        }

    } else {

        if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {

            goto err;

        }

    }

    if (avctx->debug & FF_DEBUG_PICT_INFO)

        av_log(v->s.avctx, AV_LOG_DEBUG, "pict_type: %c\n", av_get_picture_type_char(s->pict_type));

    if ((avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE)

        && s->pict_type != AV_PICTURE_TYPE_I) {

        av_log(v->s.avctx, AV_LOG_ERROR, "Sprite decoder: expected I-frame\n");

        goto err;

    }

    if ((s->mb_height >> v->field_mode) == 0) {

        av_log(v->s.avctx, AV_LOG_ERROR, "image too short\n");

        goto err;

    }

    // process pulldown flags

    s->current_picture_ptr->f.repeat_pict = 0;

    // Pulldown flags are only valid when 'broadcast' has been set.

    // So ticks_per_frame will be 2

    if (v->rff) {

        // repeat field

        s->current_picture_ptr->f.repeat_pict = 1;

    } else if (v->rptfrm) {

        // repeat frames

        s->current_picture_ptr->f.repeat_pict = v->rptfrm * 2;

    }

    // for skipping the frame

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

    s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;

    /* skip B-frames if we don't have reference frames */

    if (s->last_picture_ptr == NULL && (s->pict_type == AV_PICTURE_TYPE_B || s->dropable)) {

        goto err;

    }

    if ((avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B) ||

        (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I) ||

         avctx->skip_frame >= AVDISCARD_ALL) {

        goto end;

    }

    if (s->next_p_frame_damaged) {

        if (s->pict_type == AV_PICTURE_TYPE_B)

            goto end;

        else

            s->next_p_frame_damaged = 0;

    }

    if (ff_MPV_frame_start(s, avctx) < 0) {

        goto err;

    }

    v->s.current_picture_ptr->f.interlaced_frame = (v->fcm != PROGRESSIVE);

    v->s.current_picture_ptr->f.top_field_first  = v->tff;

    s->me.qpel_put = s->dsp.put_qpel_pixels_tab;

    s->me.qpel_avg = s->dsp.avg_qpel_pixels_tab;

    if ((CONFIG_VC1_VDPAU_DECODER)

        &&s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)

        ff_vdpau_vc1_decode_picture(s, buf_start, (buf + buf_size) - buf_start);

    else if (avctx->hwaccel) {

        if (v->field_mode && buf_start_second_field) {

            // decode first field

            s->picture_structure = PICT_BOTTOM_FIELD - v->tff;

            if (avctx->hwaccel->start_frame(avctx, buf_start, buf_start_second_field - buf_start) < 0)

                goto err;

            if (avctx->hwaccel->decode_slice(avctx, buf_start, buf_start_second_field - buf_start) < 0)

                goto err;

            if (avctx->hwaccel->end_frame(avctx) < 0)

                goto err;

            // decode second field

            s->gb = slices[n_slices1 + 1].gb;

            s->picture_structure = PICT_TOP_FIELD + v->tff;

            v->second_field = 1;

            v->pic_header_flag = 0;

            if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {

                av_log(avctx, AV_LOG_ERROR, "parsing header for second field failed");

                goto err;

            }

            v->s.current_picture_ptr->f.pict_type = v->s.pict_type;

            if (avctx->hwaccel->start_frame(avctx, buf_start_second_field, (buf + buf_size) - buf_start_second_field) < 0)

                goto err;

            if (avctx->hwaccel->decode_slice(avctx, buf_start_second_field, (buf + buf_size) - buf_start_second_field) < 0)

                goto err;

            if (avctx->hwaccel->end_frame(avctx) < 0)

                goto err;

        } else {

            s->picture_structure = PICT_FRAME;

            if (avctx->hwaccel->start_frame(avctx, buf_start, (buf + buf_size) - buf_start) < 0)

                goto err;

            if (avctx->hwaccel->decode_slice(avctx, buf_start, (buf + buf_size) - buf_start) < 0)

                goto err;

            if (avctx->hwaccel->end_frame(avctx) < 0)

                goto err;

        }

    } else {

        if (v->fcm == ILACE_FRAME && s->pict_type == AV_PICTURE_TYPE_B)

            goto err; // This codepath is still incomplete thus it is disabled

        ff_er_frame_start(s);

        v->bits = buf_size * 8;

        v->end_mb_x = s->mb_width;

        if (v->field_mode) {

            uint8_t *tmp[2];

            s->current_picture.f.linesize[0] <<= 1;

            s->current_picture.f.linesize[1] <<= 1;

            s->current_picture.f.linesize[2] <<= 1;

            s->linesize                      <<= 1;

            s->uvlinesize                    <<= 1;

            tmp[0]          = v->mv_f_last[0];

            tmp[1]          = v->mv_f_last[1];

            v->mv_f_last[0] = v->mv_f_next[0];

            v->mv_f_last[1] = v->mv_f_next[1];

            v->mv_f_next[0] = v->mv_f[0];

            v->mv_f_next[1] = v->mv_f[1];

            v->mv_f[0] = tmp[0];

            v->mv_f[1] = tmp[1];

        }

        mb_height = s->mb_height >> v->field_mode;

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

            if (i > 0 &&  slices[i - 1].mby_start >= mb_height) {

                if (v->field_mode <= 0) {

                    av_log(v->s.avctx, AV_LOG_ERROR, "Slice %d starts beyond "

                           "picture boundary (%d >= %d)\n", i,

                           slices[i - 1].mby_start, mb_height);

                    continue;

                }

                v->second_field = 1;

                v->blocks_off   = s->mb_width  * s->mb_height << 1;

                v->mb_off       = s->mb_stride * s->mb_height >> 1;

            } else {

                v->second_field = 0;

                v->blocks_off   = 0;

                v->mb_off       = 0;

            }

            if (i) {

                v->pic_header_flag = 0;

                if (v->field_mode && i == n_slices1 + 2) {

                    if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {

                        av_log(v->s.avctx, AV_LOG_ERROR, "Field header damaged\n");

                        continue;

                    }

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

                    v->pic_header_flag = 1;

                    if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {

                        av_log(v->s.avctx, AV_LOG_ERROR, "Slice header damaged\n");

                        continue;

                    }

                }

            }

            s->start_mb_y = (i == 0) ? 0 : FFMAX(0, slices[i-1].mby_start % mb_height);

            if (!v->field_mode || v->second_field)

                s->end_mb_y = (i == n_slices     ) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);

            else

                s->end_mb_y = (i <= n_slices1 + 1) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);

            if (s->end_mb_y <= s->start_mb_y) {

                av_log(v->s.avctx, AV_LOG_ERROR, "end mb y %d %d invalid\n", s->end_mb_y, s->start_mb_y);

                continue;

            }

            ff_vc1_decode_blocks(v);

            if (i != n_slices)

                s->gb = slices[i].gb;

        }

        if (v->field_mode) {

            v->second_field = 0;

            if (s->pict_type == AV_PICTURE_TYPE_B) {

                memcpy(v->mv_f_base, v->mv_f_next_base,

                       2 * (s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2));

            }

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

            s->current_picture.f.linesize[1] >>= 1;

            s->current_picture.f.linesize[2] >>= 1;

            s->linesize                      >>= 1;

            s->uvlinesize                    >>= 1;

        }

        av_dlog(s->avctx, "Consumed %i/%i bits\n",

                get_bits_count(&s->gb), s->gb.size_in_bits);

//  if (get_bits_count(&s->gb) > buf_size * 8)

//      return -1;

        if(s->error_occurred && s->pict_type == AV_PICTURE_TYPE_B)

            goto err;

        if(!v->field_mode)

            ff_er_frame_end(s);

    }

    ff_MPV_frame_end(s);

    if (avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {

image:

        avctx->width  = avctx->coded_width  = v->output_width;

        avctx->height = avctx->coded_height = v->output_height;

        if (avctx->skip_frame >= AVDISCARD_NONREF)

            goto end;

#if CONFIG_WMV3IMAGE_DECODER || CONFIG_VC1IMAGE_DECODER

        if (vc1_decode_sprites(v, &s->gb))

            goto err;

#endif

        *pict      = v->sprite_output_frame;

        *data_size = sizeof(AVFrame);

    } else {

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

            *pict = s->current_picture_ptr->f;

        } else if (s->last_picture_ptr != NULL) {

            *pict = s->last_picture_ptr->f;

        }

        if (s->last_picture_ptr || s->low_delay) {

            *data_size = sizeof(AVFrame);

            ff_print_debug_info(s, pict);

        }

    }

end:

    av_free(buf2);

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

        av_free(slices[i].buf);

    av_free(slices);

    return buf_size;

err:

    av_free(buf2);

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

        av_free(slices[i].buf);

    av_free(slices);

    return -1;

}


void blk_apply_root_state(BlockBackend *blk, BlockDriverState *bs)

{

    bs->detect_zeroes = blk->root_state.detect_zeroes;

}