int ff_h263_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MpegEncContext *s = avctx->priv_data;

    int ret;

    AVFrame *pict = data;

#ifdef PRINT_FRAME_TIME

uint64_t time= rdtsc();

#endif

#ifdef DEBUG

    av_log(avctx, AV_LOG_DEBUG, "*****frame %d size=%d\n", avctx->frame_number, buf_size);

    if(buf_size>0)

        av_log(avctx, AV_LOG_DEBUG, "bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);

#endif

    s->flags= avctx->flags;

    s->flags2= avctx->flags2;

    /* no supplementary picture */

    if (buf_size == 0) {

        /* special case for last picture */

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

            *pict= *(AVFrame*)s->next_picture_ptr;

            s->next_picture_ptr= NULL;

            *data_size = sizeof(AVFrame);

        }

        return 0;

    }

    if(s->flags&CODEC_FLAG_TRUNCATED){

        int next;

        if(CONFIG_MPEG4_DECODER && s->codec_id==CODEC_ID_MPEG4){

            next= ff_mpeg4_find_frame_end(&s->parse_context, buf, buf_size);

        }else if(CONFIG_H263_DECODER && s->codec_id==CODEC_ID_H263){

            next= ff_h263_find_frame_end(&s->parse_context, buf, buf_size);

        }else{

            av_log(s->avctx, AV_LOG_ERROR, "this codec does not support truncated bitstreams\n");

            return -1;

        }

        if( ff_combine_frame(&s->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0 )

            return buf_size;

    }

retry:

    if(s->bitstream_buffer_size && (s->divx_packed || buf_size<20)){ //divx 5.01+/xvid frame reorder

        init_get_bits(&s->gb, s->bitstream_buffer, s->bitstream_buffer_size*8);

    }else

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

    s->bitstream_buffer_size=0;

    if (!s->context_initialized) {

        if (MPV_common_init(s) < 0) //we need the idct permutaton for reading a custom matrix

            return -1;

    }

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

     * otherwise we cannot store anyting in there */

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

        int i= ff_find_unused_picture(s, 0);

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

    }

    /* let's go :-) */

    if (CONFIG_WMV2_DECODER && s->msmpeg4_version==5) {

        ret= ff_wmv2_decode_picture_header(s);

    } else if (CONFIG_MSMPEG4_DECODER && s->msmpeg4_version) {

        ret = msmpeg4_decode_picture_header(s);

    } else if (s->h263_pred) {

        if(s->avctx->extradata_size && s->picture_number==0){

            GetBitContext gb;

            init_get_bits(&gb, s->avctx->extradata, s->avctx->extradata_size*8);

            ret = ff_mpeg4_decode_picture_header(s, &gb);

        }

        ret = ff_mpeg4_decode_picture_header(s, &s->gb);

    } else if (s->codec_id == CODEC_ID_H263I) {

        ret = intel_h263_decode_picture_header(s);

    } else if (s->h263_flv) {

        ret = flv_h263_decode_picture_header(s);

    } else {

        ret = h263_decode_picture_header(s);

    }

    if(ret==FRAME_SKIPPED) return get_consumed_bytes(s, buf_size);

    /* skip if the header was thrashed */

    if (ret < 0){

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

        return -1;

    }

    avctx->has_b_frames= !s->low_delay;

    if(s->xvid_build==0 && s->divx_version==0 && s->lavc_build==0){

        if(s->stream_codec_tag == AV_RL32("XVID") ||

           s->codec_tag == AV_RL32("XVID") || s->codec_tag == AV_RL32("XVIX") ||

           s->codec_tag == AV_RL32("RMP4"))

            s->xvid_build= -1;

#if 0

        if(s->codec_tag == AV_RL32("DIVX") && s->vo_type==0 && s->vol_control_parameters==1

           && s->padding_bug_score > 0 && s->low_delay) // XVID with modified fourcc

            s->xvid_build= -1;

#endif

    }

    if(s->xvid_build==0 && s->divx_version==0 && s->lavc_build==0){

        if(s->codec_tag == AV_RL32("DIVX") && s->vo_type==0 && s->vol_control_parameters==0)

            s->divx_version= 400; //divx 4

    }

    if(s->xvid_build && s->divx_version){

        s->divx_version=

        s->divx_build= 0;

    }

    if(s->workaround_bugs&FF_BUG_AUTODETECT){

        if(s->codec_tag == AV_RL32("XVIX"))

            s->workaround_bugs|= FF_BUG_XVID_ILACE;

        if(s->codec_tag == AV_RL32("UMP4")){

            s->workaround_bugs|= FF_BUG_UMP4;

        }

        if(s->divx_version>=500 && s->divx_build<1814){

            s->workaround_bugs|= FF_BUG_QPEL_CHROMA;

        }

        if(s->divx_version>502 && s->divx_build<1814){

            s->workaround_bugs|= FF_BUG_QPEL_CHROMA2;

        }

        if(s->xvid_build && s->xvid_build<=3)

            s->padding_bug_score= 256*256*256*64;

        if(s->xvid_build && s->xvid_build<=1)

            s->workaround_bugs|= FF_BUG_QPEL_CHROMA;

        if(s->xvid_build && s->xvid_build<=12)

            s->workaround_bugs|= FF_BUG_EDGE;

        if(s->xvid_build && s->xvid_build<=32)

            s->workaround_bugs|= FF_BUG_DC_CLIP;

#define SET_QPEL_FUNC(postfix1, postfix2) \

    s->dsp.put_ ## postfix1 = ff_put_ ## postfix2;\

    s->dsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2;\

    s->dsp.avg_ ## postfix1 = ff_avg_ ## postfix2;

        if(s->lavc_build && s->lavc_build<4653)

            s->workaround_bugs|= FF_BUG_STD_QPEL;

        if(s->lavc_build && s->lavc_build<4655)

            s->workaround_bugs|= FF_BUG_DIRECT_BLOCKSIZE;

        if(s->lavc_build && s->lavc_build<4670){

            s->workaround_bugs|= FF_BUG_EDGE;

        }

        if(s->lavc_build && s->lavc_build<=4712)

            s->workaround_bugs|= FF_BUG_DC_CLIP;

        if(s->divx_version)

            s->workaround_bugs|= FF_BUG_DIRECT_BLOCKSIZE;

//printf("padding_bug_score: %d\n", s->padding_bug_score);

        if(s->divx_version==501 && s->divx_build==20020416)

            s->padding_bug_score= 256*256*256*64;

        if(s->divx_version && s->divx_version<500){

            s->workaround_bugs|= FF_BUG_EDGE;

        }

        if(s->divx_version)

            s->workaround_bugs|= FF_BUG_HPEL_CHROMA;

#if 0

        if(s->divx_version==500)

            s->padding_bug_score= 256*256*256*64;

        /* very ugly XVID padding bug detection FIXME/XXX solve this differently

         * Let us hope this at least works.

         */

        if(   s->resync_marker==0 && s->data_partitioning==0 && s->divx_version==0

           && s->codec_id==CODEC_ID_MPEG4 && s->vo_type==0)

            s->workaround_bugs|= FF_BUG_NO_PADDING;

        if(s->lavc_build && s->lavc_build<4609) //FIXME not sure about the version num but a 4609 file seems ok

            s->workaround_bugs|= FF_BUG_NO_PADDING;

#endif

    }

    if(s->workaround_bugs& FF_BUG_STD_QPEL){

        SET_QPEL_FUNC(qpel_pixels_tab[0][ 5], qpel16_mc11_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][ 7], qpel16_mc31_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][ 9], qpel16_mc12_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][ 5], qpel8_mc11_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][ 7], qpel8_mc31_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][ 9], qpel8_mc12_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)

    }

    if(avctx->debug & FF_DEBUG_BUGS)

        av_log(s->avctx, AV_LOG_DEBUG, "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",

               s->workaround_bugs, s->lavc_build, s->xvid_build, s->divx_version, s->divx_build,

               s->divx_packed ? "p" : "");

#if 0 // dump bits per frame / qp / complexity

{

    static FILE *f=NULL;

    if(!f) f=fopen("rate_qp_cplx.txt", "w");

    fprintf(f, "%d %d %f\n", buf_size, s->qscale, buf_size*(double)s->qscale);

}

#endif

#if HAVE_MMX

    if(s->codec_id == CODEC_ID_MPEG4 && s->xvid_build && avctx->idct_algo == FF_IDCT_AUTO && (mm_flags & FF_MM_MMX)){

        avctx->idct_algo= FF_IDCT_XVIDMMX;

        avctx->coded_width= 0; // force reinit

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

        s->picture_number=0;

    }

#endif

        /* After H263 & mpeg4 header decode we have the height, width,*/

        /* and other parameters. So then we could init the picture   */

        /* FIXME: By the way H263 decoder is evolving it should have */

        /* an H263EncContext                                         */

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

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

        /* H.263 could change picture size any time */

        ParseContext pc= s->parse_context; //FIXME move these demuxng hack to avformat

        s->parse_context.buffer=0;

        MPV_common_end(s);

        s->parse_context= pc;

    }

    if (!s->context_initialized) {

        avcodec_set_dimensions(avctx, s->width, s->height);

        goto retry;

    }

    if((s->codec_id==CODEC_ID_H263 || s->codec_id==CODEC_ID_H263P || s->codec_id == CODEC_ID_H263I))

        s->gob_index = ff_h263_get_gob_height(s);

    // for hurry_up==5

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

    s->current_picture.key_frame= s->pict_type == FF_I_TYPE;

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

    if(s->last_picture_ptr==NULL && (s->pict_type==FF_B_TYPE || s->dropable)) return get_consumed_bytes(s, buf_size);

    /* skip b frames if we are in a hurry */

    if(avctx->hurry_up && s->pict_type==FF_B_TYPE) return get_consumed_bytes(s, buf_size);

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

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

       ||  avctx->skip_frame >= AVDISCARD_ALL)

        return get_consumed_bytes(s, buf_size);

    /* skip everything if we are in a hurry>=5 */

    if(avctx->hurry_up>=5) return get_consumed_bytes(s, buf_size);

    if(s->next_p_frame_damaged){

        if(s->pict_type==FF_B_TYPE)

            return get_consumed_bytes(s, buf_size);

        else

            s->next_p_frame_damaged=0;

    }

    if((s->avctx->flags2 & CODEC_FLAG2_FAST) && s->pict_type==FF_B_TYPE){

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

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

    }else if((!s->no_rounding) || s->pict_type==FF_B_TYPE){

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

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

    }else{

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

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

    }

    if(MPV_frame_start(s, avctx) < 0)

        return -1;

    if (avctx->hwaccel) {

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

            return -1;

    }

#ifdef DEBUG

    av_log(avctx, AV_LOG_DEBUG, "qscale=%d\n", s->qscale);

#endif

    ff_er_frame_start(s);

    //the second part of the wmv2 header contains the MB skip bits which are stored in current_picture->mb_type

    //which is not available before MPV_frame_start()

    if (CONFIG_WMV2_DECODER && s->msmpeg4_version==5){

        ret = ff_wmv2_decode_secondary_picture_header(s);

        if(ret<0) return ret;

        if(ret==1) goto intrax8_decoded;

    }

    /* decode each macroblock */

    s->mb_x=0;

    s->mb_y=0;

    decode_slice(s);

    while(s->mb_y<s->mb_height){

        if(s->msmpeg4_version){

            if(s->slice_height==0 || s->mb_x!=0 || (s->mb_y%s->slice_height)!=0 || get_bits_count(&s->gb) > s->gb.size_in_bits)

                break;

        }else{

            if(ff_h263_resync(s)<0)

                break;

        }

        if(s->msmpeg4_version<4 && s->h263_pred)

            ff_mpeg4_clean_buffers(s);

        decode_slice(s);

    }

    if (s->h263_msmpeg4 && s->msmpeg4_version<4 && s->pict_type==FF_I_TYPE)

        if(!CONFIG_MSMPEG4_DECODER || msmpeg4_decode_ext_header(s, buf_size) < 0){

            s->error_status_table[s->mb_num-1]= AC_ERROR|DC_ERROR|MV_ERROR;

        }

    /* divx 5.01+ bistream reorder stuff */

    if(s->codec_id==CODEC_ID_MPEG4 && s->bitstream_buffer_size==0 && s->divx_packed){

        int current_pos= get_bits_count(&s->gb)>>3;

        int startcode_found=0;

        if(buf_size - current_pos > 5){

            int i;

            for(i=current_pos; i<buf_size-3; i++){

                if(buf[i]==0 && buf[i+1]==0 && buf[i+2]==1 && buf[i+3]==0xB6){

                    startcode_found=1;

                    break;

                }

            }

        }

        if(s->gb.buffer == s->bitstream_buffer && buf_size>20){ //xvid style

            startcode_found=1;

            current_pos=0;

        }

        if(startcode_found){

            av_fast_malloc(

                &s->bitstream_buffer,

                &s->allocated_bitstream_buffer_size,

                buf_size - current_pos + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!s->bitstream_buffer)

                return AVERROR(ENOMEM);

            memcpy(s->bitstream_buffer, buf + current_pos, buf_size - current_pos);

            s->bitstream_buffer_size= buf_size - current_pos;

        }

    }

intrax8_decoded:

    ff_er_frame_end(s);

    if (avctx->hwaccel) {

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

            return -1;

    }

    MPV_frame_end(s);

assert(s->current_picture.pict_type == s->current_picture_ptr->pict_type);

assert(s->current_picture.pict_type == s->pict_type);

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

        *pict= *(AVFrame*)s->current_picture_ptr;

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

        *pict= *(AVFrame*)s->last_picture_ptr;

    }

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

        *data_size = sizeof(AVFrame);

        ff_print_debug_info(s, pict);

    }

    /* Return the Picture timestamp as the frame number */

    /* we subtract 1 because it is added on utils.c     */

    avctx->frame_number = s->picture_number - 1;

#ifdef PRINT_FRAME_TIME

av_log(avctx, AV_LOG_DEBUG, "%"PRId64"\n", rdtsc()-time);

#endif

    return get_consumed_bytes(s, buf_size);

}


static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)

{

    AVFrame *decoded_frame, *filtered_frame = NULL;

    void *buffer_to_free = NULL;

    int i, ret = 0;

    float quality;

#if CONFIG_AVFILTER

    int frame_available = 1;

#endif

    if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))

        return AVERROR(ENOMEM);

    else

        avcodec_get_frame_defaults(ist->decoded_frame);

    decoded_frame = ist->decoded_frame;

    pkt->pts  = *pkt_pts;

    pkt->dts  = ist->last_dts;

    *pkt_pts  = AV_NOPTS_VALUE;

    ret = avcodec_decode_video2(ist->st->codec,

                                decoded_frame, got_output, pkt);

    if (ret < 0)

        return ret;

    quality = same_quant ? decoded_frame->quality : 0;

    if (!*got_output) {

        /* no picture yet */

        return ret;

    }

    decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,

                                           decoded_frame->pkt_dts);

    pkt->size = 0;

    pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);

    rate_emu_sleep(ist);

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

        OutputStream *ost = &output_streams[i];

        int frame_size, resample_changed;

        if (!check_output_constraints(ist, ost) || !ost->encoding_needed)

            continue;

#if CONFIG_AVFILTER

        resample_changed = ost->resample_width   != decoded_frame->width  ||

                           ost->resample_height  != decoded_frame->height ||

                           ost->resample_pix_fmt != decoded_frame->format;

        if (resample_changed) {

            av_log(NULL, AV_LOG_INFO,

                    "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",

                    ist->file_index, ist->st->index,

                    ost->resample_width,  ost->resample_height,  av_get_pix_fmt_name(ost->resample_pix_fmt),

                    decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));

            avfilter_graph_free(&ost->graph);

            if (configure_video_filters(ist, ost)) {

                av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");

                exit_program(1);

            }

            ost->resample_width   = decoded_frame->width;

            ost->resample_height  = decoded_frame->height;

            ost->resample_pix_fmt = decoded_frame->format;

        }

        if (ist->st->sample_aspect_ratio.num)

            decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;

        if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {

            FrameBuffer      *buf = decoded_frame->opaque;

            AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(

                                        decoded_frame->data, decoded_frame->linesize,

                                        AV_PERM_READ | AV_PERM_PRESERVE,

                                        ist->st->codec->width, ist->st->codec->height,

                                        ist->st->codec->pix_fmt);

            avfilter_copy_frame_props(fb, decoded_frame);

            fb->buf->priv           = buf;

            fb->buf->free           = filter_release_buffer;

            buf->refcount++;

            av_buffersrc_buffer(ost->input_video_filter, fb);

        } else

            av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame,

                                     decoded_frame->pts, decoded_frame->sample_aspect_ratio);

        if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {

            av_free(buffer_to_free);

            return AVERROR(ENOMEM);

        } else

            avcodec_get_frame_defaults(ist->filtered_frame);

        filtered_frame = ist->filtered_frame;

        frame_available = avfilter_poll_frame(ost->output_video_filter->inputs[0]);

        while (frame_available) {

            AVRational ist_pts_tb;

            if (ost->output_video_filter)

                get_filtered_video_frame(ost->output_video_filter, filtered_frame, &ost->picref, &ist_pts_tb);

            if (ost->picref)

                filtered_frame->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);

            if (ost->picref->video && !ost->frame_aspect_ratio)

                ost->st->codec->sample_aspect_ratio = ost->picref->video->pixel_aspect;

#else

            filtered_frame = decoded_frame;

#endif

            do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,

                         same_quant ? quality : ost->st->codec->global_quality);

            if (vstats_filename && frame_size)

                do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);

#if CONFIG_AVFILTER

            frame_available = ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);

            if (ost->picref)

                avfilter_unref_buffer(ost->picref);

        }

#endif

    }

    av_free(buffer_to_free);

    return ret;

}


enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)

{

    if (bps > 64U)

        return AV_CODEC_ID_NONE;

    if (flt) {

        switch (bps) {

        case 32:

            return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;

        case 64:

            return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;

        default:

            return AV_CODEC_ID_NONE;

        }

    } else {

        bps  += 7;

        bps >>= 3;

        if (sflags & (1 << (bps - 1))) {

            switch (bps) {

            case 1:

                return AV_CODEC_ID_PCM_S8;

            case 2:

                return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;

            case 3:

                return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;

            case 4:

                return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;

            default:

                return AV_CODEC_ID_NONE;

            }

        } else {

            switch (bps) {

            case 1:

                return AV_CODEC_ID_PCM_U8;

            case 2:

                return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;

            case 3:

                return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;

            case 4:

                return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;

            default:

                return AV_CODEC_ID_NONE;

            }

        }

    }

}


static int synthfilt_build_sb_samples (QDM2Context *q, GetBitContext *gb, int length, int sb_min, int sb_max)

{

    int sb, j, k, n, ch, run, channels;

    int joined_stereo, zero_encoding, chs;

    int type34_first;

    float type34_div = 0;

    float type34_predictor;

    float samples[10], sign_bits[16];

    if (length == 0) {

        // If no data use noise

        for (sb=sb_min; sb < sb_max; sb++)

            build_sb_samples_from_noise (q, sb);

        return 0;

    }

    for (sb = sb_min; sb < sb_max; sb++) {

        FIX_NOISE_IDX(q->noise_idx);

        channels = q->nb_channels;

        if (q->nb_channels <= 1 || sb < 12)

            joined_stereo = 0;

        else if (sb >= 24)

            joined_stereo = 1;

        else

            joined_stereo = (BITS_LEFT(length,gb) >= 1) ? get_bits1 (gb) : 0;

        if (joined_stereo) {

            if (BITS_LEFT(length,gb) >= 16)

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

                    sign_bits[j] = get_bits1 (gb);

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

                if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])

                    q->coding_method[0][sb][j] = q->coding_method[1][sb][j];

            fix_coding_method_array(sb, q->nb_channels, q->coding_method);

            channels = 1;

        }

        for (ch = 0; ch < channels; ch++) {

            zero_encoding = (BITS_LEFT(length,gb) >= 1) ? get_bits1(gb) : 0;

            type34_predictor = 0.0;

            type34_first = 1;

            for (j = 0; j < 128; ) {

                switch (q->coding_method[ch][sb][j / 2]) {

                    case 8:

                        if (BITS_LEFT(length,gb) >= 10) {

                            if (zero_encoding) {

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

                                    if ((j + 2 * k) >= 128)

                                        break;

                                    samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;

                                }

                            } else {

                                n = get_bits(gb, 8);

                                for (k = 0; k < 5; k++)

                                    samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];

                            }

                            for (k = 0; k < 5; k++)

                                samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        } else {

                            for (k = 0; k < 10; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 10;

                        break;

                    case 10:

                        if (BITS_LEFT(length,gb) >= 1) {

                            float f = 0.81;

                            if (get_bits1(gb))

                                f = -f;

                            f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;

                            samples[0] = f;

                        } else {

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 1;

                        break;

                    case 16:

                        if (BITS_LEFT(length,gb) >= 10) {

                            if (zero_encoding) {

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

                                    if ((j + k) >= 128)

                                        break;

                                    samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];

                                }

                            } else {

                                n = get_bits (gb, 8);

                                for (k = 0; k < 5; k++)

                                    samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];

                            }

                        } else {

                            for (k = 0; k < 5; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 5;

                        break;

                    case 24:

                        if (BITS_LEFT(length,gb) >= 7) {

                            n = get_bits(gb, 7);

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

                                samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;

                        } else {

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

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 3;

                        break;

                    case 30:

                        if (BITS_LEFT(length,gb) >= 4)

                            samples[0] = type30_dequant[qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1)];

                        else

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        run = 1;

                        break;

                    case 34:

                        if (BITS_LEFT(length,gb) >= 7) {

                            if (type34_first) {

                                type34_div = (float)(1 << get_bits(gb, 2));

                                samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;

                                type34_predictor = samples[0];

                                type34_first = 0;

                            } else {

                                unsigned v = qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1);

                                if (v >= FF_ARRAY_ELEMS(type34_delta))

                                    return AVERROR_INVALIDDATA;

                                samples[0] = type34_delta[v] / type34_div + type34_predictor;

                                type34_predictor = samples[0];

                            }

                        } else {

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 1;

                        break;

                    default:

                        samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        run = 1;

                        break;

                }

                if (joined_stereo) {

                    float tmp[10][MPA_MAX_CHANNELS];

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

                        tmp[k][0] = samples[k];

                        tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k];

                    }

                    for (chs = 0; chs < q->nb_channels; chs++)

                        for (k = 0; k < run; k++)

                            if ((j + k) < 128)

                                q->sb_samples[chs][j + k][sb] = q->tone_level[chs][sb][((j + k)/2)] * tmp[k][chs];

                } else {

                    for (k = 0; k < run; k++)

                        if ((j + k) < 128)

                            q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k];

                }

                j += run;

            } // j loop

        } // channel loop

    } // subband loop

    return 0;

}


static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)

{

    PadContext *pad = inlink->dst->priv;

    AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);

    int plane;

    inlink->dst->outputs[0]->out_buf = outpicref;

    for (plane = 0; plane < 4 && outpicref->data[plane]; plane++) {

        int hsub = (plane == 1 || plane == 2) ? pad->hsub : 0;

        int vsub = (plane == 1 || plane == 2) ? pad->vsub : 0;

        outpicref->data[plane] -= (pad->x >> hsub) * pad->line_step[plane] +

            (pad->y >> vsub) * outpicref->linesize[plane];

    }

    outpicref->video->w = pad->w;

    outpicref->video->h = pad->h;

    avfilter_start_frame(inlink->dst->outputs[0], outpicref);

}


static int thread_init(AVCodecContext *avctx)

{

    int i;

    ThreadContext *c;

    int thread_count = avctx->thread_count;

    if (!thread_count) {

        int nb_cpus = get_logical_cpus(avctx);

        // use number of cores + 1 as thread count if there is motre than one

        if (nb_cpus > 1)

            thread_count = avctx->thread_count = nb_cpus + 1;

    }

    if (thread_count <= 1) {

        avctx->active_thread_type = 0;

        return 0;

    }

    c = av_mallocz(sizeof(ThreadContext));

    if (!c)

        return -1;

    c->workers = av_mallocz(sizeof(pthread_t)*thread_count);

    if (!c->workers) {

        av_free(c);

        return -1;

    }

    avctx->thread_opaque = c;

    c->current_job = 0;

    c->job_count = 0;

    c->job_size = 0;

    c->done = 0;

    pthread_cond_init(&c->current_job_cond, NULL);

    pthread_cond_init(&c->last_job_cond, NULL);

    pthread_mutex_init(&c->current_job_lock, NULL);

    pthread_mutex_lock(&c->current_job_lock);

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

        if(pthread_create(&c->workers[i], NULL, worker, avctx)) {

           avctx->thread_count = i;

           pthread_mutex_unlock(&c->current_job_lock);

           ff_thread_free(avctx);

           return -1;

        }

    }

    avcodec_thread_park_workers(c, thread_count);

    avctx->execute = avcodec_thread_execute;

    avctx->execute2 = avcodec_thread_execute2;

    return 0;

}


static av_cold int vtenc_init(AVCodecContext *avctx)

{

    CFMutableDictionaryRef enc_info;

    CFMutableDictionaryRef pixel_buffer_info;

    CMVideoCodecType       codec_type;

    VTEncContext           *vtctx = avctx->priv_data;

    CFStringRef            profile_level;

    CFBooleanRef           has_b_frames_cfbool;

    CFNumberRef            gamma_level = NULL;

    int                    status;

    codec_type = get_cm_codec_type(avctx->codec_id);

    if (!codec_type) {

        av_log(avctx, AV_LOG_ERROR, "Error: no mapping for AVCodecID %d\n", avctx->codec_id);

        return AVERROR(EINVAL);

    }

    vtctx->has_b_frames = avctx->max_b_frames > 0;

    if(vtctx->has_b_frames && vtctx->profile == H264_PROF_BASELINE){

        av_log(avctx, AV_LOG_WARNING, "Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");

        vtctx->has_b_frames = false;

    }

    if (vtctx->entropy == VT_CABAC && vtctx->profile == H264_PROF_BASELINE) {

        av_log(avctx, AV_LOG_WARNING, "CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");

        vtctx->entropy = VT_ENTROPY_NOT_SET;

    }

    if (!get_vt_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);

    vtctx->session = NULL;

    enc_info = CFDictionaryCreateMutable(

        kCFAllocatorDefault,

        20,

        &kCFCopyStringDictionaryKeyCallBacks,

        &kCFTypeDictionaryValueCallBacks

    );

    if (!enc_info) return AVERROR(ENOMEM);

#if !TARGET_OS_IPHONE

    if (!vtctx->allow_sw) {

        CFDictionarySetValue(enc_info, kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder, kCFBooleanTrue);

    } else {

        CFDictionarySetValue(enc_info, kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,  kCFBooleanTrue);

    }

#endif

    if (avctx->pix_fmt != AV_PIX_FMT_VIDEOTOOLBOX) {

        status = create_cv_pixel_buffer_info(avctx, &pixel_buffer_info);

        if (status)

            goto init_cleanup;

    } else {

        pixel_buffer_info = NULL;

    }

    pthread_mutex_init(&vtctx->lock, NULL);

    pthread_cond_init(&vtctx->cv_sample_sent, NULL);

    vtctx->dts_delta = vtctx->has_b_frames ? -1 : 0;

    get_cv_transfer_function(avctx, &vtctx->transfer_function, &gamma_level);

    get_cv_ycbcr_matrix(avctx, &vtctx->ycbcr_matrix);

    get_cv_color_primaries(avctx, &vtctx->color_primaries);

    if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {

        status = vtenc_populate_extradata(avctx,

                                          codec_type,

                                          profile_level,

                                          gamma_level,

                                          enc_info,

                                          pixel_buffer_info);

        if (status)

            goto init_cleanup;

    }

    status = vtenc_create_encoder(avctx,

                                  codec_type,

                                  profile_level,

                                  gamma_level,

                                  enc_info,

                                  pixel_buffer_info,

                                  &vtctx->session);

    if (status < 0)

        goto init_cleanup;

    status = VTSessionCopyProperty(vtctx->session,

                                   kVTCompressionPropertyKey_AllowFrameReordering,

                                   kCFAllocatorDefault,

                                   &has_b_frames_cfbool);

    if (!status) {

        //Some devices don't output B-frames for main profile, even if requested.

        vtctx->has_b_frames = CFBooleanGetValue(has_b_frames_cfbool);

        CFRelease(has_b_frames_cfbool);

    }

    avctx->has_b_frames = vtctx->has_b_frames;

init_cleanup:

    if (gamma_level)

        CFRelease(gamma_level);

    if (pixel_buffer_info)

        CFRelease(pixel_buffer_info);

    CFRelease(enc_info);

    return status;

}


av_cold void ff_dsputil_init_alpha(DSPContext *c, AVCodecContext *avctx)

{

    const int high_bit_depth = avctx->bits_per_raw_sample > 8;

    /* amask clears all bits that correspond to present features.  */

    if (amask(AMASK_MVI) == 0) {

        c->put_pixels_clamped = put_pixels_clamped_mvi_asm;

        c->add_pixels_clamped = add_pixels_clamped_mvi_asm;

        if (!high_bit_depth)

            c->get_pixels   = get_pixels_mvi;

        c->diff_pixels      = diff_pixels_mvi;

        c->sad[0]           = pix_abs16x16_mvi_asm;

        c->sad[1]           = pix_abs8x8_mvi;

        c->pix_abs[0][0]    = pix_abs16x16_mvi_asm;

        c->pix_abs[1][0]    = pix_abs8x8_mvi;

        c->pix_abs[0][1]    = pix_abs16x16_x2_mvi;

        c->pix_abs[0][2]    = pix_abs16x16_y2_mvi;

        c->pix_abs[0][3]    = pix_abs16x16_xy2_mvi;

    }

    put_pixels_clamped_axp_p = c->put_pixels_clamped;

    add_pixels_clamped_axp_p = c->add_pixels_clamped;

    if (!avctx->lowres && avctx->bits_per_raw_sample <= 8 &&

        (avctx->idct_algo == FF_IDCT_AUTO ||

         avctx->idct_algo == FF_IDCT_SIMPLEALPHA)) {

        c->idct_put = ff_simple_idct_put_axp;

        c->idct_add = ff_simple_idct_add_axp;

        c->idct =     ff_simple_idct_axp;

    }

}


static av_always_inline int dnxhd_decode_dct_block(const DNXHDContext *ctx,

                                                   RowContext *row,

                                                   int n,

                                                   int index_bits,

                                                   int level_bias,

                                                   int level_shift,

                                                   int dc_shift)

{

    int i, j, index1, index2, len, flags;

    int level, component, sign;

    const int *scale;

    const uint8_t *weight_matrix;

    const uint8_t *ac_info = ctx->cid_table->ac_info;

    int16_t *block = row->blocks[n];

    const int eob_index     = ctx->cid_table->eob_index;

    int ret = 0;

    OPEN_READER(bs, &row->gb);

    ctx->bdsp.clear_block(block);

    if (!ctx->is_444) {

        if (n & 2) {

            component     = 1 + (n & 1);

            scale = row->chroma_scale;

            weight_matrix = ctx->cid_table->chroma_weight;

        } else {

            component     = 0;

            scale = row->luma_scale;

            weight_matrix = ctx->cid_table->luma_weight;

        }

    } else {

        component = (n >> 1) % 3;

        if (component) {

            scale = row->chroma_scale;

            weight_matrix = ctx->cid_table->chroma_weight;

        } else {

            scale = row->luma_scale;

            weight_matrix = ctx->cid_table->luma_weight;

        }

    }

    UPDATE_CACHE(bs, &row->gb);

    GET_VLC(len, bs, &row->gb, ctx->dc_vlc.table, DNXHD_DC_VLC_BITS, 1);

    if (len) {

        level = GET_CACHE(bs, &row->gb);

        LAST_SKIP_BITS(bs, &row->gb, len);

        sign  = ~level >> 31;

        level = (NEG_USR32(sign ^ level, len) ^ sign) - sign;

        row->last_dc[component] += level * (1 << dc_shift);

    }

    block[0] = row->last_dc[component];

    i = 0;

    UPDATE_CACHE(bs, &row->gb);

    GET_VLC(index1, bs, &row->gb, ctx->ac_vlc.table,

            DNXHD_VLC_BITS, 2);

    while (index1 != eob_index) {

        level = ac_info[2*index1+0];

        flags = ac_info[2*index1+1];

        sign = SHOW_SBITS(bs, &row->gb, 1);

        SKIP_BITS(bs, &row->gb, 1);

        if (flags & 1) {

            level += SHOW_UBITS(bs, &row->gb, index_bits) << 7;

            SKIP_BITS(bs, &row->gb, index_bits);

        }

        if (flags & 2) {

            UPDATE_CACHE(bs, &row->gb);

            GET_VLC(index2, bs, &row->gb, ctx->run_vlc.table,

                    DNXHD_VLC_BITS, 2);

            i += ctx->cid_table->run[index2];

        }

        if (++i > 63) {

            av_log(ctx->avctx, AV_LOG_ERROR, "ac tex damaged %d, %d\n", n, i);

            ret = -1;

            break;

        }

        j     = ctx->scantable.permutated[i];

        level *= scale[i];

        level += scale[i] >> 1;

        if (level_bias < 32 || weight_matrix[i] != level_bias)

            level += level_bias; // 1<<(level_shift-1)

        level >>= level_shift;

        block[j] = (level ^ sign) - sign;

        UPDATE_CACHE(bs, &row->gb);

        GET_VLC(index1, bs, &row->gb, ctx->ac_vlc.table,

                DNXHD_VLC_BITS, 2);

    }

    CLOSE_READER(bs, &row->gb);

    return ret;

}


static void pci_write(void *opaque, hwaddr addr, uint64_t data,

                      unsigned int size)

{

    AcpiPciHpState *s = opaque;

    switch (addr) {

    case PCI_EJ_BASE:

        if (s->hotplug_select >= ACPI_PCIHP_MAX_HOTPLUG_BUS) {

            break;

        }

        acpi_pcihp_eject_slot(s, s->hotplug_select, data);

        ACPI_PCIHP_DPRINTF("pciej write %" HWADDR_PRIx " <== %" PRIu64 "\n",

                      addr, data);

        break;

    case PCI_SEL_BASE:

        s->hotplug_select = data;

        ACPI_PCIHP_DPRINTF("pcisel write %" HWADDR_PRIx " <== %" PRIu64 "\n",

                      addr, data);

    default:

        break;

    }

}


int64_t qemu_strtosz(const char *nptr, char **end)

{

    return do_strtosz(nptr, end, 'B', 1024);

}


static bool get_phys_addr(CPUARMState *env, target_ulong address,

                          MMUAccessType access_type, ARMMMUIdx mmu_idx,

                          hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,

                          target_ulong *page_size, uint32_t *fsr,

                          ARMMMUFaultInfo *fi)

{

    if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {

        /* Call ourselves recursively to do the stage 1 and then stage 2

         * translations.

         */

        if (arm_feature(env, ARM_FEATURE_EL2)) {

            hwaddr ipa;

            int s2_prot;

            int ret;

            ret = get_phys_addr(env, address, access_type,

                                stage_1_mmu_idx(mmu_idx), &ipa, attrs,

                                prot, page_size, fsr, fi);

            /* If S1 fails or S2 is disabled, return early.  */

            if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {

                *phys_ptr = ipa;

                return ret;

            }

            /* S1 is done. Now do S2 translation.  */

            ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,

                                     phys_ptr, attrs, &s2_prot,

                                     page_size, fsr, fi);

            fi->s2addr = ipa;

            /* Combine the S1 and S2 perms.  */

            *prot &= s2_prot;

            return ret;

        } else {

            /*

             * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.

             */

            mmu_idx = stage_1_mmu_idx(mmu_idx);

        }

    }

    /* The page table entries may downgrade secure to non-secure, but

     * cannot upgrade an non-secure translation regime's attributes

     * to secure.

     */

    attrs->secure = regime_is_secure(env, mmu_idx);

    attrs->user = regime_is_user(env, mmu_idx);

    /* Fast Context Switch Extension. This doesn't exist at all in v8.

     * In v7 and earlier it affects all stage 1 translations.

     */

    if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS

        && !arm_feature(env, ARM_FEATURE_V8)) {

        if (regime_el(env, mmu_idx) == 3) {

            address += env->cp15.fcseidr_s;

        } else {

            address += env->cp15.fcseidr_ns;

        }

    }

    if (arm_feature(env, ARM_FEATURE_PMSA)) {

        bool ret;

        *page_size = TARGET_PAGE_SIZE;

        if (arm_feature(env, ARM_FEATURE_V8)) {

            /* PMSAv8 */

            ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,

                                       phys_ptr, prot, fsr);

        } else if (arm_feature(env, ARM_FEATURE_V7)) {

            /* PMSAv7 */

            ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,

                                       phys_ptr, prot, fsr);

        } else {

            /* Pre-v7 MPU */

            ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,

                                       phys_ptr, prot, fsr);

        }

        qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32

                      " mmu_idx %u -> %s (prot %c%c%c)\n",

                      access_type == MMU_DATA_LOAD ? "reading" :

                      (access_type == MMU_DATA_STORE ? "writing" : "execute"),

                      (uint32_t)address, mmu_idx,

                      ret ? "Miss" : "Hit",

                      *prot & PAGE_READ ? 'r' : '-',

                      *prot & PAGE_WRITE ? 'w' : '-',

                      *prot & PAGE_EXEC ? 'x' : '-');

        return ret;

    }

    /* Definitely a real MMU, not an MPU */

    if (regime_translation_disabled(env, mmu_idx)) {

        /* MMU disabled. */

        *phys_ptr = address;

        *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

        *page_size = TARGET_PAGE_SIZE;

        return 0;

    }

    if (regime_using_lpae_format(env, mmu_idx)) {

        return get_phys_addr_lpae(env, address, access_type, mmu_idx, phys_ptr,

                                  attrs, prot, page_size, fsr, fi);

    } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {

        return get_phys_addr_v6(env, address, access_type, mmu_idx, phys_ptr,

                                attrs, prot, page_size, fsr, fi);

    } else {

        return get_phys_addr_v5(env, address, access_type, mmu_idx, phys_ptr,

                                prot, page_size, fsr, fi);

    }

}


void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,

                       bool is_read, int error)

{

    assert(error >= 0);

    if (action == BLOCK_ERROR_ACTION_STOP) {

        /* First set the iostatus, so that "info block" returns an iostatus

         * that matches the events raised so far (an additional error iostatus

         * is fine, but not a lost one).

         */

        bdrv_iostatus_set_err(bs, error);

        /* Then raise the request to stop the VM and the event.

         * qemu_system_vmstop_request_prepare has two effects.  First,

         * it ensures that the STOP event always comes after the

         * BLOCK_IO_ERROR event.  Second, it ensures that even if management

         * can observe the STOP event and do a "cont" before the STOP

         * event is issued, the VM will not stop.  In this case, vm_start()

         * also ensures that the STOP/RESUME pair of events is emitted.

         */

        qemu_system_vmstop_request_prepare();

        send_qmp_error_event(bs, action, is_read, error);

        qemu_system_vmstop_request(RUN_STATE_IO_ERROR);

    } else {

        send_qmp_error_event(bs, action, is_read, error);

    }

}


static void ide_atapi_cmd_reply(IDEState *s, int size, int max_size)

{

    if (size > max_size)

        size = max_size;

    s->lba = -1; /* no sector read */

    s->packet_transfer_size = size;

    s->io_buffer_size = size;    /* dma: send the reply data as one chunk */

    s->elementary_transfer_size = 0;

    s->io_buffer_index = 0;

    if (s->atapi_dma) {

        block_acct_start(bdrv_get_stats(s->bs), &s->acct, size,

                         BLOCK_ACCT_READ);

        s->status = READY_STAT | SEEK_STAT | DRQ_STAT;

        ide_start_dma(s, ide_atapi_cmd_read_dma_cb);

    } else {

        s->status = READY_STAT | SEEK_STAT;

        ide_atapi_cmd_reply_end(s);

    }

}


static int stream_component_open(VideoState *is, int stream_index)

{

    AVFormatContext *ic = is->ic;

    AVCodecContext *enc;

    AVCodec *codec;

    SDL_AudioSpec wanted_spec, spec;

    if (stream_index < 0 || stream_index >= ic->nb_streams)

        return -1;

    enc = ic->streams[stream_index]->codec;

    /* prepare audio output */

    if (enc->codec_type == CODEC_TYPE_AUDIO) {

        if (enc->channels > 0) {

            enc->request_channels = FFMIN(2, enc->channels);

        } else {

            enc->request_channels = 2;

        }

    }

    codec = avcodec_find_decoder(enc->codec_id);

    enc->debug_mv = debug_mv;

    enc->debug = debug;

    enc->workaround_bugs = workaround_bugs;

    enc->lowres = lowres;

    if(lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;

    enc->idct_algo= idct;

    if(fast) enc->flags2 |= CODEC_FLAG2_FAST;

    enc->skip_frame= skip_frame;

    enc->skip_idct= skip_idct;

    enc->skip_loop_filter= skip_loop_filter;

    enc->error_recognition= error_recognition;

    enc->error_concealment= error_concealment;

    set_context_opts(enc, avcodec_opts[enc->codec_type], 0);

    if (!codec ||

        avcodec_open(enc, codec) < 0)

        return -1;

    /* prepare audio output */

    if (enc->codec_type == CODEC_TYPE_AUDIO) {

        wanted_spec.freq = enc->sample_rate;

        wanted_spec.format = AUDIO_S16SYS;

        wanted_spec.channels = enc->channels;

        wanted_spec.silence = 0;

        wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;

        wanted_spec.callback = sdl_audio_callback;

        wanted_spec.userdata = is;

        if (SDL_OpenAudio(&wanted_spec, &spec) < 0) {

            fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());

            return -1;

        }

        is->audio_hw_buf_size = spec.size;

        is->audio_src_fmt= SAMPLE_FMT_S16;

    }

    if(thread_count>1)

        avcodec_thread_init(enc, thread_count);

    enc->thread_count= thread_count;

    ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;

    switch(enc->codec_type) {

    case CODEC_TYPE_AUDIO:

        is->audio_stream = stream_index;

        is->audio_st = ic->streams[stream_index];

        is->audio_buf_size = 0;

        is->audio_buf_index = 0;

        /* init averaging filter */

        is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);

        is->audio_diff_avg_count = 0;

        /* since we do not have a precise anough audio fifo fullness,

           we correct audio sync only if larger than this threshold */

        is->audio_diff_threshold = 2.0 * SDL_AUDIO_BUFFER_SIZE / enc->sample_rate;

        memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));

        packet_queue_init(&is->audioq);

        SDL_PauseAudio(0);

        break;

    case CODEC_TYPE_VIDEO:

        is->video_stream = stream_index;

        is->video_st = ic->streams[stream_index];

        is->frame_last_delay = 40e-3;

        is->frame_timer = (double)av_gettime() / 1000000.0;

        is->video_current_pts_time = av_gettime();

        packet_queue_init(&is->videoq);

        is->video_tid = SDL_CreateThread(video_thread, is);

        break;

    case CODEC_TYPE_SUBTITLE:

        is->subtitle_stream = stream_index;

        is->subtitle_st = ic->streams[stream_index];

        packet_queue_init(&is->subtitleq);

        is->subtitle_tid = SDL_CreateThread(subtitle_thread, is);

        break;

    default:

        break;

    }

    return 0;

}


void qemu_set_version(const char *version)

{

    qemu_version = version;

}


tcg_target_ulong tcg_qemu_tb_exec(CPUArchState *env, uint8_t *tb_ptr)

{

    tcg_target_ulong next_tb = 0;

    tci_reg[TCG_AREG0] = (tcg_target_ulong)env;

    assert(tb_ptr);

    for (;;) {

#if defined(GETPC)

        tci_tb_ptr = (uintptr_t)tb_ptr;

#endif

        TCGOpcode opc = tb_ptr[0];

#if !defined(NDEBUG)

        uint8_t op_size = tb_ptr[1];

        uint8_t *old_code_ptr = tb_ptr;

#endif

        tcg_target_ulong t0;

        tcg_target_ulong t1;

        tcg_target_ulong t2;

        tcg_target_ulong label;

        TCGCond condition;

        target_ulong taddr;

#ifndef CONFIG_SOFTMMU

        tcg_target_ulong host_addr;

#endif

        uint8_t tmp8;

        uint16_t tmp16;

        uint32_t tmp32;

        uint64_t tmp64;

#if TCG_TARGET_REG_BITS == 32

        uint64_t v64;

#endif

        /* Skip opcode and size entry. */

        tb_ptr += 2;

        switch (opc) {

        case INDEX_op_end:

        case INDEX_op_nop:

            break;

        case INDEX_op_nop1:

        case INDEX_op_nop2:

        case INDEX_op_nop3:

        case INDEX_op_nopn:

        case INDEX_op_discard:

            TODO();

            break;

        case INDEX_op_set_label:

            TODO();

            break;

        case INDEX_op_call:

            t0 = tci_read_ri(&tb_ptr);

#if TCG_TARGET_REG_BITS == 32

            tmp64 = ((helper_function)t0)(tci_read_reg(TCG_REG_R0),

                                          tci_read_reg(TCG_REG_R1),

                                          tci_read_reg(TCG_REG_R2),

                                          tci_read_reg(TCG_REG_R3),

                                          tci_read_reg(TCG_REG_R5),

                                          tci_read_reg(TCG_REG_R6),

                                          tci_read_reg(TCG_REG_R7),

                                          tci_read_reg(TCG_REG_R8),

                                          tci_read_reg(TCG_REG_R9),

                                          tci_read_reg(TCG_REG_R10));

            tci_write_reg(TCG_REG_R0, tmp64);

            tci_write_reg(TCG_REG_R1, tmp64 >> 32);

#else

            tmp64 = ((helper_function)t0)(tci_read_reg(TCG_REG_R0),

                                          tci_read_reg(TCG_REG_R1),

                                          tci_read_reg(TCG_REG_R2),

                                          tci_read_reg(TCG_REG_R3),

                                          tci_read_reg(TCG_REG_R5));

            tci_write_reg(TCG_REG_R0, tmp64);

#endif

            break;

        case INDEX_op_br:

            label = tci_read_label(&tb_ptr);

            assert(tb_ptr == old_code_ptr + op_size);

            tb_ptr = (uint8_t *)label;

            continue;

        case INDEX_op_setcond_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            condition = *tb_ptr++;

            tci_write_reg32(t0, tci_compare32(t1, t2, condition));

            break;

#if TCG_TARGET_REG_BITS == 32

        case INDEX_op_setcond2_i32:

            t0 = *tb_ptr++;

            tmp64 = tci_read_r64(&tb_ptr);

            v64 = tci_read_ri64(&tb_ptr);

            condition = *tb_ptr++;

            tci_write_reg32(t0, tci_compare64(tmp64, v64, condition));

            break;

#elif TCG_TARGET_REG_BITS == 64

        case INDEX_op_setcond_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            condition = *tb_ptr++;

            tci_write_reg64(t0, tci_compare64(t1, t2, condition));

            break;

#endif

        case INDEX_op_mov_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

        case INDEX_op_movi_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_i32(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

            /* Load/store operations (32 bit). */

        case INDEX_op_ld8u_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            tci_write_reg8(t0, *(uint8_t *)(t1 + t2));

            break;

        case INDEX_op_ld8s_i32:

        case INDEX_op_ld16u_i32:

            TODO();

            break;

        case INDEX_op_ld16s_i32:

            TODO();

            break;

        case INDEX_op_ld_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            tci_write_reg32(t0, *(uint32_t *)(t1 + t2));

            break;

        case INDEX_op_st8_i32:

            t0 = tci_read_r8(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            *(uint8_t *)(t1 + t2) = t0;

            break;

        case INDEX_op_st16_i32:

            t0 = tci_read_r16(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            *(uint16_t *)(t1 + t2) = t0;

            break;

        case INDEX_op_st_i32:

            t0 = tci_read_r32(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            *(uint32_t *)(t1 + t2) = t0;

            break;

            /* Arithmetic operations (32 bit). */

        case INDEX_op_add_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 + t2);

            break;

        case INDEX_op_sub_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 - t2);

            break;

        case INDEX_op_mul_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 * t2);

            break;

#if TCG_TARGET_HAS_div_i32

        case INDEX_op_div_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, (int32_t)t1 / (int32_t)t2);

            break;

        case INDEX_op_divu_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 / t2);

            break;

        case INDEX_op_rem_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, (int32_t)t1 % (int32_t)t2);

            break;

        case INDEX_op_remu_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 % t2);

            break;

#elif TCG_TARGET_HAS_div2_i32

        case INDEX_op_div2_i32:

        case INDEX_op_divu2_i32:

            TODO();

            break;

#endif

        case INDEX_op_and_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 & t2);

            break;

        case INDEX_op_or_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 | t2);

            break;

        case INDEX_op_xor_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 ^ t2);

            break;

            /* Shift/rotate operations (32 bit). */

        case INDEX_op_shl_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 << t2);

            break;

        case INDEX_op_shr_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 >> t2);

            break;

        case INDEX_op_sar_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, ((int32_t)t1 >> t2));

            break;

#if TCG_TARGET_HAS_rot_i32

        case INDEX_op_rotl_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, (t1 << t2) | (t1 >> (32 - t2)));

            break;

        case INDEX_op_rotr_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, (t1 >> t2) | (t1 << (32 - t2)));

            break;

#endif

#if TCG_TARGET_HAS_deposit_i32

        case INDEX_op_deposit_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            t2 = tci_read_r32(&tb_ptr);

            tmp16 = *tb_ptr++;

            tmp8 = *tb_ptr++;

            tmp32 = (((1 << tmp8) - 1) << tmp16);

            tci_write_reg32(t0, (t1 & ~tmp32) | ((t2 << tmp16) & tmp32));

            break;

#endif

        case INDEX_op_brcond_i32:

            t0 = tci_read_r32(&tb_ptr);

            t1 = tci_read_ri32(&tb_ptr);

            condition = *tb_ptr++;

            label = tci_read_label(&tb_ptr);

            if (tci_compare32(t0, t1, condition)) {

                assert(tb_ptr == old_code_ptr + op_size);

                tb_ptr = (uint8_t *)label;

                continue;

            }

            break;

#if TCG_TARGET_REG_BITS == 32

        case INDEX_op_add2_i32:

            t0 = *tb_ptr++;

            t1 = *tb_ptr++;

            tmp64 = tci_read_r64(&tb_ptr);

            tmp64 += tci_read_r64(&tb_ptr);

            tci_write_reg64(t1, t0, tmp64);

            break;

        case INDEX_op_sub2_i32:

            t0 = *tb_ptr++;

            t1 = *tb_ptr++;

            tmp64 = tci_read_r64(&tb_ptr);

            tmp64 -= tci_read_r64(&tb_ptr);

            tci_write_reg64(t1, t0, tmp64);

            break;

        case INDEX_op_brcond2_i32:

            tmp64 = tci_read_r64(&tb_ptr);

            v64 = tci_read_ri64(&tb_ptr);

            condition = *tb_ptr++;

            label = tci_read_label(&tb_ptr);

            if (tci_compare64(tmp64, v64, condition)) {

                assert(tb_ptr == old_code_ptr + op_size);

                tb_ptr = (uint8_t *)label;

                continue;

            }

            break;

        case INDEX_op_mulu2_i32:

            t0 = *tb_ptr++;

            t1 = *tb_ptr++;

            t2 = tci_read_r32(&tb_ptr);

            tmp64 = tci_read_r32(&tb_ptr);

            tci_write_reg64(t1, t0, t2 * tmp64);

            break;

#endif /* TCG_TARGET_REG_BITS == 32 */

#if TCG_TARGET_HAS_ext8s_i32

        case INDEX_op_ext8s_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r8s(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext16s_i32

        case INDEX_op_ext16s_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r16s(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext8u_i32

        case INDEX_op_ext8u_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r8(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext16u_i32

        case INDEX_op_ext16u_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r16(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_bswap16_i32

        case INDEX_op_bswap16_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r16(&tb_ptr);

            tci_write_reg32(t0, bswap16(t1));

            break;

#endif

#if TCG_TARGET_HAS_bswap32_i32

        case INDEX_op_bswap32_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg32(t0, bswap32(t1));

            break;

#endif

#if TCG_TARGET_HAS_not_i32

        case INDEX_op_not_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg32(t0, ~t1);

            break;

#endif

#if TCG_TARGET_HAS_neg_i32

        case INDEX_op_neg_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg32(t0, -t1);

            break;

#endif

#if TCG_TARGET_REG_BITS == 64

        case INDEX_op_mov_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

        case INDEX_op_movi_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_i64(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

            /* Load/store operations (64 bit). */

        case INDEX_op_ld8u_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            tci_write_reg8(t0, *(uint8_t *)(t1 + t2));

            break;

        case INDEX_op_ld8s_i64:

        case INDEX_op_ld16u_i64:

        case INDEX_op_ld16s_i64:

            TODO();

            break;

        case INDEX_op_ld32u_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            tci_write_reg32(t0, *(uint32_t *)(t1 + t2));

            break;

        case INDEX_op_ld32s_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            tci_write_reg32s(t0, *(int32_t *)(t1 + t2));

            break;

        case INDEX_op_ld_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            tci_write_reg64(t0, *(uint64_t *)(t1 + t2));

            break;

        case INDEX_op_st8_i64:

            t0 = tci_read_r8(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            *(uint8_t *)(t1 + t2) = t0;

            break;

        case INDEX_op_st16_i64:

            t0 = tci_read_r16(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            *(uint16_t *)(t1 + t2) = t0;

            break;

        case INDEX_op_st32_i64:

            t0 = tci_read_r32(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            *(uint32_t *)(t1 + t2) = t0;

            break;

        case INDEX_op_st_i64:

            t0 = tci_read_r64(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_s32(&tb_ptr);

            *(uint64_t *)(t1 + t2) = t0;

            break;

            /* Arithmetic operations (64 bit). */

        case INDEX_op_add_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 + t2);

            break;

        case INDEX_op_sub_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 - t2);

            break;

        case INDEX_op_mul_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 * t2);

            break;

#if TCG_TARGET_HAS_div_i64

        case INDEX_op_div_i64:

        case INDEX_op_divu_i64:

        case INDEX_op_rem_i64:

        case INDEX_op_remu_i64:

            TODO();

            break;

#elif TCG_TARGET_HAS_div2_i64

        case INDEX_op_div2_i64:

        case INDEX_op_divu2_i64:

            TODO();

            break;

#endif

        case INDEX_op_and_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 & t2);

            break;

        case INDEX_op_or_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 | t2);

            break;

        case INDEX_op_xor_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 ^ t2);

            break;

            /* Shift/rotate operations (64 bit). */

        case INDEX_op_shl_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 << t2);

            break;

        case INDEX_op_shr_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 >> t2);

            break;

        case INDEX_op_sar_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, ((int64_t)t1 >> t2));

            break;

#if TCG_TARGET_HAS_rot_i64

        case INDEX_op_rotl_i64:

        case INDEX_op_rotr_i64:

            TODO();

            break;

#endif

#if TCG_TARGET_HAS_deposit_i64

        case INDEX_op_deposit_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            t2 = tci_read_r64(&tb_ptr);

            tmp16 = *tb_ptr++;

            tmp8 = *tb_ptr++;

            tmp64 = (((1ULL << tmp8) - 1) << tmp16);

            tci_write_reg64(t0, (t1 & ~tmp64) | ((t2 << tmp16) & tmp64));

            break;

#endif

        case INDEX_op_brcond_i64:

            t0 = tci_read_r64(&tb_ptr);

            t1 = tci_read_ri64(&tb_ptr);

            condition = *tb_ptr++;

            label = tci_read_label(&tb_ptr);

            if (tci_compare64(t0, t1, condition)) {

                assert(tb_ptr == old_code_ptr + op_size);

                tb_ptr = (uint8_t *)label;

                continue;

            }

            break;

#if TCG_TARGET_HAS_ext8u_i64

        case INDEX_op_ext8u_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r8(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext8s_i64

        case INDEX_op_ext8s_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r8s(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext16s_i64

        case INDEX_op_ext16s_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r16s(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext16u_i64

        case INDEX_op_ext16u_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r16(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext32s_i64

        case INDEX_op_ext32s_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r32s(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext32u_i64

        case INDEX_op_ext32u_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_bswap16_i64

        case INDEX_op_bswap16_i64:

            TODO();

            t0 = *tb_ptr++;

            t1 = tci_read_r16(&tb_ptr);

            tci_write_reg64(t0, bswap16(t1));

            break;

#endif

#if TCG_TARGET_HAS_bswap32_i64

        case INDEX_op_bswap32_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg64(t0, bswap32(t1));

            break;

#endif

#if TCG_TARGET_HAS_bswap64_i64

        case INDEX_op_bswap64_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            tci_write_reg64(t0, bswap64(t1));

            break;

#endif

#if TCG_TARGET_HAS_not_i64

        case INDEX_op_not_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            tci_write_reg64(t0, ~t1);

            break;

#endif

#if TCG_TARGET_HAS_neg_i64

        case INDEX_op_neg_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            tci_write_reg64(t0, -t1);

            break;

#endif

#endif /* TCG_TARGET_REG_BITS == 64 */

            /* QEMU specific operations. */

#if TARGET_LONG_BITS > TCG_TARGET_REG_BITS

        case INDEX_op_debug_insn_start:

            TODO();

            break;

#else

        case INDEX_op_debug_insn_start:

            TODO();

            break;

#endif

        case INDEX_op_exit_tb:

            next_tb = *(uint64_t *)tb_ptr;

            goto exit;

            break;

        case INDEX_op_goto_tb:

            t0 = tci_read_i32(&tb_ptr);

            assert(tb_ptr == old_code_ptr + op_size);

            tb_ptr += (int32_t)t0;

            continue;

        case INDEX_op_qemu_ld8u:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp8 = helper_ldb_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp8 = *(uint8_t *)(host_addr + GUEST_BASE);

#endif

            tci_write_reg8(t0, tmp8);

            break;

        case INDEX_op_qemu_ld8s:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp8 = helper_ldb_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp8 = *(uint8_t *)(host_addr + GUEST_BASE);

#endif

            tci_write_reg8s(t0, tmp8);

            break;

        case INDEX_op_qemu_ld16u:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp16 = helper_ldw_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp16 = tswap16(*(uint16_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg16(t0, tmp16);

            break;

        case INDEX_op_qemu_ld16s:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp16 = helper_ldw_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp16 = tswap16(*(uint16_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg16s(t0, tmp16);

            break;

#if TCG_TARGET_REG_BITS == 64

        case INDEX_op_qemu_ld32u:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp32 = helper_ldl_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp32 = tswap32(*(uint32_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg32(t0, tmp32);

            break;

        case INDEX_op_qemu_ld32s:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp32 = helper_ldl_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp32 = tswap32(*(uint32_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg32s(t0, tmp32);

            break;

#endif /* TCG_TARGET_REG_BITS == 64 */

        case INDEX_op_qemu_ld32:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp32 = helper_ldl_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp32 = tswap32(*(uint32_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg32(t0, tmp32);

            break;

        case INDEX_op_qemu_ld64:

            t0 = *tb_ptr++;

#if TCG_TARGET_REG_BITS == 32

            t1 = *tb_ptr++;

#endif

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp64 = helper_ldq_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp64 = tswap64(*(uint64_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg(t0, tmp64);

#if TCG_TARGET_REG_BITS == 32

            tci_write_reg(t1, tmp64 >> 32);

#endif

            break;

        case INDEX_op_qemu_st8:

            t0 = tci_read_r8(&tb_ptr);

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            t2 = tci_read_i(&tb_ptr);

            helper_stb_mmu(env, taddr, t0, t2);

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            *(uint8_t *)(host_addr + GUEST_BASE) = t0;

#endif

            break;

        case INDEX_op_qemu_st16:

            t0 = tci_read_r16(&tb_ptr);

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            t2 = tci_read_i(&tb_ptr);

            helper_stw_mmu(env, taddr, t0, t2);

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            *(uint16_t *)(host_addr + GUEST_BASE) = tswap16(t0);

#endif

            break;

        case INDEX_op_qemu_st32:

            t0 = tci_read_r32(&tb_ptr);

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            t2 = tci_read_i(&tb_ptr);

            helper_stl_mmu(env, taddr, t0, t2);

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            *(uint32_t *)(host_addr + GUEST_BASE) = tswap32(t0);

#endif

            break;

        case INDEX_op_qemu_st64:

            tmp64 = tci_read_r64(&tb_ptr);

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            t2 = tci_read_i(&tb_ptr);

            helper_stq_mmu(env, taddr, tmp64, t2);

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            *(uint64_t *)(host_addr + GUEST_BASE) = tswap64(tmp64);

#endif

            break;

        default:

            TODO();

            break;

        }

        assert(tb_ptr == old_code_ptr + op_size);

    }

exit:

    return next_tb;

}


static void do_commit(void)

{

    int i;

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

        if (bs_table[i])

            bdrv_commit(bs_table[i]);

    }

}


static int v9fs_do_mknod(V9fsState *s, V9fsString *path, mode_t mode, dev_t dev)

{

    return s->ops->mknod(&s->ctx, path->data, mode, dev);

}


static uint64_t g364fb_ctrl_read(void *opaque,

                                 target_phys_addr_t addr,

                                 unsigned int size)

{

    G364State *s = opaque;

    uint32_t val;

    if (addr >= REG_CURS_PAT && addr < REG_CURS_PAT + 0x1000) {

        /* cursor pattern */

        int idx = (addr - REG_CURS_PAT) >> 3;

        val = s->cursor[idx];

    } else if (addr >= REG_CURS_PAL && addr < REG_CURS_PAL + 0x18) {

        /* cursor palette */

        int idx = (addr - REG_CURS_PAL) >> 3;

        val = ((uint32_t)s->cursor_palette[idx][0] << 16);

        val |= ((uint32_t)s->cursor_palette[idx][1] << 8);

        val |= ((uint32_t)s->cursor_palette[idx][2] << 0);

    } else {

        switch (addr) {

            case REG_DISPLAY:

                val = s->width / 4;

                break;

            case REG_VDISPLAY:

                val = s->height * 2;

                break;

            case REG_CTLA:

                val = s->ctla;

                break;

            default:

            {

                error_report("g364: invalid read at [" TARGET_FMT_plx "]",

                             addr);

                val = 0;

                break;

            }

        }

    }

    trace_g364fb_read(addr, val);

    return val;

}


static void vncws_send_handshake_response(VncState *vs, const char* key)

{

    char combined_key[WS_CLIENT_KEY_LEN + WS_GUID_LEN + 1];

    unsigned char hash[SHA1_DIGEST_LEN];

    size_t hash_size = sizeof(hash);

    char *accept = NULL, *response = NULL;

    gnutls_datum_t in;

    int ret;

    g_strlcpy(combined_key, key, WS_CLIENT_KEY_LEN + 1);

    g_strlcat(combined_key, WS_GUID, WS_CLIENT_KEY_LEN + WS_GUID_LEN + 1);

    /* hash and encode it */

    in.data = (void *)combined_key;

    in.size = WS_CLIENT_KEY_LEN + WS_GUID_LEN;

    ret = gnutls_fingerprint(GNUTLS_DIG_SHA1, &in, hash, &hash_size);

    if (ret == GNUTLS_E_SUCCESS && hash_size <= SHA1_DIGEST_LEN) {

        accept = g_base64_encode(hash, hash_size);

    }

    if (accept == NULL) {

        VNC_DEBUG("Hashing Websocket combined key failed\n");

        vnc_client_error(vs);

        return;

    }

    response = g_strdup_printf(WS_HANDSHAKE, accept);

    vnc_client_write_buf(vs, (const uint8_t *)response, strlen(response));

    g_free(accept);

    g_free(response);

    vs->encode_ws = 1;

    vnc_init_state(vs);

}


av_cold int ff_ffv1_init_slice_state(FFV1Context *f, FFV1Context *fs)

{

    int j;

    fs->plane_count  = f->plane_count;

    fs->transparency = f->transparency;

    for (j = 0; j < f->plane_count; j++) {

        PlaneContext *const p = &fs->plane[j];

        if (fs->ac) {

            if (!p->state)

                p->state = av_malloc_array(p->context_count, CONTEXT_SIZE *

                                     sizeof(uint8_t));

            if (!p->state)

                return AVERROR(ENOMEM);

        } else {

            if (!p->vlc_state)

                p->vlc_state = av_malloc_array(p->context_count, sizeof(VlcState));

            if (!p->vlc_state)

                return AVERROR(ENOMEM);

        }

    }

    if (fs->ac > 1) {

        //FIXME only redo if state_transition changed

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

            fs->c. one_state[      j] = f->state_transition[j];

            fs->c.zero_state[256 - j] = 256 - fs->c.one_state[j];

        }

    }

    return 0;

}


static void spitz_init(int ram_size, int vga_ram_size, int boot_device,

                DisplayState *ds, const char **fd_filename, int snapshot,

                const char *kernel_filename, const char *kernel_cmdline,

                const char *initrd_filename, const char *cpu_model)

{

    spitz_common_init(ram_size, vga_ram_size, ds, kernel_filename,

                kernel_cmdline, initrd_filename, spitz, 0x2c9);

}


static int vcr1_decode_frame(AVCodecContext *avctx, void *data,
                             int *got_frame, AVPacket *avpkt)
{
    const uint8_t *buf        = avpkt->data;
    int buf_size              = avpkt->size;
    VCR1Context *const a      = avctx->priv_data;
    AVFrame *const p          = data;
    const uint8_t *bytestream = buf;
    int i, x, y, ret;
    if ((ret = ff_get_buffer(avctx, p, 0)) < 0) {
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
        return ret;
    }
    p->pict_type = AV_PICTURE_TYPE_I;
    p->key_frame = 1;
    if (buf_size < 32)
    for (i = 0; i < 16; i++) {
        a->delta[i] = *bytestream++;
        bytestream++;
        buf_size--;
    }
    for (y = 0; y < avctx->height; y++) {
        int offset;
        uint8_t *luma = &p->data[0][y * p->linesize[0]];
        if ((y & 3) == 0) {
            uint8_t *cb = &p->data[1][(y >> 2) * p->linesize[1]];
            uint8_t *cr = &p->data[2][(y >> 2) * p->linesize[2]];
            for (i = 0; i < 4; i++)
                a->offset[i] = *bytestream++;
            offset = a->offset[0] - a->delta[bytestream[2] & 0xF];
            for (x = 0; x < avctx->width; x += 4) {
                luma[0]     = offset += a->delta[bytestream[2] & 0xF];
                luma[1]     = offset += a->delta[bytestream[2] >>  4];
                luma[2]     = offset += a->delta[bytestream[0] & 0xF];
                luma[3]     = offset += a->delta[bytestream[0] >>  4];
                luma       += 4;
                *cb++       = bytestream[3];
                *cr++       = bytestream[1];
                bytestream += 4;
                buf_size   -= 4;
            }
        } else {
            if (buf_size < avctx->width / 2)
            offset = a->offset[y & 3] - a->delta[bytestream[2] & 0xF];
            for (x = 0; x < avctx->width; x += 8) {
                luma[0]     = offset += a->delta[bytestream[2] & 0xF];
                luma[1]     = offset += a->delta[bytestream[2] >>  4];
                luma[2]     = offset += a->delta[bytestream[3] & 0xF];
                luma[3]     = offset += a->delta[bytestream[3] >>  4];
                luma[4]     = offset += a->delta[bytestream[0] & 0xF];
                luma[5]     = offset += a->delta[bytestream[0] >>  4];
                luma[6]     = offset += a->delta[bytestream[1] & 0xF];
                luma[7]     = offset += a->delta[bytestream[1] >>  4];
                luma       += 8;
                bytestream += 4;
                buf_size   -= 4;
            }
        }
    }
    *got_frame = 1;
    return buf_size;
packet_small:
    av_log(avctx, AV_LOG_ERROR, "Input packet too small.\n");
    return AVERROR_INVALIDDATA;
}