static void hid_keyboard_process_keycode(HIDState *hs)
{
    uint8_t hid_code, index, key;
    int i, keycode, slot;
    if (hs->n == 0) {
        return;
    slot = hs->head & QUEUE_MASK; QUEUE_INCR(hs->head); hs->n--;
    keycode = hs->kbd.keycodes[slot];
    key = keycode & 0x7f;
    index = key | ((hs->kbd.modifiers & (1 << 8)) >> 1);
    hid_code = hid_usage_keys[index];
    hs->kbd.modifiers &= ~(1 << 8);
    switch (hid_code) {
    case 0x00:
        return;
    case 0xe0:
        assert(key == 0x1d);
        if (hs->kbd.modifiers & (1 << 9)) {
            /* The hid_codes for the 0xe1/0x1d scancode sequence are 0xe9/0xe0.
             * Here we're processing the second hid_code.  By dropping bit 9
             * and setting bit 8, the scancode after 0x1d will access the
             * second half of the table.
             */
            hs->kbd.modifiers ^= (1 << 8) | (1 << 9);
            return;
        /* fall through to process Ctrl_L */
    case 0xe1 ... 0xe7:
        /* Ctrl_L/Ctrl_R, Shift_L/Shift_R, Alt_L/Alt_R, Win_L/Win_R.
         * Handle releases here, or fall through to process presses.
         */
        if (keycode & (1 << 7)) {
            hs->kbd.modifiers &= ~(1 << (hid_code & 0x0f));
            return;
        /* fall through */
    case 0xe8 ... 0xe9:
        /* USB modifiers are just 1 byte long.  Bits 8 and 9 of
         * hs->kbd.modifiers implement a state machine that detects the
         * 0xe0 and 0xe1/0x1d sequences.  These bits do not follow the
         * usual rules where bit 7 marks released keys; they are cleared
         * elsewhere in the function as the state machine dictates.
         */
        hs->kbd.modifiers |= 1 << (hid_code & 0x0f);
        return;
    case 0xea ... 0xef:
        abort();
    default:
        break;
    if (keycode & (1 << 7)) {
        for (i = hs->kbd.keys - 1; i >= 0; i--) {
            if (hs->kbd.key[i] == hid_code) {
                hs->kbd.key[i] = hs->kbd.key[-- hs->kbd.keys];
                hs->kbd.key[hs->kbd.keys] = 0x00;
                break;
        if (i < 0) {
            return;
    } else {
        for (i = hs->kbd.keys - 1; i >= 0; i--) {
            if (hs->kbd.key[i] == hid_code) {
                break;
        if (i < 0) {
            if (hs->kbd.keys < sizeof(hs->kbd.key)) {
                hs->kbd.key[hs->kbd.keys++] = hid_code;
        } else {
            return;


static int nvdec_vc1_start_frame(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)

{

    VC1Context *v = avctx->priv_data;

    MpegEncContext *s = &v->s;

    NVDECContext      *ctx = avctx->internal->hwaccel_priv_data;

    CUVIDPICPARAMS     *pp = &ctx->pic_params;

    FrameDecodeData *fdd;

    NVDECFrame *cf;

    AVFrame *cur_frame = s->current_picture.f;

    int ret;

    ret = ff_nvdec_start_frame(avctx, cur_frame);

    if (ret < 0)

        return ret;

    fdd = (FrameDecodeData*)cur_frame->private_ref->data;

    cf  = (NVDECFrame*)fdd->hwaccel_priv;

    *pp = (CUVIDPICPARAMS) {

        .PicWidthInMbs     = (cur_frame->width  + 15) / 16,

        .FrameHeightInMbs  = (cur_frame->height + 15) / 16,

        .CurrPicIdx        = cf->idx,

        .field_pic_flag    = v->field_mode,

        .bottom_field_flag = v->cur_field_type,

        .second_field      = v->second_field,

        .intra_pic_flag    = s->pict_type == AV_PICTURE_TYPE_I ||

                             s->pict_type == AV_PICTURE_TYPE_BI,

        .ref_pic_flag      = s->pict_type == AV_PICTURE_TYPE_I ||

                             s->pict_type == AV_PICTURE_TYPE_P,

        .CodecSpecific.vc1 = {

            .ForwardRefIdx     = get_ref_idx(s->last_picture.f),

            .BackwardRefIdx    = get_ref_idx(s->next_picture.f),

            .FrameWidth        = cur_frame->width,

            .FrameHeight       = cur_frame->height,

            .intra_pic_flag    = s->pict_type == AV_PICTURE_TYPE_I ||

                                 s->pict_type == AV_PICTURE_TYPE_BI,

            .ref_pic_flag      = s->pict_type == AV_PICTURE_TYPE_I ||

                                 s->pict_type == AV_PICTURE_TYPE_P,

            .progressive_fcm   = v->fcm == 0,

            .profile           = v->profile,

            .postprocflag      = v->postprocflag,

            .pulldown          = v->broadcast,

            .interlace         = v->interlace,

            .tfcntrflag        = v->tfcntrflag,

            .finterpflag       = v->finterpflag,

            .psf               = v->psf,

            .multires          = v->multires,

            .syncmarker        = v->resync_marker,

            .rangered          = v->rangered,

            .maxbframes        = s->max_b_frames,

            .panscan_flag      = v->panscanflag,

            .refdist_flag      = v->refdist_flag,

            .extended_mv       = v->extended_mv,

            .dquant            = v->dquant,

            .vstransform       = v->vstransform,

            .loopfilter        = v->s.loop_filter,

            .fastuvmc          = v->fastuvmc,

            .overlap           = v->overlap,

            .quantizer         = v->quantizer_mode,

            .extended_dmv      = v->extended_dmv,

            .range_mapy_flag   = v->range_mapy_flag,

            .range_mapy        = v->range_mapy,

            .range_mapuv_flag  = v->range_mapuv_flag,

            .range_mapuv       = v->range_mapuv,

            .rangeredfrm       = v->rangeredfrm,

        }

    };

    return 0;

}


static int frame_thread_init(AVCodecContext *avctx)

{

    int thread_count = avctx->thread_count;

    AVCodec *codec = avctx->codec;

    AVCodecContext *src = avctx;

    FrameThreadContext *fctx;

    int i, err = 0;

    if (!thread_count) {

        int nb_cpus = get_logical_cpus(avctx);

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

        if (nb_cpus > 1)

            thread_count = avctx->thread_count = nb_cpus + 1;

    }

    if (thread_count <= 1) {

        avctx->active_thread_type = 0;

        return 0;

    }

    avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));

    fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);

    pthread_mutex_init(&fctx->buffer_mutex, NULL);

    fctx->delaying = 1;

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

        AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));

        PerThreadContext *p  = &fctx->threads[i];

        pthread_mutex_init(&p->mutex, NULL);

        pthread_mutex_init(&p->progress_mutex, NULL);

        pthread_cond_init(&p->input_cond, NULL);

        pthread_cond_init(&p->progress_cond, NULL);

        pthread_cond_init(&p->output_cond, NULL);

        p->parent = fctx;

        p->avctx  = copy;

        if (!copy) {

            err = AVERROR(ENOMEM);

            goto error;

        }

        *copy = *src;

        copy->thread_opaque = p;

        copy->pkt = &p->avpkt;

        if (!i) {

            src = copy;

            if (codec->init)

                err = codec->init(copy);

            update_context_from_thread(avctx, copy, 1);

        } else {

            copy->priv_data = av_malloc(codec->priv_data_size);

            if (!copy->priv_data) {

                err = AVERROR(ENOMEM);

                goto error;

            }

            memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);

            copy->internal = av_malloc(sizeof(AVCodecInternal));

            if (!copy->internal) {

                err = AVERROR(ENOMEM);

                goto error;

            }

            *(copy->internal) = *(src->internal);

            copy->internal->is_copy = 1;

            if (codec->init_thread_copy)

                err = codec->init_thread_copy(copy);

        }

        if (err) goto error;

        if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))

            p->thread_init = 1;

    }

    return 0;

error:

    frame_thread_free(avctx, i+1);

    return err;

}


static inline void gen_ins(DisasContext *s, TCGMemOp ot)

{

    if (s->base.tb->cflags & CF_USE_ICOUNT) {

        gen_io_start();

    }

    gen_string_movl_A0_EDI(s);

    /* Note: we must do this dummy write first to be restartable in

       case of page fault. */

    tcg_gen_movi_tl(cpu_T0, 0);

    gen_op_st_v(s, ot, cpu_T0, cpu_A0);

    tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_EDX]);

    tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);

    gen_helper_in_func(ot, cpu_T0, cpu_tmp2_i32);

    gen_op_st_v(s, ot, cpu_T0, cpu_A0);

    gen_op_movl_T0_Dshift(ot);

    gen_op_add_reg_T0(s->aflag, R_EDI);

    gen_bpt_io(s, cpu_tmp2_i32, ot);

    if (s->base.tb->cflags & CF_USE_ICOUNT) {

        gen_io_end();

    }

}


static void qht_bucket_reset__locked(struct qht_bucket *head)

{

    struct qht_bucket *b = head;

    int i;

    seqlock_write_begin(&head->sequence);

    do {

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

            if (b->pointers[i] == NULL) {

                goto done;

            }

            b->hashes[i] = 0;

            atomic_set(&b->pointers[i], NULL);

        }

        b = b->next;

    } while (b);

 done:

    seqlock_write_end(&head->sequence);

}


static int read_seek(AVFormatContext *s, int stream_index,

                     int64_t ts, int flags)

{

    WtvContext *wtv = s->priv_data;

    AVIOContext *pb = wtv->pb;

    AVStream *st = s->streams[0];

    int64_t ts_relative;

    int i;

    if ((flags & AVSEEK_FLAG_FRAME) || (flags & AVSEEK_FLAG_BYTE))

        return AVERROR(ENOSYS);

    /* timestamp adjustment is required because wtv->pts values are absolute,

     * whereas AVIndexEntry->timestamp values are relative to epoch. */

    ts_relative = ts;

    if (wtv->epoch != AV_NOPTS_VALUE)

        ts_relative -= wtv->epoch;

    i = ff_index_search_timestamp(wtv->index_entries, wtv->nb_index_entries, ts_relative, flags);

    if (i < 0) {

        if (wtv->last_valid_pts == AV_NOPTS_VALUE || ts < wtv->last_valid_pts)

            avio_seek(pb, 0, SEEK_SET);

        else if (st->duration != AV_NOPTS_VALUE && ts_relative > st->duration && wtv->nb_index_entries)

            avio_seek(pb, wtv->index_entries[wtv->nb_index_entries - 1].pos, SEEK_SET);

        if (parse_chunks(s, SEEK_TO_PTS, ts, 0) < 0)

            return AVERROR(ERANGE);

        return 0;

    }

    wtv->pts = wtv->index_entries[i].timestamp;

    if (wtv->epoch != AV_NOPTS_VALUE)

        wtv->pts += wtv->epoch;

    wtv->last_valid_pts = wtv->pts;

    avio_seek(pb, wtv->index_entries[i].pos, SEEK_SET);

    return 0;

}


static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,

                                 AVStream *st, MOVStreamContext *sc)

{

    int bits_per_sample, flags;

    uint16_t version = avio_rb16(pb);

    AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);

    avio_rb16(pb); /* revision level */

    avio_rb32(pb); /* vendor */

    st->codec->channels              = avio_rb16(pb); /* channel count */

    st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */

    av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codec->channels);

    sc->audio_cid = avio_rb16(pb);

    avio_rb16(pb); /* packet size = 0 */

    st->codec->sample_rate = ((avio_rb32(pb) >> 16));

    // Read QT version 1 fields. In version 0 these do not exist.

    av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);

    if (!c->isom ||

        (compatible_brands && strstr(compatible_brands->value, "qt  "))) {

        if (version == 1) {

            sc->samples_per_frame = avio_rb32(pb);

            avio_rb32(pb); /* bytes per packet */

            sc->bytes_per_frame = avio_rb32(pb);

            avio_rb32(pb); /* bytes per sample */

        } else if (version == 2) {

            avio_rb32(pb); /* sizeof struct only */

            st->codec->sample_rate = av_int2double(avio_rb64(pb));

            st->codec->channels    = avio_rb32(pb);

            avio_rb32(pb); /* always 0x7F000000 */

            st->codec->bits_per_coded_sample = avio_rb32(pb);

            flags = avio_rb32(pb); /* lpcm format specific flag */

            sc->bytes_per_frame   = avio_rb32(pb);

            sc->samples_per_frame = avio_rb32(pb);

            if (st->codec->codec_tag == MKTAG('l','p','c','m'))

                st->codec->codec_id =

                    ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,

                                             flags);

        }

        if (version == 0 || (version == 1 && sc->audio_cid != -2)) {

            /* can't correctly handle variable sized packet as audio unit */

            switch (st->codec->codec_id) {

            case AV_CODEC_ID_MP2:

            case AV_CODEC_ID_MP3:

                st->need_parsing = AVSTREAM_PARSE_FULL;

                break;

            }

        }

    }

    if (sc->format == 0) {

        if (st->codec->bits_per_coded_sample == 8)

            st->codec->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));

        else if (st->codec->bits_per_coded_sample == 16)

            st->codec->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));

    }

    switch (st->codec->codec_id) {

    case AV_CODEC_ID_PCM_S8:

    case AV_CODEC_ID_PCM_U8:

        if (st->codec->bits_per_coded_sample == 16)

            st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;

        break;

    case AV_CODEC_ID_PCM_S16LE:

    case AV_CODEC_ID_PCM_S16BE:

        if (st->codec->bits_per_coded_sample == 8)

            st->codec->codec_id = AV_CODEC_ID_PCM_S8;

        else if (st->codec->bits_per_coded_sample == 24)

            st->codec->codec_id =

                st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?

                AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;

        else if (st->codec->bits_per_coded_sample == 32)

             st->codec->codec_id =

                st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?

                AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;

        break;

    /* set values for old format before stsd version 1 appeared */

    case AV_CODEC_ID_MACE3:

        sc->samples_per_frame = 6;

        sc->bytes_per_frame   = 2 * st->codec->channels;

        break;

    case AV_CODEC_ID_MACE6:

        sc->samples_per_frame = 6;

        sc->bytes_per_frame   = 1 * st->codec->channels;

        break;

    case AV_CODEC_ID_ADPCM_IMA_QT:

        sc->samples_per_frame = 64;

        sc->bytes_per_frame   = 34 * st->codec->channels;

        break;

    case AV_CODEC_ID_GSM:

        sc->samples_per_frame = 160;

        sc->bytes_per_frame   = 33;

        break;

    default:

        break;

    }

    bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);

    if (bits_per_sample) {

        st->codec->bits_per_coded_sample = bits_per_sample;

        sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;

    }

}


iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,

                     void *command_data, void *opaque)

{

    IscsiAIOCB *acb = opaque;

    if (acb->canceled) {

        qemu_aio_release(acb);

        return;

    }

    acb->status = 0;

    if (status < 0) {

        error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",

                     iscsi_get_error(iscsi));

        acb->status = -EIO;

    }

    acb->ioh->driver_status = 0;

    acb->ioh->host_status   = 0;

    acb->ioh->resid         = 0;

#define SG_ERR_DRIVER_SENSE    0x08

    if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {

        int ss;

        acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;

        acb->ioh->sb_len_wr = acb->task->datain.size - 2;

        ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?

             acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;

        memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);

    }

    iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);

}


static int mpeg_decode_slice(MpegEncContext *s, int mb_y,

                             const uint8_t **buf, int buf_size)

{

    AVCodecContext *avctx = s->avctx;

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

    const int field_pic   = s->picture_structure != PICT_FRAME;

    int ret;

    s->resync_mb_x =

    s->resync_mb_y = -1;

    av_assert0(mb_y < s->mb_height);

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

    if (s->codec_id != AV_CODEC_ID_MPEG1VIDEO && s->mb_height > 2800/16)

        skip_bits(&s->gb, 3);

    ff_mpeg1_clean_buffers(s);

    s->interlaced_dct = 0;

    s->qscale = get_qscale(s);

    if (s->qscale == 0) {

        av_log(s->avctx, AV_LOG_ERROR, "qscale == 0\n");

        return AVERROR_INVALIDDATA;

    }

    /* extra slice info */

    if (skip_1stop_8data_bits(&s->gb) < 0)

        return AVERROR_INVALIDDATA;

    s->mb_x = 0;

    if (mb_y == 0 && s->codec_tag == AV_RL32("SLIF")) {

        skip_bits1(&s->gb);

    } else {

        while (get_bits_left(&s->gb) > 0) {

            int code = get_vlc2(&s->gb, ff_mbincr_vlc.table,

                                MBINCR_VLC_BITS, 2);

            if (code < 0) {

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

                return AVERROR_INVALIDDATA;

            }

            if (code >= 33) {

                if (code == 33)

                    s->mb_x += 33;

                /* otherwise, stuffing, nothing to do */

            } else {

                s->mb_x += code;

                break;

            }

        }

    }

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

        av_log(s->avctx, AV_LOG_ERROR, "initial skip overflow\n");

        return AVERROR_INVALIDDATA;

    }

    if (avctx->hwaccel && avctx->hwaccel->decode_slice) {

        const uint8_t *buf_end, *buf_start = *buf - 4; /* include start_code */

        int start_code = -1;

        buf_end = avpriv_find_start_code(buf_start + 2, *buf + buf_size, &start_code);

        if (buf_end < *buf + buf_size)

            buf_end -= 4;

        s->mb_y = mb_y;

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

            return DECODE_SLICE_ERROR;

        *buf = buf_end;

        return DECODE_SLICE_OK;

    }

    s->resync_mb_x = s->mb_x;

    s->resync_mb_y = s->mb_y = mb_y;

    s->mb_skip_run = 0;

    ff_init_block_index(s);

    if (s->mb_y == 0 && s->mb_x == 0 && (s->first_field || s->picture_structure == PICT_FRAME)) {

        if (s->avctx->debug & FF_DEBUG_PICT_INFO) {

            av_log(s->avctx, AV_LOG_DEBUG,

                   "qp:%d fc:%2d%2d%2d%2d %s %s %s %s %s dc:%d pstruct:%d fdct:%d cmv:%d qtype:%d ivlc:%d rff:%d %s\n",

                   s->qscale,

                   s->mpeg_f_code[0][0], s->mpeg_f_code[0][1],

                   s->mpeg_f_code[1][0], s->mpeg_f_code[1][1],

                   s->pict_type  == AV_PICTURE_TYPE_I ? "I" :

                   (s->pict_type == AV_PICTURE_TYPE_P ? "P" :

                   (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),

                   s->progressive_sequence ? "ps"  : "",

                   s->progressive_frame    ? "pf"  : "",

                   s->alternate_scan       ? "alt" : "",

                   s->top_field_first      ? "top" : "",

                   s->intra_dc_precision, s->picture_structure,

                   s->frame_pred_frame_dct, s->concealment_motion_vectors,

                   s->q_scale_type, s->intra_vlc_format,

                   s->repeat_first_field, s->chroma_420_type ? "420" : "");

        }

    }

    for (;;) {

        // If 1, we memcpy blocks in xvmcvideo.

        if ((CONFIG_MPEG1_XVMC_HWACCEL || CONFIG_MPEG2_XVMC_HWACCEL) && s->pack_pblocks)

            ff_xvmc_init_block(s); // set s->block

        if ((ret = mpeg_decode_mb(s, s->block)) < 0)

            return ret;

        // Note motion_val is normally NULL unless we want to extract the MVs.

        if (s->current_picture.motion_val[0] && !s->encoding) {

            const int wrap = s->b8_stride;

            int xy         = s->mb_x * 2 + s->mb_y * 2 * wrap;

            int b8_xy      = 4 * (s->mb_x + s->mb_y * s->mb_stride);

            int motion_x, motion_y, dir, i;

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

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

                    if (s->mb_intra ||

                        (dir == 1 && s->pict_type != AV_PICTURE_TYPE_B)) {

                        motion_x = motion_y = 0;

                    } else if (s->mv_type == MV_TYPE_16X16 ||

                               (s->mv_type == MV_TYPE_FIELD && field_pic)) {

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

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

                    } else { /* if ((s->mv_type == MV_TYPE_FIELD) || (s->mv_type == MV_TYPE_16X8)) */

                        motion_x = s->mv[dir][i][0];

                        motion_y = s->mv[dir][i][1];

                    }

                    s->current_picture.motion_val[dir][xy][0]     = motion_x;

                    s->current_picture.motion_val[dir][xy][1]     = motion_y;

                    s->current_picture.motion_val[dir][xy + 1][0] = motion_x;

                    s->current_picture.motion_val[dir][xy + 1][1] = motion_y;

                    s->current_picture.ref_index [dir][b8_xy]     =

                    s->current_picture.ref_index [dir][b8_xy + 1] = s->field_select[dir][i];

                    av_assert2(s->field_select[dir][i] == 0 ||

                               s->field_select[dir][i] == 1);

                }

                xy    += wrap;

                b8_xy += 2;

            }

        }

        s->dest[0] += 16 >> lowres;

        s->dest[1] +=(16 >> lowres) >> s->chroma_x_shift;

        s->dest[2] +=(16 >> lowres) >> s->chroma_x_shift;

        ff_mpv_decode_mb(s, s->block);

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

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

            ff_mpeg_draw_horiz_band(s, mb_size * (s->mb_y >> field_pic), mb_size);

            ff_mpv_report_decode_progress(s);

            s->mb_x  = 0;

            s->mb_y += 1 << field_pic;

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

                int left   = get_bits_left(&s->gb);

                int is_d10 = s->chroma_format == 2 &&

                             s->pict_type == AV_PICTURE_TYPE_I &&

                             avctx->profile == 0 && avctx->level == 5 &&

                             s->intra_dc_precision == 2 &&

                             s->q_scale_type == 1 && s->alternate_scan == 0 &&

                             s->progressive_frame == 0

                             /* vbv_delay == 0xBBB || 0xE10 */;

                if (left >= 32 && !is_d10) {

                    GetBitContext gb = s->gb;

                    align_get_bits(&gb);

                    if (show_bits(&gb, 24) == 0x060E2B) {

                        av_log(avctx, AV_LOG_DEBUG, "Invalid MXF data found in video stream\n");

                        is_d10 = 1;

                    }

                }

                if (left < 0 ||

                    (left && show_bits(&s->gb, FFMIN(left, 23)) && !is_d10) ||

                    ((avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_AGGRESSIVE)) && left > 8)) {

                    av_log(avctx, AV_LOG_ERROR, "end mismatch left=%d %0X\n",

                           left, show_bits(&s->gb, FFMIN(left, 23)));

                    return AVERROR_INVALIDDATA;

                } else

                    goto eos;

            }

            // There are some files out there which are missing the last slice

            // in cases where the slice is completely outside the visible

            // area, we detect this here instead of running into the end expecting

            // more data

            if (s->mb_y >= ((s->height + 15) >> 4) &&

                !s->progressive_sequence &&

                get_bits_left(&s->gb) <= 8 &&

                get_bits_left(&s->gb) >= 0 &&

                s->mb_skip_run == -1 &&

                show_bits(&s->gb, 8) == 0)

                goto eos;

            ff_init_block_index(s);

        }

        /* skip mb handling */

        if (s->mb_skip_run == -1) {

            /* read increment again */

            s->mb_skip_run = 0;

            for (;;) {

                int code = get_vlc2(&s->gb, ff_mbincr_vlc.table,

                                    MBINCR_VLC_BITS, 2);

                if (code < 0) {

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

                    return AVERROR_INVALIDDATA;

                }

                if (code >= 33) {

                    if (code == 33) {

                        s->mb_skip_run += 33;

                    } else if (code == 35) {

                        if (s->mb_skip_run != 0 || show_bits(&s->gb, 15) != 0) {

                            av_log(s->avctx, AV_LOG_ERROR, "slice mismatch\n");

                            return AVERROR_INVALIDDATA;

                        }

                        goto eos; /* end of slice */

                    }

                    /* otherwise, stuffing, nothing to do */

                } else {

                    s->mb_skip_run += code;

                    break;

                }

            }

            if (s->mb_skip_run) {

                int i;

                if (s->pict_type == AV_PICTURE_TYPE_I) {

                    av_log(s->avctx, AV_LOG_ERROR,

                           "skipped MB in I frame at %d %d\n", s->mb_x, s->mb_y);

                    return AVERROR_INVALIDDATA;

                }

                /* skip mb */

                s->mb_intra = 0;

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

                    s->block_last_index[i] = -1;

                if (s->picture_structure == PICT_FRAME)

                    s->mv_type = MV_TYPE_16X16;

                else

                    s->mv_type = MV_TYPE_FIELD;

                if (s->pict_type == AV_PICTURE_TYPE_P) {

                    /* if P type, zero motion vector is implied */

                    s->mv_dir             = MV_DIR_FORWARD;

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

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

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

                    s->field_select[0][0] = (s->picture_structure - 1) & 1;

                } else {

                    /* if B type, reuse previous vectors and directions */

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

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

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

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

                }

            }

        }

    }

eos: // end of slice

    if (get_bits_left(&s->gb) < 0) {

        av_log(s, AV_LOG_ERROR, "overread %d\n", -get_bits_left(&s->gb));

        return AVERROR_INVALIDDATA;

    }

    *buf += (get_bits_count(&s->gb) - 1) / 8;

    ff_dlog(s, "Slice start:%d %d  end:%d %d\n", s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y);

    return 0;

}


static int poll_filters(void)

{

    AVFilterBufferRef *picref;

    AVFrame *filtered_frame = NULL;

    int i, ret, ret_all;

    unsigned nb_success, nb_eof;

    int64_t frame_pts;

    while (1) {

        /* Reap all buffers present in the buffer sinks */

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

            OutputStream *ost = output_streams[i];

            OutputFile    *of = output_files[ost->file_index];

            int ret = 0;

            if (!ost->filter || ost->is_past_recording_time)

                continue;

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

                return AVERROR(ENOMEM);

            } else

                avcodec_get_frame_defaults(ost->filtered_frame);

            filtered_frame = ost->filtered_frame;

            while (1) {

                AVRational ist_pts_tb = ost->filter->filter->inputs[0]->time_base;

                if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&

                    !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))

                    ret = av_buffersink_read_samples(ost->filter->filter, &picref,

                                                    ost->st->codec->frame_size);

                else

#ifdef SINKA

                    ret = av_buffersink_read(ost->filter->filter, &picref);

#else

                    ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,

                                                       AV_BUFFERSINK_FLAG_NO_REQUEST);

#endif

                if (ret < 0) {

                    if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {

                        char buf[256];

                        av_strerror(ret, buf, sizeof(buf));

                        av_log(NULL, AV_LOG_WARNING,

                               "Error in av_buffersink_get_buffer_ref(): %s\n", buf);

                    }

                    break;

                }

                if (ost->enc->type == AVMEDIA_TYPE_VIDEO)

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

                else if (picref->pts != AV_NOPTS_VALUE)

                    filtered_frame->pts = frame_pts = av_rescale_q(picref->pts,

                                                    ost->filter->filter->inputs[0]->time_base,

                                                    ost->st->codec->time_base) -

                                        av_rescale_q(of->start_time,

                                                    AV_TIME_BASE_Q,

                                                    ost->st->codec->time_base);

                //if (ost->source_index >= 0)

                //    *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold

                if (of->start_time && filtered_frame->pts < of->start_time) {

                    avfilter_unref_buffer(picref);

                    continue;

                }

                switch (ost->filter->filter->inputs[0]->type) {

                case AVMEDIA_TYPE_VIDEO:

                    avfilter_fill_frame_from_video_buffer_ref(filtered_frame, picref);

                    filtered_frame->pts = frame_pts;

                    if (!ost->frame_aspect_ratio)

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

                    do_video_out(of->ctx, ost, filtered_frame,

                                 same_quant ? ost->last_quality :

                                              ost->st->codec->global_quality);

                    break;

                case AVMEDIA_TYPE_AUDIO:

                    avfilter_copy_buf_props(filtered_frame, picref);

                    filtered_frame->pts = frame_pts;

                    do_audio_out(of->ctx, ost, filtered_frame);

                    break;

                default:

                    // TODO support subtitle filters

                    av_assert0(0);

                }

                avfilter_unref_buffer(picref);

            }

        }

        /* Request frames through all the graphs */

        ret_all = nb_success = nb_eof = 0;

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

            ret = avfilter_graph_request_oldest(filtergraphs[i]->graph);

            if (!ret) {

                nb_success++;

            } else if (ret == AVERROR_EOF) {

                nb_eof++;

            } else if (ret != AVERROR(EAGAIN)) {

                char buf[256];

                av_strerror(ret, buf, sizeof(buf));

                av_log(NULL, AV_LOG_WARNING,

                       "Error in request_frame(): %s\n", buf);

                ret_all = ret;

            }

        }

        if (!nb_success)

            break;

        /* Try again if anything succeeded */

    }

    return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;

}


static int parse_hex32(DeviceState *dev, Property *prop, const char *str)

{

    uint32_t *ptr = qdev_get_prop_ptr(dev, prop);

    if (sscanf(str, "%" PRIx32, ptr) != 1)

        return -EINVAL;

    return 0;

}


void helper_retry(CPUSPARCState *env)

{

    trap_state *tsptr = cpu_tsptr(env);

    env->pc = tsptr->tpc;

    env->npc = tsptr->tnpc;

    cpu_put_ccr(env, tsptr->tstate >> 32);

    env->asi = (tsptr->tstate >> 24) & 0xff;

    cpu_change_pstate(env, (tsptr->tstate >> 8) & 0xf3f);

    cpu_put_cwp64(env, tsptr->tstate & 0xff);

    if (cpu_has_hypervisor(env)) {

        uint32_t new_gl = (tsptr->tstate >> 40) & 7;

        env->hpstate = env->htstate[env->tl];

        cpu_gl_switch_gregs(env, new_gl);

        env->gl = new_gl;

    }

    env->tl--;

    trace_win_helper_retry(env->tl);

#if !defined(CONFIG_USER_ONLY)

    if (cpu_interrupts_enabled(env)) {

        cpu_check_irqs(env);

    }

#endif

}


static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)

{

    int superblock_starts[3] = { 0, s->u_superblock_start, s->v_superblock_start };

    int bit = 0;

    int current_superblock = 0;

    int current_run = 0;

    int num_partial_superblocks = 0;

    int i, j;

    int current_fragment;

    int plane;

    if (s->keyframe) {

        memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);

    } else {

        /* unpack the list of partially-coded superblocks */

        bit = get_bits1(gb);

        while (current_superblock < s->superblock_count) {

                current_run = get_vlc2(gb,

                    s->superblock_run_length_vlc.table, 6, 2) + 1;

                if (current_run == 34)

                    current_run += get_bits(gb, 12);

            if (current_superblock + current_run > s->superblock_count) {

                av_log(s->avctx, AV_LOG_ERROR, "Invalid partially coded superblock run length\n");

                return -1;

            }

            memset(s->superblock_coding + current_superblock, bit, current_run);

            current_superblock += current_run;

            if (bit)

                num_partial_superblocks += current_run;

            if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)

                bit = get_bits1(gb);

            else

                bit ^= 1;

        }

        /* unpack the list of fully coded superblocks if any of the blocks were

         * not marked as partially coded in the previous step */

        if (num_partial_superblocks < s->superblock_count) {

            int superblocks_decoded = 0;

            current_superblock = 0;

            bit = get_bits1(gb);

            while (superblocks_decoded < s->superblock_count - num_partial_superblocks) {

                        current_run = get_vlc2(gb,

                            s->superblock_run_length_vlc.table, 6, 2) + 1;

                        if (current_run == 34)

                            current_run += get_bits(gb, 12);

                for (j = 0; j < current_run; current_superblock++) {

                    if (current_superblock >= s->superblock_count) {

                        av_log(s->avctx, AV_LOG_ERROR, "Invalid fully coded superblock run length\n");

                        return -1;

                    }

                /* skip any superblocks already marked as partially coded */

                if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {

                    s->superblock_coding[current_superblock] = 2*bit;

                    j++;

                }

                }

                superblocks_decoded += current_run;

                if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)

                    bit = get_bits1(gb);

                else

                    bit ^= 1;

            }

        }

        /* if there were partial blocks, initialize bitstream for

         * unpacking fragment codings */

        if (num_partial_superblocks) {

            current_run = 0;

            bit = get_bits1(gb);

            /* toggle the bit because as soon as the first run length is

             * fetched the bit will be toggled again */

            bit ^= 1;

        }

    }

    /* figure out which fragments are coded; iterate through each

     * superblock (all planes) */

    s->total_num_coded_frags = 0;

    memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);

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

        int sb_start = superblock_starts[plane];

        int sb_end = sb_start + (plane ? s->c_superblock_count : s->y_superblock_count);

        int num_coded_frags = 0;

    for (i = sb_start; i < sb_end; i++) {

        /* iterate through all 16 fragments in a superblock */

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

            /* if the fragment is in bounds, check its coding status */

            current_fragment = s->superblock_fragments[i * 16 + j];

            if (current_fragment != -1) {

                int coded = s->superblock_coding[i];

                if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {

                    /* fragment may or may not be coded; this is the case

                     * that cares about the fragment coding runs */

                    if (current_run-- == 0) {

                        bit ^= 1;

                        current_run = get_vlc2(gb,

                            s->fragment_run_length_vlc.table, 5, 2);

                    }

                    coded = bit;

                }

                    if (coded) {

                        /* default mode; actual mode will be decoded in

                         * the next phase */

                        s->all_fragments[current_fragment].coding_method =

                            MODE_INTER_NO_MV;

                        s->coded_fragment_list[plane][num_coded_frags++] =

                            current_fragment;

                    } else {

                        /* not coded; copy this fragment from the prior frame */

                        s->all_fragments[current_fragment].coding_method =

                            MODE_COPY;

                    }

            }

        }

    }

        s->total_num_coded_frags += num_coded_frags;

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

            s->num_coded_frags[plane][i] = num_coded_frags;

        if (plane < 2)

            s->coded_fragment_list[plane+1] = s->coded_fragment_list[plane] + num_coded_frags;

    }

    return 0;

}


static av_cold int mov_text_encode_init(AVCodecContext *avctx)

{

    /*

     * For now, we'll use a fixed default style. When we add styling

     * support, this will be generated from the ASS style.

     */

    static const uint8_t text_sample_entry[] = {

        0x00, 0x00, 0x00, 0x00, // uint32_t displayFlags

        0x01,                   // int8_t horizontal-justification

        0xFF,                   // int8_t vertical-justification

        0x00, 0x00, 0x00, 0x00, // uint8_t background-color-rgba[4]

        // BoxRecord {

        0x00, 0x00,             // int16_t top

        0x00, 0x00,             // int16_t left

        0x00, 0x00,             // int16_t bottom

        0x00, 0x00,             // int16_t right

        // };

        // StyleRecord {

        0x00, 0x00,             // uint16_t startChar

        0x00, 0x00,             // uint16_t endChar

        0x00, 0x01,             // uint16_t font-ID

        0x00,                   // uint8_t face-style-flags

        0x12,                   // uint8_t font-size

        0xFF, 0xFF, 0xFF, 0xFF, // uint8_t text-color-rgba[4]

        // };

        // FontTableBox {

        0x00, 0x00, 0x00, 0x12, // uint32_t size

        'f', 't', 'a', 'b',     // uint8_t name[4]

        0x00, 0x01,             // uint16_t entry-count

        // FontRecord {

        0x00, 0x01,             // uint16_t font-ID

        0x05,                   // uint8_t font-name-length

        'S', 'e', 'r', 'i', 'f',// uint8_t font[font-name-length]

        // };

        // };

    };

    MovTextContext *s = avctx->priv_data;

    avctx->extradata_size = sizeof text_sample_entry;

    avctx->extradata = av_mallocz(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);

    if (!avctx->extradata)

        return AVERROR(ENOMEM);

    av_bprint_init(&s->buffer, 0, AV_BPRINT_SIZE_UNLIMITED);

    memcpy(avctx->extradata, text_sample_entry, avctx->extradata_size);

    s->ass_ctx = ff_ass_split(avctx->subtitle_header);

    return s->ass_ctx ? 0 : AVERROR_INVALIDDATA;

}


static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)

{

    struct xlx_ethlite *s = qemu_get_nic_opaque(nc);

    unsigned int rxbase = s->rxbuf * (0x800 / 4);

    /* DA filter.  */

    if (!(buf[0] & 0x80) && memcmp(&s->conf.macaddr.a[0], buf, 6))

        return size;

    if (s->regs[rxbase + R_RX_CTRL0] & CTRL_S) {

        D(qemu_log("ethlite lost packet %x\n", s->regs[R_RX_CTRL0]));

    D(qemu_log("%s %zd rxbase=%x\n", __func__, size, rxbase));

    memcpy(&s->regs[rxbase + R_RX_BUF0], buf, size);

    s->regs[rxbase + R_RX_CTRL0] |= CTRL_S;

    if (s->regs[R_RX_CTRL0] & CTRL_I) {

        eth_pulse_irq(s);

    /* If c_rx_pingpong was set flip buffers.  */

    s->rxbuf ^= s->c_rx_pingpong;

    return size;


static void init_proc_970MP (CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_7xx(env);

    /* Time base */

    gen_tbl(env);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_clear,

                 0x60000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_750_HID2, "HID2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_970_HID5, "HID5",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 POWERPC970_HID5_INIT);

    /* Memory management */

    /* XXX: not correct */

    gen_low_BATs(env);

    /* XXX : not implemented */

    spr_register(env, SPR_MMUCFG, "MMUCFG",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000); /* TOFIX */

    /* XXX : not implemented */

    spr_register(env, SPR_MMUCSR0, "MMUCSR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000); /* TOFIX */

    spr_register(env, SPR_HIOR, "SPR_HIOR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0xFFF00000); /* XXX: This is a hack */

#if !defined(CONFIG_USER_ONLY)

    env->excp_prefix = 0xFFF00000;

#endif

#if !defined(CONFIG_USER_ONLY)

    env->slb_nr = 32;

#endif

    init_excp_970(env);

    env->dcache_line_size = 128;

    env->icache_line_size = 128;

    /* Allocate hardware IRQ controller */

    ppc970_irq_init(env);

}


void ff_h264_direct_ref_list_init(const H264Context *const h, H264SliceContext *sl)

{

    H264Ref *const ref1 = &sl->ref_list[1][0];

    H264Picture *const cur = h->cur_pic_ptr;

    int list, j, field;

    int sidx     = (h->picture_structure & 1) ^ 1;

    int ref1sidx = (ref1->reference      & 1) ^ 1;

    for (list = 0; list < sl->list_count; list++) {

        cur->ref_count[sidx][list] = sl->ref_count[list];

        for (j = 0; j < sl->ref_count[list]; j++)

            cur->ref_poc[sidx][list][j] = 4 * sl->ref_list[list][j].parent->frame_num +

                                          (sl->ref_list[list][j].reference & 3);

    }

    if (h->picture_structure == PICT_FRAME) {

        memcpy(cur->ref_count[1], cur->ref_count[0], sizeof(cur->ref_count[0]));

        memcpy(cur->ref_poc[1],   cur->ref_poc[0],   sizeof(cur->ref_poc[0]));

    }

    cur->mbaff = FRAME_MBAFF(h);

    sl->col_fieldoff = 0;

    if (sl->list_count != 2 || !sl->ref_count[1])

        return;

    if (h->picture_structure == PICT_FRAME) {

        int cur_poc  = h->cur_pic_ptr->poc;

        int *col_poc = sl->ref_list[1][0].parent->field_poc;

        sl->col_parity = (FFABS(col_poc[0] - cur_poc) >=

                          FFABS(col_poc[1] - cur_poc));

        ref1sidx =

        sidx     = sl->col_parity;

    // FL -> FL & differ parity

    } else if (!(h->picture_structure & sl->ref_list[1][0].reference) &&

               !sl->ref_list[1][0].parent->mbaff) {

        sl->col_fieldoff = 2 * sl->ref_list[1][0].reference - 3;

    }

    if (sl->slice_type_nos != AV_PICTURE_TYPE_B || sl->direct_spatial_mv_pred)

        return;

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

        fill_colmap(h, sl, sl->map_col_to_list0, list, sidx, ref1sidx, 0);

        if (FRAME_MBAFF(h))

            for (field = 0; field < 2; field++)

                fill_colmap(h, sl, sl->map_col_to_list0_field[field], list, field,

                            field, 1);

    }

}


static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,

    int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)

{

    int ret;

    BDRVQcow2State *s = bs->opaque;

    int head = sector_num % s->cluster_sectors;

    int tail = (sector_num + nb_sectors) % s->cluster_sectors;

    trace_qcow2_write_zeroes_start_req(qemu_coroutine_self(), sector_num,

                                       nb_sectors);

    if (head != 0 || tail != 0) {

        int64_t cl_start = sector_num - head;

        assert(cl_start + s->cluster_sectors >= sector_num + nb_sectors);

        sector_num = cl_start;

        nb_sectors = s->cluster_sectors;

        if (!is_zero_cluster(bs, sector_num)) {

            return -ENOTSUP;

        }

        qemu_co_mutex_lock(&s->lock);

        /* We can have new write after previous check */

        if (!is_zero_cluster_top_locked(bs, sector_num)) {

            qemu_co_mutex_unlock(&s->lock);

            return -ENOTSUP;

        }

    } else {

        qemu_co_mutex_lock(&s->lock);

    }

    trace_qcow2_write_zeroes(qemu_coroutine_self(), sector_num, nb_sectors);

    /* Whatever is left can use real zero clusters */

    ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS, nb_sectors);

    qemu_co_mutex_unlock(&s->lock);

    return ret;

}


static int read_packet(AVFormatContext *s1, AVPacket *pkt)

{

    VideoDemuxData *s = s1->priv_data;

    char filename[1024];

    int i;

    int size[3]={0}, ret[3]={0};

    AVIOContext *f[3];

    AVCodecContext *codec= s1->streams[0]->codec;

    if (!s->is_pipe) {

        /* loop over input */

        if (s->loop && s->img_number > s->img_last) {

            s->img_number = s->img_first;

        }

        if (s->img_number > s->img_last)

            return AVERROR_EOF;

        if (av_get_frame_filename(filename, sizeof(filename),

                                  s->path, s->img_number)<0 && s->img_number > 1)

            return AVERROR(EIO);

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

            if (avio_open2(&f[i], filename, AVIO_FLAG_READ,

                           &s1->interrupt_callback, NULL) < 0) {

                if(i==1)

                    break;

                av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",filename);

                return AVERROR(EIO);

            }

            size[i]= avio_size(f[i]);

            if(codec->codec_id != AV_CODEC_ID_RAWVIDEO)

                break;

            filename[ strlen(filename) - 1 ]= 'U' + i;

        }

        if(codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->width)

            infer_size(&codec->width, &codec->height, size[0]);

    } else {

        f[0] = s1->pb;

        if (f[0]->eof_reached)

            return AVERROR(EIO);

        size[0]= 4096;

    }

    av_new_packet(pkt, size[0] + size[1] + size[2]);

    pkt->stream_index = 0;

    pkt->flags |= AV_PKT_FLAG_KEY;

    pkt->size= 0;

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

        if(size[i]){

            ret[i]= avio_read(f[i], pkt->data + pkt->size, size[i]);

            if (!s->is_pipe)

                avio_close(f[i]);

            if(ret[i]>0)

                pkt->size += ret[i];

        }

    }

    if (ret[0] <= 0 || ret[1]<0 || ret[2]<0) {

        av_free_packet(pkt);

        return AVERROR(EIO); /* signal EOF */

    } else {

        s->img_count++;

        s->img_number++;

        return 0;

    }

}


static void fill_float_array(AVLFG *lfg, float *a, int len)

{

    int i;

    double bmg[2], stddev = 10.0, mean = 0.0;

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

        av_bmg_get(lfg, bmg);

        a[i]     = bmg[0] * stddev + mean;

        a[i + 1] = bmg[1] * stddev + mean;

    }

}


void visit_type_uint32(Visitor *v, uint32_t *obj, const char *name, Error **errp)

{

    int64_t value;

    if (!error_is_set(errp)) {

        if (v->type_uint32) {

            v->type_uint32(v, obj, name, errp);

        } else {

            value = *obj;

            v->type_int(v, &value, name, errp);

            if (value < 0 || value > UINT32_MAX) {

                error_set(errp, QERR_INVALID_PARAMETER_VALUE, name ? name : "null",

                          "uint32_t");

                return;

            }

            *obj = value;

        }

    }

}


static int RENAME(dct_quantize)(MpegEncContext *s,

                            DCTELEM *block, int n,

                            int qscale)

{

    int i, level, last_non_zero_p1, q;

    const UINT16 *qmat;

    static __align8 INT16 temp_block[64];

    int minLevel, maxLevel;

    if(s->avctx!=NULL && s->avctx->codec->id==CODEC_ID_MPEG4){

	/* mpeg4 */

        minLevel= -2048;

	maxLevel= 2047;

    }else if(s->out_format==FMT_MPEG1){

	/* mpeg1 */

        minLevel= -255;

	maxLevel= 255;

    }else if(s->out_format==FMT_MJPEG){

	/* (m)jpeg */

        minLevel= -1023;

	maxLevel= 1023;

    }else{

	/* h263 / msmpeg4 */

        minLevel= -128;

	maxLevel= 127;

    }

    av_fdct (block);

    if (s->mb_intra) {

        int dummy;

        if (n < 4)

            q = s->y_dc_scale;

        else

            q = s->c_dc_scale;

        /* note: block[0] is assumed to be positive */

#if 1

	asm volatile (

		"xorl %%edx, %%edx	\n\t"

		"mul %%ecx		\n\t"

		: "=d" (temp_block[0]), "=a"(dummy)

		: "a" (block[0] + (q >> 1)), "c" (inverse[q])

	);

#else

	asm volatile (

		"xorl %%edx, %%edx	\n\t"

		"divw %%cx		\n\t"

		"movzwl %%ax, %%eax	\n\t"

		: "=a" (temp_block[0])

		: "a" (block[0] + (q >> 1)), "c" (q)

		: "%edx"

	);

#endif

//        temp_block[0] = (block[0] + (q >> 1)) / q;

        i = 1;

        last_non_zero_p1 = 1;

        if (s->out_format == FMT_H263) {

            qmat = s->q_non_intra_matrix16;

        } else {

            qmat = s->q_intra_matrix16;

        }

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

            level = block[i] * qmat[i];

            level = level / (1 << (QMAT_SHIFT_MMX - 3));

            /* XXX: currently, this code is not optimal. the range should be:

               mpeg1: -255..255

               mpeg2: -2048..2047

               h263:  -128..127

               mpeg4: -2048..2047

            */

            if (level > maxLevel)

                level = maxLevel;

            else if (level < minLevel)

                level = minLevel;

            temp_block[i] = level;

	    if(level)

	        if(last_non_zero_p1 < inv_zigzag_direct16[i]) last_non_zero_p1= inv_zigzag_direct16[i];

	    block[i]=0;

        }

    } else {

        i = 0;

        last_non_zero_p1 = 0;

        qmat = s->q_non_intra_matrix16;

    }

    asm volatile( /* XXX: small rounding bug, but it shouldnt matter */

	"movd %3, %%mm3			\n\t"

	SPREADW(%%mm3)

	"movd %4, %%mm4			\n\t"

	SPREADW(%%mm4)

#ifndef HAVE_MMX2

	"movd %5, %%mm5			\n\t"

	SPREADW(%%mm5)

#endif

	"pxor %%mm7, %%mm7		\n\t"

	"movd %%eax, %%mm2		\n\t"

	SPREADW(%%mm2)

	"movl %6, %%eax			\n\t"

	".balign 16			\n\t"

	"1:				\n\t"

	"movq (%1, %%eax), %%mm0	\n\t"

	"movq (%2, %%eax), %%mm1	\n\t"

	"movq %%mm0, %%mm6		\n\t"

	"psraw $15, %%mm6		\n\t"

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

	"psubsw %%mm6, %%mm1		\n\t"

#ifdef HAVE_MMX2

	"pminsw %%mm3, %%mm1		\n\t"

	"pmaxsw %%mm4, %%mm1		\n\t"

#else

	"paddsw %%mm3, %%mm1		\n\t"

	"psubusw %%mm4, %%mm1		\n\t"

	"paddsw %%mm5, %%mm1		\n\t"

#endif

	"movq %%mm1, (%8, %%eax)	\n\t"

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

	"movq (%7, %%eax), %%mm0	\n\t"

	"movq %%mm7, (%1, %%eax)	\n\t"

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

	PMAXW(%%mm1, %%mm2)

	"addl $8, %%eax			\n\t"

	" js 1b				\n\t"

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

	"psrlq $32, %%mm2		\n\t"

	PMAXW(%%mm0, %%mm2)

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

	"psrlq $16, %%mm2		\n\t"

	PMAXW(%%mm0, %%mm2)

	"movd %%mm2, %%eax		\n\t"

	"movzbl %%al, %%eax		\n\t"

	: "+a" (last_non_zero_p1)

	: "r" (block+64), "r" (qmat+64),

#ifdef HAVE_MMX2

	  "m" (maxLevel),          "m" (minLevel),                    "m" (minLevel /* dummy */), "g" (2*i - 128),

#else

	  "m" (0x7FFF - maxLevel), "m" (0x7FFF -maxLevel + minLevel), "m" (minLevel),             "g" (2*i - 128),

#endif

	  "r" (inv_zigzag_direct16+64), "r" (temp_block+64)

    );

// last_non_zero_p1=64;

    /* permute for IDCT */

    asm volatile(

	"movl %0, %%eax			\n\t"

	"pushl %%ebp			\n\t"

	"movl %%esp, " MANGLE(esp_temp) "\n\t"

	"1:				\n\t"

	"movzbl (%1, %%eax), %%ebx	\n\t"

	"movzbl 1(%1, %%eax), %%ebp	\n\t"

	"movw (%2, %%ebx, 2), %%cx	\n\t"

	"movw (%2, %%ebp, 2), %%sp	\n\t"

	"movzbl " MANGLE(permutation) "(%%ebx), %%ebx\n\t"

	"movzbl " MANGLE(permutation) "(%%ebp), %%ebp\n\t"

	"movw %%cx, (%3, %%ebx, 2)	\n\t"

	"movw %%sp, (%3, %%ebp, 2)	\n\t"

	"addl $2, %%eax			\n\t"

	" js 1b				\n\t"

	"movl " MANGLE(esp_temp) ", %%esp\n\t"

	"popl %%ebp			\n\t"

	:

	: "g" (-last_non_zero_p1), "d" (zigzag_direct_noperm+last_non_zero_p1), "S" (temp_block), "D" (block)

	: "%eax", "%ebx", "%ecx"

	);

/*

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

    {

       int j= zigzag_direct_noperm[i];

       block[block_permute_op(j)]= temp_block[j];

    }

*/

//block_permute(block);

    return last_non_zero_p1 - 1;

}


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

{

    MXFContext *mxf = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *st = s->streams[pkt->stream_index];

    MXFStreamContext *sc = st->priv_data;

    MXFIndexEntry ie = {0};

    int err;

    if (!mxf->edit_unit_byte_count && !(mxf->edit_units_count % EDIT_UNITS_PER_BODY)) {

        if ((err = av_reallocp_array(&mxf->index_entries, mxf->edit_units_count

                                     + EDIT_UNITS_PER_BODY, sizeof(*mxf->index_entries))) < 0) {

            mxf->edit_units_count = 0;

            av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");

            return err;

    if (st->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

        if (!mxf_parse_mpeg2_frame(s, st, pkt, &ie)) {

            av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");

            return -1;

    } else if (st->codec->codec_id == AV_CODEC_ID_DNXHD) {

        if (!mxf_parse_dnxhd_frame(s, st, pkt)) {

            av_log(s, AV_LOG_ERROR, "could not get dnxhd profile\n");

            return -1;

    } else if (st->codec->codec_id == AV_CODEC_ID_DVVIDEO) {

        if (!mxf_parse_dv_frame(s, st, pkt)) {

            av_log(s, AV_LOG_ERROR, "could not get dv profile\n");

            return -1;

    } else if (st->codec->codec_id == AV_CODEC_ID_H264) {

        if (!mxf_parse_h264_frame(s, st, pkt, &ie)) {

            av_log(s, AV_LOG_ERROR, "could not get h264 profile\n");

            return -1;

    if (s->oformat == &ff_mxf_opatom_muxer)

        return mxf_write_opatom_packet(s, pkt, &ie);

    if (!mxf->header_written) {

        if (mxf->edit_unit_byte_count) {

            if ((err = mxf_write_partition(s, 1, 2, header_open_partition_key, 1)) < 0)

                return err;

            mxf_write_klv_fill(s);

            mxf_write_index_table_segment(s);

        } else {

            if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)

                return err;

        mxf->header_written = 1;

    if (st->index == 0) {

        if (!mxf->edit_unit_byte_count &&

            (!mxf->edit_units_count || mxf->edit_units_count > EDIT_UNITS_PER_BODY) &&

            !(ie.flags & 0x33)) { // I frame, Gop start

            mxf_write_klv_fill(s);

            if ((err = mxf_write_partition(s, 1, 2, body_partition_key, 0)) < 0)

                return err;

            mxf_write_klv_fill(s);

            mxf_write_index_table_segment(s);

        mxf_write_klv_fill(s);

        mxf_write_system_item(s);

        if (!mxf->edit_unit_byte_count) {

            mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;

            mxf->index_entries[mxf->edit_units_count].flags = ie.flags;

            mxf->index_entries[mxf->edit_units_count].temporal_ref = ie.temporal_ref;

            mxf->body_offset += KAG_SIZE; // size of system element

        mxf->edit_units_count++;

    } else if (!mxf->edit_unit_byte_count && st->index == 1) {

        mxf->index_entries[mxf->edit_units_count-1].slice_offset =

            mxf->body_offset - mxf->index_entries[mxf->edit_units_count-1].offset;

    mxf_write_klv_fill(s);

    avio_write(pb, sc->track_essence_element_key, 16); // write key

    if (s->oformat == &ff_mxf_d10_muxer) {

        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

            mxf_write_d10_video_packet(s, st, pkt);

        else

            mxf_write_d10_audio_packet(s, st, pkt);

    } else {

        klv_encode_ber4_length(pb, pkt->size); // write length

        avio_write(pb, pkt->data, pkt->size);

        mxf->body_offset += 16+4+pkt->size + klv_fill_size(16+4+pkt->size);

    avio_flush(pb);

    return 0;


static void set_up_watchdog (m48t59_t *NVRAM, uint8_t value)

{

    uint64_t interval; /* in 1/16 seconds */

    if (NVRAM->wd_timer != NULL) {

        qemu_del_timer(NVRAM->wd_timer);

	NVRAM->wd_timer = NULL;

    }

    NVRAM->buffer[0x1FF0] &= ~0x80;

    if (value != 0) {

	interval = (1 << (2 * (value & 0x03))) * ((value >> 2) & 0x1F);

	qemu_mod_timer(NVRAM->wd_timer, ((uint64_t)time(NULL) * 1000) +

		       ((interval * 1000) >> 4));

    }

}


static float get_band_cost_SQUAD_mips(struct AACEncContext *s,

                                      PutBitContext *pb, const float *in,

                                      const float *scaled, int size, int scale_idx,

                                      int cb, const float lambda, const float uplim,

                                      int *bits)

{

    const float Q34 = ff_aac_pow34sf_tab[POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];

    const float IQ  = ff_aac_pow2sf_tab [POW_SF2_ZERO + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];

    int i;

    float cost = 0;

    int qc1, qc2, qc3, qc4;

    int curbits = 0;

    uint8_t *p_bits  = (uint8_t *)ff_aac_spectral_bits[cb-1];

    float   *p_codes = (float   *)ff_aac_codebook_vectors[cb-1];

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

        const float *vec;

        int curidx;

        int   *in_int = (int   *)&in[i];

        float *in_pos = (float *)&in[i];

        float di0, di1, di2, di3;

        int t0, t1, t2, t3, t4, t5, t6, t7;

        qc1 = scaled[i  ] * Q34 + ROUND_STANDARD;

        qc2 = scaled[i+1] * Q34 + ROUND_STANDARD;

        qc3 = scaled[i+2] * Q34 + ROUND_STANDARD;

        qc4 = scaled[i+3] * Q34 + ROUND_STANDARD;

        __asm__ volatile (

            ".set push                                  \n\t"

            ".set noreorder                             \n\t"

            "slt        %[qc1], $zero,  %[qc1]          \n\t"

            "slt        %[qc2], $zero,  %[qc2]          \n\t"

            "slt        %[qc3], $zero,  %[qc3]          \n\t"

            "slt        %[qc4], $zero,  %[qc4]          \n\t"

            "lw         %[t0],  0(%[in_int])            \n\t"

            "lw         %[t1],  4(%[in_int])            \n\t"

            "lw         %[t2],  8(%[in_int])            \n\t"

            "lw         %[t3],  12(%[in_int])           \n\t"

            "srl        %[t0],  %[t0],  31              \n\t"

            "srl        %[t1],  %[t1],  31              \n\t"

            "srl        %[t2],  %[t2],  31              \n\t"

            "srl        %[t3],  %[t3],  31              \n\t"

            "subu       %[t4],  $zero,  %[qc1]          \n\t"

            "subu       %[t5],  $zero,  %[qc2]          \n\t"

            "subu       %[t6],  $zero,  %[qc3]          \n\t"

            "subu       %[t7],  $zero,  %[qc4]          \n\t"

            "movn       %[qc1], %[t4],  %[t0]           \n\t"

            "movn       %[qc2], %[t5],  %[t1]           \n\t"

            "movn       %[qc3], %[t6],  %[t2]           \n\t"

            "movn       %[qc4], %[t7],  %[t3]           \n\t"

            ".set pop                                   \n\t"

            : [qc1]"+r"(qc1), [qc2]"+r"(qc2),

              [qc3]"+r"(qc3), [qc4]"+r"(qc4),

              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),

              [t4]"=&r"(t4), [t5]"=&r"(t5), [t6]"=&r"(t6), [t7]"=&r"(t7)

            : [in_int]"r"(in_int)

            : "memory"

        );

        curidx = qc1;

        curidx *= 3;

        curidx += qc2;

        curidx *= 3;

        curidx += qc3;

        curidx *= 3;

        curidx += qc4;

        curidx += 40;

        curbits += p_bits[curidx];

        vec     = &p_codes[curidx*4];

        __asm__ volatile (

            ".set push                                  \n\t"

            ".set noreorder                             \n\t"

            "lwc1       $f0,    0(%[in_pos])            \n\t"

            "lwc1       $f1,    0(%[vec])               \n\t"

            "lwc1       $f2,    4(%[in_pos])            \n\t"

            "lwc1       $f3,    4(%[vec])               \n\t"

            "lwc1       $f4,    8(%[in_pos])            \n\t"

            "lwc1       $f5,    8(%[vec])               \n\t"

            "lwc1       $f6,    12(%[in_pos])           \n\t"

            "lwc1       $f7,    12(%[vec])              \n\t"

            "nmsub.s    %[di0], $f0,    $f1,    %[IQ]   \n\t"

            "nmsub.s    %[di1], $f2,    $f3,    %[IQ]   \n\t"

            "nmsub.s    %[di2], $f4,    $f5,    %[IQ]   \n\t"

            "nmsub.s    %[di3], $f6,    $f7,    %[IQ]   \n\t"

            ".set pop                                   \n\t"

            : [di0]"=&f"(di0), [di1]"=&f"(di1),

              [di2]"=&f"(di2), [di3]"=&f"(di3)

            : [in_pos]"r"(in_pos), [vec]"r"(vec),

              [IQ]"f"(IQ)

            : "$f0", "$f1", "$f2", "$f3",

              "$f4", "$f5", "$f6", "$f7",

              "memory"

        );

        cost += di0 * di0 + di1 * di1

                + di2 * di2 + di3 * di3;

    }

    if (bits)

        *bits = curbits;

    return cost * lambda + curbits;

}


static target_ulong h_register_logical_lan(CPUPPCState *env,

                                           sPAPREnvironment *spapr,

                                           target_ulong opcode,

                                           target_ulong *args)

{

    target_ulong reg = args[0];

    target_ulong buf_list = args[1];

    target_ulong rec_queue = args[2];

    target_ulong filter_list = args[3];

    VIOsPAPRDevice *sdev = spapr_vio_find_by_reg(spapr->vio_bus, reg);

    VIOsPAPRVLANDevice *dev = (VIOsPAPRVLANDevice *)sdev;

    vlan_bd_t filter_list_bd;

    if (!dev) {

        return H_PARAMETER;

    }

    if (dev->isopen) {

        hcall_dprintf("H_REGISTER_LOGICAL_LAN called twice without "

                      "H_FREE_LOGICAL_LAN\n");

        return H_RESOURCE;

    }

    if (check_bd(dev, VLAN_VALID_BD(buf_list, SPAPR_VIO_TCE_PAGE_SIZE),

                 SPAPR_VIO_TCE_PAGE_SIZE) < 0) {

        hcall_dprintf("Bad buf_list 0x" TARGET_FMT_lx "\n", buf_list);

        return H_PARAMETER;

    }

    filter_list_bd = VLAN_VALID_BD(filter_list, SPAPR_VIO_TCE_PAGE_SIZE);

    if (check_bd(dev, filter_list_bd, SPAPR_VIO_TCE_PAGE_SIZE) < 0) {

        hcall_dprintf("Bad filter_list 0x" TARGET_FMT_lx "\n", filter_list);

        return H_PARAMETER;

    }

    if (!(rec_queue & VLAN_BD_VALID)

        || (check_bd(dev, rec_queue, VLAN_RQ_ALIGNMENT) < 0)) {

        hcall_dprintf("Bad receive queue\n");

        return H_PARAMETER;

    }

    dev->buf_list = buf_list;

    sdev->signal_state = 0;

    rec_queue &= ~VLAN_BD_TOGGLE;

    /* Initialize the buffer list */

    stq_tce(sdev, buf_list, rec_queue);

    stq_tce(sdev, buf_list + 8, filter_list_bd);

    spapr_tce_dma_zero(sdev, buf_list + VLAN_RX_BDS_OFF,

                       SPAPR_VIO_TCE_PAGE_SIZE - VLAN_RX_BDS_OFF);

    dev->add_buf_ptr = VLAN_RX_BDS_OFF - 8;

    dev->use_buf_ptr = VLAN_RX_BDS_OFF - 8;

    dev->rx_bufs = 0;

    dev->rxq_ptr = 0;

    /* Initialize the receive queue */

    spapr_tce_dma_zero(sdev, VLAN_BD_ADDR(rec_queue), VLAN_BD_LEN(rec_queue));

    dev->isopen = 1;

    return H_SUCCESS;

}


av_cold void ff_psy_preprocess_end(struct FFPsyPreprocessContext *ctx)

{

    int i;

    ff_iir_filter_free_coeffs(ctx->fcoeffs);

    if (ctx->fstate)

        for (i = 0; i < ctx->avctx->channels; i++)

            ff_iir_filter_free_state(ctx->fstate[i]);

    av_freep(&ctx->fstate);

}


static int bdrv_open_common(BlockDriverState *bs, const char *filename,

    int flags, BlockDriver *drv)

{

    int ret, open_flags;

    assert(drv != NULL);

    bs->file = NULL;

    bs->total_sectors = 0;

    bs->is_temporary = 0;

    bs->encrypted = 0;

    bs->valid_key = 0;

    bs->open_flags = flags;

    /* buffer_alignment defaulted to 512, drivers can change this value */

    bs->buffer_alignment = 512;

    pstrcpy(bs->filename, sizeof(bs->filename), filename);

    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {

        return -ENOTSUP;

    }

    bs->drv = drv;

    bs->opaque = qemu_mallocz(drv->instance_size);

    /*

     * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a

     * write cache to the guest.  We do need the fdatasync to flush

     * out transactions for block allocations, and we maybe have a

     * volatile write cache in our backing device to deal with.

     */

    if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))

        bs->enable_write_cache = 1;

    /*

     * Clear flags that are internal to the block layer before opening the

     * image.

     */

    open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);

    /*

     * Snapshots should be writeable.

     */

    if (bs->is_temporary) {

        open_flags |= BDRV_O_RDWR;

    }

    /* Open the image, either directly or using a protocol */

    if (drv->bdrv_file_open) {

        ret = drv->bdrv_file_open(bs, filename, open_flags);

    } else {

        ret = bdrv_file_open(&bs->file, filename, open_flags);

        if (ret >= 0) {

            ret = drv->bdrv_open(bs, open_flags);

        }

    }

    if (ret < 0) {

        goto free_and_fail;

    }

    bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);

    ret = refresh_total_sectors(bs, bs->total_sectors);

    if (ret < 0) {

        goto free_and_fail;

    }

#ifndef _WIN32

    if (bs->is_temporary) {

        unlink(filename);

    }

#endif

    return 0;

free_and_fail:

    if (bs->file) {

        bdrv_delete(bs->file);

        bs->file = NULL;

    }

    qemu_free(bs->opaque);

    bs->opaque = NULL;

    bs->drv = NULL;

    return ret;

}


void ff_vp3_idct_put_altivec(uint8_t *dst, int stride, DCTELEM block[64])

{

    vec_u8 t;

    IDCT_START

    // pixels are signed; so add 128*16 in addition to the normal 8

    vec_s16 v2048 = vec_sl(vec_splat_s16(1), vec_splat_u16(11));

    eight = vec_add(eight, v2048);

    IDCT_1D(NOP, NOP)

    TRANSPOSE8(b0, b1, b2, b3, b4, b5, b6, b7);

    IDCT_1D(ADD8, SHIFT4)

#define PUT(a)\

    t = vec_packsu(a, a);\

    vec_ste((vec_u32)t, 0, (unsigned int *)dst);\

    vec_ste((vec_u32)t, 4, (unsigned int *)dst);

    PUT(b0)     dst += stride;

    PUT(b1)     dst += stride;

    PUT(b2)     dst += stride;

    PUT(b3)     dst += stride;

    PUT(b4)     dst += stride;

    PUT(b5)     dst += stride;

    PUT(b6)     dst += stride;

    PUT(b7)

}


static void lowpass16(WaveformContext *s, AVFrame *in, AVFrame *out,

                      int component, int intensity, int offset, int column)

{

    const int plane = s->desc->comp[component].plane;

    const int mirror = s->mirror;

    const int is_chroma = (component == 1 || component == 2);

    const int shift_w = (is_chroma ? s->desc->log2_chroma_w : 0);

    const int shift_h = (is_chroma ? s->desc->log2_chroma_h : 0);

    const int src_linesize = in->linesize[plane] / 2;

    const int dst_linesize = out->linesize[plane] / 2;

    const int dst_signed_linesize = dst_linesize * (mirror == 1 ? -1 : 1);

    const int limit = s->size - 1;

    const int max = limit - intensity;

    const int src_h = FF_CEIL_RSHIFT(in->height, shift_h);

    const int src_w = FF_CEIL_RSHIFT(in->width, shift_w);

    const uint16_t *src_data = (const uint16_t *)in->data[plane];

    uint16_t *dst_data = (uint16_t *)out->data[plane] + (column ? (offset >> shift_h) * dst_linesize : offset >> shift_w);

    uint16_t * const dst_bottom_line = dst_data + dst_linesize * ((s->size >> shift_h) - 1);

    uint16_t * const dst_line = (mirror ? dst_bottom_line : dst_data);

    const uint16_t *p;

    int y;

    if (!column && mirror)

        dst_data += s->size >> shift_w;

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

        const uint16_t *src_data_end = src_data + src_w;

        uint16_t *dst = dst_line;

        for (p = src_data; p < src_data_end; p++) {

            uint16_t *target;

            int v = FFMIN(*p, limit);

            if (column) {

                target = dst++ + dst_signed_linesize * (v >> shift_h);

            } else {

                if (mirror)

                    target = dst_data - (v >> shift_w) - 1;

                else

                    target = dst_data + (v >> shift_w);

            }

            update16(target, max, intensity, limit);

        }

        src_data += src_linesize;

        dst_data += dst_linesize;

    }

    envelope16(s, out, plane, plane);

}


static int qemu_dup_flags(int fd, int flags)

{

    int ret;

    int serrno;

    int dup_flags;

    int setfl_flags;

#ifdef F_DUPFD_CLOEXEC

    ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);

#else

    ret = dup(fd);

    if (ret != -1) {

        qemu_set_cloexec(ret);

    }

#endif

    if (ret == -1) {

        goto fail;

    }

    dup_flags = fcntl(ret, F_GETFL);

    if (dup_flags == -1) {

        goto fail;

    }

    if ((flags & O_SYNC) != (dup_flags & O_SYNC)) {

        errno = EINVAL;

        goto fail;

    }

    /* Set/unset flags that we can with fcntl */

    setfl_flags = O_APPEND | O_ASYNC | O_NONBLOCK;

#ifdef O_NOATIME

    setfl_flags |= O_NOATIME;

#endif

#ifdef O_DIRECT

    setfl_flags |= O_DIRECT;

#endif

    dup_flags &= ~setfl_flags;

    dup_flags |= (flags & setfl_flags);

    if (fcntl(ret, F_SETFL, dup_flags) == -1) {

        goto fail;

    }

    /* Truncate the file in the cases that open() would truncate it */

    if (flags & O_TRUNC ||

            ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))) {

        if (ftruncate(ret, 0) == -1) {

            goto fail;

        }

    }

    return ret;

fail:

    serrno = errno;

    if (ret != -1) {

        close(ret);

    }

    errno = serrno;

    return -1;

}


void bdrv_query_image_info(BlockDriverState *bs,

                           ImageInfo **p_info,

                           Error **errp)

{

    int64_t size;

    const char *backing_filename;

    BlockDriverInfo bdi;

    int ret;

    Error *err = NULL;

    ImageInfo *info;

    size = bdrv_getlength(bs);

    if (size < 0) {

        error_setg_errno(errp, -size, "Can't get size of device '%s'",

                         bdrv_get_device_name(bs));

        return;

    }

    info = g_new0(ImageInfo, 1);

    info->filename        = g_strdup(bs->filename);

    info->format          = g_strdup(bdrv_get_format_name(bs));

    info->virtual_size    = size;

    info->actual_size     = bdrv_get_allocated_file_size(bs);

    info->has_actual_size = info->actual_size >= 0;

    if (bdrv_is_encrypted(bs)) {

        info->encrypted = true;

        info->has_encrypted = true;

    }

    if (bdrv_get_info(bs, &bdi) >= 0) {

        if (bdi.cluster_size != 0) {

            info->cluster_size = bdi.cluster_size;

            info->has_cluster_size = true;

        }

        info->dirty_flag = bdi.is_dirty;

        info->has_dirty_flag = true;

    }

    info->format_specific     = bdrv_get_specific_info(bs);

    info->has_format_specific = info->format_specific != NULL;

    backing_filename = bs->backing_file;

    if (backing_filename[0] != '\0') {

        char *backing_filename2 = g_malloc0(1024);

        info->backing_filename = g_strdup(backing_filename);

        info->has_backing_filename = true;

        bdrv_get_full_backing_filename(bs, backing_filename2, 1024, &err);

        if (err) {

            error_propagate(errp, err);

            qapi_free_ImageInfo(info);

            g_free(backing_filename2);

            return;

        }

        if (strcmp(backing_filename, backing_filename2) != 0) {

            info->full_backing_filename =

                        g_strdup(backing_filename2);

            info->has_full_backing_filename = true;

        }

        if (bs->backing_format[0]) {

            info->backing_filename_format = g_strdup(bs->backing_format);

            info->has_backing_filename_format = true;

        }

        g_free(backing_filename2);

    }

    ret = bdrv_query_snapshot_info_list(bs, &info->snapshots, &err);

    switch (ret) {

    case 0:

        if (info->snapshots) {

            info->has_snapshots = true;

        }

        break;

    /* recoverable error */

    case -ENOMEDIUM:

    case -ENOTSUP:

        error_free(err);

        break;

    default:

        error_propagate(errp, err);

        qapi_free_ImageInfo(info);

        return;

    }

    *p_info = info;

}


static int vnc_set_x509_credential(VncDisplay *vs,

				   const char *certdir,

				   const char *filename,

				   char **cred,

				   int ignoreMissing)

{

    struct stat sb;

    if (*cred) {

	qemu_free(*cred);

	*cred = NULL;

    }

    *cred = qemu_malloc(strlen(certdir) + strlen(filename) + 2);

    strcpy(*cred, certdir);

    strcat(*cred, "/");

    strcat(*cred, filename);

    VNC_DEBUG("Check %s\n", *cred);

    if (stat(*cred, &sb) < 0) {

	qemu_free(*cred);

	*cred = NULL;

	if (ignoreMissing && errno == ENOENT)

	    return 0;

	return -1;

    }

    return 0;

}


void stw_le_phys(target_phys_addr_t addr, uint32_t val)

{

    stw_phys_internal(addr, val, DEVICE_LITTLE_ENDIAN);

}


const char *qdev_fw_name(DeviceState *dev)

{

    DeviceClass *dc = DEVICE_GET_CLASS(dev);

    if (dc->fw_name) {

        return dc->fw_name;

    } else if (dc->alias) {

        return dc->alias;

    }

    return object_get_typename(OBJECT(dev));

}


static inline void gen_op_eval_fblg(TCGv dst, TCGv src,

                                    unsigned int fcc_offset)

{

    gen_mov_reg_FCC0(dst, src, fcc_offset);

    gen_mov_reg_FCC1(cpu_tmp0, src, fcc_offset);

    tcg_gen_xor_tl(dst, dst, cpu_tmp0);

}


uint32_t omap_badwidth_read32(void *opaque, target_phys_addr_t addr)

{

    OMAP_32B_REG(addr);

    return 0;

}


SocketAddressLegacy *socket_parse(const char *str, Error **errp)

{

    SocketAddressLegacy *addr;

    addr = g_new0(SocketAddressLegacy, 1);

    if (strstart(str, "unix:", NULL)) {

        if (str[5] == '\0') {

            error_setg(errp, "invalid Unix socket address");

            goto fail;

        } else {

            addr->type = SOCKET_ADDRESS_LEGACY_KIND_UNIX;

            addr->u.q_unix.data = g_new(UnixSocketAddress, 1);

            addr->u.q_unix.data->path = g_strdup(str + 5);

        }

    } else if (strstart(str, "fd:", NULL)) {

        if (str[3] == '\0') {

            error_setg(errp, "invalid file descriptor address");

            goto fail;

        } else {

            addr->type = SOCKET_ADDRESS_LEGACY_KIND_FD;

            addr->u.fd.data = g_new(String, 1);

            addr->u.fd.data->str = g_strdup(str + 3);

        }

    } else if (strstart(str, "vsock:", NULL)) {

        addr->type = SOCKET_ADDRESS_LEGACY_KIND_VSOCK;

        addr->u.vsock.data = g_new(VsockSocketAddress, 1);

        if (vsock_parse(addr->u.vsock.data, str + strlen("vsock:"), errp)) {

            goto fail;

        }

    } else {

        addr->type = SOCKET_ADDRESS_LEGACY_KIND_INET;

        addr->u.inet.data = g_new(InetSocketAddress, 1);

        if (inet_parse(addr->u.inet.data, str, errp)) {

            goto fail;

        }

    }

    return addr;

fail:

    qapi_free_SocketAddressLegacy(addr);

    return NULL;

}


static void do_info_cpus(Monitor *mon, QObject **ret_data)

{

    CPUState *env;

    QList *cpu_list;

    cpu_list = qlist_new();

    /* just to set the default cpu if not already done */

    mon_get_cpu();

    for(env = first_cpu; env != NULL; env = env->next_cpu) {

        QDict *cpu;

        QObject *obj;

        cpu_synchronize_state(env);

        obj = qobject_from_jsonf("{ 'CPU': %d, 'current': %i, 'halted': %i }",

                                 env->cpu_index, env == mon->mon_cpu,

                                 env->halted);

        assert(obj != NULL);

        cpu = qobject_to_qdict(obj);

#if defined(TARGET_I386)

        qdict_put(cpu, "pc", qint_from_int(env->eip + env->segs[R_CS].base));

#elif defined(TARGET_PPC)

        qdict_put(cpu, "nip", qint_from_int(env->nip));

#elif defined(TARGET_SPARC)

        qdict_put(cpu, "pc", qint_from_int(env->pc));

        qdict_put(cpu, "npc", qint_from_int(env->npc));

#elif defined(TARGET_MIPS)

        qdict_put(cpu, "PC", qint_from_int(env->active_tc.PC));

#endif

        qlist_append(cpu_list, cpu);

    }

    *ret_data = QOBJECT(cpu_list);

}


void slirp_init(int restricted, const char *special_ip)

{

    //    debug_init("/tmp/slirp.log", DEBUG_DEFAULT);

#ifdef _WIN32

    {

        WSADATA Data;

        WSAStartup(MAKEWORD(2,0), &Data);

	atexit(slirp_cleanup);

    }

#endif

    link_up = 1;

    slirp_restrict = restricted;

    if_init();

    ip_init();

    /* Initialise mbufs *after* setting the MTU */

    m_init();

    /* set default addresses */

    inet_aton("127.0.0.1", &loopback_addr);

    if (get_dns_addr(&dns_addr) < 0) {

        dns_addr = loopback_addr;

        fprintf (stderr, "Warning: No DNS servers found\n");

    }

    if (special_ip)

        slirp_special_ip = special_ip;

    inet_aton(slirp_special_ip, &special_addr);

    alias_addr.s_addr = special_addr.s_addr | htonl(CTL_ALIAS);

    getouraddr();

    register_savevm("slirp", 0, 1, slirp_state_save, slirp_state_load, NULL);

}


static void test_io_channel(bool async,

                            SocketAddressLegacy *listen_addr,

                            SocketAddressLegacy *connect_addr,

                            bool passFD)

{

    QIOChannel *src, *dst;

    QIOChannelTest *test;

    if (async) {

        test_io_channel_setup_async(listen_addr, connect_addr, &src, &dst);

        g_assert(!passFD ||

                 qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(!passFD ||

                 qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_SHUTDOWN));

        g_assert(qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_SHUTDOWN));

        test = qio_channel_test_new();

        qio_channel_test_run_threads(test, true, src, dst);

        qio_channel_test_validate(test);

        object_unref(OBJECT(src));

        object_unref(OBJECT(dst));

        test_io_channel_setup_async(listen_addr, connect_addr, &src, &dst);

        g_assert(!passFD ||

                 qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(!passFD ||

                 qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_SHUTDOWN));

        g_assert(qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_SHUTDOWN));

        test = qio_channel_test_new();

        qio_channel_test_run_threads(test, false, src, dst);

        qio_channel_test_validate(test);

        object_unref(OBJECT(src));

        object_unref(OBJECT(dst));

    } else {

        test_io_channel_setup_sync(listen_addr, connect_addr, &src, &dst);

        g_assert(!passFD ||

                 qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(!passFD ||

                 qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_SHUTDOWN));

        g_assert(qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_SHUTDOWN));

        test = qio_channel_test_new();

        qio_channel_test_run_threads(test, true, src, dst);

        qio_channel_test_validate(test);

        object_unref(OBJECT(src));

        object_unref(OBJECT(dst));

        test_io_channel_setup_sync(listen_addr, connect_addr, &src, &dst);

        g_assert(!passFD ||

                 qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(!passFD ||

                 qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_SHUTDOWN));

        g_assert(qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_SHUTDOWN));

        test = qio_channel_test_new();

        qio_channel_test_run_threads(test, false, src, dst);

        qio_channel_test_validate(test);

        object_unref(OBJECT(src));

        object_unref(OBJECT(dst));

    }

}


static int v9fs_synth_name_to_path(FsContext *ctx, V9fsPath *dir_path,

                                   const char *name, V9fsPath *target)

{

    V9fsSynthNode *node;

    V9fsSynthNode *dir_node;

    /* "." and ".." are not allowed */

    if (!strcmp(name, ".") || !strcmp(name, "..")) {

        errno = EINVAL;

        return -1;

    }

    if (!dir_path) {

        dir_node = &v9fs_synth_root;

    } else {

        dir_node = *(V9fsSynthNode **)dir_path->data;

    }

    if (!strcmp(name, "/")) {

        node = dir_node;

        goto out;

    }

    /* search for the name in the childern */

    rcu_read_lock();

    QLIST_FOREACH(node, &dir_node->child, sibling) {

        if (!strcmp(node->name, name)) {

            break;

        }

    }

    rcu_read_unlock();

    if (!node) {

        errno = ENOENT;

        return -1;

    }

out:

    /* Copy the node pointer to fid */

    target->data = g_malloc(sizeof(void *));

    memcpy(target->data, &node, sizeof(void *));

    target->size = sizeof(void *);

    return 0;

}


static void virtio_ccw_9p_realize(VirtioCcwDevice *ccw_dev, Error **errp)

{

    V9fsCCWState *dev = VIRTIO_9P_CCW(ccw_dev);

    DeviceState *vdev = DEVICE(&dev->vdev);

    Error *err = NULL;

    qdev_set_parent_bus(vdev, BUS(&ccw_dev->bus));

    object_property_set_bool(OBJECT(vdev), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

    }

}


static V9fsFidState *lookup_fid(V9fsState *s, int32_t fid)

{

    V9fsFidState *f;

    for (f = s->fid_list; f; f = f->next) {

        if (f->fid == fid) {

            v9fs_do_setuid(s, f->uid);

            return f;

        }

    }

    return NULL;

}


static int hda_audio_post_load(void *opaque, int version)

{

    HDAAudioState *a = opaque;

    HDAAudioStream *st;

    int i;

    dprint(a, 1, "%s\n", __FUNCTION__);

    if (version == 1) {

        /* assume running_compat[] is for output streams */

        for (i = 0; i < ARRAY_SIZE(a->running_compat); i++)

            a->running_real[16 + i] = a->running_compat[i];

    }

    for (i = 0; i < ARRAY_SIZE(a->st); i++) {

        st = a->st + i;

        if (st->node == NULL)

            continue;

        hda_codec_parse_fmt(st->format, &st->as);

        hda_audio_setup(st);

        hda_audio_set_amp(st);

        hda_audio_set_running(st, a->running_real[st->output * 16 + st->stream]);

    }

    return 0;

}


static av_cold int dfa_decode_init(AVCodecContext *avctx)

{

    DfaContext *s = avctx->priv_data;

    int ret;

    avctx->pix_fmt = PIX_FMT_PAL8;

    if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)

        return ret;

    s->frame_buf = av_mallocz(avctx->width * avctx->height + AV_LZO_OUTPUT_PADDING);

    if (!s->frame_buf)

        return AVERROR(ENOMEM);

    return 0;

}


static int mpeg_field_start(MpegEncContext *s){

    AVCodecContext *avctx= s->avctx;

    Mpeg1Context *s1 = (Mpeg1Context*)s;

    /* start frame decoding */

    if(s->first_field || s->picture_structure==PICT_FRAME){

        if(MPV_frame_start(s, avctx) < 0)

            return -1;

        ff_er_frame_start(s);

        /* first check if we must repeat the frame */

        s->current_picture_ptr->repeat_pict = 0;

        if (s->repeat_first_field) {

            if (s->progressive_sequence) {

                if (s->top_field_first)

                    s->current_picture_ptr->repeat_pict = 4;

                else

                    s->current_picture_ptr->repeat_pict = 2;

            } else if (s->progressive_frame) {

                s->current_picture_ptr->repeat_pict = 1;

            }

        }

        *s->current_picture_ptr->pan_scan= s1->pan_scan;

    }else{ //second field

            int i;

            if(!s->current_picture_ptr){

                av_log(s->avctx, AV_LOG_ERROR, "first field missing\n");

                return -1;

            }

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

                s->current_picture.data[i] = s->current_picture_ptr->data[i];

                if(s->picture_structure == PICT_BOTTOM_FIELD){

                    s->current_picture.data[i] += s->current_picture_ptr->linesize[i];

                }

            }

    }

#if CONFIG_MPEG_XVMC_DECODER

// MPV_frame_start will call this function too,

// but we need to call it on every field

    if(s->avctx->xvmc_acceleration)

         ff_xvmc_field_start(s,avctx);

#endif

    return 0;

}


static void virtio_scsi_handle_cmd(VirtIODevice *vdev, VirtQueue *vq)

{

    /* use non-QOM casts in the data path */

    VirtIOSCSI *s = (VirtIOSCSI *)vdev;

    VirtIOSCSIReq *req, *next;

    QTAILQ_HEAD(, VirtIOSCSIReq) reqs = QTAILQ_HEAD_INITIALIZER(reqs);

    if (s->ctx && !s->dataplane_started) {

        virtio_scsi_dataplane_start(s);

        return;

    }

    while ((req = virtio_scsi_pop_req(s, vq))) {

        if (virtio_scsi_handle_cmd_req_prepare(s, req)) {

            QTAILQ_INSERT_TAIL(&reqs, req, next);

        }

    }

    QTAILQ_FOREACH_SAFE(req, &reqs, next, next) {

        virtio_scsi_handle_cmd_req_submit(s, req);

    }

}


static inline void RENAME(bgr24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, int width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    RENAME(bgr24ToUV_mmx)(dstU, dstV, src1, width, PIX_FMT_BGR24);

#else

    int i;

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

        int b= src1[3*i + 0];

        int g= src1[3*i + 1];

        int r= src1[3*i + 2];

        dstU[i]= (RU*r + GU*g + BU*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;

        dstV[i]= (RV*r + GV*g + BV*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;

    }

#endif /* COMPILE_TEMPLATE_MMX */

    assert(src1 == src2);

}


static QEMUFile *open_test_file(bool write)

{

    int fd = dup(temp_fd);

    QIOChannel *ioc;

    lseek(fd, 0, SEEK_SET);

    if (write) {

        g_assert_cmpint(ftruncate(fd, 0), ==, 0);

    }

    ioc = QIO_CHANNEL(qio_channel_file_new_fd(fd));

    if (write) {

        return qemu_fopen_channel_output(ioc);

    } else {

        return qemu_fopen_channel_input(ioc);

    }

}


static void hScale16_c(SwsContext *c, int16_t *_dst, int dstW, const uint8_t *_src,

                       const int16_t *filter,

                       const int16_t *filterPos, int filterSize)

{

    int i;

    int32_t *dst = (int32_t *) _dst;

    const uint16_t *src = (const uint16_t *) _src;

    int bits = av_pix_fmt_descriptors[c->srcFormat].comp[0].depth_minus1;

    int sh = (bits <= 7) ? 11 : (bits - 4);

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

        int j;

        int srcPos = filterPos[i];

        unsigned int val = 0;

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

            val += src[srcPos + j] * filter[filterSize * i + j];

        }

        // filter=14 bit, input=16 bit, output=30 bit, >> 11 makes 19 bit

        dst[i] = FFMIN(val >> sh, (1 << 19) - 1);

    }

}


static uint64_t kvmppc_read_int_cpu_dt(const char *propname)

{

    char buf[PATH_MAX];

    union {

        uint32_t v32;

        uint64_t v64;

    } u;

    FILE *f;

    int len;

    if (kvmppc_find_cpu_dt(buf, sizeof(buf))) {

        return -1;

    }

    strncat(buf, "/", sizeof(buf) - strlen(buf));

    strncat(buf, propname, sizeof(buf) - strlen(buf));

    f = fopen(buf, "rb");

    if (!f) {

        return -1;

    }

    len = fread(&u, 1, sizeof(u), f);

    fclose(f);

    switch (len) {

    case 4:

        /* property is a 32-bit quantity */

        return be32_to_cpu(u.v32);

    case 8:

        return be64_to_cpu(u.v64);

    }

    return 0;

}


void icp_pit_init(uint32_t base, qemu_irq *pic, int irq)

{

    int iomemtype;

    icp_pit_state *s;

    s = (icp_pit_state *)qemu_mallocz(sizeof(icp_pit_state));

    s->base = base;

    /* Timer 0 runs at the system clock speed (40MHz).  */

    s->timer[0] = arm_timer_init(40000000, pic[irq]);

    /* The other two timers run at 1MHz.  */

    s->timer[1] = arm_timer_init(1000000, pic[irq + 1]);

    s->timer[2] = arm_timer_init(1000000, pic[irq + 2]);

    iomemtype = cpu_register_io_memory(0, icp_pit_readfn,

                                       icp_pit_writefn, s);

    cpu_register_physical_memory(base, 0x00000fff, iomemtype);

    /* ??? Save/restore.  */

}


static int adts_write_header(AVFormatContext *s)

{

    ADTSContext *adts = s->priv_data;

    AVCodecContext *avc = s->streams[0]->codec;

    if(avc->extradata_size > 0)

        decode_extradata(adts, avc->extradata, avc->extradata_size);

    return 0;

}


start_xmit(E1000State *s)

{

    PCIDevice *d = PCI_DEVICE(s);

    dma_addr_t base;

    struct e1000_tx_desc desc;

    uint32_t tdh_start = s->mac_reg[TDH], cause = E1000_ICS_TXQE;

    if (!(s->mac_reg[TCTL] & E1000_TCTL_EN)) {

        DBGOUT(TX, "tx disabled\n");

        return;

    }

    while (s->mac_reg[TDH] != s->mac_reg[TDT]) {

        base = tx_desc_base(s) +

               sizeof(struct e1000_tx_desc) * s->mac_reg[TDH];

        pci_dma_read(d, base, &desc, sizeof(desc));

        DBGOUT(TX, "index %d: %p : %x %x\n", s->mac_reg[TDH],

               (void *)(intptr_t)desc.buffer_addr, desc.lower.data,

               desc.upper.data);

        process_tx_desc(s, &desc);

        cause |= txdesc_writeback(s, base, &desc);

        if (++s->mac_reg[TDH] * sizeof(desc) >= s->mac_reg[TDLEN])

            s->mac_reg[TDH] = 0;

        /*

         * the following could happen only if guest sw assigns

         * bogus values to TDT/TDLEN.

         * there's nothing too intelligent we could do about this.

         */

        if (s->mac_reg[TDH] == tdh_start) {

            DBGOUT(TXERR, "TDH wraparound @%x, TDT %x, TDLEN %x\n",

                   tdh_start, s->mac_reg[TDT], s->mac_reg[TDLEN]);

            break;

        }

    }

    set_ics(s, 0, cause);

}


static void vector_fmul_window_mips(float *dst, const float *src0,

                                    const float *src1, const float *win, int len)

{

    float * dst_j, *win_j, *src0_i, *src1_j, *dst_i, *win_i;

    float temp, temp1, temp2, temp3;

    float s0, s01, s1, s11;

    float wi, wi1, wi2, wi3;

    float wj, wj1, wj2, wj3;

    const float * lp_end = win + len;

    win_i  = (float *)win;

    win_j  = (float *)(win + 2 * len -1);

    src1_j = (float *)(src1 + len - 1);

    src0_i = (float *)src0;

    dst_i  = (float *)dst;

    dst_j  = (float *)(dst + 2 * len -1);

    /* loop unrolled 4 times */

    __asm__ volatile (

        "1:"

        "lwc1    %[s1],     0(%[src1_j])                \n\t"

        "lwc1    %[wi],     0(%[win_i])                 \n\t"

        "lwc1    %[wj],     0(%[win_j])                 \n\t"

        "lwc1    %[s11],   -4(%[src1_j])                \n\t"

        "lwc1    %[wi1],    4(%[win_i])                 \n\t"

        "lwc1    %[wj1],   -4(%[win_j])                 \n\t"

        "lwc1    %[s0],     0(%[src0_i])                \n\t"

        "lwc1    %[s01],    4(%[src0_i])                \n\t"

        "mul.s   %[temp],   %[s1],   %[wi]              \n\t"

        "mul.s   %[temp1],  %[s1],   %[wj]              \n\t"

        "mul.s   %[temp2],  %[s11],  %[wi1]             \n\t"

        "mul.s   %[temp3],  %[s11],  %[wj1]             \n\t"

        "lwc1    %[s1],    -8(%[src1_j])                \n\t"

        "lwc1    %[wi2],    8(%[win_i])                 \n\t"

        "lwc1    %[wj2],   -8(%[win_j])                 \n\t"

        "lwc1    %[s11],   -12(%[src1_j])               \n\t"

        "msub.s  %[temp],   %[temp],  %[s0],  %[wj]     \n\t"

        "madd.s  %[temp1],  %[temp1], %[s0],  %[wi]     \n\t"

        "msub.s  %[temp2],  %[temp2], %[s01], %[wj1]    \n\t"

        "madd.s  %[temp3],  %[temp3], %[s01], %[wi1]    \n\t"

        "lwc1    %[wi3],    12(%[win_i])                \n\t"

        "lwc1    %[wj3],   -12(%[win_j])                \n\t"

        "lwc1    %[s0],     8(%[src0_i])                \n\t"

        "lwc1    %[s01],    12(%[src0_i])               \n\t"

        "addiu   %[src1_j],-16                          \n\t"

        "addiu   %[win_i],  16                          \n\t"

        "addiu   %[win_j], -16                          \n\t"

        "addiu   %[src0_i], 16                          \n\t"

        "swc1    %[temp],   0(%[dst_i])                 \n\t" /* dst[i] = s0*wj - s1*wi; */

        "swc1    %[temp1],  0(%[dst_j])                 \n\t" /* dst[j] = s0*wi + s1*wj; */

        "swc1    %[temp2],  4(%[dst_i])                 \n\t" /* dst[i+1] = s01*wj1 - s11*wi1; */

        "swc1    %[temp3], -4(%[dst_j])                 \n\t" /* dst[j-1] = s01*wi1 + s11*wj1; */

        "mul.s   %[temp],   %[s1],    %[wi2]            \n\t"

        "mul.s   %[temp1],  %[s1],    %[wj2]            \n\t"

        "mul.s   %[temp2],  %[s11],   %[wi3]            \n\t"

        "mul.s   %[temp3],  %[s11],   %[wj3]            \n\t"

        "msub.s  %[temp],   %[temp],  %[s0],  %[wj2]    \n\t"

        "madd.s  %[temp1],  %[temp1], %[s0],  %[wi2]    \n\t"

        "msub.s  %[temp2],  %[temp2], %[s01], %[wj3]    \n\t"

        "madd.s  %[temp3],  %[temp3], %[s01], %[wi3]    \n\t"

        "swc1    %[temp],   8(%[dst_i])                 \n\t" /* dst[i+2] = s0*wj2 - s1*wi2; */

        "swc1    %[temp1], -8(%[dst_j])                 \n\t" /* dst[j-2] = s0*wi2 + s1*wj2; */

        "swc1    %[temp2],  12(%[dst_i])                \n\t" /* dst[i+2] = s01*wj3 - s11*wi3; */

        "swc1    %[temp3], -12(%[dst_j])                \n\t" /* dst[j-3] = s01*wi3 + s11*wj3; */

        "addiu   %[dst_i],  16                          \n\t"

        "addiu   %[dst_j], -16                          \n\t"

        "bne     %[win_i], %[lp_end], 1b                \n\t"

        : [temp]"=&f"(temp), [temp1]"=&f"(temp1), [temp2]"=&f"(temp2),

          [temp3]"=&f"(temp3), [src0_i]"+r"(src0_i), [win_i]"+r"(win_i),

          [src1_j]"+r"(src1_j), [win_j]"+r"(win_j), [dst_i]"+r"(dst_i),

          [dst_j]"+r"(dst_j), [s0] "=&f"(s0), [s01]"=&f"(s01), [s1] "=&f"(s1),

          [s11]"=&f"(s11), [wi] "=&f"(wi), [wj] "=&f"(wj), [wi2]"=&f"(wi2),

          [wj2]"=&f"(wj2), [wi3]"=&f"(wi3), [wj3]"=&f"(wj3), [wi1]"=&f"(wi1),

          [wj1]"=&f"(wj1)

        : [lp_end]"r"(lp_end)

        : "memory"

    );

}