int ff_h263_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             const uint8_t *buf, int buf_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->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;

#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){

            s->bitstream_buffer= av_fast_realloc(

                s->bitstream_buffer,

                &s->allocated_bitstream_buffer_size,

                buf_size - current_pos + FF_INPUT_BUFFER_PADDING_SIZE);

            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);

    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 dscm1xxxx_attach(PCMCIACardState *card)

{

    MicroDriveState *md = MICRODRIVE(card);

    PCMCIACardClass *pcc = PCMCIA_CARD_GET_CLASS(card);

    md->attr_base = pcc->cis[0x74] | (pcc->cis[0x76] << 8);

    md->io_base = 0x0;

    device_reset(DEVICE(md));

    md_interrupt_update(md);

    card->slot->card_string = "DSCM-1xxxx Hitachi Microdrive";

    return 0;

}


static av_always_inline int lcg_random(int previous_val)

{

    return previous_val * 1664525 + 1013904223;

}


static void s390_init(ram_addr_t ram_size,

                      const char *boot_device,

                      const char *kernel_filename,

                      const char *kernel_cmdline,

                      const char *initrd_filename,

                      const char *cpu_model)

{

    CPUState *env = NULL;

    ram_addr_t ram_addr;

    ram_addr_t kernel_size = 0;

    ram_addr_t initrd_offset;

    ram_addr_t initrd_size = 0;

    int i;

    /* XXX we only work on KVM for now */

    if (!kvm_enabled()) {

        fprintf(stderr, "The S390 target only works with KVM enabled\n");

        exit(1);

    }

    /* get a BUS */

    s390_bus = s390_virtio_bus_init(&ram_size);

    /* allocate RAM */

    ram_addr = qemu_ram_alloc(NULL, "s390.ram", ram_size);

    cpu_register_physical_memory(0, ram_size, ram_addr);

    /* init CPUs */

    if (cpu_model == NULL) {

        cpu_model = "host";

    }

    ipi_states = qemu_malloc(sizeof(CPUState *) * smp_cpus);

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

        CPUState *tmp_env;

        tmp_env = cpu_init(cpu_model);

        if (!env) {

            env = tmp_env;

        }

        ipi_states[i] = tmp_env;

        tmp_env->halted = 1;

        tmp_env->exception_index = EXCP_HLT;

    }

    env->halted = 0;

    env->exception_index = 0;

    if (kernel_filename) {

        kernel_size = load_image(kernel_filename, qemu_get_ram_ptr(0));

        if (lduw_phys(KERN_IMAGE_START) != 0x0dd0) {

            fprintf(stderr, "Specified image is not an s390 boot image\n");

            exit(1);

        }

        env->psw.addr = KERN_IMAGE_START;

        env->psw.mask = 0x0000000180000000ULL;

    } else {

        ram_addr_t bios_size = 0;

        char *bios_filename;

        /* Load zipl bootloader */

        if (bios_name == NULL) {

            bios_name = ZIPL_FILENAME;

        }

        bios_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        bios_size = load_image(bios_filename, qemu_get_ram_ptr(ZIPL_LOAD_ADDR));

        if ((long)bios_size < 0) {

            hw_error("could not load bootloader '%s'\n", bios_name);

        }

        if (bios_size > 4096) {

            hw_error("stage1 bootloader is > 4k\n");

        }

        env->psw.addr = ZIPL_START;

        env->psw.mask = 0x0000000180000000ULL;

    }

    if (initrd_filename) {

        initrd_offset = INITRD_START;

        while (kernel_size + 0x100000 > initrd_offset) {

            initrd_offset += 0x100000;

        }

        initrd_size = load_image(initrd_filename, qemu_get_ram_ptr(initrd_offset));

        stq_phys(INITRD_PARM_START, initrd_offset);

        stq_phys(INITRD_PARM_SIZE, initrd_size);

    }

    if (kernel_cmdline) {

        cpu_physical_memory_rw(KERN_PARM_AREA, (uint8_t *)kernel_cmdline,

                               strlen(kernel_cmdline), 1);

    }

    /* Create VirtIO network adapters */

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

        NICInfo *nd = &nd_table[i];

        DeviceState *dev;

        if (!nd->model) {

            nd->model = qemu_strdup("virtio");

        }

        if (strcmp(nd->model, "virtio")) {

            fprintf(stderr, "S390 only supports VirtIO nics\n");

            exit(1);

        }

        dev = qdev_create((BusState *)s390_bus, "virtio-net-s390");

        qdev_set_nic_properties(dev, nd);

        qdev_init_nofail(dev);

    }

    /* Create VirtIO disk drives */

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

        DriveInfo *dinfo;

        DeviceState *dev;

        dinfo = drive_get(IF_IDE, 0, i);

        if (!dinfo) {

            continue;

        }

        dev = qdev_create((BusState *)s390_bus, "virtio-blk-s390");

        qdev_prop_set_drive_nofail(dev, "drive", dinfo->bdrv);

        qdev_init_nofail(dev);

    }

}


static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)

{

    switch (mmu_idx) {

    case ARMMMUIdx_S2NS:

    case ARMMMUIdx_S1E2:

        return 2;

    case ARMMMUIdx_S1E3:

        return 3;

    case ARMMMUIdx_S1SE0:

        return arm_el_is_aa64(env, 3) ? 1 : 3;

    case ARMMMUIdx_S1SE1:

    case ARMMMUIdx_S1NSE0:

    case ARMMMUIdx_S1NSE1:

        return 1;

    default:

        g_assert_not_reached();

    }

}


static int open_slave(AVFormatContext *avf, char *slave, TeeSlave *tee_slave)

{

    int i, ret;

    AVDictionary *options = NULL;

    AVDictionaryEntry *entry;

    char *filename;

    char *format = NULL, *select = NULL;

    AVFormatContext *avf2 = NULL;

    AVStream *st, *st2;

    int stream_count;

    int fullret;

    char *subselect = NULL, *next_subselect = NULL, *first_subselect = NULL, *tmp_select = NULL;

    if ((ret = parse_slave_options(avf, slave, &options, &filename)) < 0)

        return ret;

#define STEAL_OPTION(option, field) do {                                \

        if ((entry = av_dict_get(options, option, NULL, 0))) {          \

            field = entry->value;                                       \

            entry->value = NULL; /* prevent it from being freed */      \

            av_dict_set(&options, option, NULL, 0);                     \

        }                                                               \

    } while (0)

    STEAL_OPTION("f", format);

    STEAL_OPTION("select", select);

    ret = avformat_alloc_output_context2(&avf2, NULL, format, filename);

    if (ret < 0)

        goto end;

    av_dict_copy(&avf2->metadata, avf->metadata, 0);

    avf2->opaque   = avf->opaque;

    avf2->io_open  = avf->io_open;

    avf2->io_close = avf->io_close;

    tee_slave->stream_map = av_calloc(avf->nb_streams, sizeof(*tee_slave->stream_map));

    if (!tee_slave->stream_map) {

        ret = AVERROR(ENOMEM);

        goto end;

    }

    stream_count = 0;

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

        st = avf->streams[i];

        if (select) {

            tmp_select = av_strdup(select);  // av_strtok is destructive so we regenerate it in each loop

            if (!tmp_select) {

                ret = AVERROR(ENOMEM);

                goto end;

            }

            fullret = 0;

            first_subselect = tmp_select;

            next_subselect = NULL;

            while (subselect = av_strtok(first_subselect, slave_select_sep, &next_subselect)) {

                first_subselect = NULL;

                ret = avformat_match_stream_specifier(avf, avf->streams[i], subselect);

                if (ret < 0) {

                    av_log(avf, AV_LOG_ERROR,

                           "Invalid stream specifier '%s' for output '%s'\n",

                           subselect, slave);

                    goto end;

                }

                if (ret != 0) {

                    fullret = 1; // match

                    break;

                }

            }

            av_freep(&tmp_select);

            if (fullret == 0) { /* no match */

                tee_slave->stream_map[i] = -1;

                continue;

            }

        }

        tee_slave->stream_map[i] = stream_count++;

        if (!(st2 = avformat_new_stream(avf2, NULL))) {

            ret = AVERROR(ENOMEM);

            goto end;

        }

        st2->id = st->id;

        st2->r_frame_rate        = st->r_frame_rate;

        st2->time_base           = st->time_base;

        st2->start_time          = st->start_time;

        st2->duration            = st->duration;

        st2->nb_frames           = st->nb_frames;

        st2->disposition         = st->disposition;

        st2->sample_aspect_ratio = st->sample_aspect_ratio;

        st2->avg_frame_rate      = st->avg_frame_rate;

        av_dict_copy(&st2->metadata, st->metadata, 0);

        if ((ret = avcodec_parameters_copy(st2->codecpar, st->codecpar)) < 0)

            goto end;

    }

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

        if ((ret = avf2->io_open(avf2, &avf2->pb, filename, AVIO_FLAG_WRITE, NULL)) < 0) {

            av_log(avf, AV_LOG_ERROR, "Slave '%s': error opening: %s\n",

                   slave, av_err2str(ret));

            goto end;

        }

    }

    if ((ret = avformat_write_header(avf2, &options)) < 0) {

        av_log(avf, AV_LOG_ERROR, "Slave '%s': error writing header: %s\n",

               slave, av_err2str(ret));

        goto end;

    }

    tee_slave->avf = avf2;

    tee_slave->bsfs = av_calloc(avf2->nb_streams, sizeof(TeeSlave));

    if (!tee_slave->bsfs) {

        ret = AVERROR(ENOMEM);

        goto end;

    }

    entry = NULL;

    while (entry = av_dict_get(options, "bsfs", NULL, AV_DICT_IGNORE_SUFFIX)) {

        const char *spec = entry->key + strlen("bsfs");

        if (*spec) {

            if (strspn(spec, slave_bsfs_spec_sep) != 1) {

                av_log(avf, AV_LOG_ERROR,

                       "Specifier separator in '%s' is '%c', but only characters '%s' "

                       "are allowed\n", entry->key, *spec, slave_bsfs_spec_sep);

                return AVERROR(EINVAL);

            }

            spec++; /* consume separator */

        }

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

            ret = avformat_match_stream_specifier(avf2, avf2->streams[i], spec);

            if (ret < 0) {

                av_log(avf, AV_LOG_ERROR,

                       "Invalid stream specifier '%s' in bsfs option '%s' for slave "

                       "output '%s'\n", spec, entry->key, filename);

                goto end;

            }

            if (ret > 0) {

                av_log(avf, AV_LOG_DEBUG, "spec:%s bsfs:%s matches stream %d of slave "

                       "output '%s'\n", spec, entry->value, i, filename);

                if (tee_slave->bsfs[i]) {

                    av_log(avf, AV_LOG_WARNING,

                           "Duplicate bsfs specification associated to stream %d of slave "

                           "output '%s', filters will be ignored\n", i, filename);

                    continue;

                }

                ret = parse_bsfs(avf, entry->value, &tee_slave->bsfs[i]);

                if (ret < 0) {

                    av_log(avf, AV_LOG_ERROR,

                           "Error parsing bitstream filter sequence '%s' associated to "

                           "stream %d of slave output '%s'\n", entry->value, i, filename);

                    goto end;

                }

            }

        }

        av_dict_set(&options, entry->key, NULL, 0);

    }

    if (options) {

        entry = NULL;

        while ((entry = av_dict_get(options, "", entry, AV_DICT_IGNORE_SUFFIX)))

            av_log(avf2, AV_LOG_ERROR, "Unknown option '%s'\n", entry->key);

        ret = AVERROR_OPTION_NOT_FOUND;

        goto end;

    }

end:

    av_free(format);

    av_free(select);

    av_dict_free(&options);

    av_freep(&tmp_select);

    return ret;

}


static uint16_t nvme_del_cq(NvmeCtrl *n, NvmeCmd *cmd)

{

    NvmeDeleteQ *c = (NvmeDeleteQ *)cmd;

    NvmeCQueue *cq;

    uint16_t qid = le16_to_cpu(c->qid);

    if (!qid || nvme_check_cqid(n, qid)) {

        return NVME_INVALID_CQID | NVME_DNR;

    }

    cq = n->cq[qid];

    if (!QTAILQ_EMPTY(&cq->sq_list)) {

        return NVME_INVALID_QUEUE_DEL;

    }

    nvme_free_cq(cq, n);

    return NVME_SUCCESS;

}


static void test_acpi_q35_tcg_cphp(void)

{

    test_data data;

    memset(&data, 0, sizeof(data));

    data.machine = MACHINE_Q35;

    data.variant = ".cphp";

    test_acpi_one(" -smp 2,cores=3,sockets=2,maxcpus=6",

                  &data);

    free_test_data(&data);

}


TPMVersion tpm_backend_get_tpm_version(TPMBackend *s)

{

    TPMBackendClass *k = TPM_BACKEND_GET_CLASS(s);

    assert(k->get_tpm_version);

    return k->get_tpm_version(s);

}


static av_cold int cuvid_decode_init(AVCodecContext *avctx)

{

    CuvidContext *ctx = avctx->priv_data;

    AVCUDADeviceContext *device_hwctx;

    AVHWDeviceContext *device_ctx;

    AVHWFramesContext *hwframe_ctx;

    CUVIDPARSERPARAMS cuparseinfo;

    CUVIDEOFORMATEX cuparse_ext;

    CUVIDSOURCEDATAPACKET seq_pkt;

    CUdevice device;

    CUcontext cuda_ctx = NULL;

    CUcontext dummy;

    const AVBitStreamFilter *bsf;

    int ret = 0;

    enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,

                                       AV_PIX_FMT_NV12,

                                       AV_PIX_FMT_NONE };

    ret = ff_get_format(avctx, pix_fmts);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", ret);

        return ret;

    }

    ctx->frame_queue = av_fifo_alloc(MAX_FRAME_COUNT * sizeof(CUVIDPARSERDISPINFO));

    if (!ctx->frame_queue) {

        ret = AVERROR(ENOMEM);

        goto error;

    }

    avctx->pix_fmt = ret;

    if (avctx->hw_frames_ctx) {

        ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);

        if (!ctx->hwframe) {

            ret = AVERROR(ENOMEM);

            goto error;

        }

        hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;

        ctx->hwdevice = av_buffer_ref(hwframe_ctx->device_ref);

        if (!ctx->hwdevice) {

            ret = AVERROR(ENOMEM);

            goto error;

        }

        device_ctx = hwframe_ctx->device_ctx;

        device_hwctx = device_ctx->hwctx;

        cuda_ctx = device_hwctx->cuda_ctx;

    } else {

        ctx->hwdevice = av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_CUDA);

        if (!ctx->hwdevice) {

            av_log(avctx, AV_LOG_ERROR, "Error allocating hwdevice\n");

            ret = AVERROR(ENOMEM);

            goto error;

        }

        ret = CHECK_CU(cuInit(0));

        if (ret < 0)

            goto error;

        ret = CHECK_CU(cuDeviceGet(&device, 0));

        if (ret < 0)

            goto error;

        ret = CHECK_CU(cuCtxCreate(&cuda_ctx, CU_CTX_SCHED_BLOCKING_SYNC, device));

        if (ret < 0)

            goto error;

        device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;

        device_ctx->free = cuvid_ctx_free;

        device_hwctx = device_ctx->hwctx;

        device_hwctx->cuda_ctx = cuda_ctx;

        ret = CHECK_CU(cuCtxPopCurrent(&dummy));

        if (ret < 0)

            goto error;

        ret = av_hwdevice_ctx_init(ctx->hwdevice);

        if (ret < 0) {

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

            goto error;

        }

        ctx->hwframe = av_hwframe_ctx_alloc(ctx->hwdevice);

        if (!ctx->hwframe) {

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

            ret = AVERROR(ENOMEM);

            goto error;

        }

    }

    memset(&cuparseinfo, 0, sizeof(cuparseinfo));

    memset(&cuparse_ext, 0, sizeof(cuparse_ext));

    memset(&seq_pkt, 0, sizeof(seq_pkt));

    cuparseinfo.pExtVideoInfo = &cuparse_ext;

    switch (avctx->codec->id) {

#if CONFIG_H264_CUVID_DECODER

    case AV_CODEC_ID_H264:

        cuparseinfo.CodecType = cudaVideoCodec_H264;

#if CONFIG_HEVC_CUVID_DECODER

    case AV_CODEC_ID_HEVC:

        cuparseinfo.CodecType = cudaVideoCodec_HEVC;

#if CONFIG_MJPEG_CUVID_DECODER

    case AV_CODEC_ID_MJPEG:

        cuparseinfo.CodecType = cudaVideoCodec_JPEG;

#if CONFIG_MPEG1_CUVID_DECODER

    case AV_CODEC_ID_MPEG1VIDEO:

        cuparseinfo.CodecType = cudaVideoCodec_MPEG1;

#if CONFIG_MPEG2_CUVID_DECODER

    case AV_CODEC_ID_MPEG2VIDEO:

        cuparseinfo.CodecType = cudaVideoCodec_MPEG2;

#if CONFIG_MPEG4_CUVID_DECODER

    case AV_CODEC_ID_MPEG4:

#if CONFIG_VP8_CUVID_DECODER

    case AV_CODEC_ID_VP8:

        cuparseinfo.CodecType = cudaVideoCodec_VP8;

#if CONFIG_VP9_CUVID_DECODER

    case AV_CODEC_ID_VP9:

        cuparseinfo.CodecType = cudaVideoCodec_VP9;

#if CONFIG_VC1_CUVID_DECODER

    case AV_CODEC_ID_VC1:

        cuparseinfo.CodecType = cudaVideoCodec_VC1;

    default:

        av_log(avctx, AV_LOG_ERROR, "Invalid CUVID codec!\n");

        return AVERROR_BUG;

    }

    if (avctx->codec->id == AV_CODEC_ID_H264 || avctx->codec->id == AV_CODEC_ID_HEVC) {

        if (avctx->codec->id == AV_CODEC_ID_H264)

            bsf = av_bsf_get_by_name("h264_mp4toannexb");

        else

            bsf = av_bsf_get_by_name("hevc_mp4toannexb");

        if (!bsf) {

            ret = AVERROR_BSF_NOT_FOUND;

            goto error;

        }

        if (ret = av_bsf_alloc(bsf, &ctx->bsf)) {

            goto error;

        }

        if (((ret = avcodec_parameters_from_context(ctx->bsf->par_in, avctx)) < 0) || ((ret = av_bsf_init(ctx->bsf)) < 0)) {

            av_bsf_free(&ctx->bsf);

            goto error;

        }

        cuparse_ext.format.seqhdr_data_length = ctx->bsf->par_out->extradata_size;

        memcpy(cuparse_ext.raw_seqhdr_data,

               ctx->bsf->par_out->extradata,

               FFMIN(sizeof(cuparse_ext.raw_seqhdr_data), ctx->bsf->par_out->extradata_size));

    } else if (avctx->extradata_size > 0) {

        cuparse_ext.format.seqhdr_data_length = avctx->extradata_size;

        memcpy(cuparse_ext.raw_seqhdr_data,

               avctx->extradata,

               FFMIN(sizeof(cuparse_ext.raw_seqhdr_data), avctx->extradata_size));

    }

    cuparseinfo.ulMaxNumDecodeSurfaces = MAX_FRAME_COUNT;

    cuparseinfo.ulMaxDisplayDelay = 4;

    cuparseinfo.pUserData = avctx;

    cuparseinfo.pfnSequenceCallback = cuvid_handle_video_sequence;

    cuparseinfo.pfnDecodePicture = cuvid_handle_picture_decode;

    cuparseinfo.pfnDisplayPicture = cuvid_handle_picture_display;

    ret = CHECK_CU(cuCtxPushCurrent(cuda_ctx));

    if (ret < 0)

        goto error;

    ret = cuvid_test_dummy_decoder(avctx, &cuparseinfo);

    if (ret < 0)

        goto error;

    ret = CHECK_CU(cuvidCreateVideoParser(&ctx->cuparser, &cuparseinfo));

    if (ret < 0)

        goto error;

    seq_pkt.payload = cuparse_ext.raw_seqhdr_data;

    seq_pkt.payload_size = cuparse_ext.format.seqhdr_data_length;

    if (seq_pkt.payload && seq_pkt.payload_size) {

        ret = CHECK_CU(cuvidParseVideoData(ctx->cuparser, &seq_pkt));

        if (ret < 0)

            goto error;

    }

    ret = CHECK_CU(cuCtxPopCurrent(&dummy));

    if (ret < 0)

        goto error;

    return 0;

error:

    cuvid_decode_end(avctx);

    return ret;

}


static int tcp_wait_fd(int fd, int write)

{

    int ev = write ? POLLOUT : POLLIN;

    struct pollfd p = { .fd = fd, .events = ev, .revents = 0 };

    int ret;

    ret = poll(&p, 1, 100);

    return ret < 0 ? ff_neterrno() : p.revents & ev ? 0 : AVERROR(EAGAIN);

}


static int file_check(URLContext *h, int mask)

{

#if HAVE_ACCESS && defined(R_OK)

    int ret = 0;

    if (access(h->filename, F_OK) < 0)

        return AVERROR(errno);

    if (mask&AVIO_FLAG_READ)

        if (access(h->filename, R_OK) >= 0)

            ret |= AVIO_FLAG_READ;

    if (mask&AVIO_FLAG_WRITE)

        if (access(h->filename, W_OK) >= 0)

            ret |= AVIO_FLAG_WRITE;

#else

    struct stat st;

    int ret = stat(h->filename, &st);

    if (ret < 0)

        return AVERROR(errno);

    ret |= st.st_mode&S_IRUSR ? mask&AVIO_FLAG_READ  : 0;

    ret |= st.st_mode&S_IWUSR ? mask&AVIO_FLAG_WRITE : 0;

#endif

    return ret;

}


int qemu_bh_poll(void)

{

    return aio_bh_poll(qemu_aio_context);

}


static struct omap_sti_s *omap_sti_init(struct omap_target_agent_s *ta,

                MemoryRegion *sysmem,

                target_phys_addr_t channel_base, qemu_irq irq, omap_clk clk,

                CharDriverState *chr)

{

    struct omap_sti_s *s = (struct omap_sti_s *)

            g_malloc0(sizeof(struct omap_sti_s));

    s->irq = irq;

    omap_sti_reset(s);

    s->chr = chr ?: qemu_chr_new("null", "null", NULL);

    memory_region_init_io(&s->iomem, &omap_sti_ops, s, "omap.sti",

                          omap_l4_region_size(ta, 0));

    omap_l4_attach(ta, 0, &s->iomem);

    memory_region_init_io(&s->iomem_fifo, &omap_sti_fifo_ops, s,

                          "omap.sti.fifo", 0x10000);

    memory_region_add_subregion(sysmem, channel_base, &s->iomem_fifo);

    return s;

}


static int init_event_facility(SCLPEventFacility *event_facility)

{

    DeviceState *sdev = DEVICE(event_facility);

    DeviceState *quiesce;

    /* Spawn a new bus for SCLP events */

    qbus_create_inplace(&event_facility->sbus, sizeof(event_facility->sbus),

                        TYPE_SCLP_EVENTS_BUS, sdev, NULL);

    quiesce = qdev_create(&event_facility->sbus.qbus, "sclpquiesce");

    if (!quiesce) {

        return -1;

    }

    qdev_init_nofail(quiesce);

    object_initialize(&cpu_hotplug, sizeof(cpu_hotplug), TYPE_SCLP_CPU_HOTPLUG);

    qdev_set_parent_bus(DEVICE(&cpu_hotplug), BUS(&event_facility->sbus));

    object_property_set_bool(OBJECT(&cpu_hotplug), true, "realized", NULL);

    return 0;

}


static ssize_t qio_channel_websock_writev(QIOChannel *ioc,

                                          const struct iovec *iov,

                                          size_t niov,

                                          int *fds,

                                          size_t nfds,

                                          Error **errp)

{

    QIOChannelWebsock *wioc = QIO_CHANNEL_WEBSOCK(ioc);

    size_t i;

    ssize_t done = 0;

    ssize_t ret;

    if (wioc->io_err) {

        *errp = error_copy(wioc->io_err);

        return -1;

    }

    if (wioc->io_eof) {

        error_setg(errp, "%s", "Broken pipe");

        return -1;

    }

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

        size_t want = iov[i].iov_len;

        if ((want + wioc->rawoutput.offset) > QIO_CHANNEL_WEBSOCK_MAX_BUFFER) {

            want = (QIO_CHANNEL_WEBSOCK_MAX_BUFFER - wioc->rawoutput.offset);

        }

        if (want == 0) {

            goto done;

        }

        buffer_reserve(&wioc->rawoutput, want);

        buffer_append(&wioc->rawoutput, iov[i].iov_base, want);

        done += want;

        if (want < iov[i].iov_len) {

            break;

        }

    }

 done:

    ret = qio_channel_websock_write_wire(wioc, errp);

    if (ret < 0 &&

        ret != QIO_CHANNEL_ERR_BLOCK) {

        qio_channel_websock_unset_watch(wioc);

        return -1;

    }

    qio_channel_websock_set_watch(wioc);

    if (done == 0) {

        return QIO_CHANNEL_ERR_BLOCK;

    }

    return done;

}


static int virtio_blk_load(QEMUFile *f, void *opaque, int version_id)

{

    VirtIOBlock *s = opaque;

    if (version_id != 2)

        return -EINVAL;

    virtio_load(&s->vdev, f);

    while (qemu_get_sbyte(f)) {

        VirtIOBlockReq *req = virtio_blk_alloc_request(s);

        qemu_get_buffer(f, (unsigned char*)&req->elem, sizeof(req->elem));

        req->next = s->rq;

        s->rq = req->next;

    }

    return 0;

}


bool timerlist_has_timers(QEMUTimerList *timer_list)

{

    return !!timer_list->active_timers;

}


int inet_connect_opts(QemuOpts *opts, Error **errp)

{

    struct addrinfo ai,*res,*e;

    const char *addr;

    const char *port;

    char uaddr[INET6_ADDRSTRLEN+1];

    char uport[33];

    int sock,rc;

    bool block;

    memset(&ai,0, sizeof(ai));

    ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;

    ai.ai_family = PF_UNSPEC;

    ai.ai_socktype = SOCK_STREAM;

    addr = qemu_opt_get(opts, "host");

    port = qemu_opt_get(opts, "port");

    block = qemu_opt_get_bool(opts, "block", 0);

    if (addr == NULL || port == NULL) {

        fprintf(stderr, "inet_connect: host and/or port not specified\n");

        error_set(errp, QERR_SOCKET_CREATE_FAILED);

        return -1;

    }

    if (qemu_opt_get_bool(opts, "ipv4", 0))

        ai.ai_family = PF_INET;

    if (qemu_opt_get_bool(opts, "ipv6", 0))

        ai.ai_family = PF_INET6;

    /* lookup */

    if (0 != (rc = getaddrinfo(addr, port, &ai, &res))) {

        fprintf(stderr,"getaddrinfo(%s,%s): %s\n", addr, port,

                gai_strerror(rc));

        error_set(errp, QERR_SOCKET_CREATE_FAILED);

	return -1;

    }

    for (e = res; e != NULL; e = e->ai_next) {

        if (getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,

                            uaddr,INET6_ADDRSTRLEN,uport,32,

                            NI_NUMERICHOST | NI_NUMERICSERV) != 0) {

            fprintf(stderr,"%s: getnameinfo: oops\n", __FUNCTION__);

            continue;

        }

        sock = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);

        if (sock < 0) {

            fprintf(stderr,"%s: socket(%s): %s\n", __FUNCTION__,

            inet_strfamily(e->ai_family), strerror(errno));

            continue;

        }

        setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(void*)&on,sizeof(on));

        if (!block) {

            socket_set_nonblock(sock);

        }

        /* connect to peer */

        do {

            rc = 0;

            if (connect(sock, e->ai_addr, e->ai_addrlen) < 0) {

                rc = -socket_error();

            }

        } while (rc == -EINTR);

  #ifdef _WIN32

        if (!block && (rc == -EINPROGRESS || rc == -EWOULDBLOCK

                       || rc == -WSAEALREADY)) {

  #else

        if (!block && (rc == -EINPROGRESS)) {

  #endif

            error_set(errp, QERR_SOCKET_CONNECT_IN_PROGRESS);

        } else if (rc < 0) {

            if (NULL == e->ai_next)

                fprintf(stderr, "%s: connect(%s,%s,%s,%s): %s\n", __FUNCTION__,

                        inet_strfamily(e->ai_family),

                        e->ai_canonname, uaddr, uport, strerror(errno));

            closesocket(sock);

            continue;

        }

        freeaddrinfo(res);

        return sock;

    }

    error_set(errp, QERR_SOCKET_CONNECT_FAILED);

    freeaddrinfo(res);

    return -1;

}


static void ppc_cpu_do_nmi_on_cpu(CPUState *cs, run_on_cpu_data arg)

{

    cpu_synchronize_state(cs);

    ppc_cpu_do_system_reset(cs);

}


void HELPER(stby_e)(CPUHPPAState *env, target_ulong addr, target_ulong val)

{

    uintptr_t ra = GETPC();

    switch (addr & 3) {

    case 3:

        /* The 3 byte store must appear atomic.  */

        if (parallel_cpus) {

            atomic_store_3(env, addr - 3, val, 0xffffff00u, ra);

        } else {

            cpu_stw_data_ra(env, addr - 3, val >> 16, ra);

            cpu_stb_data_ra(env, addr - 1, val >> 8, ra);

        }

        break;

    case 2:

        cpu_stw_data_ra(env, addr - 2, val >> 16, ra);

        break;

    case 1:

        cpu_stb_data_ra(env, addr - 1, val >> 24, ra);

        break;

    default:

        /* Nothing is stored, but protection is checked and the

           cacheline is marked dirty.  */

#ifndef CONFIG_USER_ONLY

        probe_write(env, addr, cpu_mmu_index(env, 0), ra);

#endif

        break;

    }

}


static int rv10_decode_packet(AVCodecContext *avctx,

                             uint8_t *buf, int buf_size)

{

    MpegEncContext *s = avctx->priv_data;

    int i, mb_count, mb_pos, left;

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

#if 0

    for(i=0; i<buf_size*8 && i<100; i++)

        printf("%d", get_bits1(&s->gb));

    printf("\n");

    return 0;

#endif

    if(s->codec_id ==CODEC_ID_RV10)

        mb_count = rv10_decode_picture_header(s);

    else

        mb_count = rv20_decode_picture_header(s);

    if (mb_count < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "HEADER ERROR\n");

        return -1;

    }

    if (s->mb_x >= s->mb_width ||

        s->mb_y >= s->mb_height) {

        av_log(s->avctx, AV_LOG_ERROR, "POS ERROR %d %d\n", s->mb_x, s->mb_y);

        return -1;

    }

    mb_pos = s->mb_y * s->mb_width + s->mb_x;

    left = s->mb_width * s->mb_height - mb_pos;

    if (mb_count > left) {

        av_log(s->avctx, AV_LOG_ERROR, "COUNT ERROR\n");

        return -1;

    }

//if(s->pict_type == P_TYPE) return 0;

    if (s->mb_x == 0 && s->mb_y == 0) {

        if(MPV_frame_start(s, avctx) < 0)

            return -1;

    }

#ifdef DEBUG

    printf("qscale=%d\n", s->qscale);

#endif

    /* default quantization values */

    if(s->codec_id== CODEC_ID_RV10){

        if(s->mb_y==0) s->first_slice_line=1;

    }else{

        s->first_slice_line=1;

        s->resync_mb_x= s->mb_x;

        s->resync_mb_y= s->mb_y;

    }

    if(s->h263_aic){

        s->y_dc_scale_table=

        s->c_dc_scale_table= ff_aic_dc_scale_table;

    }else{

        s->y_dc_scale_table=

        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;

    }

    s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];

    s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];

    s->rv10_first_dc_coded[0] = 0;

    s->rv10_first_dc_coded[1] = 0;

    s->rv10_first_dc_coded[2] = 0;

    s->block_wrap[0]=

    s->block_wrap[1]=

    s->block_wrap[2]=

    s->block_wrap[3]= s->mb_width*2 + 2;

    s->block_wrap[4]=

    s->block_wrap[5]= s->mb_width + 2;

    ff_init_block_index(s);

    /* decode each macroblock */

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

        int ret;

        ff_update_block_index(s);

#ifdef DEBUG

        printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);

#endif

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

        s->mv_dir = MV_DIR_FORWARD;

        s->mv_type = MV_TYPE_16X16;

        ret=ff_h263_decode_mb(s, s->block);

        if (ret == SLICE_ERROR) {

            av_log(s->avctx, AV_LOG_ERROR, "ERROR at MB %d %d\n", s->mb_x, s->mb_y);

            return -1;

        }

        ff_h263_update_motion_val(s);

        MPV_decode_mb(s, s->block);

        if (++s->mb_x == s->mb_width) {

            s->mb_x = 0;

            s->mb_y++;

            ff_init_block_index(s);

        }

        if(s->mb_x == s->resync_mb_x)

            s->first_slice_line=0;

        if(ret == SLICE_END) break;

    }

    return buf_size;

}


uint32_t net_checksum_add_cont(int len, uint8_t *buf, int seq)

{

    uint32_t sum = 0;

    int i;

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

        if (i & 1) {

            sum += (uint32_t)buf[i - seq];

        } else {

            sum += (uint32_t)buf[i - seq] << 8;

        }

    }

    return sum;

}


static void write_dump_header(DumpState *s, Error **errp)

{

     Error *local_err = NULL;

    if (s->dump_info.d_class == ELFCLASS32) {

        create_header32(s, &local_err);

    } else {

        create_header64(s, &local_err);

    }

    if (local_err) {

        error_propagate(errp, local_err);

    }

}


static int parse_short_name(BDRVVVFATState* s,

	long_file_name* lfn, direntry_t* direntry)

{

    int i, j;

    if (!is_short_name(direntry))

	return 1;

    for (j = 7; j >= 0 && direntry->name[j] == ' '; j--);

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

	if (direntry->name[i] <= ' ' || direntry->name[i] > 0x7f)

	    return -1;

	else if (s->downcase_short_names)

	    lfn->name[i] = qemu_tolower(direntry->name[i]);

	else

	    lfn->name[i] = direntry->name[i];

    }

    for (j = 2; j >= 0 && direntry->extension[j] == ' '; j--);

    if (j >= 0) {

	lfn->name[i++] = '.';

	lfn->name[i + j + 1] = '\0';

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

	    if (direntry->extension[j] <= ' ' || direntry->extension[j] > 0x7f)

		return -2;

	    else if (s->downcase_short_names)

		lfn->name[i + j] = qemu_tolower(direntry->extension[j]);

	    else

		lfn->name[i + j] = direntry->extension[j];

	}

    } else

	lfn->name[i + j + 1] = '\0';

    lfn->len = strlen((char*)lfn->name);

    return 0;

}


void gen_intermediate_code(CPUState *cs, TranslationBlock *tb)

{

    CPUARMState *env = cs->env_ptr;

    ARMCPU *cpu = arm_env_get_cpu(env);

    DisasContext dc1, *dc = &dc1;

    target_ulong pc_start;

    target_ulong next_page_start;

    int num_insns;

    int max_insns;

    bool end_of_page;

    /* generate intermediate code */

    /* The A64 decoder has its own top level loop, because it doesn't need

     * the A32/T32 complexity to do with conditional execution/IT blocks/etc.

     */

    if (ARM_TBFLAG_AARCH64_STATE(tb->flags)) {

        gen_intermediate_code_a64(cs, tb);

        return;

    }

    pc_start = tb->pc;

    dc->tb = tb;

    dc->is_jmp = DISAS_NEXT;

    dc->pc = pc_start;

    dc->singlestep_enabled = cs->singlestep_enabled;

    dc->condjmp = 0;

    dc->aarch64 = 0;

    /* If we are coming from secure EL0 in a system with a 32-bit EL3, then

     * there is no secure EL1, so we route exceptions to EL3.

     */

    dc->secure_routed_to_el3 = arm_feature(env, ARM_FEATURE_EL3) &&

                               !arm_el_is_aa64(env, 3);

    dc->thumb = ARM_TBFLAG_THUMB(tb->flags);

    dc->sctlr_b = ARM_TBFLAG_SCTLR_B(tb->flags);

    dc->be_data = ARM_TBFLAG_BE_DATA(tb->flags) ? MO_BE : MO_LE;

    dc->condexec_mask = (ARM_TBFLAG_CONDEXEC(tb->flags) & 0xf) << 1;

    dc->condexec_cond = ARM_TBFLAG_CONDEXEC(tb->flags) >> 4;

    dc->mmu_idx = core_to_arm_mmu_idx(env, ARM_TBFLAG_MMUIDX(tb->flags));

    dc->current_el = arm_mmu_idx_to_el(dc->mmu_idx);

#if !defined(CONFIG_USER_ONLY)

    dc->user = (dc->current_el == 0);

#endif

    dc->ns = ARM_TBFLAG_NS(tb->flags);

    dc->fp_excp_el = ARM_TBFLAG_FPEXC_EL(tb->flags);

    dc->vfp_enabled = ARM_TBFLAG_VFPEN(tb->flags);

    dc->vec_len = ARM_TBFLAG_VECLEN(tb->flags);

    dc->vec_stride = ARM_TBFLAG_VECSTRIDE(tb->flags);

    dc->c15_cpar = ARM_TBFLAG_XSCALE_CPAR(tb->flags);

    dc->v7m_handler_mode = ARM_TBFLAG_HANDLER(tb->flags);

    dc->cp_regs = cpu->cp_regs;

    dc->features = env->features;

    /* Single step state. The code-generation logic here is:

     *  SS_ACTIVE == 0:

     *   generate code with no special handling for single-stepping (except

     *   that anything that can make us go to SS_ACTIVE == 1 must end the TB;

     *   this happens anyway because those changes are all system register or

     *   PSTATE writes).

     *  SS_ACTIVE == 1, PSTATE.SS == 1: (active-not-pending)

     *   emit code for one insn

     *   emit code to clear PSTATE.SS

     *   emit code to generate software step exception for completed step

     *   end TB (as usual for having generated an exception)

     *  SS_ACTIVE == 1, PSTATE.SS == 0: (active-pending)

     *   emit code to generate a software step exception

     *   end the TB

     */

    dc->ss_active = ARM_TBFLAG_SS_ACTIVE(tb->flags);

    dc->pstate_ss = ARM_TBFLAG_PSTATE_SS(tb->flags);

    dc->is_ldex = false;

    dc->ss_same_el = false; /* Can't be true since EL_d must be AArch64 */

    cpu_F0s = tcg_temp_new_i32();

    cpu_F1s = tcg_temp_new_i32();

    cpu_F0d = tcg_temp_new_i64();

    cpu_F1d = tcg_temp_new_i64();

    cpu_V0 = cpu_F0d;

    cpu_V1 = cpu_F1d;

    /* FIXME: cpu_M0 can probably be the same as cpu_V0.  */

    cpu_M0 = tcg_temp_new_i64();

    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0) {

        max_insns = CF_COUNT_MASK;

    }

    if (max_insns > TCG_MAX_INSNS) {

        max_insns = TCG_MAX_INSNS;

    }

    gen_tb_start(tb);

    tcg_clear_temp_count();

    /* A note on handling of the condexec (IT) bits:

     *

     * We want to avoid the overhead of having to write the updated condexec

     * bits back to the CPUARMState for every instruction in an IT block. So:

     * (1) if the condexec bits are not already zero then we write

     * zero back into the CPUARMState now. This avoids complications trying

     * to do it at the end of the block. (For example if we don't do this

     * it's hard to identify whether we can safely skip writing condexec

     * at the end of the TB, which we definitely want to do for the case

     * where a TB doesn't do anything with the IT state at all.)

     * (2) if we are going to leave the TB then we call gen_set_condexec()

     * which will write the correct value into CPUARMState if zero is wrong.

     * This is done both for leaving the TB at the end, and for leaving

     * it because of an exception we know will happen, which is done in

     * gen_exception_insn(). The latter is necessary because we need to

     * leave the TB with the PC/IT state just prior to execution of the

     * instruction which caused the exception.

     * (3) if we leave the TB unexpectedly (eg a data abort on a load)

     * then the CPUARMState will be wrong and we need to reset it.

     * This is handled in the same way as restoration of the

     * PC in these situations; we save the value of the condexec bits

     * for each PC via tcg_gen_insn_start(), and restore_state_to_opc()

     * then uses this to restore them after an exception.

     *

     * Note that there are no instructions which can read the condexec

     * bits, and none which can write non-static values to them, so

     * we don't need to care about whether CPUARMState is correct in the

     * middle of a TB.

     */

    /* Reset the conditional execution bits immediately. This avoids

       complications trying to do it at the end of the block.  */

    if (dc->condexec_mask || dc->condexec_cond)

      {

        TCGv_i32 tmp = tcg_temp_new_i32();

        tcg_gen_movi_i32(tmp, 0);

        store_cpu_field(tmp, condexec_bits);

      }

    do {

        dc->insn_start_idx = tcg_op_buf_count();

        tcg_gen_insn_start(dc->pc,

                           (dc->condexec_cond << 4) | (dc->condexec_mask >> 1),

                           0);

        num_insns++;

#ifdef CONFIG_USER_ONLY

        /* Intercept jump to the magic kernel page.  */

        if (dc->pc >= 0xffff0000) {

            /* We always get here via a jump, so know we are not in a

               conditional execution block.  */

            gen_exception_internal(EXCP_KERNEL_TRAP);

            dc->is_jmp = DISAS_NORETURN;

            break;

        }

#endif

        if (unlikely(!QTAILQ_EMPTY(&cs->breakpoints))) {

            CPUBreakpoint *bp;

            QTAILQ_FOREACH(bp, &cs->breakpoints, entry) {

                if (bp->pc == dc->pc) {

                    if (bp->flags & BP_CPU) {

                        gen_set_condexec(dc);

                        gen_set_pc_im(dc, dc->pc);

                        gen_helper_check_breakpoints(cpu_env);

                        /* End the TB early; it's likely not going to be executed */

                        dc->is_jmp = DISAS_UPDATE;

                    } else {

                        gen_exception_internal_insn(dc, 0, EXCP_DEBUG);

                        /* The address covered by the breakpoint must be

                           included in [tb->pc, tb->pc + tb->size) in order

                           to for it to be properly cleared -- thus we

                           increment the PC here so that the logic setting

                           tb->size below does the right thing.  */

                        /* TODO: Advance PC by correct instruction length to

                         * avoid disassembler error messages */

                        dc->pc += 2;

                        goto done_generating;

                    }

                    break;

                }

            }

        }

        if (num_insns == max_insns && (tb->cflags & CF_LAST_IO)) {

            gen_io_start();

        }

        if (dc->ss_active && !dc->pstate_ss) {

            /* Singlestep state is Active-pending.

             * If we're in this state at the start of a TB then either

             *  a) we just took an exception to an EL which is being debugged

             *     and this is the first insn in the exception handler

             *  b) debug exceptions were masked and we just unmasked them

             *     without changing EL (eg by clearing PSTATE.D)

             * In either case we're going to take a swstep exception in the

             * "did not step an insn" case, and so the syndrome ISV and EX

             * bits should be zero.

             */

            assert(num_insns == 1);

            gen_exception(EXCP_UDEF, syn_swstep(dc->ss_same_el, 0, 0),

                          default_exception_el(dc));

            goto done_generating;

        }

        if (dc->thumb) {

            disas_thumb_insn(env, dc);

            if (dc->condexec_mask) {

                dc->condexec_cond = (dc->condexec_cond & 0xe)

                                   | ((dc->condexec_mask >> 4) & 1);

                dc->condexec_mask = (dc->condexec_mask << 1) & 0x1f;

                if (dc->condexec_mask == 0) {

                    dc->condexec_cond = 0;

                }

            }

        } else {

            unsigned int insn = arm_ldl_code(env, dc->pc, dc->sctlr_b);

            dc->pc += 4;

            disas_arm_insn(dc, insn);

        }

        if (dc->condjmp && !dc->is_jmp) {

            gen_set_label(dc->condlabel);

            dc->condjmp = 0;

        }

        if (tcg_check_temp_count()) {

            fprintf(stderr, "TCG temporary leak before "TARGET_FMT_lx"\n",

                    dc->pc);

        }

        /* Translation stops when a conditional branch is encountered.

         * Otherwise the subsequent code could get translated several times.

         * Also stop translation when a page boundary is reached.  This

         * ensures prefetch aborts occur at the right place.  */

        /* We want to stop the TB if the next insn starts in a new page,

         * or if it spans between this page and the next. This means that

         * if we're looking at the last halfword in the page we need to

         * see if it's a 16-bit Thumb insn (which will fit in this TB)

         * or a 32-bit Thumb insn (which won't).

         * This is to avoid generating a silly TB with a single 16-bit insn

         * in it at the end of this page (which would execute correctly

         * but isn't very efficient).

         */

        end_of_page = (dc->pc >= next_page_start) ||

            ((dc->pc >= next_page_start - 3) && insn_crosses_page(env, dc));

    } while (!dc->is_jmp && !tcg_op_buf_full() &&

             !is_singlestepping(dc) &&

             !singlestep &&

             !end_of_page &&

             num_insns < max_insns);

    if (tb->cflags & CF_LAST_IO) {

        if (dc->condjmp) {

            /* FIXME:  This can theoretically happen with self-modifying

               code.  */

            cpu_abort(cs, "IO on conditional branch instruction");

        }

        gen_io_end();

    }

    /* At this stage dc->condjmp will only be set when the skipped

       instruction was a conditional branch or trap, and the PC has

       already been written.  */

    gen_set_condexec(dc);

    if (dc->is_jmp == DISAS_BX_EXCRET) {

        /* Exception return branches need some special case code at the

         * end of the TB, which is complex enough that it has to

         * handle the single-step vs not and the condition-failed

         * insn codepath itself.

         */

        gen_bx_excret_final_code(dc);

    } else if (unlikely(is_singlestepping(dc))) {

        /* Unconditional and "condition passed" instruction codepath. */

        switch (dc->is_jmp) {

        case DISAS_SWI:

            gen_ss_advance(dc);

            gen_exception(EXCP_SWI, syn_aa32_svc(dc->svc_imm, dc->thumb),

                          default_exception_el(dc));

            break;

        case DISAS_HVC:

            gen_ss_advance(dc);

            gen_exception(EXCP_HVC, syn_aa32_hvc(dc->svc_imm), 2);

            break;

        case DISAS_SMC:

            gen_ss_advance(dc);

            gen_exception(EXCP_SMC, syn_aa32_smc(), 3);

            break;

        case DISAS_NEXT:

        case DISAS_UPDATE:

            gen_set_pc_im(dc, dc->pc);

            /* fall through */

        default:

            /* FIXME: Single stepping a WFI insn will not halt the CPU. */

            gen_singlestep_exception(dc);

            break;

        case DISAS_NORETURN:

            break;

        }

    } else {

        /* While branches must always occur at the end of an IT block,

           there are a few other things that can cause us to terminate

           the TB in the middle of an IT block:

            - Exception generating instructions (bkpt, swi, undefined).

            - Page boundaries.

            - Hardware watchpoints.

           Hardware breakpoints have already been handled and skip this code.

         */

        switch(dc->is_jmp) {

        case DISAS_NEXT:

            gen_goto_tb(dc, 1, dc->pc);

            break;

        case DISAS_JUMP:

            gen_goto_ptr();

            break;

        case DISAS_UPDATE:

            gen_set_pc_im(dc, dc->pc);

            /* fall through */

        default:

            /* indicate that the hash table must be used to find the next TB */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_NORETURN:

            /* nothing more to generate */

            break;

        case DISAS_WFI:

            gen_helper_wfi(cpu_env);

            /* The helper doesn't necessarily throw an exception, but we

             * must go back to the main loop to check for interrupts anyway.

             */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_WFE:

            gen_helper_wfe(cpu_env);

            break;

        case DISAS_YIELD:

            gen_helper_yield(cpu_env);

            break;

        case DISAS_SWI:

            gen_exception(EXCP_SWI, syn_aa32_svc(dc->svc_imm, dc->thumb),

                          default_exception_el(dc));

            break;

        case DISAS_HVC:

            gen_exception(EXCP_HVC, syn_aa32_hvc(dc->svc_imm), 2);

            break;

        case DISAS_SMC:

            gen_exception(EXCP_SMC, syn_aa32_smc(), 3);

            break;

        }

    }

    if (dc->condjmp) {

        /* "Condition failed" instruction codepath for the branch/trap insn */

        gen_set_label(dc->condlabel);

        gen_set_condexec(dc);

        if (unlikely(is_singlestepping(dc))) {

            gen_set_pc_im(dc, dc->pc);

            gen_singlestep_exception(dc);

        } else {

            gen_goto_tb(dc, 1, dc->pc);

        }

    }

done_generating:

    gen_tb_end(tb, num_insns);

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM) &&

        qemu_log_in_addr_range(pc_start)) {

        qemu_log_lock();

        qemu_log("----------------\n");

        qemu_log("IN: %s\n", lookup_symbol(pc_start));

        log_target_disas(cs, pc_start, dc->pc - pc_start,

                         dc->thumb | (dc->sctlr_b << 1));

        qemu_log("\n");

        qemu_log_unlock();

    }

#endif

    tb->size = dc->pc - pc_start;

    tb->icount = num_insns;

}


static void tgen_brcond(TCGContext *s, TCGType type, TCGCond c,

                        TCGReg r1, TCGArg c2, int c2const, int labelno)

{

    int cc;

    if (facilities & FACILITY_GEN_INST_EXT) {

        bool is_unsigned = is_unsigned_cond(c);

        bool in_range;

        S390Opcode opc;

        cc = tcg_cond_to_s390_cond[c];

        if (!c2const) {

            opc = (type == TCG_TYPE_I32

                   ? (is_unsigned ? RIE_CLRJ : RIE_CRJ)

                   : (is_unsigned ? RIE_CLGRJ : RIE_CGRJ));

            tgen_compare_branch(s, opc, cc, r1, c2, labelno);

            return;

        }

        /* COMPARE IMMEDIATE AND BRANCH RELATIVE has an 8-bit immediate field.

           If the immediate we've been given does not fit that range, we'll

           fall back to separate compare and branch instructions using the

           larger comparison range afforded by COMPARE IMMEDIATE.  */

        if (type == TCG_TYPE_I32) {

            if (is_unsigned) {

                opc = RIE_CLIJ;

                in_range = (uint32_t)c2 == (uint8_t)c2;

            } else {

                opc = RIE_CIJ;

                in_range = (int32_t)c2 == (int8_t)c2;

            }

        } else {

            if (is_unsigned) {

                opc = RIE_CLGIJ;

                in_range = (uint64_t)c2 == (uint8_t)c2;

            } else {

                opc = RIE_CGIJ;

                in_range = (int64_t)c2 == (int8_t)c2;

            }

        }

        if (in_range) {

            tgen_compare_imm_branch(s, opc, cc, r1, c2, labelno);

            return;

        }

    }

    cc = tgen_cmp(s, type, c, r1, c2, c2const);

    tgen_branch(s, cc, labelno);

}


void mips_malta_init (ram_addr_t ram_size,

                      const char *boot_device,

                      const char *kernel_filename, const char *kernel_cmdline,

                      const char *initrd_filename, const char *cpu_model)

{

    char *filename;

    pflash_t *fl;

    MemoryRegion *system_memory = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *bios, *bios_alias = g_new(MemoryRegion, 1);

    target_long bios_size;

    int64_t kernel_entry;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    CPUState *env;

    qemu_irq *isa_irq;

    qemu_irq *cpu_exit_irq;

    int piix4_devfn;

    i2c_bus *smbus;

    int i;

    DriveInfo *dinfo;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    DriveInfo *fd[MAX_FD];

    int fl_idx = 0;

    int fl_sectors = 0;

    int be;

    DeviceState *dev = qdev_create(NULL, "mips-malta");

    MaltaState *s = DO_UPCAST(MaltaState, busdev.qdev, dev);

    qdev_init_nofail(dev);

    /* Make sure the first 3 serial ports are associated with a device. */

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

        if (!serial_hds[i]) {

            char label[32];

            snprintf(label, sizeof(label), "serial%d", i);

            serial_hds[i] = qemu_chr_new(label, "null", NULL);

        }

    }

    /* init CPUs */

    if (cpu_model == NULL) {

#ifdef TARGET_MIPS64

        cpu_model = "20Kc";

#else

        cpu_model = "24Kf";

#endif

    }

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

        env = cpu_init(cpu_model);

        if (!env) {

            fprintf(stderr, "Unable to find CPU definition\n");

            exit(1);

        }

        /* Init internal devices */

        cpu_mips_irq_init_cpu(env);

        cpu_mips_clock_init(env);

        qemu_register_reset(main_cpu_reset, env);

    }

    env = first_cpu;

    /* allocate RAM */

    if (ram_size > (256 << 20)) {

        fprintf(stderr,

                "qemu: Too much memory for this machine: %d MB, maximum 256 MB\n",

                ((unsigned int)ram_size / (1 << 20)));

        exit(1);

    }

    memory_region_init_ram(ram, "mips_malta.ram", ram_size);

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(system_memory, 0, ram);

#ifdef TARGET_WORDS_BIGENDIAN

    be = 1;

#else

    be = 0;

#endif

    /* FPGA */

    malta_fpga_init(system_memory, 0x1f000000LL, env->irq[2], serial_hds[2]);

    /* Load firmware in flash / BIOS unless we boot directly into a kernel. */

    if (kernel_filename) {

        /* Write a small bootloader to the flash location. */

        bios = g_new(MemoryRegion, 1);

        memory_region_init_ram(bios, "mips_malta.bios", BIOS_SIZE);

        vmstate_register_ram_global(bios);

        memory_region_set_readonly(bios, true);

        memory_region_init_alias(bios_alias, "bios.1fc", bios, 0, BIOS_SIZE);

        /* Map the bios at two physical locations, as on the real board. */

        memory_region_add_subregion(system_memory, 0x1e000000LL, bios);

        memory_region_add_subregion(system_memory, 0x1fc00000LL, bios_alias);

        loaderparams.ram_size = ram_size;

        loaderparams.kernel_filename = kernel_filename;

        loaderparams.kernel_cmdline = kernel_cmdline;

        loaderparams.initrd_filename = initrd_filename;

        kernel_entry = load_kernel();

        write_bootloader(env, memory_region_get_ram_ptr(bios), kernel_entry);

    } else {

        dinfo = drive_get(IF_PFLASH, 0, fl_idx);

        if (dinfo) {

            /* Load firmware from flash. */

            bios_size = 0x400000;

            fl_sectors = bios_size >> 16;

#ifdef DEBUG_BOARD_INIT

            printf("Register parallel flash %d size " TARGET_FMT_lx " at "

                   "addr %08llx '%s' %x\n",

                   fl_idx, bios_size, 0x1e000000LL,

                   bdrv_get_device_name(dinfo->bdrv), fl_sectors);

#endif

            fl = pflash_cfi01_register(0x1e000000LL,

                                       NULL, "mips_malta.bios", BIOS_SIZE,

                                       dinfo->bdrv, 65536, fl_sectors,

                                       4, 0x0000, 0x0000, 0x0000, 0x0000, be);

            bios = pflash_cfi01_get_memory(fl);

            /* Map the bios at two physical locations, as on the real board. */

            memory_region_init_alias(bios_alias, "bios.1fc",

                                     bios, 0, BIOS_SIZE);

            memory_region_add_subregion(system_memory, 0x1fc00000LL,

                                        bios_alias);

           fl_idx++;

        } else {

            bios = g_new(MemoryRegion, 1);

            memory_region_init_ram(bios, "mips_malta.bios", BIOS_SIZE);

            vmstate_register_ram_global(bios);

            memory_region_set_readonly(bios, true);

            memory_region_init_alias(bios_alias, "bios.1fc",

                                     bios, 0, BIOS_SIZE);

            /* Map the bios at two physical locations, as on the real board. */

            memory_region_add_subregion(system_memory, 0x1e000000LL, bios);

            memory_region_add_subregion(system_memory, 0x1fc00000LL,

                                        bios_alias);

            /* Load a BIOS image. */

            if (bios_name == NULL)

                bios_name = BIOS_FILENAME;

            filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

            if (filename) {

                bios_size = load_image_targphys(filename, 0x1fc00000LL,

                                                BIOS_SIZE);

                g_free(filename);

            } else {

                bios_size = -1;

            }

            if ((bios_size < 0 || bios_size > BIOS_SIZE) && !kernel_filename) {

                fprintf(stderr,

                        "qemu: Could not load MIPS bios '%s', and no -kernel argument was specified\n",

                        bios_name);

                exit(1);

            }

        }

        /* In little endian mode the 32bit words in the bios are swapped,

           a neat trick which allows bi-endian firmware. */

#ifndef TARGET_WORDS_BIGENDIAN

        {

            uint32_t *addr = memory_region_get_ram_ptr(bios);

            uint32_t *end = addr + bios_size;

            while (addr < end) {

                bswap32s(addr);

                addr++;

            }

        }

#endif

    }

    /* Board ID = 0x420 (Malta Board with CoreLV)

       XXX: theoretically 0x1e000010 should map to flash and 0x1fc00010 should

       map to the board ID. */

    stl_p(memory_region_get_ram_ptr(bios) + 0x10, 0x00000420);

    /* Init internal devices */

    cpu_mips_irq_init_cpu(env);

    cpu_mips_clock_init(env);

    /*

     * We have a circular dependency problem: pci_bus depends on isa_irq,

     * isa_irq is provided by i8259, i8259 depends on ISA, ISA depends

     * on piix4, and piix4 depends on pci_bus.  To stop the cycle we have

     * qemu_irq_proxy() adds an extra bit of indirection, allowing us

     * to resolve the isa_irq -> i8259 dependency after i8259 is initialized.

     */

    isa_irq = qemu_irq_proxy(&s->i8259, 16);

    /* Northbridge */

    pci_bus = gt64120_register(isa_irq);

    /* Southbridge */

    ide_drive_get(hd, MAX_IDE_BUS);

    piix4_devfn = piix4_init(pci_bus, &isa_bus, 80);

    /* Interrupt controller */

    /* The 8259 is attached to the MIPS CPU INT0 pin, ie interrupt 2 */

    s->i8259 = i8259_init(isa_bus, env->irq[2]);

    isa_bus_irqs(isa_bus, s->i8259);

    pci_piix4_ide_init(pci_bus, hd, piix4_devfn + 1);

    usb_uhci_piix4_init(pci_bus, piix4_devfn + 2);

    smbus = piix4_pm_init(pci_bus, piix4_devfn + 3, 0x1100,

                          isa_get_irq(NULL, 9), NULL, NULL, 0);

    /* TODO: Populate SPD eeprom data.  */

    smbus_eeprom_init(smbus, 8, NULL, 0);

    pit = pit_init(isa_bus, 0x40, 0);

    cpu_exit_irq = qemu_allocate_irqs(cpu_request_exit, NULL, 1);

    DMA_init(0, cpu_exit_irq);

    /* Super I/O */

    isa_create_simple(isa_bus, "i8042");

    rtc_init(isa_bus, 2000, NULL);

    serial_isa_init(isa_bus, 0, serial_hds[0]);

    serial_isa_init(isa_bus, 1, serial_hds[1]);

    if (parallel_hds[0])

        parallel_init(isa_bus, 0, parallel_hds[0]);

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

        fd[i] = drive_get(IF_FLOPPY, 0, i);

    }

    fdctrl_init_isa(isa_bus, fd);

    /* Sound card */

    audio_init(isa_bus, pci_bus);

    /* Network card */

    network_init();

    /* Optional PCI video card */

    if (cirrus_vga_enabled) {

        pci_cirrus_vga_init(pci_bus);

    } else if (vmsvga_enabled) {

        if (!pci_vmsvga_init(pci_bus)) {

            fprintf(stderr, "Warning: vmware_vga not available,"

                    " using standard VGA instead\n");

            pci_vga_init(pci_bus);

        }

    } else if (std_vga_enabled) {

        pci_vga_init(pci_bus);

    }

}


void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)

{

    Error *local_err = NULL;

    SYSTEMTIME ts;

    FILETIME tf;

    LONGLONG time;

    if (!has_time) {

        /* Unfortunately, Windows libraries don't provide an easy way to access

         * RTC yet:

         *

         * https://msdn.microsoft.com/en-us/library/aa908981.aspx

         */

        error_setg(errp, "Time argument is required on this platform");

        return;

    }

    /* Validate time passed by user. */

    if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {

        error_setg(errp, "Time %" PRId64 "is invalid", time_ns);

        return;

    }

    time = time_ns / 100 + W32_FT_OFFSET;

    tf.dwLowDateTime = (DWORD) time;

    tf.dwHighDateTime = (DWORD) (time >> 32);

    if (!FileTimeToSystemTime(&tf, &ts)) {

        error_setg(errp, "Failed to convert system time %d",

                   (int)GetLastError());

        return;

    }

    acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    if (!SetSystemTime(&ts)) {

        error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());

        return;

    }

}


static uint32_t qpi_mem_readb(void *opaque, target_phys_addr_t addr)

{

    return 0;

}


struct MUSBState *musb_init(qemu_irq *irqs)

{

    MUSBState *s = g_malloc0(sizeof(*s));

    int i;

    s->irqs = irqs;

    s->faddr = 0x00;

    s->power = MGC_M_POWER_HSENAB;

    s->tx_intr = 0x0000;

    s->rx_intr = 0x0000;

    s->tx_mask = 0xffff;

    s->rx_mask = 0xffff;

    s->intr = 0x00;

    s->mask = 0x06;

    s->idx = 0;

    /* TODO: _DW */

    s->ep[0].config = MGC_M_CONFIGDATA_SOFTCONE | MGC_M_CONFIGDATA_DYNFIFO;

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

        s->ep[i].fifosize = 64;

        s->ep[i].maxp[0] = 0x40;

        s->ep[i].maxp[1] = 0x40;

        s->ep[i].musb = s;

        s->ep[i].epnum = i;

        usb_packet_init(&s->ep[i].packey[0].p);

        usb_packet_init(&s->ep[i].packey[1].p);

    }

    usb_bus_new(&s->bus, &musb_bus_ops, NULL /* FIXME */);

    usb_register_port(&s->bus, &s->port, s, 0, &musb_port_ops,

                      USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL);

    return s;

}


static void RENAME(extract_even)(const uint8_t *src, uint8_t *dst, x86_reg count)

{

    dst +=   count;

    src += 2*count;

    count= - count;

#if COMPILE_TEMPLATE_MMX

    if(count <= -16) {

        count += 15;

        __asm__ volatile(

            "pcmpeqw       %%mm7, %%mm7        \n\t"

            "psrlw            $8, %%mm7        \n\t"

            "1:                                \n\t"

            "movq -30(%1, %0, 2), %%mm0        \n\t"

            "movq -22(%1, %0, 2), %%mm1        \n\t"

            "movq -14(%1, %0, 2), %%mm2        \n\t"

            "movq  -6(%1, %0, 2), %%mm3        \n\t"

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

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

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

            "pand          %%mm7, %%mm3        \n\t"

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

            "packuswb      %%mm3, %%mm2        \n\t"

            MOVNTQ"        %%mm0,-15(%2, %0)   \n\t"

            MOVNTQ"        %%mm2,- 7(%2, %0)   \n\t"

            "add             $16, %0           \n\t"

            " js 1b                            \n\t"

            : "+r"(count)

            : "r"(src), "r"(dst)

        );

        count -= 15;

    }

#endif

    while(count<0) {

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

        count++;

    }

}


static void intra_predict_horiz_16x16_msa(uint8_t *src, int32_t src_stride,

                                          uint8_t *dst, int32_t dst_stride)

{

    uint32_t row;

    uint8_t inp0, inp1, inp2, inp3;

    v16u8 src0, src1, src2, src3;

    for (row = 4; row--;) {

        inp0 = src[0];

        src += src_stride;

        inp1 = src[0];

        src += src_stride;

        inp2 = src[0];

        src += src_stride;

        inp3 = src[0];

        src += src_stride;

        src0 = (v16u8) __msa_fill_b(inp0);

        src1 = (v16u8) __msa_fill_b(inp1);

        src2 = (v16u8) __msa_fill_b(inp2);

        src3 = (v16u8) __msa_fill_b(inp3);

        ST_UB4(src0, src1, src2, src3, dst, dst_stride);

        dst += (4 * dst_stride);

    }

}


void pc_cmos_init(ram_addr_t ram_size, ram_addr_t above_4g_mem_size,

                  const char *boot_device,

                  ISADevice *floppy, BusState *idebus0, BusState *idebus1,

                  ISADevice *s)

{

    int val, nb, i;

    FDriveType fd_type[2] = { FDRIVE_DRV_NONE, FDRIVE_DRV_NONE };

    static pc_cmos_init_late_arg arg;

    /* various important CMOS locations needed by PC/Bochs bios */

    /* memory size */

    val = 640; /* base memory in K */

    rtc_set_memory(s, 0x15, val);

    rtc_set_memory(s, 0x16, val >> 8);

    val = (ram_size / 1024) - 1024;

    if (val > 65535)

        val = 65535;

    rtc_set_memory(s, 0x17, val);

    rtc_set_memory(s, 0x18, val >> 8);

    rtc_set_memory(s, 0x30, val);

    rtc_set_memory(s, 0x31, val >> 8);

    if (above_4g_mem_size) {

        rtc_set_memory(s, 0x5b, (unsigned int)above_4g_mem_size >> 16);

        rtc_set_memory(s, 0x5c, (unsigned int)above_4g_mem_size >> 24);

        rtc_set_memory(s, 0x5d, (uint64_t)above_4g_mem_size >> 32);

    }

    if (ram_size > (16 * 1024 * 1024))

        val = (ram_size / 65536) - ((16 * 1024 * 1024) / 65536);

    else

        val = 0;

    if (val > 65535)

        val = 65535;

    rtc_set_memory(s, 0x34, val);

    rtc_set_memory(s, 0x35, val >> 8);

    /* set the number of CPU */

    rtc_set_memory(s, 0x5f, smp_cpus - 1);

    /* set boot devices, and disable floppy signature check if requested */

    if (set_boot_dev(s, boot_device, fd_bootchk)) {

        exit(1);

    }

    /* floppy type */

    if (floppy) {

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

            fd_type[i] = isa_fdc_get_drive_type(floppy, i);

        }

    }

    val = (cmos_get_fd_drive_type(fd_type[0]) << 4) |

        cmos_get_fd_drive_type(fd_type[1]);

    rtc_set_memory(s, 0x10, val);

    val = 0;

    nb = 0;

    if (fd_type[0] < FDRIVE_DRV_NONE) {

        nb++;

    }

    if (fd_type[1] < FDRIVE_DRV_NONE) {

        nb++;

    }

    switch (nb) {

    case 0:

        break;

    case 1:

        val |= 0x01; /* 1 drive, ready for boot */

        break;

    case 2:

        val |= 0x41; /* 2 drives, ready for boot */

        break;

    }

    val |= 0x02; /* FPU is there */

    val |= 0x04; /* PS/2 mouse installed */

    rtc_set_memory(s, REG_EQUIPMENT_BYTE, val);

    /* hard drives */

    arg.rtc_state = s;

    arg.idebus[0] = idebus0;

    arg.idebus[1] = idebus1;

    qemu_register_reset(pc_cmos_init_late, &arg);

}


int read_file(const char *filename, char **bufptr, size_t *size)

{

    FILE *f = fopen(filename, "rb");

    if (!f) {

        av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename, strerror(errno));

        return AVERROR(errno);

    }

    fseek(f, 0, SEEK_END);

    *size = ftell(f);

    fseek(f, 0, SEEK_SET);

    *bufptr = av_malloc(*size + 1);

    if (!*bufptr) {

        av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");

        fclose(f);

        return AVERROR(ENOMEM);

    }

    fread(*bufptr, 1, *size, f);

    (*bufptr)[*size++] = '\0';

    fclose(f);

    return 0;

}


int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,

                      int64_t pos_min, int64_t pos_max, int64_t pos_limit,

                      int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,

                      int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))

{

    int64_t pos, ts;

    int64_t start_pos, filesize;

    int no_change;

    av_dlog(s, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));

    if(ts_min == AV_NOPTS_VALUE){

        pos_min = s->data_offset;

        ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);

        if (ts_min == AV_NOPTS_VALUE)

            return -1;

    }

    if(ts_min >= target_ts){

        *ts_ret= ts_min;

        return pos_min;

    }

    if(ts_max == AV_NOPTS_VALUE){

        int step= 1024;

        filesize = avio_size(s->pb);

        pos_max = filesize - 1;

        do{

            pos_max = FFMAX(0, pos_max - step);

            ts_max = ff_read_timestamp(s, stream_index, &pos_max, pos_max + step, read_timestamp);

            step += step;

        }while(ts_max == AV_NOPTS_VALUE && pos_max > 0);

        if (ts_max == AV_NOPTS_VALUE)

            return -1;

        for(;;){

            int64_t tmp_pos= pos_max + 1;

            int64_t tmp_ts= ff_read_timestamp(s, stream_index, &tmp_pos, INT64_MAX, read_timestamp);

            if(tmp_ts == AV_NOPTS_VALUE)

                break;

            ts_max= tmp_ts;

            pos_max= tmp_pos;

            if(tmp_pos >= filesize)

                break;

        }

        pos_limit= pos_max;

    }

    if(ts_max <= target_ts){

        *ts_ret= ts_max;

        return pos_max;

    }

    if(ts_min > ts_max){

        return -1;

    }else if(ts_min == ts_max){

        pos_limit= pos_min;

    }

    no_change=0;

    while (pos_min < pos_limit) {

        av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",

                pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));

        assert(pos_limit <= pos_max);

        if(no_change==0){

            int64_t approximate_keyframe_distance= pos_max - pos_limit;

            // interpolate position (better than dichotomy)

            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)

                + pos_min - approximate_keyframe_distance;

        }else if(no_change==1){

            // bisection, if interpolation failed to change min or max pos last time

            pos = (pos_min + pos_limit)>>1;

        }else{

            /* linear search if bisection failed, can only happen if there

               are very few or no keyframes between min/max */

            pos=pos_min;

        }

        if(pos <= pos_min)

            pos= pos_min + 1;

        else if(pos > pos_limit)

            pos= pos_limit;

        start_pos= pos;

        ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp); //may pass pos_limit instead of -1

        if(pos == pos_max)

            no_change++;

        else

            no_change=0;

        av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",

                pos_min, pos, pos_max,

                av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),

                pos_limit, start_pos, no_change);

        if(ts == AV_NOPTS_VALUE){

            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");

            return -1;

        }

        assert(ts != AV_NOPTS_VALUE);

        if (target_ts <= ts) {

            pos_limit = start_pos - 1;

            pos_max = pos;

            ts_max = ts;

        }

        if (target_ts >= ts) {

            pos_min = pos;

            ts_min = ts;

        }

    }

    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;

    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;

#if 0

    pos_min = pos;

    ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);

    pos_min++;

    ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);

    av_dlog(s, "pos=0x%"PRIx64" %s<=%s<=%s\n",

            pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));

#endif

    *ts_ret= ts;

    return pos;

}


struct GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
                                          int64_t count, Error **errp)
{
    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
    GuestFileRead *read_data = NULL;
    guchar *buf;
    FILE *fh;
    size_t read_count;
    if (!gfh) {
    if (!has_count) {
        count = QGA_READ_COUNT_DEFAULT;
    } else if (count < 0) {
        error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
                   count);
    fh = gfh->fh;
    buf = g_malloc0(count+1);
    read_count = fread(buf, 1, count, fh);
    if (ferror(fh)) {
        error_setg_errno(errp, errno, "failed to read file");
        slog("guest-file-read failed, handle: %" PRId64, handle);
    } else {
        buf[read_count] = 0;
        read_data = g_new0(GuestFileRead, 1);
        read_data->count = read_count;
        read_data->eof = feof(fh);
        if (read_count) {
            read_data->buf_b64 = g_base64_encode(buf, read_count);
        gfh->state = RW_STATE_READING;
    g_free(buf);
    clearerr(fh);
    return read_data;


static inline int get_amv(Mpeg4DecContext *ctx, int n)

{

    MpegEncContext *s = &ctx->m;

    int x, y, mb_v, sum, dx, dy, shift;

    int len     = 1 << (s->f_code + 4);

    const int a = s->sprite_warping_accuracy;

    if (s->workaround_bugs & FF_BUG_AMV)

        len >>= s->quarter_sample;

    if (s->real_sprite_warping_points == 1) {

        if (ctx->divx_version == 500 && ctx->divx_build == 413)

            sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample));

        else

            sum = RSHIFT(s->sprite_offset[0][n] << s->quarter_sample, a);

    } else {

        dx    = s->sprite_delta[n][0];

        dy    = s->sprite_delta[n][1];

        shift = ctx->sprite_shift[0];

        if (n)

            dy -= 1 << (shift + a + 1);

        else

            dx -= 1 << (shift + a + 1);

        mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16;

        sum = 0;

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

            int v;

            v = mb_v + dy * y;

            // FIXME optimize

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

                sum += v >> shift;

                v   += dx;

            }

        }

        sum = RSHIFT(sum, a + 8 - s->quarter_sample);

    }

    if (sum < -len)

        sum = -len;

    else if (sum >= len)

        sum = len - 1;

    return sum;

}


int64_t cpu_get_ticks(void)

{

    if (use_icount) {

        return cpu_get_icount();

    }

    if (!timers_state.cpu_ticks_enabled) {

        return timers_state.cpu_ticks_offset;

    } else {

        int64_t ticks;

        ticks = cpu_get_real_ticks();

        if (timers_state.cpu_ticks_prev > ticks) {

            /* Note: non increasing ticks may happen if the host uses

               software suspend */

            timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;

        }

        timers_state.cpu_ticks_prev = ticks;

        return ticks + timers_state.cpu_ticks_offset;

    }

}


static void gen_rev16(TCGv var)

{

    TCGv tmp = new_tmp();

    tcg_gen_shri_i32(tmp, var, 8);

    tcg_gen_andi_i32(tmp, tmp, 0x00ff00ff);

    tcg_gen_shli_i32(var, var, 8);

    tcg_gen_andi_i32(var, var, 0xff00ff00);

    tcg_gen_or_i32(var, var, tmp);

    dead_tmp(tmp);

}


static void ready_codebook(vorbis_enc_codebook *cb)

{

    int i;

    ff_vorbis_len2vlc(cb->lens, cb->codewords, cb->nentries);

    if (!cb->lookup) {

        cb->pow2 = cb->dimentions = NULL;

    } else {

        int vals = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);

        cb->dimentions = av_malloc(sizeof(float) * cb->nentries * cb->ndimentions);

        cb->pow2 = av_mallocz(sizeof(float) * cb->nentries);

        for (i = 0; i < cb->nentries; i++) {

            float last = 0;

            int j;

            int div = 1;

            for (j = 0; j < cb->ndimentions; j++) {

                int off;

                if (cb->lookup == 1)

                    off = (i / div) % vals; // lookup type 1

                else

                    off = i * cb->ndimentions + j; // lookup type 2

                cb->dimentions[i * cb->ndimentions + j] = last + cb->min + cb->quantlist[off] * cb->delta;

                if (cb->seq_p)

                    last = cb->dimentions[i * cb->ndimentions + j];

                cb->pow2[i] += cb->dimentions[i * cb->ndimentions + j] * cb->dimentions[i * cb->ndimentions + j];

                div *= vals;

            }

            cb->pow2[i] /= 2.;

        }

    }

}


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

                            int *got_frame_ptr, AVPacket *avpkt)

{

    int buf_size        = avpkt->size;

    ADXContext *c       = avctx->priv_data;

    int16_t *samples;

    const uint8_t *buf  = avpkt->data;

    int num_blocks, ch, ret;

    if (c->eof) {

        *got_frame_ptr = 0;

        return buf_size;

    }

    if(AV_RB16(buf) == 0x8000){

        int header_size;

        if ((ret = avpriv_adx_decode_header(avctx, buf,

                                            buf_size, &header_size,

                                            c->coeff)) < 0) {

            av_log(avctx, AV_LOG_ERROR, "error parsing ADX header\n");

        }

        c->channels = avctx->channels;

        if(buf_size < header_size)

        buf += header_size;

        buf_size -= header_size;

    }

    /* calculate number of blocks in the packet */

    num_blocks = buf_size / (BLOCK_SIZE * c->channels);

    /* if the packet is not an even multiple of BLOCK_SIZE, check for an EOF

       packet */

    if (!num_blocks || buf_size % (BLOCK_SIZE * avctx->channels)) {

        if (buf_size >= 4 && (AV_RB16(buf) & 0x8000)) {

            c->eof = 1;

            *got_frame_ptr = 0;

            return avpkt->size;

        }

    }

    /* get output buffer */

    c->frame.nb_samples = num_blocks * BLOCK_SAMPLES;

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

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

        return ret;

    }

    samples = (int16_t *)c->frame.data[0];

    while (num_blocks--) {

        for (ch = 0; ch < c->channels; ch++) {

            if (adx_decode(c, samples + ch, buf, ch)) {

                c->eof = 1;

                buf = avpkt->data + avpkt->size;

                break;

            }

            buf_size -= BLOCK_SIZE;

            buf      += BLOCK_SIZE;

        }

        samples += BLOCK_SAMPLES * c->channels;

    }

    *got_frame_ptr   = 1;

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

    return buf - avpkt->data;

}


static void spapr_dt_ov5_platform_support(void *fdt, int chosen)

{

    PowerPCCPU *first_ppc_cpu = POWERPC_CPU(first_cpu);

    char val[2 * 4] = {

        23, 0x00, /* Xive mode: 0 = legacy (as in ISA 2.7), 1 = Exploitation */

        24, 0x00, /* Hash/Radix, filled in below. */

        25, 0x00, /* Hash options: Segment Tables == no, GTSE == no. */

        26, 0x40, /* Radix options: GTSE == yes. */

    };

    if (kvm_enabled()) {

        if (kvmppc_has_cap_mmu_radix() && kvmppc_has_cap_mmu_hash_v3()) {

            val[3] = 0x80; /* OV5_MMU_BOTH */

        } else if (kvmppc_has_cap_mmu_radix()) {

            val[3] = 0x40; /* OV5_MMU_RADIX_300 */

        } else {

            val[3] = 0x00; /* Hash */

        }

    } else {

        if (first_ppc_cpu->env.mmu_model & POWERPC_MMU_V3) {

            /* V3 MMU supports both hash and radix (with dynamic switching) */

            val[3] = 0xC0;

        } else {

            /* Otherwise we can only do hash */

            val[3] = 0x00;

        }

    }

    _FDT(fdt_setprop(fdt, chosen, "ibm,arch-vec-5-platform-support",

                     val, sizeof(val)));

}


    vmstate_get_subsection(const VMStateSubsection *sub, char *idstr)

{

    while (sub && sub->needed) {

        if (strcmp(idstr, sub->vmsd->name) == 0) {

            return sub->vmsd;

        }

        sub++;

    }

    return NULL;

}


static int gif_read_image(GifState *s, AVFrame *frame)

{

    int left, top, width, height, bits_per_pixel, code_size, flags;

    int is_interleaved, has_local_palette, y, pass, y1, linesize, pal_size;

    uint32_t *ptr, *pal, *px, *pr, *ptr1;

    int ret;

    uint8_t *idx;

    /* At least 9 bytes of Image Descriptor. */

    if (bytestream2_get_bytes_left(&s->gb) < 9)

        return AVERROR_INVALIDDATA;

    left   = bytestream2_get_le16u(&s->gb);

    top    = bytestream2_get_le16u(&s->gb);

    width  = bytestream2_get_le16u(&s->gb);

    height = bytestream2_get_le16u(&s->gb);

    flags  = bytestream2_get_byteu(&s->gb);

    is_interleaved = flags & 0x40;

    has_local_palette = flags & 0x80;

    bits_per_pixel = (flags & 0x07) + 1;

    av_dlog(s->avctx, "image x=%d y=%d w=%d h=%d\n", left, top, width, height);

    if (has_local_palette) {

        pal_size = 1 << bits_per_pixel;

        if (bytestream2_get_bytes_left(&s->gb) < pal_size * 3)

            return AVERROR_INVALIDDATA;

        gif_read_palette(s, s->local_palette, pal_size);

        pal = s->local_palette;

    } else {

        if (!s->has_global_palette) {

            av_log(s->avctx, AV_LOG_ERROR, "picture doesn't have either global or local palette.\n");

            return AVERROR_INVALIDDATA;

        }

        pal = s->global_palette;

    }

    if (s->keyframe) {

        if (s->transparent_color_index == -1 && s->has_global_palette) {

            /* transparency wasn't set before the first frame, fill with background color */

            gif_fill(frame, s->bg_color);

        } else {

            /* otherwise fill with transparent color.

             * this is necessary since by default picture filled with 0x80808080. */

            gif_fill(frame, s->trans_color);

        }

    }

    /* verify that all the image is inside the screen dimensions */

    if (left + width > s->screen_width ||

        top + height > s->screen_height) {

        av_log(s->avctx, AV_LOG_ERROR, "image is outside the screen dimensions.\n");

        return AVERROR_INVALIDDATA;

    }

    if (width <= 0 || height <= 0) {

        av_log(s->avctx, AV_LOG_ERROR, "Invalid image dimensions.\n");

        return AVERROR_INVALIDDATA;

    }

    /* process disposal method */

    if (s->gce_prev_disposal == GCE_DISPOSAL_BACKGROUND) {

        gif_fill_rect(frame, s->stored_bg_color, s->gce_l, s->gce_t, s->gce_w, s->gce_h);

    } else if (s->gce_prev_disposal == GCE_DISPOSAL_RESTORE) {

        gif_copy_img_rect(s->stored_img, (uint32_t *)frame->data[0],

            frame->linesize[0] / sizeof(uint32_t), s->gce_l, s->gce_t, s->gce_w, s->gce_h);

    }

    s->gce_prev_disposal = s->gce_disposal;

    if (s->gce_disposal != GCE_DISPOSAL_NONE) {

        s->gce_l = left;  s->gce_t = top;

        s->gce_w = width; s->gce_h = height;

        if (s->gce_disposal == GCE_DISPOSAL_BACKGROUND) {

            if (s->transparent_color_index >= 0)

                s->stored_bg_color = s->trans_color;

            else

                s->stored_bg_color = s->bg_color;

        } else if (s->gce_disposal == GCE_DISPOSAL_RESTORE) {

            av_fast_malloc(&s->stored_img, &s->stored_img_size, frame->linesize[0] * frame->height);

            if (!s->stored_img)

                return AVERROR(ENOMEM);

            gif_copy_img_rect((uint32_t *)frame->data[0], s->stored_img,

                frame->linesize[0] / sizeof(uint32_t), left, top, width, height);

        }

    }

    /* Expect at least 2 bytes: 1 for lzw code size and 1 for block size. */

    if (bytestream2_get_bytes_left(&s->gb) < 2)

        return AVERROR_INVALIDDATA;

    /* now get the image data */

    code_size = bytestream2_get_byteu(&s->gb);

    if ((ret = ff_lzw_decode_init(s->lzw, code_size, s->gb.buffer,

                                  bytestream2_get_bytes_left(&s->gb), FF_LZW_GIF)) < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "LZW init failed\n");

        return ret;

    }

    /* read all the image */

    linesize = frame->linesize[0] / sizeof(uint32_t);

    ptr1 = (uint32_t *)frame->data[0] + top * linesize + left;

    ptr = ptr1;

    pass = 0;

    y1 = 0;

    for (y = 0; y < height; y++) {

        int count = ff_lzw_decode(s->lzw, s->idx_line, width);

        if (count != width) {

            if (count)

                av_log(s->avctx, AV_LOG_ERROR, "LZW decode failed\n");

            goto decode_tail;

        }

        pr = ptr + width;

        for (px = ptr, idx = s->idx_line; px < pr; px++, idx++) {

            if (*idx != s->transparent_color_index)

                *px = pal[*idx];

        }

        if (is_interleaved) {

            switch(pass) {

            default:

            case 0:

            case 1:

                y1 += 8;

                ptr += linesize * 8;

                if (y1 >= height) {

                    y1 = pass ? 2 : 4;

                    ptr = ptr1 + linesize * y1;

                    pass++;

                }

                break;

            case 2:

                y1 += 4;

                ptr += linesize * 4;

                if (y1 >= height) {

                    y1 = 1;

                    ptr = ptr1 + linesize;

                    pass++;

                }

                break;

            case 3:

                y1 += 2;

                ptr += linesize * 2;

                break;

            }

        } else {

            ptr += linesize;

        }

    }

 decode_tail:

    /* read the garbage data until end marker is found */

    ff_lzw_decode_tail(s->lzw);

    /* Graphic Control Extension's scope is single frame.

     * Remove its influence. */

    s->transparent_color_index = -1;

    s->gce_disposal = GCE_DISPOSAL_NONE;

    return 0;

}