static void gen_dmfc0(DisasContext *ctx, TCGv arg, int reg, int sel)

{

    const char *rn = "invalid";

    if (sel != 0)

        check_insn(ctx, ISA_MIPS64);

    switch (reg) {

    case 0:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Index));

            rn = "Index";

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mfc0_mvpcontrol(arg, cpu_env);

            rn = "MVPControl";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mfc0_mvpconf0(arg, cpu_env);

            rn = "MVPConf0";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mfc0_mvpconf1(arg, cpu_env);

            rn = "MVPConf1";

            CP0_CHECK(ctx->vp);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPControl));

            rn = "VPControl";

        default:

            goto cp0_unimplemented;

        }

    case 1:

        switch (sel) {

        case 0:

            CP0_CHECK(!(ctx->insn_flags & ISA_MIPS32R6));

            gen_helper_mfc0_random(arg, cpu_env);

            rn = "Random";

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEControl));

            rn = "VPEControl";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEConf0));

            rn = "VPEConf0";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEConf1));

            rn = "VPEConf1";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_YQMask));

            rn = "YQMask";

        case 5:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_VPESchedule));

            rn = "VPESchedule";

        case 6:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_VPEScheFBack));

            rn = "VPEScheFBack";

        case 7:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEOpt));

            rn = "VPEOpt";

        default:

            goto cp0_unimplemented;

        }

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EntryLo0));

            rn = "EntryLo0";

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mfc0_tcstatus(arg, cpu_env);

            rn = "TCStatus";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mfc0_tcbind(arg, cpu_env);

            rn = "TCBind";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_dmfc0_tcrestart(arg, cpu_env);

            rn = "TCRestart";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_dmfc0_tchalt(arg, cpu_env);

            rn = "TCHalt";

        case 5:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_dmfc0_tccontext(arg, cpu_env);

            rn = "TCContext";

        case 6:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_dmfc0_tcschedule(arg, cpu_env);

            rn = "TCSchedule";

        case 7:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_dmfc0_tcschefback(arg, cpu_env);

            rn = "TCScheFBack";

        default:

            goto cp0_unimplemented;

        }

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EntryLo1));

            rn = "EntryLo1";

        case 1:

            CP0_CHECK(ctx->vp);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_GlobalNumber));

            rn = "GlobalNumber";

        default:

            goto cp0_unimplemented;

        }

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_Context));

            rn = "Context";

        case 1:

//            gen_helper_dmfc0_contextconfig(arg); /* SmartMIPS ASE */

            rn = "ContextConfig";

            goto cp0_unimplemented;

            CP0_CHECK(ctx->ulri);

            tcg_gen_ld_tl(arg, cpu_env,

                          offsetof(CPUMIPSState, active_tc.CP0_UserLocal));

            rn = "UserLocal";

        default:

            goto cp0_unimplemented;

        }

    case 5:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_PageMask));

            rn = "PageMask";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_PageGrain));

            rn = "PageGrain";

        default:

            goto cp0_unimplemented;

        }

    case 6:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Wired));

            rn = "Wired";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf0));

            rn = "SRSConf0";

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf1));

            rn = "SRSConf1";

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf2));

            rn = "SRSConf2";

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf3));

            rn = "SRSConf3";

        case 5:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf4));

            rn = "SRSConf4";

        default:

            goto cp0_unimplemented;

        }

    case 7:

        switch (sel) {

        case 0:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_HWREna));

            rn = "HWREna";

        default:

            goto cp0_unimplemented;

        }

    case 8:

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_BadVAddr));

            rn = "BadVAddr";

        case 1:

            CP0_CHECK(ctx->bi);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_BadInstr));

            rn = "BadInstr";

            CP0_CHECK(ctx->bp);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_BadInstrP));

            rn = "BadInstrP";

        default:

            goto cp0_unimplemented;

        }

    case 9:

        switch (sel) {

        case 0:

            /* Mark as an IO operation because we read the time.  */

            if (ctx->tb->cflags & CF_USE_ICOUNT) {

                gen_io_start();

            }

            gen_helper_mfc0_count(arg, cpu_env);

            if (ctx->tb->cflags & CF_USE_ICOUNT) {

                gen_io_end();

            }

            /* Break the TB to be able to take timer interrupts immediately

               after reading count.  */

            ctx->bstate = BS_STOP;

            rn = "Count";

        /* 6,7 are implementation dependent */

        default:

            goto cp0_unimplemented;

        }

    case 10:

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EntryHi));

            rn = "EntryHi";

        default:

            goto cp0_unimplemented;

        }

    case 11:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Compare));

            rn = "Compare";

        /* 6,7 are implementation dependent */

        default:

            goto cp0_unimplemented;

        }

    case 12:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Status));

            rn = "Status";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_IntCtl));

            rn = "IntCtl";

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSCtl));

            rn = "SRSCtl";

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSMap));

            rn = "SRSMap";

        default:

            goto cp0_unimplemented;

        }

    case 13:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Cause));

            rn = "Cause";

        default:

            goto cp0_unimplemented;

        }

    case 14:

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EPC));

            rn = "EPC";

        default:

            goto cp0_unimplemented;

        }

    case 15:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_PRid));

            rn = "PRid";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EBase));

            rn = "EBase";

            check_insn(ctx, ISA_MIPS32R2);

            CP0_CHECK(ctx->cmgcr);

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_CMGCRBase));

            rn = "CMGCRBase";

        default:

            goto cp0_unimplemented;

        }

    case 16:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config0));

            rn = "Config";

        case 1:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config1));

            rn = "Config1";

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config2));

            rn = "Config2";

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config3));

            rn = "Config3";

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config4));

            rn = "Config4";

        case 5:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config5));

            rn = "Config5";

       /* 6,7 are implementation dependent */

        case 6:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config6));

            rn = "Config6";

        case 7:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config7));

            rn = "Config7";

        default:

            goto cp0_unimplemented;

        }

    case 17:

        switch (sel) {

        case 0:

            gen_helper_dmfc0_lladdr(arg, cpu_env);

            rn = "LLAddr";

        case 1:

            CP0_CHECK(ctx->mrp);

            gen_helper_dmfc0_maar(arg, cpu_env);

            rn = "MAAR";

            CP0_CHECK(ctx->mrp);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_MAARI));

            rn = "MAARI";

        default:

            goto cp0_unimplemented;

        }

    case 18:

        switch (sel) {

        case 0 ... 7:

            gen_helper_1e0i(dmfc0_watchlo, arg, sel);

            rn = "WatchLo";

        default:

            goto cp0_unimplemented;

        }

    case 19:

        switch (sel) {

        case 0 ... 7:

            gen_helper_1e0i(mfc0_watchhi, arg, sel);

            rn = "WatchHi";

        default:

            goto cp0_unimplemented;

        }

    case 20:

        switch (sel) {

        case 0:

            check_insn(ctx, ISA_MIPS3);

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_XContext));

            rn = "XContext";

        default:

            goto cp0_unimplemented;

        }

    case 21:

       /* Officially reserved, but sel 0 is used for R1x000 framemask */

        CP0_CHECK(!(ctx->insn_flags & ISA_MIPS32R6));

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Framemask));

            rn = "Framemask";

        default:

            goto cp0_unimplemented;

        }

    case 22:

        tcg_gen_movi_tl(arg, 0); /* unimplemented */

        rn = "'Diagnostic"; /* implementation dependent */

    case 23:

        switch (sel) {

        case 0:

            gen_helper_mfc0_debug(arg, cpu_env); /* EJTAG support */

            rn = "Debug";

        case 1:

//            gen_helper_dmfc0_tracecontrol(arg, cpu_env); /* PDtrace support */

            rn = "TraceControl";

            goto cp0_unimplemented;

//            gen_helper_dmfc0_tracecontrol2(arg, cpu_env); /* PDtrace support */

            rn = "TraceControl2";

            goto cp0_unimplemented;

//            gen_helper_dmfc0_usertracedata(arg, cpu_env); /* PDtrace support */

            rn = "UserTraceData";

            goto cp0_unimplemented;

//            gen_helper_dmfc0_tracebpc(arg, cpu_env); /* PDtrace support */

            rn = "TraceBPC";

            goto cp0_unimplemented;

        default:

            goto cp0_unimplemented;

        }

    case 24:

        switch (sel) {

        case 0:

            /* EJTAG support */

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_DEPC));

            rn = "DEPC";

        default:

            goto cp0_unimplemented;

        }

    case 25:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Performance0));

            rn = "Performance0";

        case 1:

//            gen_helper_dmfc0_performance1(arg);

            rn = "Performance1";

            goto cp0_unimplemented;

//            gen_helper_dmfc0_performance2(arg);

            rn = "Performance2";

            goto cp0_unimplemented;

//            gen_helper_dmfc0_performance3(arg);

            rn = "Performance3";

            goto cp0_unimplemented;

//            gen_helper_dmfc0_performance4(arg);

            rn = "Performance4";

            goto cp0_unimplemented;

        case 5:

//            gen_helper_dmfc0_performance5(arg);

            rn = "Performance5";

            goto cp0_unimplemented;

        case 6:

//            gen_helper_dmfc0_performance6(arg);

            rn = "Performance6";

            goto cp0_unimplemented;

        case 7:

//            gen_helper_dmfc0_performance7(arg);

            rn = "Performance7";

            goto cp0_unimplemented;

        default:

            goto cp0_unimplemented;

        }

    case 26:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_ErrCtl));

            rn = "ErrCtl";

        default:

            goto cp0_unimplemented;

        }

    case 27:

        switch (sel) {

        /* ignored */

        case 0 ... 3:

            tcg_gen_movi_tl(arg, 0); /* unimplemented */

            rn = "CacheErr";

        default:

            goto cp0_unimplemented;

        }

    case 28:

        switch (sel) {

        case 0:

        case 6:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_TagLo));

            rn = "TagLo";

        case 1:

        case 5:

        case 7:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_DataLo));

            rn = "DataLo";

        default:

            goto cp0_unimplemented;

        }

    case 29:

        switch (sel) {

        case 0:

        case 6:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_TagHi));

            rn = "TagHi";

        case 1:

        case 5:

        case 7:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_DataHi));

            rn = "DataHi";

        default:

            goto cp0_unimplemented;

        }

    case 30:

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_ErrorEPC));

            rn = "ErrorEPC";

        default:

            goto cp0_unimplemented;

        }

    case 31:

        switch (sel) {

        case 0:

            /* EJTAG support */

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_DESAVE));

            rn = "DESAVE";

        case 2 ... 7:

            CP0_CHECK(ctx->kscrexist & (1 << sel));

            tcg_gen_ld_tl(arg, cpu_env,

                          offsetof(CPUMIPSState, CP0_KScratch[sel-2]));

            rn = "KScratch";

        default:

            goto cp0_unimplemented;

        }

    default:

        goto cp0_unimplemented;

    }

    trace_mips_translate_c0("dmfc0", rn, reg, sel);

    return;

cp0_unimplemented:

    qemu_log_mask(LOG_UNIMP, "dmfc0 %s (reg %d sel %d)\n", rn, reg, sel);

    gen_mfc0_unimplemented(ctx, arg);

}


static inline uint16_t mipsdsp_trunc16_sat16_round(int32_t a,

                                                   CPUMIPSState *env)

{

    int64_t temp;

    temp = (int32_t)a + 0x00008000;

    if (a > (int)0x7fff8000) {

        temp = 0x7FFFFFFF;

        set_DSPControl_overflow_flag(1, 22, env);

    }

    return (temp >> 16) & 0xFFFF;

}


static void celt_pvq_search(float *X, int *y, int K, int N)

{

    int i;

    float res = 0.0f, y_norm = 0.0f, xy_norm = 0.0f;

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

        res += FFABS(X[i]);

    res = K/res;

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

        y[i] = lrintf(res*X[i]);

        y_norm  += y[i]*y[i];

        xy_norm += y[i]*X[i];

        K -= FFABS(y[i]);

    }

    while (K) {

        int max_idx = 0, phase = FFSIGN(K);

        float max_den = 1.0f, max_num = 0.0f;

        y_norm += 1.0f;

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

            float xy_new = xy_norm + 1*phase*FFABS(X[i]);

            float y_new  = y_norm  + 2*phase*FFABS(y[i]);

            xy_new = xy_new * xy_new;

            /* FIXME: the y[i] check makes the search slightly worse at Ks below 5 */

            if (y[i] && (max_den*xy_new) > (y_new*max_num)) {

                max_den = y_new;

                max_num = xy_new;

                max_idx = i;

            }

        }

        K -= phase;

        phase *= FFSIGN(X[max_idx]);

        xy_norm += 1*phase*X[max_idx];

        y_norm  += 2*phase*y[max_idx];

        y[max_idx] += phase;

    }

}


static int rtsp_read_seek(AVFormatContext *s, int stream_index,

                          int64_t timestamp, int flags)

{

    RTSPState *rt = s->priv_data;

    rt->seek_timestamp = av_rescale_q(timestamp, s->streams[stream_index]->time_base, AV_TIME_BASE_Q);

    switch(rt->state) {

    default:

    case RTSP_STATE_IDLE:

        break;

    case RTSP_STATE_PLAYING:

        if (rtsp_read_pause(s) != 0)

            return -1;

        rt->state = RTSP_STATE_SEEKING;

        if (rtsp_read_play(s) != 0)

            return -1;

        break;

    case RTSP_STATE_PAUSED:

        rt->state = RTSP_STATE_IDLE;

        break;

    }

    return 0;

}


static inline void RENAME(yuy2ToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(

        "movq "MANGLE(bm01010101)", %%mm2           \n\t"

        "mov                    %0, %%"REG_a"       \n\t"

        "1:                                         \n\t"

        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"

        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"

        "pand                %%mm2, %%mm0           \n\t"

        "pand                %%mm2, %%mm1           \n\t"

        "packuswb            %%mm1, %%mm0           \n\t"

        "movq                %%mm0, (%2, %%"REG_a") \n\t"

        "add                    $8, %%"REG_a"       \n\t"

        " js                    1b                  \n\t"

        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst+width)

        : "%"REG_a

    );

#else

    int i;

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

        dst[i]= src[2*i];

#endif

}


static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){

    AVFrame *pic=NULL;

    int64_t pts;

    int i;

    const int encoding_delay= s->max_b_frames;

    int direct=1;

    if(pic_arg){

        pts= pic_arg->pts;

        pic_arg->display_picture_number= s->input_picture_number++;

        if(pts != AV_NOPTS_VALUE){

            if(s->user_specified_pts != AV_NOPTS_VALUE){

                int64_t time= pts;

                int64_t last= s->user_specified_pts;

                if(time <= last){

                    av_log(s->avctx, AV_LOG_ERROR, "Error, Invalid timestamp=%"PRId64", last=%"PRId64"\n", pts, s->user_specified_pts);

                    return -1;

                }

            }

            s->user_specified_pts= pts;

        }else{

            if(s->user_specified_pts != AV_NOPTS_VALUE){

                s->user_specified_pts=

                pts= s->user_specified_pts + 1;

                av_log(s->avctx, AV_LOG_INFO, "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n", pts);

            }else{

                pts= pic_arg->display_picture_number;

            }

        }

    }

  if(pic_arg){

    if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;

    if(pic_arg->linesize[0] != s->linesize) direct=0;

    if(pic_arg->linesize[1] != s->uvlinesize) direct=0;

    if(pic_arg->linesize[2] != s->uvlinesize) direct=0;

//    av_log(AV_LOG_DEBUG, "%d %d %d %d\n",pic_arg->linesize[0], pic_arg->linesize[1], s->linesize, s->uvlinesize);

    if(direct){

        i= ff_find_unused_picture(s, 1);

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

        pic->reference= 3;

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

            pic->data[i]= pic_arg->data[i];

            pic->linesize[i]= pic_arg->linesize[i];

        }

        ff_alloc_picture(s, (Picture*)pic, 1);

    }else{

        i= ff_find_unused_picture(s, 0);

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

        pic->reference= 3;

        ff_alloc_picture(s, (Picture*)pic, 0);

        if(   pic->data[0] + INPLACE_OFFSET == pic_arg->data[0]

           && pic->data[1] + INPLACE_OFFSET == pic_arg->data[1]

           && pic->data[2] + INPLACE_OFFSET == pic_arg->data[2]){

       // empty

        }else{

            int h_chroma_shift, v_chroma_shift;

            avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);

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

                int src_stride= pic_arg->linesize[i];

                int dst_stride= i ? s->uvlinesize : s->linesize;

                int h_shift= i ? h_chroma_shift : 0;

                int v_shift= i ? v_chroma_shift : 0;

                int w= s->width >>h_shift;

                int h= s->height>>v_shift;

                uint8_t *src= pic_arg->data[i];

                uint8_t *dst= pic->data[i];

                if(!s->avctx->rc_buffer_size)

                    dst +=INPLACE_OFFSET;

                if(src_stride==dst_stride)

                    memcpy(dst, src, src_stride*h);

                else{

                    while(h--){

                        memcpy(dst, src, w);

                        dst += dst_stride;

                        src += src_stride;

                    }

                }

            }

        }

    }

    copy_picture_attributes(s, pic, pic_arg);

    pic->pts= pts; //we set this here to avoid modifiying pic_arg

  }

    /* shift buffer entries */

    for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)

        s->input_picture[i-1]= s->input_picture[i];

    s->input_picture[encoding_delay]= (Picture*)pic;

    return 0;

}


static inline void MPV_motion_lowres(MpegEncContext *s,

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

                              int dir, uint8_t **ref_picture,

                              h264_chroma_mc_func *pix_op)

{

    int mx, my;

    int mb_x, mb_y, i;

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

    const int block_s= 8>>lowres;

    mb_x = s->mb_x;

    mb_y = s->mb_y;

    switch(s->mv_type) {

    case MV_TYPE_16X16:

        mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,

                    0, 0, 0,

                    ref_picture, pix_op,

                    s->mv[dir][0][0], s->mv[dir][0][1], 2*block_s);

        break;

    case MV_TYPE_8X8:

        mx = 0;

        my = 0;

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

                hpel_motion_lowres(s, dest_y + ((i & 1) + (i >> 1) * s->linesize)*block_s,

                            ref_picture[0], 0, 0,

                            (2*mb_x + (i & 1))*block_s, (2*mb_y + (i >>1))*block_s,

                            s->width, s->height, s->linesize,

                            s->h_edge_pos >> lowres, s->v_edge_pos >> lowres,

                            block_s, block_s, pix_op,

                            s->mv[dir][i][0], s->mv[dir][i][1]);

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

                my += s->mv[dir][i][1];

            }

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

            chroma_4mv_motion_lowres(s, dest_cb, dest_cr, ref_picture, pix_op, mx, my);

        break;

    case MV_TYPE_FIELD:

        if (s->picture_structure == PICT_FRAME) {

            /* top field */

            mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,

                        1, 0, s->field_select[dir][0],

                        ref_picture, pix_op,

                        s->mv[dir][0][0], s->mv[dir][0][1], block_s);

            /* bottom field */

            mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,

                        1, 1, s->field_select[dir][1],

                        ref_picture, pix_op,

                        s->mv[dir][1][0], s->mv[dir][1][1], block_s);

        } else {

            if(s->picture_structure != s->field_select[dir][0] + 1 && s->pict_type != B_TYPE && !s->first_field){

                ref_picture= s->current_picture_ptr->data;

            }

            mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,

                        0, 0, s->field_select[dir][0],

                        ref_picture, pix_op,

                        s->mv[dir][0][0], s->mv[dir][0][1], 2*block_s);

        }

        break;

    case MV_TYPE_16X8:

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

            uint8_t ** ref2picture;

            if(s->picture_structure == s->field_select[dir][i] + 1 || s->pict_type == B_TYPE || s->first_field){

                ref2picture= ref_picture;

            }else{

                ref2picture= s->current_picture_ptr->data;

            }

            mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,

                        0, 0, s->field_select[dir][i],

                        ref2picture, pix_op,

                        s->mv[dir][i][0], s->mv[dir][i][1] + 2*block_s*i, block_s);

            dest_y += 2*block_s*s->linesize;

            dest_cb+= (2*block_s>>s->chroma_y_shift)*s->uvlinesize;

            dest_cr+= (2*block_s>>s->chroma_y_shift)*s->uvlinesize;

        }

        break;

    case MV_TYPE_DMV:

        if(s->picture_structure == PICT_FRAME){

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

                int j;

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

                    mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,

                                1, j, j^i,

                                ref_picture, pix_op,

                                s->mv[dir][2*i + j][0], s->mv[dir][2*i + j][1], block_s);

                }

                pix_op = s->dsp.avg_h264_chroma_pixels_tab;

            }

        }else{

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

                mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,

                            0, 0, s->picture_structure != i+1,

                            ref_picture, pix_op,

                            s->mv[dir][2*i][0],s->mv[dir][2*i][1],2*block_s);

                // after put we make avg of the same block

                pix_op = s->dsp.avg_h264_chroma_pixels_tab;

                //opposite parity is always in the same frame if this is second field

                if(!s->first_field){

                    ref_picture = s->current_picture_ptr->data;

                }

            }

        }

    break;

    default: assert(0);

    }

}


static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)

{

    int ret, i;

    int tp_index = 0;

    s->bit_index = 8;

    if (tile->poc.nb_poc) {

        for (i=0; i<tile->poc.nb_poc; i++) {

            Jpeg2000POCEntry *e = &tile->poc.poc[i];

            ret = jpeg2000_decode_packets_po_iteration(s, tile,

                e->RSpoc, e->CSpoc,

                e->LYEpoc, e->REpoc, e->CEpoc,

                e->Ppoc, &tp_index

                );

            if (ret < 0)

                return ret;

        }

    } else {

        ret = jpeg2000_decode_packets_po_iteration(s, tile,

            0, 0,

            tile->codsty[0].nlayers,

            33,

            s->ncomponents,

            tile->codsty[0].prog_order,

            &tp_index

        );

    }

    /* EOC marker reached */

    bytestream2_skip(&s->g, 2);

    return ret;

}


static int blk_prw(BlockBackend *blk, int64_t offset, uint8_t *buf,

                   int64_t bytes, CoroutineEntry co_entry,

                   BdrvRequestFlags flags)

{

    AioContext *aio_context;

    QEMUIOVector qiov;

    struct iovec iov;

    Coroutine *co;

    BlkRwCo rwco;

    iov = (struct iovec) {

        .iov_base = buf,

        .iov_len = bytes,

    };

    qemu_iovec_init_external(&qiov, &iov, 1);

    rwco = (BlkRwCo) {

        .blk    = blk,

        .offset = offset,

        .qiov   = &qiov,

        .flags  = flags,

        .ret    = NOT_DONE,

    };

    co = qemu_coroutine_create(co_entry);

    qemu_coroutine_enter(co, &rwco);

    aio_context = blk_get_aio_context(blk);

    while (rwco.ret == NOT_DONE) {

        aio_poll(aio_context, true);

    }

    return rwco.ret;

}


static void gen_spr_thrm (CPUPPCState *env)

{

    /* Thermal management */

    /* XXX : not implemented */

    spr_register(env, SPR_THRM1, "THRM1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_THRM2, "THRM2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_THRM3, "THRM3",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

}


static int pix_sum_altivec(uint8_t *pix, int line_size)

{

    int i, s;

    const vector unsigned int zero =

        (const vector unsigned int) vec_splat_u32(0);

    vector unsigned int sad = (vector unsigned int) vec_splat_u32(0);

    vector signed int sumdiffs;

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

        /* Read the potentially unaligned 16 pixels into t1. */

        //vector unsigned char pixl = vec_ld(0,  pix);

        //vector unsigned char pixr = vec_ld(15, pix);

        //vector unsigned char t1   = vec_perm(pixl, pixr, perm);

        vector unsigned char t1   = vec_vsx_ld(0,  pix);

        /* Add each 4 pixel group together and put 4 results into sad. */

        sad = vec_sum4s(t1, sad);

        pix += line_size;

    }

    /* Sum up the four partial sums, and put the result into s. */

    sumdiffs = vec_sums((vector signed int) sad, (vector signed int) zero);

    sumdiffs = vec_splat(sumdiffs, 3);

    vec_vsx_st(sumdiffs, 0, &s);

    return s;

}


static void mb_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    MicroBlazeCPU *cpu = MICROBLAZE_CPU(obj);

    CPUMBState *env = &cpu->env;

    static bool tcg_initialized;

    cs->env_ptr = env;

    cpu_exec_init(cs, &error_abort);

    set_float_rounding_mode(float_round_nearest_even, &env->fp_status);

#ifndef CONFIG_USER_ONLY

    /* Inbound IRQ and FIR lines */

    qdev_init_gpio_in(DEVICE(cpu), microblaze_cpu_set_irq, 2);

#endif

    if (tcg_enabled() && !tcg_initialized) {

        tcg_initialized = true;

        mb_tcg_init();

    }

}


int bdrv_create(BlockDriver *drv, const char* filename,

                QemuOpts *opts, Error **errp)

{

    int ret;

    Coroutine *co;

    CreateCo cco = {

        .drv = drv,

        .filename = g_strdup(filename),

        .opts = opts,

        .ret = NOT_DONE,

        .err = NULL,

    };

    if (!drv->bdrv_create) {

        error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);

        ret = -ENOTSUP;

        goto out;

    }

    if (qemu_in_coroutine()) {

        /* Fast-path if already in coroutine context */

        bdrv_create_co_entry(&cco);

    } else {

        co = qemu_coroutine_create(bdrv_create_co_entry);

        qemu_coroutine_enter(co, &cco);

        while (cco.ret == NOT_DONE) {

            aio_poll(qemu_get_aio_context(), true);

        }

    }

    ret = cco.ret;

    if (ret < 0) {

        if (cco.err) {

            error_propagate(errp, cco.err);

        } else {

            error_setg_errno(errp, -ret, "Could not create image");

        }

    }

out:

    g_free(cco.filename);

    return ret;

}


ssize_t qsb_get_buffer(const QEMUSizedBuffer *qsb, off_t start,

                       size_t count, uint8_t *buffer)

{

    const struct iovec *iov;

    size_t to_copy, all_copy;

    ssize_t index;

    off_t s_off;

    off_t d_off = 0;

    char *s;

    if (start > qsb->used) {

        return 0;

    }

    all_copy = qsb->used - start;

    if (all_copy > count) {

        all_copy = count;

    } else {

        count = all_copy;

    }

    index = qsb_get_iovec(qsb, start, &s_off);

    if (index < 0) {

        return 0;

    }

    while (all_copy > 0) {

        iov = &qsb->iov[index];

        s = iov->iov_base;

        to_copy = iov->iov_len - s_off;

        if (to_copy > all_copy) {

            to_copy = all_copy;

        }

        memcpy(&buffer[d_off], &s[s_off], to_copy);

        d_off += to_copy;

        all_copy -= to_copy;

        s_off = 0;

        index++;

    }

    return count;

}


static void vfio_probe_ati_bar4_quirk(VFIOPCIDevice *vdev, int nr)

{

    VFIOQuirk *quirk;

    VFIOConfigWindowQuirk *window;

    /* This windows doesn't seem to be used except by legacy VGA code */

    if (!vfio_pci_is(vdev, PCI_VENDOR_ID_ATI, PCI_ANY_ID) ||

        !vdev->has_vga || nr != 4) {

        return;

    }

    quirk = g_malloc0(sizeof(*quirk));

    quirk->mem = g_malloc0(sizeof(MemoryRegion) * 2);

    quirk->nr_mem = 2;

    window = quirk->data = g_malloc0(sizeof(*window) +

                                     sizeof(VFIOConfigWindowMatch));

    window->vdev = vdev;

    window->address_offset = 0;

    window->data_offset = 4;

    window->nr_matches = 1;

    window->matches[0].match = 0x4000;

    window->matches[0].mask = PCIE_CONFIG_SPACE_SIZE - 1;

    window->bar = nr;

    window->addr_mem = &quirk->mem[0];

    window->data_mem = &quirk->mem[1];

    memory_region_init_io(window->addr_mem, OBJECT(vdev),

                          &vfio_generic_window_address_quirk, window,

                          "vfio-ati-bar4-window-address-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        window->address_offset,

                                        window->addr_mem, 1);

    memory_region_init_io(window->data_mem, OBJECT(vdev),

                          &vfio_generic_window_data_quirk, window,

                          "vfio-ati-bar4-window-data-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        window->data_offset,

                                        window->data_mem, 1);

    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    trace_vfio_quirk_ati_bar4_probe(vdev->vbasedev.name);

}


static void scsi_read_data(SCSIDevice *d, uint32_t tag)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);

    SCSIDiskReq *r;

    r = scsi_find_request(s, tag);

    if (!r) {

        BADF("Bad read tag 0x%x\n", tag);

        /* ??? This is the wrong error.  */

        scsi_command_complete(r, CHECK_CONDITION, HARDWARE_ERROR);

        return;

    }

    scsi_read_request(r);

}


static inline void mix_3f_1r_to_dolby(AC3DecodeContext *ctx)

{

    int i;

    float (*output)[256] = ctx->audio_block.block_output;

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

        output[1][i] += (output[2][i] - output[4][i]);

        output[2][i] += (output[3][i] + output[4][i]);

    }

    memset(output[3], 0, sizeof(output[3]));

    memset(output[4], 0, sizeof(output[4]));

}


static int has_codec_parameters(AVCodecContext *enc)

{

    int val;

    switch(enc->codec_type) {

    case CODEC_TYPE_AUDIO:

        val = enc->sample_rate;

        break;

    case CODEC_TYPE_VIDEO:

        val = enc->width && enc->pix_fmt != PIX_FMT_NONE;

        break;

    default:

        val = 1;

        break;

    }

    return (val != 0);

}


static int test_vector_fmul_scalar(AVFloatDSPContext *fdsp, AVFloatDSPContext *cdsp,

                                   const float *v1, float scale)

{

    LOCAL_ALIGNED(32, float, cdst, [LEN]);

    LOCAL_ALIGNED(32, float, odst, [LEN]);

    int ret;

    cdsp->vector_fmul_scalar(cdst, v1, scale, LEN);

    fdsp->vector_fmul_scalar(odst, v1, scale, LEN);

    if (ret = compare_floats(cdst, odst, LEN, FLT_EPSILON))

        av_log(NULL, AV_LOG_ERROR, "vector_fmul_scalar failed\n");

    return ret;

}


static void smp_parse(QemuOpts *opts)

{

    if (opts) {

        unsigned cpus    = qemu_opt_get_number(opts, "cpus", 0);

        unsigned sockets = qemu_opt_get_number(opts, "sockets", 0);

        unsigned cores   = qemu_opt_get_number(opts, "cores", 0);

        unsigned threads = qemu_opt_get_number(opts, "threads", 0);

        /* compute missing values, prefer sockets over cores over threads */

        if (cpus == 0 || sockets == 0) {

            sockets = sockets > 0 ? sockets : 1;

            cores = cores > 0 ? cores : 1;

            threads = threads > 0 ? threads : 1;

            if (cpus == 0) {

                cpus = cores * threads * sockets;

            }

        } else if (cores == 0) {

            threads = threads > 0 ? threads : 1;

            cores = cpus / (sockets * threads);

        } else if (threads == 0) {

            threads = cpus / (cores * sockets);

        } else if (sockets * cores * threads < cpus) {

            fprintf(stderr, "cpu topology: error: "

                    "sockets (%u) * cores (%u) * threads (%u) < "

                    "smp_cpus (%u)\n",

                    sockets, cores, threads, cpus);

            exit(1);

        }

        max_cpus = qemu_opt_get_number(opts, "maxcpus", 0);

        smp_cpus = cpus;

        smp_cores = cores > 0 ? cores : 1;

        smp_threads = threads > 0 ? threads : 1;

    }

    if (max_cpus == 0) {

        max_cpus = smp_cpus;

    }

    if (max_cpus > MAX_CPUMASK_BITS) {

        fprintf(stderr, "Unsupported number of maxcpus\n");

        exit(1);

    }

    if (max_cpus < smp_cpus) {

        fprintf(stderr, "maxcpus must be equal to or greater than smp\n");

        exit(1);

    }

}


static void interface_set_client_capabilities(QXLInstance *sin,
                                              uint8_t client_present,
                                              uint8_t caps[58])
{
    PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
    qxl->shadow_rom.client_present = client_present;
    memcpy(qxl->shadow_rom.client_capabilities, caps, sizeof(caps));
    qxl->rom->client_present = client_present;
    memcpy(qxl->rom->client_capabilities, caps, sizeof(caps));
    qxl_rom_set_dirty(qxl);
    qxl_send_events(qxl, QXL_INTERRUPT_CLIENT);


AUXReply aux_request(AUXBus *bus, AUXCommand cmd, uint32_t address,

                      uint8_t len, uint8_t *data)

{

    AUXReply ret = AUX_NACK;

    I2CBus *i2c_bus = aux_get_i2c_bus(bus);

    size_t i;

    bool is_write = false;

    DPRINTF("request at address 0x%" PRIX32 ", command %u, len %u\n", address,

            cmd, len);

    switch (cmd) {

    /*

     * Forward the request on the AUX bus..

     */

    case WRITE_AUX:

    case READ_AUX:

        is_write = cmd == READ_AUX ? false : true;

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

            if (!address_space_rw(&bus->aux_addr_space, address++,

                                  MEMTXATTRS_UNSPECIFIED, data++, 1,

                                  is_write)) {

                ret = AUX_I2C_ACK;

            } else {

                ret = AUX_NACK;

                break;

            }

        }

        break;

    /*

     * Classic I2C transactions..

     */

    case READ_I2C:

    case WRITE_I2C:

        is_write = cmd == READ_I2C ? false : true;

        if (i2c_bus_busy(i2c_bus)) {

            i2c_end_transfer(i2c_bus);

        }

        if (i2c_start_transfer(i2c_bus, address, is_write)) {

            ret = AUX_I2C_NACK;

            break;

        }

        ret = AUX_I2C_ACK;

        while (len > 0) {

            if (i2c_send_recv(i2c_bus, data++, is_write) < 0) {

                ret = AUX_I2C_NACK;

                break;

            }

            len--;

        }

        i2c_end_transfer(i2c_bus);

        break;

    /*

     * I2C MOT transactions.

     *

     * Here we send a start when:

     *  - We didn't start transaction yet.

     *  - We had a READ and we do a WRITE.

     *  - We changed the address.

     */

    case WRITE_I2C_MOT:

    case READ_I2C_MOT:

        is_write = cmd == READ_I2C_MOT ? false : true;

        ret = AUX_I2C_NACK;

        if (!i2c_bus_busy(i2c_bus)) {

            /*

             * No transactions started..

             */

            if (i2c_start_transfer(i2c_bus, address, is_write)) {

                break;

            }

        } else if ((address != bus->last_i2c_address) ||

                   (bus->last_transaction != cmd)) {

            /*

             * Transaction started but we need to restart..

             */

            i2c_end_transfer(i2c_bus);

            if (i2c_start_transfer(i2c_bus, address, is_write)) {

                break;

            }

        }

        bus->last_transaction = cmd;

        bus->last_i2c_address = address;

        while (len > 0) {

            if (i2c_send_recv(i2c_bus, data++, is_write) < 0) {

                i2c_end_transfer(i2c_bus);

                break;

            }

            len--;

        }

        if (len == 0) {

            ret = AUX_I2C_ACK;

        }

        break;

    default:

        DPRINTF("Not implemented!\n");

        return AUX_NACK;

    }

    DPRINTF("reply: %u\n", ret);

    return ret;

}


static sd_rsp_type_t sd_app_command(SDState *sd,

                                    SDRequest req)

{

    DPRINTF("ACMD%d 0x%08x\n", req.cmd, req.arg);

    switch (req.cmd) {

    case 6:	/* ACMD6:  SET_BUS_WIDTH */

        switch (sd->state) {

        case sd_transfer_state:

            sd->sd_status[0] &= 0x3f;

            sd->sd_status[0] |= (req.arg & 0x03) << 6;

            return sd_r1;

        default:

            break;

        }

        break;

    case 13:	/* ACMD13: SD_STATUS */

        switch (sd->state) {

        case sd_transfer_state:

            sd->state = sd_sendingdata_state;

            sd->data_start = 0;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */

        switch (sd->state) {

        case sd_transfer_state:

            *(uint32_t *) sd->data = sd->blk_written;

            sd->state = sd_sendingdata_state;

            sd->data_start = 0;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    case 23:	/* ACMD23: SET_WR_BLK_ERASE_COUNT */

        switch (sd->state) {

        case sd_transfer_state:

            return sd_r1;

        default:

            break;

        }

        break;

    case 41:	/* ACMD41: SD_APP_OP_COND */

        if (sd->spi) {

            /* SEND_OP_CMD */

            sd->state = sd_transfer_state;

            return sd_r1;

        }

        switch (sd->state) {

        case sd_idle_state:

            /* We accept any voltage.  10000 V is nothing.  */

            if (req.arg)

                sd->state = sd_ready_state;

            return sd_r3;

        default:

            break;

        }

        break;

    case 42:	/* ACMD42: SET_CLR_CARD_DETECT */

        switch (sd->state) {

        case sd_transfer_state:

            /* Bringing in the 50KOhm pull-up resistor... Done.  */

            return sd_r1;

        default:

            break;

        }

        break;

    case 51:	/* ACMD51: SEND_SCR */

        switch (sd->state) {

        case sd_transfer_state:

            sd->state = sd_sendingdata_state;

            sd->data_start = 0;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    default:

        /* Fall back to standard commands.  */

        sd->card_status &= ~APP_CMD;

        return sd_normal_command(sd, req);

    }

    fprintf(stderr, "SD: ACMD%i in a wrong state\n", req.cmd);

    return sd_illegal;

}


static int smc91c111_can_receive(NetClientState *nc)

{

    smc91c111_state *s = qemu_get_nic_opaque(nc);

    if ((s->rcr & RCR_RXEN) == 0 || (s->rcr & RCR_SOFT_RST))

        return 1;

    if (s->allocated == (1 << NUM_PACKETS) - 1)

        return 0;

    return 1;

}


static ssize_t mp_dacl_listxattr(FsContext *ctx, const char *path,

                                 char *name, void *value, size_t osize)

{

    ssize_t len = sizeof(ACL_DEFAULT);

    if (!value) {

        return len;

    }

    if (osize < len) {

        errno = ERANGE;

        return -1;

    }

    /* len includes the trailing NUL */

    memcpy(value, ACL_ACCESS, len);

    return 0;

}


static int vc1_decode_p_mb(VC1Context *v, DCTELEM block[6][64])

{

    MpegEncContext *s = &v->s;

    GetBitContext *gb = &s->gb;

    int i, j;

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

    int cbp; /* cbp decoding stuff */

    int mqdiff, mquant; /* MB quantization */

    int ttmb = v->ttfrm; /* MB Transform type */

    int status;

    static const int size_table[6] = { 0, 2, 3, 4, 5, 8 },

      offset_table[6] = { 0, 1, 3, 7, 15, 31 };

    int mb_has_coeffs = 1; /* last_flag */

    int dmv_x, dmv_y; /* Differential MV components */

    int index, index1; /* LUT indices */

    int val, sign; /* temp values */

    int first_block = 1;

    int dst_idx, off;

    int skipped, fourmv;

    mquant = v->pq; /* Loosy initialization */

    if (v->mv_type_is_raw)

        fourmv = get_bits1(gb);

    else

        fourmv = v->mv_type_mb_plane[mb_pos];

    if (v->skip_is_raw)

        skipped = get_bits1(gb);

    else

        skipped = v->s.mbskip_table[mb_pos];

    s->dsp.clear_blocks(s->block[0]);

    if (!fourmv) /* 1MV mode */

    {

        if (!skipped)

        {

            GET_MVDATA(dmv_x, dmv_y);

            s->current_picture.mb_type[mb_pos] = s->mb_intra ? MB_TYPE_INTRA : MB_TYPE_16x16;

            vc1_pred_mv(s, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0]);

            /* FIXME Set DC val for inter block ? */

            if (s->mb_intra && !mb_has_coeffs)

            {

                GET_MQUANT();

                s->ac_pred = get_bits(gb, 1);

                cbp = 0;

            }

            else if (mb_has_coeffs)

            {

                if (s->mb_intra) s->ac_pred = get_bits(gb, 1);

                cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

                GET_MQUANT();

            }

            else

            {

                mquant = v->pq;

                cbp = 0;

            }

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

            if (!v->ttmbf && !s->mb_intra && mb_has_coeffs)

                ttmb = get_vlc2(gb, vc1_ttmb_vlc[v->tt_index].table,

                                VC1_TTMB_VLC_BITS, 2);

            if(!s->mb_intra) vc1_mc_1mv(v);

            dst_idx = 0;

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

            {

                s->dc_val[0][s->block_index[i]] = 0;

                dst_idx += i >> 2;

                val = ((cbp >> (5 - i)) & 1);

                off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);

                v->mb_type[0][s->block_index[i]] = s->mb_intra;

                if(s->mb_intra) {

                    /* check if prediction blocks A and C are available */

                    v->a_avail = v->c_avail = 0;

                    if(i == 2 || i == 3 || s->mb_y)

                        v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];

                    if(i == 1 || i == 3 || s->mb_x)

                        v->c_avail = v->mb_type[0][s->block_index[i] - 1];

                    vc1_decode_intra_block(v, block[i], i, val, mquant, (i&4)?v->codingset2:v->codingset);

                    vc1_inv_trans(block[i], 8, 8);

                    for(j = 0; j < 64; j++) block[i][j] += 128;

                    s->dsp.put_pixels_clamped(block[i], s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));

                    /* TODO: proper loop filtering */

                    if(v->pq >= 9 && v->overlap) {

                        if(v->a_avail)

                            s->dsp.h263_v_loop_filter(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2), s->y_dc_scale);

                        if(v->c_avail)

                            s->dsp.h263_h_loop_filter(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2), s->y_dc_scale);

                    }

                } else if(val) {

                    vc1_decode_p_block(v, block[i], i, mquant, ttmb, first_block);

                    if(!v->ttmbf && ttmb < 8) ttmb = -1;

                    first_block = 0;

                    s->dsp.add_pixels_clamped(block[i], s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize);

                }

            }

        }

        else //Skipped

        {

            s->mb_intra = 0;

            for(i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0;

            s->current_picture.mb_type[mb_pos] = MB_TYPE_SKIP;

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

            vc1_pred_mv(s, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0]);

            vc1_mc_1mv(v);

            return 0;

        }

    } //1MV mode

    else //4MV mode

    {

        if (!skipped /* unskipped MB */)

        {

            int intra_count = 0, coded_inter = 0;

            int is_intra[6], is_coded[6];

            /* Get CBPCY */

            cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

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

            {

                val = ((cbp >> (5 - i)) & 1);

                s->dc_val[0][s->block_index[i]] = 0;

                s->mb_intra = 0;

                if(i < 4) {

                    dmv_x = dmv_y = 0;

                    s->mb_intra = 0;

                    mb_has_coeffs = 0;

                    if(val) {

                        GET_MVDATA(dmv_x, dmv_y);

                    }

                    vc1_pred_mv(s, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0]);

                    if(!s->mb_intra) vc1_mc_4mv_luma(v, i);

                    intra_count += s->mb_intra;

                    is_intra[i] = s->mb_intra;

                    is_coded[i] = mb_has_coeffs;

                }

                if(i&4){

                    is_intra[i] = (intra_count >= 3);

                    is_coded[i] = val;

                }

                if(i == 4) vc1_mc_4mv_chroma(v);

                v->mb_type[0][s->block_index[i]] = is_intra[i];

                if(!coded_inter) coded_inter = !is_intra[i] & is_coded[i];

            }

            dst_idx = 0;

            GET_MQUANT();

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

            /* test if block is intra and has pred */

            {

                int intrapred = 0;

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

                    if(is_intra[i]) {

                        if(((s->mb_y || (i==2 || i==3)) && v->mb_type[0][s->block_index[i] - s->block_wrap[i]])

                             || ((s->mb_x || (i==1 || i==3)) && v->mb_type[0][s->block_index[i] - 1])) {

                            intrapred = 1;

                            break;

                        }

                    }

                if(intrapred)s->ac_pred = get_bits(gb, 1);

                else s->ac_pred = 0;

            }

            if (!v->ttmbf && coded_inter)

                ttmb = get_vlc2(gb, vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 12);

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

            {

                dst_idx += i >> 2;

                off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);

                s->mb_intra = is_intra[i];

                if (is_intra[i]) {

                    /* check if prediction blocks A and C are available */

                    v->a_avail = v->c_avail = 0;

                    if(i == 2 || i == 3 || s->mb_y)

                        v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];

                    if(i == 1 || i == 3 || s->mb_x)

                        v->c_avail = v->mb_type[0][s->block_index[i] - 1];

                    vc1_decode_intra_block(v, s->block[i], i, is_coded[i], mquant, (i&4)?v->codingset2:v->codingset);

                    vc1_inv_trans(block[i], 8, 8);

                    for(j = 0; j < 64; j++) block[i][j] += 128;

                    s->dsp.put_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize);

                    /* TODO: proper loop filtering */

                    if(v->pq >= 9 && v->overlap) {

                        if(v->a_avail)

                            s->dsp.h263_v_loop_filter(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2), s->y_dc_scale);

                        if(v->c_avail)

                            s->dsp.h263_h_loop_filter(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2), s->y_dc_scale);

                    }

                } else if(is_coded[i]) {

                    status = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block);

                    if(!v->ttmbf && ttmb < 8) ttmb = -1;

                    first_block = 0;

                    s->dsp.add_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize);

                }

            }

            return status;

        }

        else //Skipped MB

        {

            s->mb_intra = 0;

            for (i=0; i<6; i++) v->mb_type[0][s->block_index[i]] = 0;

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

            {

                vc1_pred_mv(s, i, 0, 0, 0, v->range_x, v->range_y, v->mb_type[0]);

                vc1_mc_4mv_luma(v, i);

            }

            vc1_mc_4mv_chroma(v);

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

            return 0;

        }

    }

    /* Should never happen */

    return -1;

}


int avfilter_parse_graph(AVFilterGraph *graph, const char *filters,

                         AVFilterInOut *open_inputs,

                         AVFilterInOut *open_outputs, AVClass *log_ctx)

{

    int index = 0;

    char chr = 0;

    AVFilterInOut *curr_inputs = NULL;

    do {

        AVFilterContext *filter;

        filters += consume_whitespace(filters);

        if(parse_inputs(&filters, &curr_inputs, &open_outputs, log_ctx) < 0)

            goto fail;

        filter = parse_filter(&filters, graph, index, log_ctx);

        if(!filter)

            goto fail;

        if(filter->input_count == 1 && !curr_inputs && !index) {

            /* First input can be omitted if it is "[in]" */

            const char *tmp = "[in]";

            if(parse_inputs(&tmp, &curr_inputs, &open_outputs, log_ctx) < 0)

                goto fail;

        }

        if(link_filter_inouts(filter, &curr_inputs, &open_inputs, log_ctx) < 0)

            goto fail;

        if(parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,

                         log_ctx) < 0)

            goto fail;

        filters += consume_whitespace(filters);

        chr = *filters++;

        if(chr == ';' && curr_inputs) {

            av_log(log_ctx, AV_LOG_ERROR,

                   "Could not find a output to link when parsing \"%s\"\n",

                   filters - 1);

            goto fail;

        }

        index++;

    } while(chr == ',' || chr == ';');

    if (*filters) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Unable to parse graph description substring: \"%s\"\n",

               filters - 1);

        goto fail;

    }

    if(open_inputs && !strcmp(open_inputs->name, "out") && curr_inputs) {

        /* Last output can be omitted if it is "[out]" */

        const char *tmp = "[out]";

        if(parse_outputs(&tmp, &curr_inputs, &open_inputs,

                         &open_outputs, log_ctx) < 0)

            goto fail;

    }

    return 0;

 fail:

    avfilter_destroy_graph(graph);

    free_inout(open_inputs);

    free_inout(open_outputs);

    free_inout(curr_inputs);

    return -1;

}


int ff_mpv_frame_size_alloc(MpegEncContext *s, int linesize)

{

    int alloc_size = FFALIGN(FFABS(linesize) + 64, 32);

    // edge emu needs blocksize + filter length - 1

    // (= 17x17 for  halfpel / 21x21 for  h264)

    // VC1 computes luma and chroma simultaneously and needs 19X19 + 9x9

    // at uvlinesize. It supports only YUV420 so 24x24 is enough

    // linesize * interlaced * MBsize

    FF_ALLOCZ_OR_GOTO(s->avctx, s->edge_emu_buffer, alloc_size * 4 * 24,

                      fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->me.scratchpad, alloc_size * 2 * 16 * 2,

                      fail)

    s->me.temp         = s->me.scratchpad;

    s->rd_scratchpad   = s->me.scratchpad;

    s->b_scratchpad    = s->me.scratchpad;

    s->obmc_scratchpad = s->me.scratchpad + 16;

    return 0;

fail:

    av_freep(&s->edge_emu_buffer);

    return AVERROR(ENOMEM);

}


static av_cold int cook_decode_init(AVCodecContext *avctx)

{

    COOKContext *q = avctx->priv_data;

    const uint8_t *edata_ptr = avctx->extradata;

    const uint8_t *edata_ptr_end = edata_ptr + avctx->extradata_size;

    int extradata_size = avctx->extradata_size;

    int s = 0;

    unsigned int channel_mask = 0;

    q->avctx = avctx;

    /* Take care of the codec specific extradata. */

    if (extradata_size <= 0) {

        av_log(avctx,AV_LOG_ERROR,"Necessary extradata missing!\n");

        return -1;

    }

    av_log(avctx,AV_LOG_DEBUG,"codecdata_length=%d\n",avctx->extradata_size);

    /* Take data from the AVCodecContext (RM container). */

    q->sample_rate = avctx->sample_rate;

    q->nb_channels = avctx->channels;

    q->bit_rate = avctx->bit_rate;

    /* Initialize RNG. */

    av_lfg_init(&q->random_state, 0);

    while(edata_ptr < edata_ptr_end){

        /* 8 for mono, 16 for stereo, ? for multichannel

           Swap to right endianness so we don't need to care later on. */

        if (extradata_size >= 8){

            q->subpacket[s].cookversion = bytestream_get_be32(&edata_ptr);

            q->subpacket[s].samples_per_frame =  bytestream_get_be16(&edata_ptr);

            q->subpacket[s].subbands = bytestream_get_be16(&edata_ptr);

            extradata_size -= 8;

        }

        if (avctx->extradata_size >= 8){

            bytestream_get_be32(&edata_ptr);    //Unknown unused

            q->subpacket[s].js_subband_start = bytestream_get_be16(&edata_ptr);

            q->subpacket[s].js_vlc_bits = bytestream_get_be16(&edata_ptr);

            extradata_size -= 8;

        }

        /* Initialize extradata related variables. */

        q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame / q->nb_channels;

        q->subpacket[s].bits_per_subpacket = avctx->block_align * 8;

        /* Initialize default data states. */

        q->subpacket[s].log2_numvector_size = 5;

        q->subpacket[s].total_subbands = q->subpacket[s].subbands;

        q->subpacket[s].num_channels = 1;

        /* Initialize version-dependent variables */

        av_log(avctx,AV_LOG_DEBUG,"subpacket[%i].cookversion=%x\n",s,q->subpacket[s].cookversion);

        q->subpacket[s].joint_stereo = 0;

        switch (q->subpacket[s].cookversion) {

            case MONO:

                if (q->nb_channels != 1) {

                    av_log_ask_for_sample(avctx, "Container channels != 1.\n");

                    return -1;

                }

                av_log(avctx,AV_LOG_DEBUG,"MONO\n");

                break;

            case STEREO:

                if (q->nb_channels != 1) {

                    q->subpacket[s].bits_per_subpdiv = 1;

                    q->subpacket[s].num_channels = 2;

                }

                av_log(avctx,AV_LOG_DEBUG,"STEREO\n");

                break;

            case JOINT_STEREO:

                if (q->nb_channels != 2) {

                    av_log_ask_for_sample(avctx, "Container channels != 2.\n");

                    return -1;

                }

                av_log(avctx,AV_LOG_DEBUG,"JOINT_STEREO\n");

                if (avctx->extradata_size >= 16){

                    q->subpacket[s].total_subbands = q->subpacket[s].subbands + q->subpacket[s].js_subband_start;

                    q->subpacket[s].joint_stereo = 1;

                    q->subpacket[s].num_channels = 2;

                }

                if (q->subpacket[s].samples_per_channel > 256) {

                    q->subpacket[s].log2_numvector_size  = 6;

                }

                if (q->subpacket[s].samples_per_channel > 512) {

                    q->subpacket[s].log2_numvector_size  = 7;

                }

                break;

            case MC_COOK:

                av_log(avctx,AV_LOG_DEBUG,"MULTI_CHANNEL\n");

                if(extradata_size >= 4)

                    channel_mask |= q->subpacket[s].channel_mask = bytestream_get_be32(&edata_ptr);

                if(cook_count_channels(q->subpacket[s].channel_mask) > 1){

                    q->subpacket[s].total_subbands = q->subpacket[s].subbands + q->subpacket[s].js_subband_start;

                    q->subpacket[s].joint_stereo = 1;

                    q->subpacket[s].num_channels = 2;

                    q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame >> 1;

                    if (q->subpacket[s].samples_per_channel > 256) {

                        q->subpacket[s].log2_numvector_size  = 6;

                    }

                    if (q->subpacket[s].samples_per_channel > 512) {

                        q->subpacket[s].log2_numvector_size  = 7;

                    }

                }else

                    q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame;

                break;

            default:

                av_log_ask_for_sample(avctx, "Unknown Cook version.\n");

                return -1;

        }

        if(s > 1 && q->subpacket[s].samples_per_channel != q->samples_per_channel) {

            av_log(avctx,AV_LOG_ERROR,"different number of samples per channel!\n");

            return -1;

        } else

            q->samples_per_channel = q->subpacket[0].samples_per_channel;

        /* Initialize variable relations */

        q->subpacket[s].numvector_size = (1 << q->subpacket[s].log2_numvector_size);

        /* Try to catch some obviously faulty streams, othervise it might be exploitable */

        if (q->subpacket[s].total_subbands > 53) {

            av_log_ask_for_sample(avctx, "total_subbands > 53\n");

            return -1;

        }

        if ((q->subpacket[s].js_vlc_bits > 6) || (q->subpacket[s].js_vlc_bits < 0)) {

            av_log(avctx,AV_LOG_ERROR,"js_vlc_bits = %d, only >= 0 and <= 6 allowed!\n",q->subpacket[s].js_vlc_bits);

            return -1;

        }

        if (q->subpacket[s].subbands > 50) {

            av_log_ask_for_sample(avctx, "subbands > 50\n");

            return -1;

        }

        q->subpacket[s].gains1.now      = q->subpacket[s].gain_1;

        q->subpacket[s].gains1.previous = q->subpacket[s].gain_2;

        q->subpacket[s].gains2.now      = q->subpacket[s].gain_3;

        q->subpacket[s].gains2.previous = q->subpacket[s].gain_4;

        q->num_subpackets++;

        s++;

        if (s > MAX_SUBPACKETS) {

            av_log_ask_for_sample(avctx, "Too many subpackets > 5\n");

            return -1;

        }

    }

    /* Generate tables */

    init_pow2table();

    init_gain_table(q);

    init_cplscales_table(q);

    if (init_cook_vlc_tables(q) != 0)

        return -1;

    if(avctx->block_align >= UINT_MAX/2)

        return -1;

    /* Pad the databuffer with:

       DECODE_BYTES_PAD1 or DECODE_BYTES_PAD2 for decode_bytes(),

       FF_INPUT_BUFFER_PADDING_SIZE, for the bitstreamreader. */

        q->decoded_bytes_buffer =

          av_mallocz(avctx->block_align

                     + DECODE_BYTES_PAD1(avctx->block_align)

                     + FF_INPUT_BUFFER_PADDING_SIZE);

    if (q->decoded_bytes_buffer == NULL)

        return -1;

    /* Initialize transform. */

    if ( init_cook_mlt(q) != 0 )

        return -1;

    /* Initialize COOK signal arithmetic handling */

    if (1) {

        q->scalar_dequant  = scalar_dequant_float;

        q->decouple        = decouple_float;

        q->imlt_window     = imlt_window_float;

        q->interpolate     = interpolate_float;

        q->saturate_output = saturate_output_float;

    }

    /* Try to catch some obviously faulty streams, othervise it might be exploitable */

    if ((q->samples_per_channel == 256) || (q->samples_per_channel == 512) || (q->samples_per_channel == 1024)) {

    } else {

        av_log_ask_for_sample(avctx,

                              "unknown amount of samples_per_channel = %d\n",

                              q->samples_per_channel);

        return -1;

    }

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    if (channel_mask)

        avctx->channel_layout = channel_mask;

    else

        avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;

#ifdef DEBUG

    dump_cook_context(q);

#endif

    return 0;

}


static int http_read(URLContext *h, uint8_t *buf, int size)

{

    HTTPContext *s = h->priv_data;

    int size1, len;

    size1 = size;

    while (size > 0) {

        /* read bytes from input buffer first */

        len = s->buf_end - s->buf_ptr;

        if (len > 0) {

            if (len > size)

                len = size;

            memcpy(buf, s->buf_ptr, len);

            s->buf_ptr += len;

        } else {

            len = url_read (s->hd, buf, size);

            if (len < 0) {

                return len;

            } else if (len == 0) {

                break;

            }

        }

        size -= len;

        buf += len;

    }

    return size1 - size;

}


static void dump_json_image_info_list(ImageInfoList *list)

{

    Error *local_err = NULL;

    QString *str;

    QmpOutputVisitor *ov = qmp_output_visitor_new();

    QObject *obj;

    visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,

                             &local_err);

    obj = qmp_output_get_qobject(ov);

    str = qobject_to_json_pretty(obj);

    assert(str != NULL);

    printf("%s\n", qstring_get_str(str));

    qobject_decref(obj);

    qmp_output_visitor_cleanup(ov);

    QDECREF(str);

}


static void setup_frame(int sig, struct target_sigaction *ka,

                        target_sigset_t *set, CPUS390XState *env)

{

    sigframe *frame;

    abi_ulong frame_addr;

    frame_addr = get_sigframe(ka, env, sizeof(*frame));

    qemu_log("%s: frame_addr 0x%llx\n", __FUNCTION__,

             (unsigned long long)frame_addr);

    if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0)) {

            goto give_sigsegv;

    }

    qemu_log("%s: 1\n", __FUNCTION__);

    if (__put_user(set->sig[0], &frame->sc.oldmask[0])) {

              goto give_sigsegv;

    }

    save_sigregs(env, &frame->sregs);

    __put_user((abi_ulong)(unsigned long)&frame->sregs,

               (abi_ulong *)&frame->sc.sregs);

    /* Set up to return from userspace.  If provided, use a stub

       already in userspace.  */

    if (ka->sa_flags & TARGET_SA_RESTORER) {

            env->regs[14] = (unsigned long)

                    ka->sa_restorer | PSW_ADDR_AMODE;

    } else {

            env->regs[14] = (unsigned long)

                    frame->retcode | PSW_ADDR_AMODE;

            if (__put_user(S390_SYSCALL_OPCODE | TARGET_NR_sigreturn,

                           (uint16_t *)(frame->retcode)))

                    goto give_sigsegv;

    }

    /* Set up backchain. */

    if (__put_user(env->regs[15], (abi_ulong *) frame)) {

            goto give_sigsegv;

    }

    /* Set up registers for signal handler */

    env->regs[15] = frame_addr;

    env->psw.addr = (target_ulong) ka->_sa_handler | PSW_ADDR_AMODE;

    env->regs[2] = sig; //map_signal(sig);

    env->regs[3] = frame_addr += offsetof(typeof(*frame), sc);

    /* We forgot to include these in the sigcontext.

       To avoid breaking binary compatibility, they are passed as args. */

    env->regs[4] = 0; // FIXME: no clue... current->thread.trap_no;

    env->regs[5] = 0; // FIXME: no clue... current->thread.prot_addr;

    /* Place signal number on stack to allow backtrace from handler.  */

    if (__put_user(env->regs[2], (int *) &frame->signo)) {

            goto give_sigsegv;

    }

    unlock_user_struct(frame, frame_addr, 1);

    return;

give_sigsegv:

    qemu_log("%s: give_sigsegv\n", __FUNCTION__);

    unlock_user_struct(frame, frame_addr, 1);

    force_sig(TARGET_SIGSEGV);

}


av_cold void ff_vc2enc_free_transforms(VC2TransformContext *s)

{

    av_freep(&s->buffer);

}


static int find_snapshot_by_id_or_name(BlockDriverState *bs, const char *name)

{

    BDRVQcowState *s = bs->opaque;

    int i, ret;

    ret = find_snapshot_by_id(bs, name);

    if (ret >= 0)

        return ret;

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

        if (!strcmp(s->snapshots[i].name, name))

            return i;

    }

    return -1;

}


void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)

{

    BdrvDirtyBitmap *bitmap;

    QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {

        hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);

    }

}


static av_cold int v410_encode_init(AVCodecContext *avctx)

{

    if (avctx->width & 1) {

        av_log(avctx, AV_LOG_ERROR, "v410 requires even width.\n");

        return AVERROR_INVALIDDATA;

    }

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame) {

        av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");

        return AVERROR(ENOMEM);

    }

    return 0;

}


static inline int svq3_decode_block(GetBitContext *gb, DCTELEM *block,

                                    int index, const int type)

{

    static const uint8_t *const scan_patterns[4] =

    { luma_dc_zigzag_scan, zigzag_scan, svq3_scan, chroma_dc_scan };

    int run, level, sign, vlc, limit;

    const int intra = (3 * type) >> 2;

    const uint8_t *const scan = scan_patterns[type];

    for (limit = (16 >> intra); index < 16; index = limit, limit += 8) {

        for (; (vlc = svq3_get_ue_golomb(gb)) != 0; index++) {

          if (vlc == INVALID_VLC)

              return -1;

          sign = (vlc & 0x1) - 1;

          vlc  = (vlc + 1) >> 1;

          if (type == 3) {

              if (vlc < 3) {

                  run   = 0;

                  level = vlc;

              } else if (vlc < 4) {

                  run   = 1;

                  level = 1;

              } else {

                  run   = (vlc & 0x3);

                  level = ((vlc + 9) >> 2) - run;

              }

          } else {

              if (vlc < 16) {

                  run   = svq3_dct_tables[intra][vlc].run;

                  level = svq3_dct_tables[intra][vlc].level;

              } else if (intra) {

                  run   = (vlc & 0x7);

                  level = (vlc >> 3) + ((run == 0) ? 8 : ((run < 2) ? 2 : ((run < 5) ? 0 : -1)));

              } else {

                  run   = (vlc & 0xF);

                  level = (vlc >> 4) + ((run == 0) ? 4 : ((run < 3) ? 2 : ((run < 10) ? 1 : 0)));

              }

          }

          if ((index += run) >= limit)

              return -1;

          block[scan[index]] = (level ^ sign) - sign;

        }

        if (type != 2) {

            break;

        }

    }

    return 0;

}


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

{

    DeviceClass *k = DEVICE_CLASS(klass);

    k->init = pci_qdev_init;

    k->exit = pci_unregister_device;

    k->bus_type = TYPE_PCI_BUS;

    k->props = pci_props;

}


CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))

{

    const char *p;

    CharDriverState *chr;

    QemuOpts *opts;

    if (strstart(filename, "chardev:", &p)) {

        return qemu_chr_find(p);

    }

    opts = qemu_chr_parse_compat(label, filename);

    if (!opts)

        return NULL;

    chr = qemu_chr_open_opts(opts, init);

    if (chr && qemu_opt_get_bool(opts, "mux", 0)) {

        monitor_init(chr, MONITOR_USE_READLINE);

    }

    return chr;

}


static int print_drive(DeviceState *dev, Property *prop, char *dest, size_t len)

{

    DriveInfo **ptr = qdev_get_prop_ptr(dev, prop);

    return snprintf(dest, len, "%s", (*ptr)->id);

}


static int find_headers_search_validate(FLACParseContext *fpc, int offset)
{
    FLACFrameInfo fi;
    uint8_t *header_buf;
    int size = 0;
    header_buf = flac_fifo_read_wrap(fpc, offset,
                                     MAX_FRAME_HEADER_SIZE,
                                     &fpc->wrap_buf,
                                     &fpc->wrap_buf_allocated_size);
    if (frame_header_is_valid(fpc->avctx, header_buf, &fi)) {
        FLACHeaderMarker **end_handle = &fpc->headers;
        int i;
        size = 0;
        while (*end_handle) {
            end_handle = &(*end_handle)->next;
            size++;
        *end_handle = av_mallocz(sizeof(**end_handle));
        if (!*end_handle) {
            av_log(fpc->avctx, AV_LOG_ERROR,
                   "couldn't allocate FLACHeaderMarker\n");
        (*end_handle)->fi           = fi;
        (*end_handle)->offset       = offset;
        (*end_handle)->link_penalty = av_malloc(sizeof(int) *
                                            FLAC_MAX_SEQUENTIAL_HEADERS);
        for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++)
            (*end_handle)->link_penalty[i] = FLAC_HEADER_NOT_PENALIZED_YET;
        fpc->nb_headers_found++;
        size++;
    return size;


void ppc_set_compat(PowerPCCPU *cpu, uint32_t compat_pvr, Error **errp)

{

    const CompatInfo *compat = compat_by_pvr(compat_pvr);

    CPUPPCState *env = &cpu->env;

    PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cpu);

    uint64_t pcr;

    if (!compat_pvr) {

        pcr = 0;

    } else if (!compat) {

        error_setg(errp, "Unknown compatibility PVR 0x%08"PRIx32, compat_pvr);

    } else {

        pcr = compat->pcr;

    }

    cpu->compat_pvr = compat_pvr;

    env->spr[SPR_PCR] = pcr & pcc->pcr_mask;

    if (kvm_enabled()) {

        int ret = kvmppc_set_compat(cpu, cpu->compat_pvr);

        if (ret < 0) {

            error_setg_errno(errp, -ret,

                             "Unable to set CPU compatibility mode in KVM");

        }

    }

}


static int mxf_timestamp_to_str(uint64_t timestamp, char **str)
{
    struct tm time = { 0 };
    time.tm_year = (timestamp >> 48) - 1900;
    time.tm_mon  = (timestamp >> 40 & 0xFF) - 1;
    time.tm_mday = (timestamp >> 32 & 0xFF);
    time.tm_hour = (timestamp >> 24 & 0xFF);
    time.tm_min  = (timestamp >> 16 & 0xFF);
    time.tm_sec  = (timestamp >> 8  & 0xFF);
    *str = av_mallocz(32);
    if (!*str)
        return AVERROR(ENOMEM);
    strftime(*str, 32, "%Y-%m-%d %H:%M:%S", &time);
    return 0;
}


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

{

    MOVMuxContext *mov = s->priv_data;

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

    if (trk->entry) {

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

        if (duration < 0 || duration > INT_MAX) {

            av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",

                duration, pkt->dts

            );

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

            pkt->pts = AV_NOPTS_VALUE;

        }

    } else if (pkt->dts <= INT_MIN || pkt->dts >= INT_MAX) {

            av_log(s, AV_LOG_ERROR, "Application provided initial timestamp: %"PRId64" is out of range for mov/mp4 format\n",

                pkt->dts

            );

            pkt->dts = 0;

            pkt->pts = AV_NOPTS_VALUE;

    }

    if (pkt->duration < 0 || pkt->duration > INT_MAX) {

        av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);

        return AVERROR(EINVAL);

    }

    return 0;

}


static int get_siz(Jpeg2000DecoderContext *s)

{

    int i;

    if (bytestream2_get_bytes_left(&s->g) < 36)

        return AVERROR(EINVAL);

    s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz

    s->width          = bytestream2_get_be32u(&s->g); // Width

    s->height         = bytestream2_get_be32u(&s->g); // Height

    s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz

    s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz

    s->tile_width     = bytestream2_get_be32u(&s->g); // XTSiz

    s->tile_height    = bytestream2_get_be32u(&s->g); // YTSiz

    s->tile_offset_x  = bytestream2_get_be32u(&s->g); // XT0Siz

    s->tile_offset_y  = bytestream2_get_be32u(&s->g); // YT0Siz

    s->ncomponents    = bytestream2_get_be16u(&s->g); // CSiz

    if (s->ncomponents <= 0 || s->ncomponents > 4) {

        av_log(s->avctx, AV_LOG_ERROR, "unsupported/invalid ncomponents: %d\n", s->ncomponents);

        return AVERROR(EINVAL);

    }

    if (s->tile_width<=0 || s->tile_height<=0)

        return AVERROR(EINVAL);

    if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)

        return AVERROR(EINVAL);

    for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i

        uint8_t x = bytestream2_get_byteu(&s->g);

        s->cbps[i]   = (x & 0x7f) + 1;

        s->precision = FFMAX(s->cbps[i], s->precision);

        s->sgnd[i]   = !!(x & 0x80);

        s->cdx[i]    = bytestream2_get_byteu(&s->g);

        s->cdy[i]    = bytestream2_get_byteu(&s->g);

        if (s->cdx[i] != 1 || s->cdy[i] != 1) {

            av_log(s->avctx, AV_LOG_ERROR, "unsupported/ CDxy values %d %d for component %d\n", s->cdx[i], s->cdy[i], i);

            if (!s->cdx[i] || !s->cdy[i])

                return AVERROR_INVALIDDATA;

        }

    }

    s->numXtiles = ff_jpeg2000_ceildiv(s->width  - s->tile_offset_x, s->tile_width);

    s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);

    if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(Jpeg2000Tile))

        return AVERROR(EINVAL);

    s->tile = av_mallocz(s->numXtiles * s->numYtiles * sizeof(*s->tile));

    if (!s->tile)

        return AVERROR(ENOMEM);

    for (i = 0; i < s->numXtiles * s->numYtiles; i++) {

        Jpeg2000Tile *tile = s->tile + i;

        tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));

        if (!tile->comp)

            return AVERROR(ENOMEM);

    }

    /* compute image size with reduction factor */

    s->avctx->width  = ff_jpeg2000_ceildivpow2(s->width  - s->image_offset_x,

                                               s->reduction_factor);

    s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,

                                               s->reduction_factor);

    switch(s->ncomponents) {

    case 1:

        if (s->precision > 8)

            s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;

        else

            s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;

        break;

    case 3:

        switch (s->avctx->profile) {

        case FF_PROFILE_JPEG2000_DCINEMA_2K:

        case FF_PROFILE_JPEG2000_DCINEMA_4K:

            /* XYZ color-space for digital cinema profiles */

            s->avctx->pix_fmt = AV_PIX_FMT_XYZ12;

            break;

        default:

            if (s->precision > 8)

                s->avctx->pix_fmt = AV_PIX_FMT_RGB48;

            else

                s->avctx->pix_fmt = AV_PIX_FMT_RGB24;

            break;

        }

        break;

    case 4:

        s->avctx->pix_fmt = AV_PIX_FMT_RGBA;

        break;

    default:

        /* pixel format can not be identified */

        s->avctx->pix_fmt = AV_PIX_FMT_NONE;

        break;

    }

    return 0;

}


void qemu_start_incoming_migration(const char *uri, Error **errp)

{

    const char *p;

    if (strstart(uri, "tcp:", &p))

        tcp_start_incoming_migration(p, errp);

#ifdef CONFIG_RDMA

    else if (strstart(uri, "rdma:", &p))

        rdma_start_incoming_migration(p, errp);

#endif

#if !defined(WIN32)

    else if (strstart(uri, "exec:", &p))

        exec_start_incoming_migration(p, errp);

    else if (strstart(uri, "unix:", &p))

        unix_start_incoming_migration(p, errp);

    else if (strstart(uri, "fd:", &p))

        fd_start_incoming_migration(p, errp);

#endif

    else {

        error_setg(errp, "unknown migration protocol: %s", uri);

    }

}


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

                               int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *buf     = avpkt->data;

    int buf_size           = avpkt->size;

    MP3On4DecodeContext *s = avctx->priv_data;

    MPADecodeContext *m;

    int fsize, len = buf_size, out_size = 0;

    uint32_t header;

    OUT_INT *out_samples;

    OUT_INT *outptr, *bp;

    int fr, j, n, ch, ret;

    /* get output buffer */

    s->frame->nb_samples = MPA_FRAME_SIZE;

    if ((ret = avctx->get_buffer(avctx, s->frame)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return ret;

    out_samples = (OUT_INT *)s->frame->data[0];

    // Discard too short frames

    if (buf_size < HEADER_SIZE)

    // If only one decoder interleave is not needed

    outptr = s->frames == 1 ? out_samples : s->decoded_buf;

    avctx->bit_rate = 0;

    ch = 0;

    for (fr = 0; fr < s->frames; fr++) {

        fsize = AV_RB16(buf) >> 4;

        fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);

        m     = s->mp3decctx[fr];

        assert(m != NULL);

        header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header

        if (ff_mpa_check_header(header) < 0) // Bad header, discard block

            break;

        avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);

        if (ch + m->nb_channels > avctx->channels) {

            av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "

                                        "channel count\n");

        ch += m->nb_channels;

        out_size += mp_decode_frame(m, outptr, buf, fsize);

        buf      += fsize;

        len      -= fsize;

        if (s->frames > 1) {

            n = m->avctx->frame_size*m->nb_channels;

            /* interleave output data */

            bp = out_samples + s->coff[fr];

            if (m->nb_channels == 1) {

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

                    *bp = s->decoded_buf[j];

                    bp += avctx->channels;

            } else {

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

                    bp[0] = s->decoded_buf[j++];

                    bp[1] = s->decoded_buf[j];

                    bp   += avctx->channels;

        avctx->bit_rate += m->bit_rate;

    /* update codec info */

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

    s->frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));

    *got_frame_ptr   = 1;

    *(AVFrame *)data = *s->frame;

    return buf_size;


void OPPROTO op_subfo (void)

{

    do_subfo();

    RETURN();

}


static void ehci_port_test(struct qhc *hc, int port, uint32_t expect)

{

    void *addr = hc->base + 0x64 + 4 * port;

    uint32_t value = qpci_io_readl(hc->dev, addr);

    uint16_t mask = ~(PORTSC_CSC | PORTSC_PEDC | PORTSC_OCC);

#if 0

    fprintf(stderr, "%s: %d, have 0x%08x, want 0x%08x\n",

            __func__, port, value & mask, expect & mask);

#endif

    g_assert((value & mask) == (expect & mask));

}


static int read_dcs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b,

                    int start_bits, int has_sign)

{

    int i, j, len, len2, bsize, sign, v, v2;

    int16_t *dst = (int16_t*)b->cur_dec;

    CHECK_READ_VAL(gb, b, len);

    v = get_bits(gb, start_bits - has_sign);

    if (v && has_sign) {

        sign = -get_bits1(gb);

        v = (v ^ sign) - sign;

    }

    *dst++ = v;

    len--;

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

        len2 = FFMIN(len - i, 8);

        bsize = get_bits(gb, 4);

        if (bsize) {

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

                v2 = get_bits(gb, bsize);

                if (v2) {

                    sign = -get_bits1(gb);

                    v2 = (v2 ^ sign) - sign;

                }

                v += v2;

                *dst++ = v;

                if (v < -32768 || v > 32767) {

                    av_log(avctx, AV_LOG_ERROR, "DC value went out of bounds: %d\n", v);

                    return -1;

                }

            }

        } else {

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

                *dst++ = v;

        }

    }

    b->cur_dec = (uint8_t*)dst;

    return 0;

}


static void opt_output_file(void *optctx, const char *filename)

{

    OptionsContext *o = optctx;

    AVFormatContext *oc;

    int i, err;

    AVOutputFormat *file_oformat;

    OutputStream *ost;

    InputStream  *ist;

    if (!strcmp(filename, "-"))

        filename = "pipe:";

    err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);

    if (!oc) {

        print_error(filename, err);

        exit_program(1);

    }

    file_oformat= oc->oformat;

    oc->interrupt_callback = int_cb;

    if (!strcmp(file_oformat->name, "ffm") &&

        av_strstart(filename, "http:", NULL)) {

        int j;

        /* special case for files sent to ffserver: we get the stream

           parameters from ffserver */

        int err = read_ffserver_streams(o, oc, filename);

        if (err < 0) {

            print_error(filename, err);

            exit_program(1);

        }

        for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {

            ost = &output_streams[j];

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

                ist = &input_streams[i];

                if(ist->st->codec->codec_type == ost->st->codec->codec_type){

                    ost->sync_ist= ist;

                    ost->source_index= i;

                    ist->discard = 0;

                    break;

                }

            }

            if(!ost->sync_ist){

                av_log(NULL, AV_LOG_FATAL, "Missing %s stream which is required by this ffm\n", av_get_media_type_string(ost->st->codec->codec_type));

                exit_program(1);

            }

        }

    } else if (!o->nb_stream_maps) {

        /* pick the "best" stream of each type */

#define NEW_STREAM(type, index)\

        if (index >= 0) {\

            ost = new_ ## type ## _stream(o, oc);\

            ost->source_index = index;\

            ost->sync_ist     = &input_streams[index];\

            input_streams[index].discard = 0;\

        }

        /* video: highest resolution */

        if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {

            int area = 0, idx = -1;

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

                ist = &input_streams[i];

                if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&

                    ist->st->codec->width * ist->st->codec->height > area) {

                    area = ist->st->codec->width * ist->st->codec->height;

                    idx = i;

                }

            }

            NEW_STREAM(video, idx);

        }

        /* audio: most channels */

        if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {

            int channels = 0, idx = -1;

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

                ist = &input_streams[i];

                if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&

                    ist->st->codec->channels > channels) {

                    channels = ist->st->codec->channels;

                    idx = i;

                }

            }

            NEW_STREAM(audio, idx);

        }

        /* subtitles: pick first */

        if (!o->subtitle_disable && (oc->oformat->subtitle_codec != CODEC_ID_NONE || subtitle_codec_name)) {

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

                if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {

                    NEW_STREAM(subtitle, i);

                    break;

                }

        }

        /* do something with data? */

    } else {

        for (i = 0; i < o->nb_stream_maps; i++) {

            StreamMap *map = &o->stream_maps[i];

            if (map->disabled)

                continue;

            ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];

            if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)

                continue;

            if(o->   audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)

                continue;

            if(o->   video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

                continue;

            if(o->    data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)

                continue;

            switch (ist->st->codec->codec_type) {

            case AVMEDIA_TYPE_VIDEO:    ost = new_video_stream(o, oc);    break;

            case AVMEDIA_TYPE_AUDIO:    ost = new_audio_stream(o, oc);    break;

            case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc); break;

            case AVMEDIA_TYPE_DATA:     ost = new_data_stream(o, oc);     break;

            case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc); break;

            default:

                av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",

                       map->file_index, map->stream_index);

                exit_program(1);

            }

            ost->source_index = input_files[map->file_index].ist_index + map->stream_index;

            ost->sync_ist     = &input_streams[input_files[map->sync_file_index].ist_index +

                                           map->sync_stream_index];

            ist->discard = 0;

        }

    }

    /* handle attached files */

    for (i = 0; i < o->nb_attachments; i++) {

        AVIOContext *pb;

        uint8_t *attachment;

        const char *p;

        int64_t len;

        if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {

            av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",

                   o->attachments[i]);

            exit_program(1);

        }

        if ((len = avio_size(pb)) <= 0) {

            av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",

                   o->attachments[i]);

            exit_program(1);

        }

        if (!(attachment = av_malloc(len))) {

            av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",

                   o->attachments[i]);

            exit_program(1);

        }

        avio_read(pb, attachment, len);

        ost = new_attachment_stream(o, oc);

        ost->stream_copy               = 0;

        ost->source_index              = -1;

        ost->attachment_filename       = o->attachments[i];

        ost->st->codec->extradata      = attachment;

        ost->st->codec->extradata_size = len;

        p = strrchr(o->attachments[i], '/');

        av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);

        avio_close(pb);

    }

    output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);

    output_files[nb_output_files - 1].ctx       = oc;

    output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;

    output_files[nb_output_files - 1].recording_time = o->recording_time;

    output_files[nb_output_files - 1].start_time     = o->start_time;

    output_files[nb_output_files - 1].limit_filesize = o->limit_filesize;

    av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);

    /* check filename in case of an image number is expected */

    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {

        if (!av_filename_number_test(oc->filename)) {

            print_error(oc->filename, AVERROR(EINVAL));

            exit_program(1);

        }

    }

    if (!(oc->oformat->flags & AVFMT_NOFILE)) {

        /* test if it already exists to avoid losing precious files */

        assert_file_overwrite(filename);

        /* open the file */

        if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,

                              &oc->interrupt_callback,

                              &output_files[nb_output_files - 1].opts)) < 0) {

            print_error(filename, err);

            exit_program(1);

        }

    }

    if (o->mux_preload) {

        uint8_t buf[64];

        snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));

        av_dict_set(&output_files[nb_output_files - 1].opts, "preload", buf, 0);

    }

    oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);

    if (loop_output >= 0) {

        av_log(NULL, AV_LOG_WARNING, "-loop_output is deprecated, use -loop\n");

        oc->loop_output = loop_output;

    }

    /* copy metadata */

    for (i = 0; i < o->nb_metadata_map; i++) {

        char *p;

        int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);

        if (in_file_index < 0)

            continue;

        if (in_file_index >= nb_input_files) {

            av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);

            exit_program(1);

        }

        copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, input_files[in_file_index].ctx, o);

    }

    /* copy chapters */

    if (o->chapters_input_file >= nb_input_files) {

        if (o->chapters_input_file == INT_MAX) {

            /* copy chapters from the first input file that has them*/

            o->chapters_input_file = -1;

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

                if (input_files[i].ctx->nb_chapters) {

                    o->chapters_input_file = i;

                    break;

                }

        } else {

            av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",

                   o->chapters_input_file);

            exit_program(1);

        }

    }

    if (o->chapters_input_file >= 0)

        copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],

                      !o->metadata_chapters_manual);

    /* copy global metadata by default */

    if (!o->metadata_global_manual && nb_input_files){

        av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,

                     AV_DICT_DONT_OVERWRITE);

        if(o->recording_time != INT64_MAX)

            av_dict_set(&oc->metadata, "duration", NULL, 0);

    }

    if (!o->metadata_streams_manual)

        for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {

            InputStream *ist;

            if (output_streams[i].source_index < 0)         /* this is true e.g. for attached files */

                continue;

            ist = &input_streams[output_streams[i].source_index];

            av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);

        }

    /* process manually set metadata */

    for (i = 0; i < o->nb_metadata; i++) {

        AVDictionary **m;

        char type, *val;

        const char *stream_spec;

        int index = 0, j, ret;

        val = strchr(o->metadata[i].u.str, '=');

        if (!val) {

            av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",

                   o->metadata[i].u.str);

            exit_program(1);

        }

        *val++ = 0;

        parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);

        if (type == 's') {

            for (j = 0; j < oc->nb_streams; j++) {

                if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {

                    av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);

                } else if (ret < 0)

                    exit_program(1);

            }

            printf("ret %d, stream_spec %s\n", ret, stream_spec);

        }

        else {

            switch (type) {

            case 'g':

                m = &oc->metadata;

                break;

            case 'c':

                if (index < 0 || index >= oc->nb_chapters) {

                    av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);

                    exit_program(1);

                }

                m = &oc->chapters[index]->metadata;

                break;

            default:

                av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);

                exit_program(1);

            }

            av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);

        }

    }

    reset_options(o, 0);

}