void do_interrupt (CPUState *env)

{

#if defined (CONFIG_USER_ONLY)

    env->exception_index |= 0x100;

#else

    uint32_t msr;

    int excp = env->exception_index;

    msr = _load_msr(env);

#if defined (DEBUG_EXCEPTIONS)

    if ((excp == EXCP_PROGRAM || excp == EXCP_DSI) && msr_pr == 1)

    {

        if (loglevel > 0) {

            fprintf(logfile, "Raise exception at 0x%08x => 0x%08x (%02x)\n",

                    env->nip, excp << 8, env->error_code);

    }

	if (loglevel > 0)

	    cpu_ppc_dump_state(env, logfile, 0);

    }

#endif

    /* Generate informations in save/restore registers */

    switch (excp) {

    case EXCP_OFCALL:

#if defined (USE_OPEN_FIRMWARE)

        env->gpr[3] = OF_client_entry((void *)env->gpr[3]);

#endif

        return;

    case EXCP_RTASCALL:

#if defined (USE_OPEN_FIRMWARE)

        printf("RTAS call !\n");

        env->gpr[3] = RTAS_entry((void *)env->gpr[3]);

        printf("RTAS call done\n");

#endif

        return;

    case EXCP_NONE:

        /* Do nothing */

#if defined (DEBUG_EXCEPTIONS)

        printf("%s: escape EXCP_NONE\n", __func__);

#endif

        return;

    case EXCP_RESET:

        if (msr_ip)

            excp += 0xFFC00;

        goto store_next;

    case EXCP_MACHINE_CHECK:

        if (msr_me == 0) {

            cpu_abort(env, "Machine check exception while not allowed\n");

        }

        msr_me = 0;

        break;

    case EXCP_DSI:

        /* Store exception cause */

        /* data location address has been stored

         * when the fault has been detected

     */

	msr &= ~0xFFFF0000;

	env->spr[DSISR] = 0;

	if (env->error_code &  EXCP_DSI_TRANSLATE)

	    env->spr[DSISR] |= 0x40000000;

	else if (env->error_code & EXCP_DSI_PROT)

	    env->spr[DSISR] |= 0x08000000;

	else if (env->error_code & EXCP_DSI_NOTSUP) {

	    env->spr[DSISR] |= 0x80000000;

	    if (env->error_code & EXCP_DSI_DIRECT)

		env->spr[DSISR] |= 0x04000000;

	}

	if (env->error_code & EXCP_DSI_STORE)

	    env->spr[DSISR] |= 0x02000000;

	if ((env->error_code & 0xF) == EXCP_DSI_DABR)

	    env->spr[DSISR] |= 0x00400000;

	if (env->error_code & EXCP_DSI_ECXW)

	    env->spr[DSISR] |= 0x00100000;

#if defined (DEBUG_EXCEPTIONS)

	if (loglevel) {

	    fprintf(logfile, "DSI exception: DSISR=0x%08x, DAR=0x%08x\n",

		    env->spr[DSISR], env->spr[DAR]);

	} else {

	    printf("DSI exception: DSISR=0x%08x, DAR=0x%08x nip=0x%08x\n",

		   env->spr[DSISR], env->spr[DAR], env->nip);

	}

#endif

        goto store_next;

    case EXCP_ISI:

        /* Store exception cause */

	msr &= ~0xFFFF0000;

        if (env->error_code == EXCP_ISI_TRANSLATE)

            msr |= 0x40000000;

        else if (env->error_code == EXCP_ISI_NOEXEC ||

		 env->error_code == EXCP_ISI_GUARD ||

		 env->error_code == EXCP_ISI_DIRECT)

            msr |= 0x10000000;

        else

            msr |= 0x08000000;

#if defined (DEBUG_EXCEPTIONS)

	if (loglevel) {

	    fprintf(logfile, "ISI exception: msr=0x%08x, nip=0x%08x\n",

		    msr, env->nip);

	} else {

	    printf("ISI exception: msr=0x%08x, nip=0x%08x tbl:0x%08x\n",

		   msr, env->nip, env->spr[V_TBL]);

	}

#endif

        goto store_next;

    case EXCP_EXTERNAL:

        if (msr_ee == 0) {

#if defined (DEBUG_EXCEPTIONS)

            if (loglevel > 0) {

                fprintf(logfile, "Skipping hardware interrupt\n");

    }

#endif

            /* Requeue it */

            do_raise_exception(EXCP_EXTERNAL);

            return;

            }

        goto store_next;

    case EXCP_ALIGN:

        /* Store exception cause */

        /* Get rS/rD and rA from faulting opcode */

        env->spr[DSISR] |=

            (ldl_code((void *)(env->nip - 4)) & 0x03FF0000) >> 16;

        /* data location address has been stored

         * when the fault has been detected

         */

        goto store_current;

    case EXCP_PROGRAM:

        msr &= ~0xFFFF0000;

        switch (env->error_code & ~0xF) {

        case EXCP_FP:

            if (msr_fe0 == 0 && msr_fe1 == 0) {

#if defined (DEBUG_EXCEPTIONS)

                printf("Ignore floating point exception\n");

#endif

                return;

        }

            msr |= 0x00100000;

            /* Set FX */

            env->fpscr[7] |= 0x8;

            /* Finally, update FEX */

            if ((((env->fpscr[7] & 0x3) << 3) | (env->fpscr[6] >> 1)) &

                ((env->fpscr[1] << 1) | (env->fpscr[0] >> 3)))

                env->fpscr[7] |= 0x4;

        break;

        case EXCP_INVAL:

            //	    printf("Invalid instruction at 0x%08x\n", env->nip);

            msr |= 0x00080000;

        break;

        case EXCP_PRIV:

            msr |= 0x00040000;

        break;

        case EXCP_TRAP:

            msr |= 0x00020000;

            break;

        default:

            /* Should never occur */

        break;

    }

        msr |= 0x00010000;

        goto store_current;

    case EXCP_NO_FP:

        goto store_current;

    case EXCP_DECR:

        if (msr_ee == 0) {

            /* Requeue it */

            do_raise_exception(EXCP_DECR);

            return;

        }

        goto store_next;

    case EXCP_SYSCALL:

#if defined (DEBUG_EXCEPTIONS)

	if (msr_pr) {

	    if (loglevel) {

		fprintf(logfile, "syscall %d 0x%08x 0x%08x 0x%08x 0x%08x\n",

			env->gpr[0], env->gpr[3], env->gpr[4],

			env->gpr[5], env->gpr[6]);

	    } else {

		printf("syscall %d from 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",

		       env->gpr[0], env->nip, env->gpr[3], env->gpr[4],

		       env->gpr[5], env->gpr[6]);

	    }

	}

#endif

        goto store_next;

    case EXCP_TRACE:

        goto store_next;

    case EXCP_FP_ASSIST:

        goto store_next;

    case EXCP_MTMSR:

        /* Nothing to do */

        return;

    case EXCP_BRANCH:

        /* Nothing to do */

        return;

    case EXCP_RFI:

        /* Restore user-mode state */

	tb_flush(env);

#if defined (DEBUG_EXCEPTIONS)

	if (msr_pr == 1)

	    printf("Return from exception => 0x%08x\n", (uint32_t)env->nip);

#endif

        return;

    store_current:

        /* SRR0 is set to current instruction */

        env->spr[SRR0] = (uint32_t)env->nip - 4;

        break;

    store_next:

        /* SRR0 is set to next instruction */

        env->spr[SRR0] = (uint32_t)env->nip;

        break;

    }

    env->spr[SRR1] = msr;

    /* reload MSR with correct bits */

    msr_pow = 0;

    msr_ee = 0;

    msr_pr = 0;

    msr_fp = 0;

    msr_fe0 = 0;

    msr_se = 0;

    msr_be = 0;

    msr_fe1 = 0;

    msr_ir = 0;

    msr_dr = 0;

    msr_ri = 0;

    msr_le = msr_ile;

    /* Jump to handler */

    env->nip = excp << 8;

    env->exception_index = EXCP_NONE;

    /* Invalidate all TLB as we may have changed translation mode */

    tlb_flush(env, 1);

    /* ensure that no TB jump will be modified as

       the program flow was changed */

#ifdef __sparc__

    tmp_T0 = 0;

#else

    T0 = 0;

#endif

#endif

    env->exception_index = -1;

}


int rom_add_blob(const char *name, const void *blob, size_t len,

                 target_phys_addr_t addr)

{

    Rom *rom;

    rom = g_malloc0(sizeof(*rom));

    rom->name    = g_strdup(name);

    rom->addr    = addr;

    rom->romsize = len;

    rom->data    = g_malloc0(rom->romsize);

    memcpy(rom->data, blob, len);

    rom_insert(rom);

    return 0;

}


static av_cold int decode_init_mp3on4(AVCodecContext * avctx)

{

    MP3On4DecodeContext *s = avctx->priv_data;

    MPEG4AudioConfig cfg;

    int i;

    if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {

        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");

        return AVERROR_INVALIDDATA;

    }

    avpriv_mpeg4audio_get_config(&cfg, avctx->extradata,

                                 avctx->extradata_size * 8, 1);

    if (!cfg.chan_config || cfg.chan_config > 7) {

        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");

        return AVERROR_INVALIDDATA;

    }

    s->frames             = mp3Frames[cfg.chan_config];

    s->coff               = chan_offset[cfg.chan_config];

    avctx->channels       = ff_mpeg4audio_channels[cfg.chan_config];

    avctx->channel_layout = chan_layout[cfg.chan_config];

    if (cfg.sample_rate < 16000)

        s->syncword = 0xffe00000;

    else

        s->syncword = 0xfff00000;

    /* Init the first mp3 decoder in standard way, so that all tables get builded

     * We replace avctx->priv_data with the context of the first decoder so that

     * decode_init() does not have to be changed.

     * Other decoders will be initialized here copying data from the first context

     */

    // Allocate zeroed memory for the first decoder context

    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));

    if (!s->mp3decctx[0])

        goto alloc_fail;

    // Put decoder context in place to make init_decode() happy

    avctx->priv_data = s->mp3decctx[0];

    decode_init(avctx);

    // Restore mp3on4 context pointer

    avctx->priv_data = s;

    s->mp3decctx[0]->adu_mode = 1; // Set adu mode

    /* Create a separate codec/context for each frame (first is already ok).

     * Each frame is 1 or 2 channels - up to 5 frames allowed

     */

    for (i = 1; i < s->frames; i++) {

        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));

        if (!s->mp3decctx[i])

            goto alloc_fail;

        s->mp3decctx[i]->adu_mode = 1;

        s->mp3decctx[i]->avctx = avctx;

        s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;

    }

    return 0;

alloc_fail:

    decode_close_mp3on4(avctx);

    return AVERROR(ENOMEM);

}


static void avc_luma_midv_qrt_and_aver_dst_8w_msa(const uint8_t *src,

                                                  int32_t src_stride,

                                                  uint8_t *dst,

                                                  int32_t dst_stride,

                                                  int32_t height,

                                                  uint8_t vert_offset)

{

    int32_t loop_cnt;

    v16i8 src0, src1, src2, src3, src4;

    v16u8 dst0, dst1, dst2, dst3;

    v16i8 mask0, mask1, mask2;

    v8i16 hz_out0, hz_out1, hz_out2, hz_out3;

    v8i16 hz_out4, hz_out5, hz_out6, hz_out7, hz_out8;

    v8i16 res0, res1, res2, res3;

    v8i16 res4, res5, res6, res7;

    LD_SB3(&luma_mask_arr[0], 16, mask0, mask1, mask2);

    LD_SB5(src, src_stride, src0, src1, src2, src3, src4);

    XORI_B5_128_SB(src0, src1, src2, src3, src4);

    src += (5 * src_stride);

    hz_out0 = AVC_HORZ_FILTER_SH(src0, mask0, mask1, mask2);

    hz_out1 = AVC_HORZ_FILTER_SH(src1, mask0, mask1, mask2);

    hz_out2 = AVC_HORZ_FILTER_SH(src2, mask0, mask1, mask2);

    hz_out3 = AVC_HORZ_FILTER_SH(src3, mask0, mask1, mask2);

    hz_out4 = AVC_HORZ_FILTER_SH(src4, mask0, mask1, mask2);

    for (loop_cnt = (height >> 2); loop_cnt--;) {

        LD_SB4(src, src_stride, src0, src1, src2, src3);

        XORI_B4_128_SB(src0, src1, src2, src3);

        src += (4 * src_stride);

        LD_UB4(dst, dst_stride, dst0, dst1, dst2, dst3);

        hz_out5 = AVC_HORZ_FILTER_SH(src0, mask0, mask1, mask2);

        hz_out6 = AVC_HORZ_FILTER_SH(src1, mask0, mask1, mask2);

        hz_out7 = AVC_HORZ_FILTER_SH(src2, mask0, mask1, mask2);

        hz_out8 = AVC_HORZ_FILTER_SH(src3, mask0, mask1, mask2);

        res0 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out0, hz_out1, hz_out2,

                                               hz_out3, hz_out4, hz_out5);

        res2 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out1, hz_out2, hz_out3,

                                               hz_out4, hz_out5, hz_out6);

        res4 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out2, hz_out3, hz_out4,

                                               hz_out5, hz_out6, hz_out7);

        res6 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out3, hz_out4, hz_out5,

                                               hz_out6, hz_out7, hz_out8);

        if (vert_offset) {

            res1 = __msa_srari_h(hz_out3, 5);

            res3 = __msa_srari_h(hz_out4, 5);

            res5 = __msa_srari_h(hz_out5, 5);

            res7 = __msa_srari_h(hz_out6, 5);

        } else {

            res1 = __msa_srari_h(hz_out2, 5);

            res3 = __msa_srari_h(hz_out3, 5);

            res5 = __msa_srari_h(hz_out4, 5);

            res7 = __msa_srari_h(hz_out5, 5);

        }

        SAT_SH4_SH(res1, res3, res5, res7, 7);

        res0 = __msa_aver_s_h(res0, res1);

        res1 = __msa_aver_s_h(res2, res3);

        res2 = __msa_aver_s_h(res4, res5);

        res3 = __msa_aver_s_h(res6, res7);

        ILVR_D2_UB(dst1, dst0, dst3, dst2, dst0, dst1);

        CONVERT_UB_AVG_ST8x4_UB(res0, res1, res2, res3, dst0, dst1,

                                dst, dst_stride);

        dst += (4 * dst_stride);

        hz_out0 = hz_out4;

        hz_out1 = hz_out5;

        hz_out2 = hz_out6;

        hz_out3 = hz_out7;

        hz_out4 = hz_out8;

    }

}


static const AVClass *filter_child_class_next(const AVClass *prev)

{

    AVFilter **f = NULL;

    while (prev && *(f = av_filter_next(f)))

        if ((*f)->priv_class == prev)

            break;

    while (*(f = av_filter_next(f)))

        if ((*f)->priv_class)

            return (*f)->priv_class;

    return NULL;

}


void qmp_output_visitor_cleanup(QmpOutputVisitor *v)

{

    QStackEntry *e, *tmp;

    QTAILQ_FOREACH_SAFE(e, &v->stack, node, tmp) {

        QTAILQ_REMOVE(&v->stack, e, node);

        if (e->value) {

            qobject_decref(e->value);

        }

        g_free(e);

    }

    g_free(v);

}


static int qemu_chr_open_udp(QemuOpts *opts, CharDriverState **_chr)

{

    CharDriverState *chr = NULL;

    NetCharDriver *s = NULL;

    int fd = -1;

    int ret;

    chr = g_malloc0(sizeof(CharDriverState));

    s = g_malloc0(sizeof(NetCharDriver));

    fd = inet_dgram_opts(opts);

    if (fd < 0) {

        fprintf(stderr, "inet_dgram_opts failed\n");

        ret = -errno;

        goto return_err;

    }

    s->fd = fd;

    s->bufcnt = 0;

    s->bufptr = 0;

    chr->opaque = s;

    chr->chr_write = udp_chr_write;

    chr->chr_update_read_handler = udp_chr_update_read_handler;

    chr->chr_close = udp_chr_close;

    *_chr = chr;

    return 0;

return_err:

    g_free(chr);

    g_free(s);

    if (fd >= 0) {

        closesocket(fd);

    }

    return ret;

}


void helper_wrpsr(CPUSPARCState *env, target_ulong new_psr)

{

    if ((new_psr & PSR_CWP) >= env->nwindows) {

        cpu_raise_exception_ra(env, TT_ILL_INSN, GETPC());

    } else {

        cpu_put_psr(env, new_psr);

    }

}


void helper_wrpstate(CPUSPARCState *env, target_ulong new_state)

{

    cpu_change_pstate(env, new_state & 0xf3f);

#if !defined(CONFIG_USER_ONLY)

    if (cpu_interrupts_enabled(env)) {

        cpu_check_irqs(env);

    }

#endif

}


void tb_flush(CPUState *cpu)

{

#if defined(DEBUG_FLUSH)

    printf("qemu: flush code_size=%ld nb_tbs=%d avg_tb_size=%ld\n",

           (unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer),

           tcg_ctx.tb_ctx.nb_tbs, tcg_ctx.tb_ctx.nb_tbs > 0 ?

           ((unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer)) /

           tcg_ctx.tb_ctx.nb_tbs : 0);

#endif

    if ((unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer)

        > tcg_ctx.code_gen_buffer_size) {

        cpu_abort(cpu, "Internal error: code buffer overflow\n");

    tcg_ctx.tb_ctx.nb_tbs = 0;

    CPU_FOREACH(cpu) {

        memset(cpu->tb_jmp_cache, 0, sizeof(cpu->tb_jmp_cache));

        cpu->tb_flushed = true;

    qht_reset_size(&tcg_ctx.tb_ctx.htable, CODE_GEN_HTABLE_SIZE);

    page_flush_tb();

    tcg_ctx.code_gen_ptr = tcg_ctx.code_gen_buffer;

    /* XXX: flush processor icache at this point if cache flush is

       expensive */

    tcg_ctx.tb_ctx.tb_flush_count++;


int register_savevm(DeviceState *dev,

                    const char *idstr,

                    int instance_id,

                    int version_id,

                    SaveStateHandler *save_state,

                    LoadStateHandler *load_state,

                    void *opaque)

{

    SaveVMHandlers *ops = g_malloc0(sizeof(SaveVMHandlers));

    ops->save_state = save_state;

    ops->load_state = load_state;

    return register_savevm_live(dev, idstr, instance_id, version_id,

                                ops, opaque);

}


static void test_validate_union(TestInputVisitorData *data,

                                 const void *unused)

{

    UserDefUnion *tmp = NULL;

    Visitor *v;

    Error *err = NULL;

    v = validate_test_init(data, "{ 'type': 'b', 'integer': 41, 'data' : { 'integer': 42 } }");

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

    g_assert(!err);

    qapi_free_UserDefUnion(tmp);

}


static av_always_inline void mpeg_motion_lowres(MpegEncContext *s,

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

                               int field_based, int bottom_field, int field_select,

                               uint8_t **ref_picture, h264_chroma_mc_func *pix_op,

                               int motion_x, int motion_y, int h)

{

    uint8_t *ptr_y, *ptr_cb, *ptr_cr;

    int mx, my, src_x, src_y, uvsrc_x, uvsrc_y, uvlinesize, linesize, sx, sy, uvsx, uvsy;

    const int lowres= s->avctx->lowres;

    const int block_s= 8>>lowres;

    const int s_mask= (2<<lowres)-1;

    const int h_edge_pos = s->h_edge_pos >> lowres;

    const int v_edge_pos = s->v_edge_pos >> lowres;

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

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

    if(s->quarter_sample){ //FIXME obviously not perfect but qpel wont work in lowres anyway

        motion_x/=2;

        motion_y/=2;

    }

    if(field_based){

        motion_y += (bottom_field - field_select)*((1<<lowres)-1);

    }

    sx= motion_x & s_mask;

    sy= motion_y & s_mask;

    src_x = s->mb_x*2*block_s               + (motion_x >> (lowres+1));

    src_y =(s->mb_y*2*block_s>>field_based) + (motion_y >> (lowres+1));

    if (s->out_format == FMT_H263) {

        uvsx = ((motion_x>>1) & s_mask) | (sx&1);

        uvsy = ((motion_y>>1) & s_mask) | (sy&1);

        uvsrc_x = src_x>>1;

        uvsrc_y = src_y>>1;

    }else if(s->out_format == FMT_H261){//even chroma mv's are full pel in H261

        mx = motion_x / 4;

        my = motion_y / 4;

        uvsx = (2*mx) & s_mask;

        uvsy = (2*my) & s_mask;

        uvsrc_x = s->mb_x*block_s               + (mx >> lowres);

        uvsrc_y = s->mb_y*block_s               + (my >> lowres);

    } else {

        mx = motion_x / 2;

        my = motion_y / 2;

        uvsx = mx & s_mask;

        uvsy = my & s_mask;

        uvsrc_x = s->mb_x*block_s               + (mx >> (lowres+1));

        uvsrc_y =(s->mb_y*block_s>>field_based) + (my >> (lowres+1));

    }

    ptr_y  = ref_picture[0] + src_y * linesize + src_x;

    ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;

    ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;

    if(   (unsigned)src_x > h_edge_pos                 - (!!sx) - 2*block_s

       || (unsigned)src_y >(v_edge_pos >> field_based) - (!!sy) - h){

            ff_emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize, 17, 17+field_based,

                             src_x, src_y<<field_based, h_edge_pos, v_edge_pos);

            ptr_y = s->edge_emu_buffer;

            if(!(s->flags&CODEC_FLAG_GRAY)){

                uint8_t *uvbuf= s->edge_emu_buffer+18*s->linesize;

                ff_emulated_edge_mc(uvbuf  , ptr_cb, s->uvlinesize, 9, 9+field_based,

                                 uvsrc_x, uvsrc_y<<field_based, h_edge_pos>>1, v_edge_pos>>1);

                ff_emulated_edge_mc(uvbuf+16, ptr_cr, s->uvlinesize, 9, 9+field_based,

                                 uvsrc_x, uvsrc_y<<field_based, h_edge_pos>>1, v_edge_pos>>1);

                ptr_cb= uvbuf;

                ptr_cr= uvbuf+16;

            }

    }

    if(bottom_field){ //FIXME use this for field pix too instead of the obnoxious hack which changes picture.data

        dest_y += s->linesize;

        dest_cb+= s->uvlinesize;

        dest_cr+= s->uvlinesize;

    }

    if(field_select){

        ptr_y += s->linesize;

        ptr_cb+= s->uvlinesize;

        ptr_cr+= s->uvlinesize;

    }

    sx <<= 2 - lowres;

    sy <<= 2 - lowres;

    pix_op[lowres-1](dest_y, ptr_y, linesize, h, sx, sy);

    if(!(s->flags&CODEC_FLAG_GRAY)){

        uvsx <<= 2 - lowres;

        uvsy <<= 2 - lowres;

        pix_op[lowres](dest_cb, ptr_cb, uvlinesize, h >> s->chroma_y_shift, uvsx, uvsy);

        pix_op[lowres](dest_cr, ptr_cr, uvlinesize, h >> s->chroma_y_shift, uvsx, uvsy);

    }

    //FIXME h261 lowres loop filter

}


static int encode_slice_plane(AVCodecContext *avctx, int mb_count,

        uint8_t *src, int src_stride, uint8_t *buf, unsigned buf_size,

        int *qmat, int chroma)

{

    ProresContext* ctx = avctx->priv_data;

    FDCTDSPContext *fdsp = &ctx->fdsp;

    DECLARE_ALIGNED(16, int16_t, blocks)[DEFAULT_SLICE_MB_WIDTH << 8], *block;

    int i, blocks_per_slice;

    PutBitContext pb;

    block = blocks;

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

        fdct_get(fdsp, src,                  src_stride, block + (0 << 6));

        fdct_get(fdsp, src + 8 * src_stride, src_stride, block + ((2 - chroma) << 6));

        if (!chroma) {

            fdct_get(fdsp, src + 16,                  src_stride, block + (1 << 6));

            fdct_get(fdsp, src + 16 + 8 * src_stride, src_stride, block + (3 << 6));

        }

        block += (256 >> chroma);

        src   += (32  >> chroma);

    }

    blocks_per_slice = mb_count << (2 - chroma);

    init_put_bits(&pb, buf, buf_size << 3);

    encode_dc_coeffs(&pb, blocks, blocks_per_slice, qmat);

    encode_ac_coeffs(avctx, &pb, blocks, blocks_per_slice, qmat);

    flush_put_bits(&pb);

    return put_bits_ptr(&pb) - pb.buf;

}


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

                                        intptr_t sy, int ady, int adx,

                                        float *buf)

{

    int err = -adx;

    x -= x1 - 1;

    buf += x1 - 1;

    while (++x < 0) {

        err += ady;

        if (err >= 0) {

            err += ady - adx;

            y   += sy;

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

        }

        buf[x] = ff_vorbis_floor1_inverse_db_table[y];

    }

    if (x <= 0) {

        if (err + ady >= 0)

            y += sy;

        buf[x] = ff_vorbis_floor1_inverse_db_table[y];

    }

}


static int webm_dash_manifest_write_trailer(AVFormatContext *s)

{

    WebMDashMuxContext *w = s->priv_data;

    int i;

    for (i = 0; i < w->nb_as; i++) {

        av_freep(&w->as[i].streams);

    }

    av_freep(&w->as);

    return 0;

}


void test_misc(void)

{

    char table[256];

    long res, i;

    for(i=0;i<256;i++) table[i] = 256 - i;

    res = 0x12345678;

    asm ("xlat" : "=a" (res) : "b" (table), "0" (res));

    printf("xlat: EAX=" FMTLX "\n", res);

#if defined(__x86_64__)

#if 0

    {

        /* XXX: see if Intel Core2 and AMD64 behavior really

           differ. Here we implemented the Intel way which is not

           compatible yet with QEMU. */

        static struct __attribute__((packed)) {

            uint64_t offset;

            uint16_t seg;

        } desc;

        long cs_sel;

        asm volatile ("mov %%cs, %0" : "=r" (cs_sel));

        asm volatile ("push %1\n"

                      "call func_lret\n"

                      : "=a" (res)

                      : "r" (cs_sel) : "memory", "cc");

        printf("func_lret=" FMTLX "\n", res);

        desc.offset = (long)&func_lret;

        desc.seg = cs_sel;

        asm volatile ("xor %%rax, %%rax\n"

                      "rex64 lcall *(%%rcx)\n"

                      : "=a" (res)

                      : "c" (&desc)

                      : "memory", "cc");

        printf("func_lret2=" FMTLX "\n", res);

        asm volatile ("push %2\n"

                      "mov $ 1f, %%rax\n"

                      "push %%rax\n"

                      "rex64 ljmp *(%%rcx)\n"

                      "1:\n"

                      : "=a" (res)

                      : "c" (&desc), "b" (cs_sel)

                      : "memory", "cc");

        printf("func_lret3=" FMTLX "\n", res);

    }

#endif

#else

    asm volatile ("push %%cs ; call %1"

                  : "=a" (res)

                  : "m" (func_lret): "memory", "cc");

    printf("func_lret=" FMTLX "\n", res);

    asm volatile ("pushf ; push %%cs ; call %1"

                  : "=a" (res)

                  : "m" (func_iret): "memory", "cc");

    printf("func_iret=" FMTLX "\n", res);

#endif

#if defined(__x86_64__)

    /* specific popl test */

    asm volatile ("push $12345432 ; push $0x9abcdef ; pop (%%rsp) ; pop %0"

                  : "=g" (res));

    printf("popl esp=" FMTLX "\n", res);

#else

    /* specific popl test */

    asm volatile ("pushl $12345432 ; pushl $0x9abcdef ; popl (%%esp) ; popl %0"

                  : "=g" (res));

    printf("popl esp=" FMTLX "\n", res);

    /* specific popw test */

    asm volatile ("pushl $12345432 ; pushl $0x9abcdef ; popw (%%esp) ; addl $2, %%esp ; popl %0"

                  : "=g" (res));

    printf("popw esp=" FMTLX "\n", res);

#endif

}


static int pci_rtl8139_init(PCIDevice *dev)

{

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

    uint8_t *pci_conf;

    pci_conf = s->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_REALTEK);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_REALTEK_8139);

    pci_conf[PCI_REVISION_ID] = RTL8139_PCI_REVID; /* >=0x20 is for 8139C+ */

    pci_config_set_class(pci_conf, PCI_CLASS_NETWORK_ETHERNET);

    pci_conf[PCI_INTERRUPT_PIN] = 1;    /* interrupt pin 0 */

    /* TODO: start of capability list, but no capability

     * list bit in status register, and offset 0xdc seems unused. */

    pci_conf[PCI_CAPABILITY_LIST] = 0xdc;

    /* I/O handler for memory-mapped I/O */

    s->rtl8139_mmio_io_addr =

        cpu_register_io_memory(rtl8139_mmio_read, rtl8139_mmio_write, s,

                               DEVICE_LITTLE_ENDIAN);

    pci_register_bar(&s->dev, 0, 0x100,

                           PCI_BASE_ADDRESS_SPACE_IO,  rtl8139_ioport_map);

    pci_register_bar_simple(&s->dev, 1, 0x100, 0, s->rtl8139_mmio_io_addr);

    qemu_macaddr_default_if_unset(&s->conf.macaddr);

    /* prepare eeprom */

    s->eeprom.contents[0] = 0x8129;

#if 1

    /* PCI vendor and device ID should be mirrored here */

    s->eeprom.contents[1] = PCI_VENDOR_ID_REALTEK;

    s->eeprom.contents[2] = PCI_DEVICE_ID_REALTEK_8139;

#endif

    s->eeprom.contents[7] = s->conf.macaddr.a[0] | s->conf.macaddr.a[1] << 8;

    s->eeprom.contents[8] = s->conf.macaddr.a[2] | s->conf.macaddr.a[3] << 8;

    s->eeprom.contents[9] = s->conf.macaddr.a[4] | s->conf.macaddr.a[5] << 8;

    s->nic = qemu_new_nic(&net_rtl8139_info, &s->conf,

                          dev->qdev.info->name, dev->qdev.id, s);

    qemu_format_nic_info_str(&s->nic->nc, s->conf.macaddr.a);

    s->cplus_txbuffer = NULL;

    s->cplus_txbuffer_len = 0;

    s->cplus_txbuffer_offset = 0;

    s->TimerExpire = 0;

    s->timer = qemu_new_timer_ns(vm_clock, rtl8139_timer, s);

    rtl8139_set_next_tctr_time(s, qemu_get_clock_ns(vm_clock));

    add_boot_device_path(s->conf.bootindex, &dev->qdev, "/ethernet-phy@0");

    return 0;

}


void ff_rv40dsp_init_neon(RV34DSPContext *c, DSPContext* dsp)

{

    c->put_pixels_tab[0][ 1] = ff_put_rv40_qpel16_mc10_neon;

    c->put_pixels_tab[0][ 3] = ff_put_rv40_qpel16_mc30_neon;

    c->put_pixels_tab[0][ 4] = ff_put_rv40_qpel16_mc01_neon;

    c->put_pixels_tab[0][ 5] = ff_put_rv40_qpel16_mc11_neon;

    c->put_pixels_tab[0][ 6] = ff_put_rv40_qpel16_mc21_neon;

    c->put_pixels_tab[0][ 7] = ff_put_rv40_qpel16_mc31_neon;

    c->put_pixels_tab[0][ 9] = ff_put_rv40_qpel16_mc12_neon;

    c->put_pixels_tab[0][10] = ff_put_rv40_qpel16_mc22_neon;

    c->put_pixels_tab[0][11] = ff_put_rv40_qpel16_mc32_neon;

    c->put_pixels_tab[0][12] = ff_put_rv40_qpel16_mc03_neon;

    c->put_pixels_tab[0][13] = ff_put_rv40_qpel16_mc13_neon;

    c->put_pixels_tab[0][14] = ff_put_rv40_qpel16_mc23_neon;

    c->put_pixels_tab[0][15] = ff_put_rv40_qpel16_mc33_neon;

    c->avg_pixels_tab[0][ 1] = ff_avg_rv40_qpel16_mc10_neon;

    c->avg_pixels_tab[0][ 3] = ff_avg_rv40_qpel16_mc30_neon;

    c->avg_pixels_tab[0][ 4] = ff_avg_rv40_qpel16_mc01_neon;

    c->avg_pixels_tab[0][ 5] = ff_avg_rv40_qpel16_mc11_neon;

    c->avg_pixels_tab[0][ 6] = ff_avg_rv40_qpel16_mc21_neon;

    c->avg_pixels_tab[0][ 7] = ff_avg_rv40_qpel16_mc31_neon;

    c->avg_pixels_tab[0][ 9] = ff_avg_rv40_qpel16_mc12_neon;

    c->avg_pixels_tab[0][10] = ff_avg_rv40_qpel16_mc22_neon;

    c->avg_pixels_tab[0][11] = ff_avg_rv40_qpel16_mc32_neon;

    c->avg_pixels_tab[0][12] = ff_avg_rv40_qpel16_mc03_neon;

    c->avg_pixels_tab[0][13] = ff_avg_rv40_qpel16_mc13_neon;

    c->avg_pixels_tab[0][14] = ff_avg_rv40_qpel16_mc23_neon;

    c->avg_pixels_tab[0][15] = ff_avg_rv40_qpel16_mc33_neon;

    c->put_pixels_tab[1][ 1] = ff_put_rv40_qpel8_mc10_neon;

    c->put_pixels_tab[1][ 3] = ff_put_rv40_qpel8_mc30_neon;

    c->put_pixels_tab[1][ 4] = ff_put_rv40_qpel8_mc01_neon;

    c->put_pixels_tab[1][ 5] = ff_put_rv40_qpel8_mc11_neon;

    c->put_pixels_tab[1][ 6] = ff_put_rv40_qpel8_mc21_neon;

    c->put_pixels_tab[1][ 7] = ff_put_rv40_qpel8_mc31_neon;

    c->put_pixels_tab[1][ 9] = ff_put_rv40_qpel8_mc12_neon;

    c->put_pixels_tab[1][10] = ff_put_rv40_qpel8_mc22_neon;

    c->put_pixels_tab[1][11] = ff_put_rv40_qpel8_mc32_neon;

    c->put_pixels_tab[1][12] = ff_put_rv40_qpel8_mc03_neon;

    c->put_pixels_tab[1][13] = ff_put_rv40_qpel8_mc13_neon;

    c->put_pixels_tab[1][14] = ff_put_rv40_qpel8_mc23_neon;

    c->put_pixels_tab[1][15] = ff_put_rv40_qpel8_mc33_neon;

    c->avg_pixels_tab[1][ 1] = ff_avg_rv40_qpel8_mc10_neon;

    c->avg_pixels_tab[1][ 3] = ff_avg_rv40_qpel8_mc30_neon;

    c->avg_pixels_tab[1][ 4] = ff_avg_rv40_qpel8_mc01_neon;

    c->avg_pixels_tab[1][ 5] = ff_avg_rv40_qpel8_mc11_neon;

    c->avg_pixels_tab[1][ 6] = ff_avg_rv40_qpel8_mc21_neon;

    c->avg_pixels_tab[1][ 7] = ff_avg_rv40_qpel8_mc31_neon;

    c->avg_pixels_tab[1][ 9] = ff_avg_rv40_qpel8_mc12_neon;

    c->avg_pixels_tab[1][10] = ff_avg_rv40_qpel8_mc22_neon;

    c->avg_pixels_tab[1][11] = ff_avg_rv40_qpel8_mc32_neon;

    c->avg_pixels_tab[1][12] = ff_avg_rv40_qpel8_mc03_neon;

    c->avg_pixels_tab[1][13] = ff_avg_rv40_qpel8_mc13_neon;

    c->avg_pixels_tab[1][14] = ff_avg_rv40_qpel8_mc23_neon;

    c->avg_pixels_tab[1][15] = ff_avg_rv40_qpel8_mc33_neon;

    c->put_chroma_pixels_tab[0] = ff_put_rv40_chroma_mc8_neon;

    c->put_chroma_pixels_tab[1] = ff_put_rv40_chroma_mc4_neon;

    c->avg_chroma_pixels_tab[0] = ff_avg_rv40_chroma_mc8_neon;

    c->avg_chroma_pixels_tab[1] = ff_avg_rv40_chroma_mc4_neon;

    c->rv40_weight_pixels_tab[0][0] = ff_rv40_weight_func_16_neon;

    c->rv40_weight_pixels_tab[0][1] = ff_rv40_weight_func_8_neon;

    c->rv40_loop_filter_strength[0] = ff_rv40_h_loop_filter_strength_neon;

    c->rv40_loop_filter_strength[1] = ff_rv40_v_loop_filter_strength_neon;

    c->rv40_weak_loop_filter[0]     = ff_rv40_h_weak_loop_filter_neon;

    c->rv40_weak_loop_filter[1]     = ff_rv40_v_weak_loop_filter_neon;

}


VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,

                                                     void *opaque)

{

    VMChangeStateEntry *e;

    e = qemu_mallocz(sizeof (*e));

    e->cb = cb;

    e->opaque = opaque;

    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);

    return e;

}


static int ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band,

                             IVITile *tile, AVCodecContext *avctx)

{

    int mbn, blk, num_blocks, blk_size, ret, is_intra, mc_type = 0;

    int mv_x = 0, mv_y = 0;

    int32_t prev_dc;

    uint32_t cbp, quant, buf_offs;

    IVIMbInfo *mb;

    ivi_mc_func mc_with_delta_func, mc_no_delta_func;

    const uint8_t *scale_tab;

    /* init intra prediction for the DC coefficient */

    prev_dc    = 0;

    blk_size   = band->blk_size;

    /* number of blocks per mb */

    num_blocks = (band->mb_size != blk_size) ? 4 : 1;

    if (blk_size == 8) {

        mc_with_delta_func = ff_ivi_mc_8x8_delta;

        mc_no_delta_func   = ff_ivi_mc_8x8_no_delta;

    } else {

        mc_with_delta_func = ff_ivi_mc_4x4_delta;

        mc_no_delta_func   = ff_ivi_mc_4x4_no_delta;

    }

    for (mbn = 0, mb = tile->mbs; mbn < tile->num_MBs; mb++, mbn++) {

        is_intra = !mb->type;

        cbp      = mb->cbp;

        buf_offs = mb->buf_offs;

        quant = band->glob_quant + mb->q_delta;

        if (avctx->codec_id == AV_CODEC_ID_INDEO4)

            quant = av_clip(quant, 0, 31);

        else

            quant = av_clip(quant, 0, 23);

        scale_tab = is_intra ? band->intra_scale : band->inter_scale;

        if (scale_tab)

            quant = scale_tab[quant];

        if (!is_intra) {

            mv_x = mb->mv_x;

            mv_y = mb->mv_y;

            if (band->is_halfpel) {

                mc_type = ((mv_y & 1) << 1) | (mv_x & 1);

                mv_x >>= 1;

                mv_y >>= 1; /* convert halfpel vectors into fullpel ones */

            }

            if (mb->type) {

                int dmv_x, dmv_y, cx, cy;

                dmv_x = mb->mv_x >> band->is_halfpel;

                dmv_y = mb->mv_y >> band->is_halfpel;

                cx    = mb->mv_x &  band->is_halfpel;

                cy    = mb->mv_y &  band->is_halfpel;

                if (mb->xpos + dmv_x < 0 ||

                    mb->xpos + dmv_x + band->mb_size + cx > band->pitch ||

                    mb->ypos + dmv_y < 0 ||

                    mb->ypos + dmv_y + band->mb_size + cy > band->aheight) {

                    return AVERROR_INVALIDDATA;

                }

            }

        }

        for (blk = 0; blk < num_blocks; blk++) {

            /* adjust block position in the buffer according to its number */

            if (blk & 1) {

                buf_offs += blk_size;

            } else if (blk == 2) {

                buf_offs -= blk_size;

                buf_offs += blk_size * band->pitch;

            }

            if (cbp & 1) { /* block coded ? */

                ret = ivi_decode_coded_blocks(gb, band, mc_with_delta_func,

                                              mv_x, mv_y, &prev_dc, is_intra,

                                              mc_type, quant, buf_offs, avctx);

                if (ret < 0)

                    return ret;

            } else {

                /* block not coded */

                /* for intra blocks apply the dc slant transform */

                /* for inter - perform the motion compensation without delta */

                if (is_intra) {

                    if (band->dc_transform)

                        band->dc_transform(&prev_dc, band->buf + buf_offs,

                                           band->pitch, blk_size);

                } else {

                    ret = ivi_mc(mc_no_delta_func, band->buf, band->ref_buf,

                                 buf_offs, mv_x, mv_y, band->pitch, mc_type);

                    if (ret < 0)

                        return ret;

                }

            }

            cbp >>= 1;

        }// for blk

    }// for mbn

    align_get_bits(gb);

    return 0;

}


static void rtas_read_pci_config(sPAPREnvironment *spapr,

                                 uint32_t token, uint32_t nargs,

                                 target_ulong args,

                                 uint32_t nret, target_ulong rets)

{

    uint32_t val, size, addr;

    PCIDevice *dev = find_dev(spapr, 0, rtas_ld(args, 0));

    if (!dev) {

        rtas_st(rets, 0, -1);

        return;

    }

    size = rtas_ld(args, 1);

    addr = rtas_pci_cfgaddr(rtas_ld(args, 0));

    val = pci_host_config_read_common(dev, addr, pci_config_size(dev), size);

    rtas_st(rets, 0, 0);

    rtas_st(rets, 1, val);

}


void qmp_dump_guest_memory(bool paging, const char *file, bool has_begin,

                           int64_t begin, bool has_length, int64_t length,

                           Error **errp)

{

    const char *p;

    int fd = -1;

    DumpState *s;

    int ret;

    if (has_begin && !has_length) {

        error_set(errp, QERR_MISSING_PARAMETER, "length");

        return;

    }

    if (!has_begin && has_length) {

        error_set(errp, QERR_MISSING_PARAMETER, "begin");

        return;

    }

#if !defined(WIN32)

    if (strstart(file, "fd:", &p)) {

        fd = monitor_get_fd(cur_mon, p, errp);

        if (fd == -1) {

            return;

        }

    }

#endif

    if  (strstart(file, "file:", &p)) {

        fd = qemu_open(p, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IRUSR);

        if (fd < 0) {

            error_setg_file_open(errp, errno, p);

            return;

        }

    }

    if (fd == -1) {

        error_set(errp, QERR_INVALID_PARAMETER, "protocol");

        return;

    }

    s = g_malloc(sizeof(DumpState));

    ret = dump_init(s, fd, paging, has_begin, begin, length, errp);

    if (ret < 0) {

        g_free(s);

        return;

    }

    if (create_vmcore(s) < 0 && !error_is_set(s->errp)) {

        error_set(errp, QERR_IO_ERROR);

    }

    g_free(s);

}


static bool bdrv_requests_pending(BlockDriverState *bs)

{

    if (!QLIST_EMPTY(&bs->tracked_requests)) {

        return true;

    }

    if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {

        return true;

    }

    if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {

        return true;

    }

    if (bs->file && bdrv_requests_pending(bs->file)) {

        return true;

    }

    if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {

        return true;

    }

    return false;

}


void checkasm_check_fixed_dsp(void)

{

    LOCAL_ALIGNED_32(int32_t, src0, [BUF_SIZE]);

    LOCAL_ALIGNED_32(int32_t, src1, [BUF_SIZE]);

    LOCAL_ALIGNED_32(int32_t, src2, [BUF_SIZE]);

    AVFixedDSPContext *fdsp = avpriv_alloc_fixed_dsp(1);

    randomize_buffers();

    if (check_func(fdsp->vector_fmul, "vector_fmul"))

        check_vector_fmul(src0, src1);

    if (check_func(fdsp->vector_fmul_add, "vector_fmul_add"))

        check_vector_fmul_add(src0, src1, src2);

    if (check_func(fdsp->vector_fmul_reverse, "vector_fmul_reverse"))

        check_vector_fmul(src0, src1);

    if (check_func(fdsp->vector_fmul_window, "vector_fmul_window"))

        check_vector_fmul_window(src0, src1, src2);

    if (check_func(fdsp->vector_fmul_window_scaled, "vector_fmul_window_scaled"))

        check_vector_fmul_window_scaled(src0, src1, src2);

    report("vector_fmul");

    if (check_func(fdsp->butterflies_fixed, "butterflies_fixed"))

        check_butterflies(src0, src1);

    report("butterflies_fixed");

    if (check_func(fdsp->scalarproduct_fixed, "scalarproduct_fixed"))

        check_scalarproduct_fixed(src0, src1);

    report("scalarproduct_fixed");

    av_freep(&fdsp);

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = etsec_realize;

    dc->reset = etsec_reset;

    dc->props = etsec_properties;

}


int ff_read_riff_info(AVFormatContext *s, int64_t size)

{

    int64_t start, end, cur;

    AVIOContext *pb = s->pb;

    start = avio_tell(pb);

    end = start + size;

    while ((cur = avio_tell(pb)) >= 0 && cur <= end - 8 /* = tag + size */) {

        uint32_t chunk_code;

        int64_t chunk_size;

        char key[5] = {0};

        char *value;

        chunk_code = avio_rl32(pb);

        chunk_size = avio_rl32(pb);

        if (chunk_size > end || end - chunk_size < cur || chunk_size == UINT_MAX) {

            avio_seek(pb, -9, SEEK_CUR);

            chunk_code = avio_rl32(pb);

            chunk_size = avio_rl32(pb);

            if (chunk_size > end || end - chunk_size < cur || chunk_size == UINT_MAX) {

                av_log(s, AV_LOG_WARNING, "too big INFO subchunk\n");

                return AVERROR_INVALIDDATA;

            }

        }

        chunk_size += (chunk_size & 1);

        if (!chunk_code) {

            if (chunk_size)

                avio_skip(pb, chunk_size);

            continue;

        }

        value = av_mallocz(chunk_size + 1);

        if (!value) {

            av_log(s, AV_LOG_ERROR, "out of memory, unable to read INFO tag\n");

            return AVERROR(ENOMEM);

        }

        AV_WL32(key, chunk_code);

        if (avio_read(pb, value, chunk_size) != chunk_size) {

            av_log(s, AV_LOG_WARNING, "premature end of file while reading INFO tag\n");

        }

        av_dict_set(&s->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);

    }

    return 0;

}


void ff_mpeg_flush(AVCodecContext *avctx){

    int i;

    MpegEncContext *s = avctx->priv_data;

    if(s==NULL || s->picture==NULL)

        return;

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

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

    s->current_picture_ptr = s->last_picture_ptr = s->next_picture_ptr = NULL;

    ff_mpeg_unref_picture(s, &s->current_picture);

    ff_mpeg_unref_picture(s, &s->last_picture);

    ff_mpeg_unref_picture(s, &s->next_picture);

    s->mb_x= s->mb_y= 0;

    s->parse_context.state= -1;

    s->parse_context.frame_start_found= 0;

    s->parse_context.overread= 0;

    s->parse_context.overread_index= 0;

    s->parse_context.index= 0;

    s->parse_context.last_index= 0;

    s->bitstream_buffer_size=0;

    s->pp_time=0;

}


static int bdrv_qed_is_allocated(BlockDriverState *bs, int64_t sector_num,

                                  int nb_sectors, int *pnum)

{

    BDRVQEDState *s = bs->opaque;

    uint64_t pos = (uint64_t)sector_num * BDRV_SECTOR_SIZE;

    size_t len = (size_t)nb_sectors * BDRV_SECTOR_SIZE;

    QEDIsAllocatedCB cb = {

        .is_allocated = -1,

        .pnum = pnum,

    };

    QEDRequest request = { .l2_table = NULL };

    async_context_push();

    qed_find_cluster(s, &request, pos, len, qed_is_allocated_cb, &cb);

    while (cb.is_allocated == -1) {

        qemu_aio_wait();

    }

    async_context_pop();

    qed_unref_l2_cache_entry(request.l2_table);

    return cb.is_allocated;

}


static int rwpipe_read_ppm_header( rwpipe *rw, int *width, int *height )

{

    char line[ 3 ];

    FILE *in = rwpipe_reader( rw );

    int max;

    fgets( line, 3, in );

    if ( !strncmp( line, "P6", 2 ) )

    {

        *width = rwpipe_read_number( rw );

        *height = rwpipe_read_number( rw );

        max = rwpipe_read_number( rw );

        return max != 255 || *width <= 0 || *height <= 0;

    }

    return 1;

}


static int vhost_user_get_u64(struct vhost_dev *dev, int request, uint64_t *u64)

{

    VhostUserMsg msg = {

        .request = request,

        .flags = VHOST_USER_VERSION,

    };

    if (vhost_user_one_time_request(request) && dev->vq_index != 0) {

        return 0;

    }

    vhost_user_write(dev, &msg, NULL, 0);

    if (vhost_user_read(dev, &msg) < 0) {

        return 0;

    }

    if (msg.request != request) {

        error_report("Received unexpected msg type. Expected %d received %d",

                     request, msg.request);

        return -1;

    }

    if (msg.size != sizeof(m.u64)) {

        error_report("Received bad msg size.");

        return -1;

    }

    *u64 = msg.u64;

    return 0;

}


static int crc_write_header(struct AVFormatContext *s)

{

    CRCState *crc = s->priv_data;

    /* init CRC */

    crc->crcval = adler32(0, NULL, 0);

    return 0;

}


ObjectClass *object_class_dynamic_cast_assert(ObjectClass *class,

                                              const char *typename,

                                              const char *file, int line,

                                              const char *func)

{

    ObjectClass *ret = object_class_dynamic_cast(class, typename);

    if (!ret && class) {

        fprintf(stderr, "%s:%d:%s: Object %p is not an instance of type %s\n",

                file, line, func, class, typename);

        abort();

    }

    return ret;

}


static void nvme_set_bootindex(Object *obj, Visitor *v, void *opaque,

                                  const char *name, Error **errp)

{

    NvmeCtrl *s = NVME(obj);

    int32_t boot_index;

    Error *local_err = NULL;

    visit_type_int32(v, &boot_index, name, &local_err);

    if (local_err) {

        goto out;

    }

    /* check whether bootindex is present in fw_boot_order list  */

    check_boot_index(boot_index, &local_err);

    if (local_err) {

        goto out;

    }

    /* change bootindex to a new one */

    s->conf.bootindex = boot_index;

out:

    if (local_err) {

        error_propagate(errp, local_err);

    }

}


static av_cold int initFilter(int16_t **outFilter, int32_t **filterPos,

                              int *outFilterSize, int xInc, int srcW,

                              int dstW, int filterAlign, int one,

                              int flags, int cpu_flags,

                              SwsVector *srcFilter, SwsVector *dstFilter,

                              double param[2], int is_horizontal)

{

    int i;

    int filterSize;

    int filter2Size;

    int minFilterSize;

    int64_t *filter    = NULL;

    int64_t *filter2   = NULL;

    const int64_t fone = 1LL << 54;

    int ret            = -1;

    emms_c(); // FIXME should not be required but IS (even for non-MMX versions)

    // NOTE: the +3 is for the MMX(+1) / SSE(+3) scaler which reads over the end

    FF_ALLOC_OR_GOTO(NULL, *filterPos, (dstW + 3) * sizeof(**filterPos), fail);

    if (FFABS(xInc - 0x10000) < 10) { // unscaled

        int i;

        filterSize = 1;

        FF_ALLOCZ_OR_GOTO(NULL, filter,

                          dstW * sizeof(*filter) * filterSize, fail);

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

            filter[i * filterSize] = fone;

            (*filterPos)[i]        = i;

        }

    } else if (flags & SWS_POINT) { // lame looking point sampling mode

        int i;

        int xDstInSrc;

        filterSize = 1;

        FF_ALLOC_OR_GOTO(NULL, filter,

                         dstW * sizeof(*filter) * filterSize, fail);

        xDstInSrc = xInc / 2 - 0x8000;

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

            int xx = (xDstInSrc - ((filterSize - 1) << 15) + (1 << 15)) >> 16;

            (*filterPos)[i] = xx;

            filter[i]       = fone;

            xDstInSrc      += xInc;

        }

    } else if ((xInc <= (1 << 16) && (flags & SWS_AREA)) ||

               (flags & SWS_FAST_BILINEAR)) { // bilinear upscale

        int i;

        int xDstInSrc;

        filterSize = 2;

        FF_ALLOC_OR_GOTO(NULL, filter,

                         dstW * sizeof(*filter) * filterSize, fail);

        xDstInSrc = xInc / 2 - 0x8000;

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

            int xx = (xDstInSrc - ((filterSize - 1) << 15) + (1 << 15)) >> 16;

            int j;

            (*filterPos)[i] = xx;

            // bilinear upscale / linear interpolate / area averaging

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

                int64_t coeff = fone - FFABS((xx << 16) - xDstInSrc) *

                                (fone >> 16);

                if (coeff < 0)

                    coeff = 0;

                filter[i * filterSize + j] = coeff;

                xx++;

            }

            xDstInSrc += xInc;

        }

    } else {

        int64_t xDstInSrc;

        int sizeFactor;

        if (flags & SWS_BICUBIC)

            sizeFactor = 4;

        else if (flags & SWS_X)

            sizeFactor = 8;

        else if (flags & SWS_AREA)

            sizeFactor = 1;     // downscale only, for upscale it is bilinear

        else if (flags & SWS_GAUSS)

            sizeFactor = 8;     // infinite ;)

        else if (flags & SWS_LANCZOS)

            sizeFactor = param[0] != SWS_PARAM_DEFAULT ? ceil(2 * param[0]) : 6;

        else if (flags & SWS_SINC)

            sizeFactor = 20;    // infinite ;)

        else if (flags & SWS_SPLINE)

            sizeFactor = 20;    // infinite ;)

        else if (flags & SWS_BILINEAR)

            sizeFactor = 2;

        else {

            sizeFactor = 0;     // GCC warning killer

            assert(0);

        }

        if (xInc <= 1 << 16)

            filterSize = 1 + sizeFactor;    // upscale

        else

            filterSize = 1 + (sizeFactor * srcW + dstW - 1) / dstW;

        filterSize = FFMIN(filterSize, srcW - 2);

        filterSize = FFMAX(filterSize, 1);

        FF_ALLOC_OR_GOTO(NULL, filter,

                         dstW * sizeof(*filter) * filterSize, fail);

        xDstInSrc = xInc - 0x10000;

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

            int xx = (xDstInSrc - ((filterSize - 2) << 16)) / (1 << 17);

            int j;

            (*filterPos)[i] = xx;

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

                int64_t d = (FFABS(((int64_t)xx << 17) - xDstInSrc)) << 13;

                double floatd;

                int64_t coeff;

                if (xInc > 1 << 16)

                    d = d * dstW / srcW;

                floatd = d * (1.0 / (1 << 30));

                if (flags & SWS_BICUBIC) {

                    int64_t B = (param[0] != SWS_PARAM_DEFAULT ? param[0] :   0) * (1 << 24);

                    int64_t C = (param[1] != SWS_PARAM_DEFAULT ? param[1] : 0.6) * (1 << 24);

                    if (d >= 1LL << 31) {

                        coeff = 0.0;

                    } else {

                        int64_t dd  = (d  * d) >> 30;

                        int64_t ddd = (dd * d) >> 30;

                        if (d < 1LL << 30)

                            coeff =  (12 * (1 << 24) -  9 * B - 6 * C) * ddd +

                                    (-18 * (1 << 24) + 12 * B + 6 * C) *  dd +

                                      (6 * (1 << 24) -  2 * B)         * (1 << 30);

                        else

                            coeff =      (-B -  6 * C) * ddd +

                                      (6 * B + 30 * C) * dd  +

                                    (-12 * B - 48 * C) * d   +

                                      (8 * B + 24 * C) * (1 << 30);

                    }

                    coeff *= fone >> (30 + 24);

                }

#if 0

                else if (flags & SWS_X) {

                    double p  = param ? param * 0.01 : 0.3;

                    coeff     = d ? sin(d * M_PI) / (d * M_PI) : 1.0;

                    coeff    *= pow(2.0, -p * d * d);

                }

#endif

                else if (flags & SWS_X) {

                    double A = param[0] != SWS_PARAM_DEFAULT ? param[0] : 1.0;

                    double c;

                    if (floatd < 1.0)

                        c = cos(floatd * M_PI);

                    else

                        c = -1.0;

                    if (c < 0.0)

                        c = -pow(-c, A);

                    else

                        c = pow(c, A);

                    coeff = (c * 0.5 + 0.5) * fone;

                } else if (flags & SWS_AREA) {

                    int64_t d2 = d - (1 << 29);

                    if (d2 * xInc < -(1LL << (29 + 16)))

                        coeff = 1.0 * (1LL << (30 + 16));

                    else if (d2 * xInc < (1LL << (29 + 16)))

                        coeff = -d2 * xInc + (1LL << (29 + 16));

                    else

                        coeff = 0.0;

                    coeff *= fone >> (30 + 16);

                } else if (flags & SWS_GAUSS) {

                    double p = param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;

                    coeff = (pow(2.0, -p * floatd * floatd)) * fone;

                } else if (flags & SWS_SINC) {

                    coeff = (d ? sin(floatd * M_PI) / (floatd * M_PI) : 1.0) * fone;

                } else if (flags & SWS_LANCZOS) {

                    double p = param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;

                    coeff = (d ? sin(floatd * M_PI) * sin(floatd * M_PI / p) /

                             (floatd * floatd * M_PI * M_PI / p) : 1.0) * fone;

                    if (floatd > p)

                        coeff = 0;

                } else if (flags & SWS_BILINEAR) {

                    coeff = (1 << 30) - d;

                    if (coeff < 0)

                        coeff = 0;

                    coeff *= fone >> 30;

                } else if (flags & SWS_SPLINE) {

                    double p = -2.196152422706632;

                    coeff = getSplineCoeff(1.0, 0.0, p, -p - 1.0, floatd) * fone;

                } else {

                    coeff = 0.0; // GCC warning killer

                    assert(0);

                }

                filter[i * filterSize + j] = coeff;

                xx++;

            }

            xDstInSrc += 2 * xInc;

        }

    }

    /* apply src & dst Filter to filter -> filter2

     * av_free(filter);

     */

    assert(filterSize > 0);

    filter2Size = filterSize;

    if (srcFilter)

        filter2Size += srcFilter->length - 1;

    if (dstFilter)

        filter2Size += dstFilter->length - 1;

    assert(filter2Size > 0);

    FF_ALLOCZ_OR_GOTO(NULL, filter2, filter2Size * dstW * sizeof(*filter2), fail);

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

        int j, k;

        if (srcFilter) {

            for (k = 0; k < srcFilter->length; k++) {

                for (j = 0; j < filterSize; j++)

                    filter2[i * filter2Size + k + j] +=

                        srcFilter->coeff[k] * filter[i * filterSize + j];

            }

        } else {

            for (j = 0; j < filterSize; j++)

                filter2[i * filter2Size + j] = filter[i * filterSize + j];

        }

        // FIXME dstFilter

        (*filterPos)[i] += (filterSize - 1) / 2 - (filter2Size - 1) / 2;

    }

    av_freep(&filter);

    /* try to reduce the filter-size (step1 find size and shift left) */

    // Assume it is near normalized (*0.5 or *2.0 is OK but * 0.001 is not).

    minFilterSize = 0;

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

        int min = filter2Size;

        int j;

        int64_t cutOff = 0.0;

        /* get rid of near zero elements on the left by shifting left */

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

            int k;

            cutOff += FFABS(filter2[i * filter2Size]);

            if (cutOff > SWS_MAX_REDUCE_CUTOFF * fone)

                break;

            /* preserve monotonicity because the core can't handle the

             * filter otherwise */

            if (i < dstW - 1 && (*filterPos)[i] >= (*filterPos)[i + 1])

                break;

            // move filter coefficients left

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

                filter2[i * filter2Size + k - 1] = filter2[i * filter2Size + k];

            filter2[i * filter2Size + k - 1] = 0;

            (*filterPos)[i]++;

        }

        cutOff = 0;

        /* count near zeros on the right */

        for (j = filter2Size - 1; j > 0; j--) {

            cutOff += FFABS(filter2[i * filter2Size + j]);

            if (cutOff > SWS_MAX_REDUCE_CUTOFF * fone)

                break;

            min--;

        }

        if (min > minFilterSize)

            minFilterSize = min;

    }

    if (PPC_ALTIVEC(cpu_flags)) {

        // we can handle the special case 4, so we don't want to go the full 8

        if (minFilterSize < 5)

            filterAlign = 4;

        /* We really don't want to waste our time doing useless computation, so

         * fall back on the scalar C code for very small filters.

         * Vectorizing is worth it only if you have a decent-sized vector. */

        if (minFilterSize < 3)

            filterAlign = 1;

    }

    if (INLINE_MMX(cpu_flags)) {

        // special case for unscaled vertical filtering

        if (minFilterSize == 1 && filterAlign == 2)

            filterAlign = 1;

    }

    assert(minFilterSize > 0);

    filterSize = (minFilterSize + (filterAlign - 1)) & (~(filterAlign - 1));

    assert(filterSize > 0);

    filter = av_malloc(filterSize * dstW * sizeof(*filter));

    if (filterSize >= MAX_FILTER_SIZE * 16 /

                      ((flags & SWS_ACCURATE_RND) ? APCK_SIZE : 16) || !filter)

        goto fail;

    *outFilterSize = filterSize;

    if (flags & SWS_PRINT_INFO)

        av_log(NULL, AV_LOG_VERBOSE,

               "SwScaler: reducing / aligning filtersize %d -> %d\n",

               filter2Size, filterSize);

    /* try to reduce the filter-size (step2 reduce it) */

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

        int j;

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

            if (j >= filter2Size)

                filter[i * filterSize + j] = 0;

            else

                filter[i * filterSize + j] = filter2[i * filter2Size + j];

            if ((flags & SWS_BITEXACT) && j >= minFilterSize)

                filter[i * filterSize + j] = 0;

        }

    }

    // FIXME try to align filterPos if possible

    // fix borders

    if (is_horizontal) {

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

            int j;

            if ((*filterPos)[i] < 0) {

                // move filter coefficients left to compensate for filterPos

                for (j = 1; j < filterSize; j++) {

                    int left = FFMAX(j + (*filterPos)[i], 0);

                    filter[i * filterSize + left] += filter[i * filterSize + j];

                    filter[i * filterSize + j]     = 0;

                }

                (*filterPos)[i] = 0;

            }

            if ((*filterPos)[i] + filterSize > srcW) {

                int shift = (*filterPos)[i] + filterSize - srcW;

                // move filter coefficients right to compensate for filterPos

                for (j = filterSize - 2; j >= 0; j--) {

                    int right = FFMIN(j + shift, filterSize - 1);

                    filter[i * filterSize + right] += filter[i * filterSize + j];

                    filter[i * filterSize + j]      = 0;

                }

                (*filterPos)[i] = srcW - filterSize;

            }

        }

    }

    // Note the +1 is for the MMX scaler which reads over the end

    /* align at 16 for AltiVec (needed by hScale_altivec_real) */

    FF_ALLOCZ_OR_GOTO(NULL, *outFilter,

                      *outFilterSize * (dstW + 3) * sizeof(int16_t), fail);

    /* normalize & store in outFilter */

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

        int j;

        int64_t error = 0;

        int64_t sum   = 0;

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

            sum += filter[i * filterSize + j];

        }

        sum = (sum + one / 2) / one;

        for (j = 0; j < *outFilterSize; j++) {

            int64_t v = filter[i * filterSize + j] + error;

            int intV  = ROUNDED_DIV(v, sum);

            (*outFilter)[i * (*outFilterSize) + j] = intV;

            error                                  = v - intV * sum;

        }

    }

    (*filterPos)[dstW + 0] =

    (*filterPos)[dstW + 1] =

    (*filterPos)[dstW + 2] = (*filterPos)[dstW - 1]; /* the MMX/SSE scaler will

                                                      * read over the end */

    for (i = 0; i < *outFilterSize; i++) {

        int k = (dstW - 1) * (*outFilterSize) + i;

        (*outFilter)[k + 1 * (*outFilterSize)] =

        (*outFilter)[k + 2 * (*outFilterSize)] =

        (*outFilter)[k + 3 * (*outFilterSize)] = (*outFilter)[k];

    }

    ret = 0;

fail:

    av_free(filter);

    av_free(filter2);

    return ret;

}


void *rom_add_blob(const char *name, const void *blob, size_t len,

                   hwaddr addr, const char *fw_file_name,

                   FWCfgReadCallback fw_callback, void *callback_opaque)

{

    Rom *rom;

    void *data = NULL;

    rom           = g_malloc0(sizeof(*rom));

    rom->name     = g_strdup(name);

    rom->addr     = addr;

    rom->romsize  = len;

    rom->datasize = len;

    rom->data     = g_malloc0(rom->datasize);

    memcpy(rom->data, blob, len);

    rom_insert(rom);

    if (fw_file_name && fw_cfg) {

        char devpath[100];

        snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);

        if (rom_file_has_mr) {

            data = rom_set_mr(rom, OBJECT(fw_cfg), devpath);

        } else {

            data = rom->data;

        }

        fw_cfg_add_file_callback(fw_cfg, fw_file_name,

                                 fw_callback, callback_opaque,

                                 data, rom->romsize);

    }

    return data;

}


static int qed_write_table(BDRVQEDState *s, uint64_t offset, QEDTable *table,

                           unsigned int index, unsigned int n, bool flush)

{

    unsigned int sector_mask = BDRV_SECTOR_SIZE / sizeof(uint64_t) - 1;

    unsigned int start, end, i;

    QEDTable *new_table;

    struct iovec iov;

    QEMUIOVector qiov;

    size_t len_bytes;

    int ret;

    trace_qed_write_table(s, offset, table, index, n);

    /* Calculate indices of the first and one after last elements */

    start = index & ~sector_mask;

    end = (index + n + sector_mask) & ~sector_mask;

    len_bytes = (end - start) * sizeof(uint64_t);

    new_table = qemu_blockalign(s->bs, len_bytes);

    iov = (struct iovec) {

        .iov_base = new_table->offsets,

        .iov_len = len_bytes,

    };

    qemu_iovec_init_external(&qiov, &iov, 1);

    /* Byteswap table */

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

        uint64_t le_offset = cpu_to_le64(table->offsets[i]);

        new_table->offsets[i - start] = le_offset;

    }

    /* Adjust for offset into table */

    offset += start * sizeof(uint64_t);

    ret = bdrv_pwritev(s->bs->file, offset, &qiov);

    trace_qed_write_table_cb(s, table, flush, ret);

    if (ret < 0) {

        goto out;

    }

    if (flush) {

        qed_acquire(s);

        ret = bdrv_flush(s->bs);

        qed_release(s);

        if (ret < 0) {

            goto out;

        }

    }

    ret = 0;

out:

    qemu_vfree(new_table);

    return ret;

}


static void vnc_init_basic_info(SocketAddress *addr,

                                VncBasicInfo *info,

                                Error **errp)

{

    switch (addr->type) {

    case SOCKET_ADDRESS_KIND_INET:

        info->host = g_strdup(addr->u.inet->host);

        info->service = g_strdup(addr->u.inet->port);

        if (addr->u.inet->ipv6) {

            info->family = NETWORK_ADDRESS_FAMILY_IPV6;

        } else {

            info->family = NETWORK_ADDRESS_FAMILY_IPV4;

        }

        break;

    case SOCKET_ADDRESS_KIND_UNIX:

        info->host = g_strdup("");

        info->service = g_strdup(addr->u.q_unix->path);

        info->family = NETWORK_ADDRESS_FAMILY_UNIX;

        break;

    default:

        error_setg(errp, "Unsupported socket kind %d",

                   addr->type);

        break;

    }

    return;

}


static void disable_interrupt(EEPRO100State * s)

{

    if (s->int_stat) {

        logout("interrupt disabled\n");

        qemu_irq_lower(s->pci_dev->irq[0]);

        s->int_stat = 0;

    }

}


void cpu_physical_memory_rw(target_phys_addr_t addr, uint8_t *buf,

                            int len, int is_write)

{

    int l, io_index;

    uint8_t *ptr;

    uint32_t val;

    target_phys_addr_t page;

    unsigned long pd;

    PhysPageDesc *p;

    while (len > 0) {

        page = addr & TARGET_PAGE_MASK;

        l = (page + TARGET_PAGE_SIZE) - addr;

        if (l > len)

            l = len;

        p = phys_page_find(page >> TARGET_PAGE_BITS);

        if (!p) {

            pd = IO_MEM_UNASSIGNED;

        } else {

            pd = p->phys_offset;

        }

        if (is_write) {

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

                io_index = (pd >> IO_MEM_SHIFT) & (IO_MEM_NB_ENTRIES - 1);

                if (p)

                    addr = (addr & ~TARGET_PAGE_MASK) + p->region_offset;

                /* XXX: could force cpu_single_env to NULL to avoid

                   potential bugs */

                if (l >= 4 && ((addr & 3) == 0)) {

                    /* 32 bit write access */

                    val = ldl_p(buf);

                    io_mem_write[io_index][2](io_mem_opaque[io_index], addr, val);

                    l = 4;

                } else if (l >= 2 && ((addr & 1) == 0)) {

                    /* 16 bit write access */

                    val = lduw_p(buf);

                    io_mem_write[io_index][1](io_mem_opaque[io_index], addr, val);

                    l = 2;

                } else {

                    /* 8 bit write access */

                    val = ldub_p(buf);

                    io_mem_write[io_index][0](io_mem_opaque[io_index], addr, val);

                    l = 1;

                }

            } else {

                unsigned long addr1;

                addr1 = (pd & TARGET_PAGE_MASK) + (addr & ~TARGET_PAGE_MASK);

                /* RAM case */

                ptr = phys_ram_base + addr1;

                memcpy(ptr, buf, l);

                if (!cpu_physical_memory_is_dirty(addr1)) {

                    /* invalidate code */

                    tb_invalidate_phys_page_range(addr1, addr1 + l, 0);

                    /* set dirty bit */

                    phys_ram_dirty[addr1 >> TARGET_PAGE_BITS] |=

                        (0xff & ~CODE_DIRTY_FLAG);

                }

            }

        } else {

            if ((pd & ~TARGET_PAGE_MASK) > IO_MEM_ROM &&

                !(pd & IO_MEM_ROMD)) {

                /* I/O case */

                io_index = (pd >> IO_MEM_SHIFT) & (IO_MEM_NB_ENTRIES - 1);

                if (p)

                    addr = (addr & ~TARGET_PAGE_MASK) + p->region_offset;

                if (l >= 4 && ((addr & 3) == 0)) {

                    /* 32 bit read access */

                    val = io_mem_read[io_index][2](io_mem_opaque[io_index], addr);

                    stl_p(buf, val);

                    l = 4;

                } else if (l >= 2 && ((addr & 1) == 0)) {

                    /* 16 bit read access */

                    val = io_mem_read[io_index][1](io_mem_opaque[io_index], addr);

                    stw_p(buf, val);

                    l = 2;

                } else {

                    /* 8 bit read access */

                    val = io_mem_read[io_index][0](io_mem_opaque[io_index], addr);

                    stb_p(buf, val);

                    l = 1;

                }

            } else {

                /* RAM case */

                ptr = phys_ram_base + (pd & TARGET_PAGE_MASK) +

                    (addr & ~TARGET_PAGE_MASK);

                memcpy(buf, ptr, l);

            }

        }

        len -= l;

        buf += l;

        addr += l;

    }

}


static int av_dict_set_fxp(AVDictionary **pm, const char *key, uint64_t value, unsigned int digits,

                int flags)

{

    char valuestr[44];

    snprintf(valuestr, sizeof(valuestr), "%"PRId64".%0*"PRId64,

             value / PRECISION, digits, ( value % PRECISION ) / ( PRECISION / uintpow(10,digits) ));

    return av_dict_set(pm, key, valuestr, flags);

}


int av_packet_ref(AVPacket *dst, const AVPacket *src)

{

    int ret;

    ret = av_packet_copy_props(dst, src);

    if (ret < 0)

        return ret;

    if (!src->buf) {

        ret = packet_alloc(&dst->buf, src->size);

        if (ret < 0)

            goto fail;

        memcpy(dst->buf->data, src->data, src->size);

        dst->data = dst->buf->data;

    } else {

        dst->buf = av_buffer_ref(src->buf);

        if (!dst->buf) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        dst->data = src->data;

    }

    dst->size = src->size;

    return 0;

fail:

    av_packet_free_side_data(dst);

    return ret;

}


int ff_h264_pred_weight_table(GetBitContext *gb, const SPS *sps,

                              const int *ref_count, int slice_type_nos,

                              H264PredWeightTable *pwt,

                              int picture_structure, void *logctx)

{

    int list, i, j;

    int luma_def, chroma_def;

    pwt->use_weight             = 0;

    pwt->use_weight_chroma      = 0;

    pwt->luma_log2_weight_denom = get_ue_golomb(gb);

    if (sps->chroma_format_idc)

        pwt->chroma_log2_weight_denom = get_ue_golomb(gb);

    if (pwt->luma_log2_weight_denom > 7U) {

        av_log(logctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", pwt->luma_log2_weight_denom);

        pwt->luma_log2_weight_denom = 0;

    }

    if (pwt->chroma_log2_weight_denom > 7U) {

        av_log(logctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", pwt->chroma_log2_weight_denom);

        pwt->chroma_log2_weight_denom = 0;

    }

    luma_def   = 1 << pwt->luma_log2_weight_denom;

    chroma_def = 1 << pwt->chroma_log2_weight_denom;

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

        pwt->luma_weight_flag[list]   = 0;

        pwt->chroma_weight_flag[list] = 0;

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

            int luma_weight_flag, chroma_weight_flag;

            luma_weight_flag = get_bits1(gb);

            if (luma_weight_flag) {

                pwt->luma_weight[i][list][0] = get_se_golomb(gb);

                pwt->luma_weight[i][list][1] = get_se_golomb(gb);

                if ((int8_t)pwt->luma_weight[i][list][0] != pwt->luma_weight[i][list][0] ||

                    (int8_t)pwt->luma_weight[i][list][1] != pwt->luma_weight[i][list][1])

                    goto out_range_weight;

                if (pwt->luma_weight[i][list][0] != luma_def ||

                    pwt->luma_weight[i][list][1] != 0) {

                    pwt->use_weight             = 1;

                    pwt->luma_weight_flag[list] = 1;

                }

            } else {

                pwt->luma_weight[i][list][0] = luma_def;

                pwt->luma_weight[i][list][1] = 0;

            }

            if (sps->chroma_format_idc) {

                chroma_weight_flag = get_bits1(gb);

                if (chroma_weight_flag) {

                    int j;

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

                        pwt->chroma_weight[i][list][j][0] = get_se_golomb(gb);

                        pwt->chroma_weight[i][list][j][1] = get_se_golomb(gb);

                        if ((int8_t)pwt->chroma_weight[i][list][j][0] != pwt->chroma_weight[i][list][j][0] ||

                            (int8_t)pwt->chroma_weight[i][list][j][1] != pwt->chroma_weight[i][list][j][1])

                            goto out_range_weight;

                        if (pwt->chroma_weight[i][list][j][0] != chroma_def ||

                            pwt->chroma_weight[i][list][j][1] != 0) {

                            pwt->use_weight_chroma        = 1;

                            pwt->chroma_weight_flag[list] = 1;

                        }

                    }

                } else {

                    int j;

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

                        pwt->chroma_weight[i][list][j][0] = chroma_def;

                        pwt->chroma_weight[i][list][j][1] = 0;

                    }

                }

            }

            // for MBAFF

            if (picture_structure == PICT_FRAME) {

                pwt->luma_weight[16 + 2 * i][list][0] = pwt->luma_weight[16 + 2 * i + 1][list][0] = pwt->luma_weight[i][list][0];

                pwt->luma_weight[16 + 2 * i][list][1] = pwt->luma_weight[16 + 2 * i + 1][list][1] = pwt->luma_weight[i][list][1];

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

                    pwt->chroma_weight[16 + 2 * i][list][j][0] = pwt->chroma_weight[16 + 2 * i + 1][list][j][0] = pwt->chroma_weight[i][list][j][0];

                    pwt->chroma_weight[16 + 2 * i][list][j][1] = pwt->chroma_weight[16 + 2 * i + 1][list][j][1] = pwt->chroma_weight[i][list][j][1];

                }

            }

        }

        if (slice_type_nos != AV_PICTURE_TYPE_B)

            break;

    }

    pwt->use_weight = pwt->use_weight || pwt->use_weight_chroma;

    return 0;

out_range_weight:

    avpriv_request_sample(logctx, "Out of range weight\n");

    return AVERROR_INVALIDDATA;

}


static int libschroedinger_encode_init(AVCodecContext *avccontext)

{

    FfmpegSchroEncoderParams* p_schro_params = avccontext->priv_data;

    SchroVideoFormatEnum preset;

    /* Initialize the libraries that libschroedinger depends on. */

    schro_init();

    /* Create an encoder object. */

    p_schro_params->encoder = schro_encoder_new();

    if (!p_schro_params->encoder) {

        av_log(avccontext, AV_LOG_ERROR,

               "Unrecoverable Error: schro_encoder_new failed. ");

        return -1;

    }

    /* Initialize the format. */

    preset = ff_get_schro_video_format_preset(avccontext);

    p_schro_params->format =

                    schro_encoder_get_video_format(p_schro_params->encoder);

    schro_video_format_set_std_video_format (p_schro_params->format, preset);

    p_schro_params->format->width = avccontext->width;

    p_schro_params->format->height = avccontext->height;

    if (SetSchroChromaFormat(avccontext) == -1)

        return -1;

    if (ff_get_schro_frame_format(p_schro_params->format->chroma_format,

                                  &p_schro_params->frame_format) == -1) {

        av_log (avccontext, AV_LOG_ERROR,

                "This codec currently supports only planar YUV 4:2:0, 4:2:2"

                " and 4:4:4 formats.\n");

        return -1;

    }

    p_schro_params->format->frame_rate_numerator   = avccontext->time_base.den;

    p_schro_params->format->frame_rate_denominator = avccontext->time_base.num;

    p_schro_params->frame_size = avpicture_get_size(avccontext->pix_fmt,

                                                    avccontext->width,

                                                    avccontext->height);

    avccontext->coded_frame = &p_schro_params->picture;

    if (avccontext->gop_size == 0){

        schro_encoder_setting_set_double (p_schro_params->encoder,

                                          "gop_structure",

                                          SCHRO_ENCODER_GOP_INTRA_ONLY);

        if (avccontext->coder_type == FF_CODER_TYPE_VLC) {

            schro_encoder_setting_set_double (p_schro_params->encoder,

                                              "enable_noarith", 1);

        }

    }

    else {

        schro_encoder_setting_set_double (p_schro_params->encoder,

                                          "gop_structure",

                                          SCHRO_ENCODER_GOP_BIREF);

        avccontext->has_b_frames = 1;

    }

    /* FIXME - Need to handle SCHRO_ENCODER_RATE_CONTROL_LOW_DELAY. */

    if (avccontext->flags & CODEC_FLAG_QSCALE) {

        if (avccontext->global_quality == 0) {

            /* lossless coding */

            schro_encoder_setting_set_double (p_schro_params->encoder,

                                          "rate_control",

                                          SCHRO_ENCODER_RATE_CONTROL_LOSSLESS);

        } else {

            int noise_threshold;

            schro_encoder_setting_set_double (p_schro_params->encoder,

                          "rate_control",

                          SCHRO_ENCODER_RATE_CONTROL_CONSTANT_NOISE_THRESHOLD);

            noise_threshold = avccontext->global_quality/FF_QP2LAMBDA;

            if (noise_threshold > 100)

                noise_threshold = 100;

            schro_encoder_setting_set_double (p_schro_params->encoder,

                                              "noise_threshold",

                                              noise_threshold);

        }

    }

    else {

        schro_encoder_setting_set_double ( p_schro_params->encoder,

                               "rate_control",

                               SCHRO_ENCODER_RATE_CONTROL_CONSTANT_BITRATE);

        schro_encoder_setting_set_double (p_schro_params->encoder,

                                          "bitrate",

                                          avccontext->bit_rate);

    }

    if (avccontext->flags & CODEC_FLAG_INTERLACED_ME) {

        /* All material can be coded as interlaced or progressive

           irrespective of the type of source material. */

        schro_encoder_setting_set_double (p_schro_params->encoder,

                                            "interlaced_coding", 1);

    }

    /* FIXME: Signal range hardcoded to 8-bit data until both libschroedinger

     * and libdirac support other bit-depth data. */

    schro_video_format_set_std_signal_range(p_schro_params->format,

                                            SCHRO_SIGNAL_RANGE_8BIT_VIDEO);

    /* Hardcode motion vector precision to quarter pixel. */

    schro_encoder_setting_set_double (p_schro_params->encoder,

                                      "mv_precision", 2);

    /* Set the encoder format. */

    schro_encoder_set_video_format(p_schro_params->encoder,

                                   p_schro_params->format);

    /* Set the debug level. */

    schro_debug_set_level (avccontext->debug);

    schro_encoder_start (p_schro_params->encoder);

    /* Initialize the encoded frame queue. */

    ff_dirac_schro_queue_init (&p_schro_params->enc_frame_queue);

    return 0 ;

}


int h263_decode_mb(MpegEncContext *s,

                   DCTELEM block[6][64])

{

    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;

    unsigned int val;

    INT16 *mot_val;

    static INT8 quant_tab[4] = { -1, -2, 1, 2 };

    /* Check for GOB Start Code */

    val = show_bits(&s->gb, 16);

    if (val == 0) {

        /* We have a GBSC probably with GSTUFF */

#ifdef DEBUG

        unsigned int gn, gfid;

#endif

        //skip_bits(&s->gb, 16); /* Drop the zeros */

        while (get_bits1(&s->gb) == 0); /* Seek the '1' bit */

#ifdef DEBUG

        fprintf(stderr,"\nGOB Start Code at MB %d\n",

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

        gn = get_bits(&s->gb, 5); /* GN */

        gfid = get_bits(&s->gb, 2); /* GFID */

#else

        skip_bits(&s->gb, 5); /* GN */

        skip_bits(&s->gb, 2); /* GFID */

#endif

        s->qscale = get_bits(&s->gb, 5); /* GQUANT */

#ifdef DEBUG

        fprintf(stderr, "\nGN: %u GFID: %u Quant: %u\n", gn, gfid, s->qscale);

#endif

    }

    if (s->pict_type == P_TYPE) {

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

            /* skip mb */

            s->mb_intra = 0;

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

                s->block_last_index[i] = -1;

            s->mv_dir = MV_DIR_FORWARD;

            s->mv_type = MV_TYPE_16X16;

            s->mv[0][0][0] = 0;

            s->mv[0][0][1] = 0;

            s->mb_skiped = 1;

            return 0;

        }

        cbpc = get_vlc(&s->gb, &inter_MCBPC_vlc);

        //fprintf(stderr, "\tCBPC: %d", cbpc);

        if (cbpc < 0)

            return -1;

        dquant = cbpc & 8;

        s->mb_intra = ((cbpc & 4) != 0);

    } else {

        cbpc = get_vlc(&s->gb, &intra_MCBPC_vlc);

        if (cbpc < 0)

            return -1;

        dquant = cbpc & 4;

        s->mb_intra = 1;

    }

    if (!s->mb_intra) {

        cbpy = get_vlc(&s->gb, &cbpy_vlc);

        cbp = (cbpc & 3) | ((cbpy ^ 0xf) << 2);

        if (dquant) {

            s->qscale += quant_tab[get_bits(&s->gb, 2)];

            if (s->qscale < 1)

                s->qscale = 1;

            else if (s->qscale > 31)

                s->qscale = 31;

        }

        s->mv_dir = MV_DIR_FORWARD;

        if ((cbpc & 16) == 0) {

            /* 16x16 motion prediction */

            s->mv_type = MV_TYPE_16X16;

            h263_pred_motion(s, 0, &pred_x, &pred_y);

            if (s->umvplus_dec)

               mx = h263p_decode_umotion(s, pred_x);

            else

               mx = h263_decode_motion(s, pred_x);

            if (mx >= 0xffff)

                return -1;

            if (s->umvplus_dec)

               my = h263p_decode_umotion(s, pred_y);

            else

               my = h263_decode_motion(s, pred_y);

            if (my >= 0xffff)

                return -1;

            s->mv[0][0][0] = mx;

            s->mv[0][0][1] = my;

            if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)

               skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */

        } else {

            s->mv_type = MV_TYPE_8X8;

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

                mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);

                if (s->umvplus_dec)

                  mx = h263p_decode_umotion(s, pred_x);

                else

                  mx = h263_decode_motion(s, pred_x);

                if (mx >= 0xffff)

                    return -1;

                if (s->umvplus_dec)

                  my = h263p_decode_umotion(s, pred_y);

                else

                  my = h263_decode_motion(s, pred_y);

                if (my >= 0xffff)

                    return -1;

                s->mv[0][i][0] = mx;

                s->mv[0][i][1] = my;

                if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)

                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */

                mot_val[0] = mx;

                mot_val[1] = my;

            }

        }

    } else {

        s->ac_pred = 0;

	    if (s->h263_pred) {

            s->ac_pred = get_bits1(&s->gb);

        }

        cbpy = get_vlc(&s->gb, &cbpy_vlc);

        cbp = (cbpc & 3) | (cbpy << 2);

        if (dquant) {

            s->qscale += quant_tab[get_bits(&s->gb, 2)];

            if (s->qscale < 1)

                s->qscale = 1;

            else if (s->qscale > 31)

                s->qscale = 31;

        }

    }

    /* decode each block */

    if (s->h263_pred) {

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

	    if (mpeg4_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1) < 0)

                return -1;

	}

    } else {

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

	    if (h263_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1) < 0)

                return -1;

	}

    }

    return 0;

}


VirtIODevice *virtio_serial_init(DeviceState *dev, virtio_serial_conf *conf)

{

    VirtIOSerial *vser;

    VirtIODevice *vdev;

    uint32_t i, max_supported_ports;

    if (!conf->max_virtserial_ports)

        return NULL;

    /* Each port takes 2 queues, and one pair is for the control queue */

    max_supported_ports = VIRTIO_PCI_QUEUE_MAX / 2 - 1;

    if (conf->max_virtserial_ports > max_supported_ports) {

        error_report("maximum ports supported: %u", max_supported_ports);

        return NULL;

    }

    vdev = virtio_common_init("virtio-serial", VIRTIO_ID_CONSOLE,

                              sizeof(struct virtio_console_config),

                              sizeof(VirtIOSerial));

    vser = DO_UPCAST(VirtIOSerial, vdev, vdev);

    /* Spawn a new virtio-serial bus on which the ports will ride as devices */

    vser->bus = virtser_bus_new(dev);

    vser->bus->vser = vser;

    QTAILQ_INIT(&vser->ports);

    vser->bus->max_nr_ports = conf->max_virtserial_ports;

    vser->ivqs = qemu_malloc(conf->max_virtserial_ports * sizeof(VirtQueue *));

    vser->ovqs = qemu_malloc(conf->max_virtserial_ports * sizeof(VirtQueue *));

    /* Add a queue for host to guest transfers for port 0 (backward compat) */

    vser->ivqs[0] = virtio_add_queue(vdev, 128, handle_input);

    /* Add a queue for guest to host transfers for port 0 (backward compat) */

    vser->ovqs[0] = virtio_add_queue(vdev, 128, handle_output);

    /* TODO: host to guest notifications can get dropped

     * if the queue fills up. Implement queueing in host,

     * this might also make it possible to reduce the control

     * queue size: as guest preposts buffers there,

     * this will save 4Kbyte of guest memory per entry. */

    /* control queue: host to guest */

    vser->c_ivq = virtio_add_queue(vdev, 32, control_in);

    /* control queue: guest to host */

    vser->c_ovq = virtio_add_queue(vdev, 32, control_out);

    for (i = 1; i < vser->bus->max_nr_ports; i++) {

        /* Add a per-port queue for host to guest transfers */

        vser->ivqs[i] = virtio_add_queue(vdev, 128, handle_input);

        /* Add a per-per queue for guest to host transfers */

        vser->ovqs[i] = virtio_add_queue(vdev, 128, handle_output);

    }

    vser->config.max_nr_ports = tswap32(conf->max_virtserial_ports);

    vser->ports_map = qemu_mallocz(((conf->max_virtserial_ports + 31) / 32)

        * sizeof(vser->ports_map[0]));

    /*

     * Reserve location 0 for a console port for backward compat

     * (old kernel, new qemu)

     */

    mark_port_added(vser, 0);

    vser->vdev.get_features = get_features;

    vser->vdev.get_config = get_config;

    vser->vdev.set_config = set_config;

    vser->qdev = dev;

    /*

     * Register for the savevm section with the virtio-console name

     * to preserve backward compat

     */

    register_savevm(dev, "virtio-console", -1, 3, virtio_serial_save,

                    virtio_serial_load, vser);

    return vdev;

}


static void kempf_restore_buf(const uint8_t *src, int len,

                              uint8_t *dst, int stride,

                              const uint8_t *jpeg_tile, int tile_stride,

                              int width, int height,

                              const uint8_t *pal, int npal, int tidx)

{

    GetBitContext gb;

    int i, j, nb, col;

    init_get_bits8(&gb, src, len);

    if (npal <= 2)       nb = 1;

    else if (npal <= 4)  nb = 2;

    else if (npal <= 16) nb = 4;

    else                 nb = 8;

    for (j = 0; j < height; j++, dst += stride, jpeg_tile += tile_stride) {

        if (get_bits(&gb, 8))

            continue;

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

            col = get_bits(&gb, nb);

            if (col != tidx)

                memcpy(dst + i * 3, pal + col * 3, 3);

            else

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

        }

    }

}


static JavaVM *get_java_vm(const char *name, void *log_ctx)

{

    JavaVM *vm = NULL;

    jsize nb_vm = 0;

    void *handle = NULL;

    jint (*get_created_java_vms) (JavaVM ** vmBuf, jsize bufLen, jsize *nVMs) = NULL;

    handle = dlopen(name, RTLD_LOCAL);

    if (!handle) {

        return NULL;

    }

    get_created_java_vms = (jint (*)(JavaVM **, jsize, jsize *)) dlsym(handle, "JNI_GetCreatedJavaVMs");

    if (!get_created_java_vms) {

        av_log(log_ctx, AV_LOG_ERROR, "Could not find JNI_GetCreatedJavaVMs symbol in library '%s'\n", name);

        goto done;

    }

    if (get_created_java_vms(&vm, 1, &nb_vm) != JNI_OK) {

        av_log(log_ctx, AV_LOG_ERROR, "Could not get created Java virtual machines\n");

        goto done;

    }

done:

    if (handle) {

        dlclose(handle);

    }

    return vm;

}


static int mpegts_push_data(MpegTSFilter *filter,

                            const uint8_t *buf, int buf_size, int is_start,

                            int64_t pos)

{

    PESContext *pes = filter->u.pes_filter.opaque;

    MpegTSContext *ts = pes->ts;

    const uint8_t *p;

    int len, code;

    if(!ts->pkt)

        return 0;

    if (is_start) {

        if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {

            new_pes_packet(pes, ts->pkt);

            ts->stop_parse = 1;

        }

        pes->state = MPEGTS_HEADER;

        pes->data_index = 0;

        pes->ts_packet_pos = pos;

    }

    p = buf;

    while (buf_size > 0) {

        switch(pes->state) {

        case MPEGTS_HEADER:

            len = PES_START_SIZE - pes->data_index;

            if (len > buf_size)

                len = buf_size;

            memcpy(pes->header + pes->data_index, p, len);

            pes->data_index += len;

            p += len;

            buf_size -= len;

            if (pes->data_index == PES_START_SIZE) {

                /* we got all the PES or section header. We can now

                   decide */

#if 0

                av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);

#endif

                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&

                    pes->header[2] == 0x01) {

                    /* it must be an mpeg2 PES stream */

                    code = pes->header[3] | 0x100;

                    dprintf(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);

                    if ((pes->st && pes->st->discard == AVDISCARD_ALL) ||

                        code == 0x1be) /* padding_stream */

                        goto skip;

                    /* stream not present in PMT */

                    if (!pes->st)

                        pes->st = new_pes_av_stream(pes, 0, code);

                    if (!pes->st)

                        return AVERROR(ENOMEM);

                    pes->total_size = AV_RB16(pes->header + 4);

                    /* NOTE: a zero total size means the PES size is

                       unbounded */

                    if (!pes->total_size)

                        pes->total_size = MAX_PES_PAYLOAD;

                    /* allocate pes buffer */

                    pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);

                    if (!pes->buffer)

                        return AVERROR(ENOMEM);

                    if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */

                        code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */

                        code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */

                        code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */

                        pes->state = MPEGTS_PESHEADER_FILL;

                        pes->pes_header_size = pes->header[8] + 9;

                    } else {

                        pes->state = MPEGTS_PAYLOAD;

                        pes->data_index = 0;

                    }

                } else {

                    /* otherwise, it should be a table */

                    /* skip packet */

                skip:

                    pes->state = MPEGTS_SKIP;

                    continue;

                }

            }

            break;

            /**********************************************/

            /* PES packing parsing */

        case MPEGTS_PESHEADER_FILL:

            len = pes->pes_header_size - pes->data_index;

            if (len < 0)

                return -1;

            if (len > buf_size)

                len = buf_size;

            memcpy(pes->header + pes->data_index, p, len);

            pes->data_index += len;

            p += len;

            buf_size -= len;

            if (pes->data_index == pes->pes_header_size) {

                const uint8_t *r;

                unsigned int flags;

                flags = pes->header[7];

                r = pes->header + 9;

                pes->pts = AV_NOPTS_VALUE;

                pes->dts = AV_NOPTS_VALUE;

                if ((flags & 0xc0) == 0x80) {

                    pes->dts = pes->pts = get_pts(r);

                    r += 5;

                } else if ((flags & 0xc0) == 0xc0) {

                    pes->pts = get_pts(r);

                    r += 5;

                    pes->dts = get_pts(r);

                    r += 5;

                }

                /* we got the full header. We parse it and get the payload */

                pes->state = MPEGTS_PAYLOAD;

                pes->data_index = 0;

            }

            break;

        case MPEGTS_PAYLOAD:

            if (buf_size > 0) {

                if (pes->data_index+buf_size > pes->total_size) {

                    new_pes_packet(pes, ts->pkt);

                    pes->total_size = MAX_PES_PAYLOAD;

                    pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);

                    if (!pes->buffer)

                        return AVERROR(ENOMEM);

                    ts->stop_parse = 1;

                }

                memcpy(pes->buffer+pes->data_index, p, buf_size);

                pes->data_index += buf_size;

            }

            buf_size = 0;

            break;

        case MPEGTS_SKIP:

            buf_size = 0;

            break;

        }

    }

    return 0;

}


static int proxy_fstat(FsContext *fs_ctx, int fid_type,

                       V9fsFidOpenState *fs, struct stat *stbuf)

{

    int fd;

    if (fid_type == P9_FID_DIR) {

        fd = dirfd(fs->dir);

    } else {

        fd = fs->fd;

    }

    return fstat(fd, stbuf);

}


static uint64_t cmd646_data_read(void *opaque, target_phys_addr_t addr,

                                 unsigned size)

{

    CMD646BAR *cmd646bar = opaque;

    if (size == 1) {

        return ide_ioport_read(cmd646bar->bus, addr);

    } else if (addr == 0) {

        if (size == 2) {

            return ide_data_readw(cmd646bar->bus, addr);

        } else {

            return ide_data_readl(cmd646bar->bus, addr);

        }

    }

    return ((uint64_t)1 << (size * 8)) - 1;

}


int kvm_arch_insert_sw_breakpoint(CPUState *env, struct kvm_sw_breakpoint *bp)

{

    static const uint8_t int3 = 0xcc;

    if (cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||

        cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&int3, 1, 1))

        return -EINVAL;

    return 0;

}