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

                        int *got_frame_ptr, AVPacket *avpkt)

{

    BinkAudioContext *s = avctx->priv_data;

    AVFrame *frame      = data;

    GetBitContext *gb = &s->gb;

    int ret, consumed = 0;

    if (!get_bits_left(gb)) {

        uint8_t *buf;

        /* handle end-of-stream */

        if (!avpkt->size) {

            *got_frame_ptr = 0;

            return 0;

        }

        if (avpkt->size < 4) {

            av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");

            return AVERROR_INVALIDDATA;

        }

        buf = av_realloc(s->packet_buffer, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);

        if (!buf)

            return AVERROR(ENOMEM);

        s->packet_buffer = buf;

        memcpy(s->packet_buffer, avpkt->data, avpkt->size);

        if ((ret = init_get_bits8(gb, s->packet_buffer, avpkt->size)) < 0)

            return ret;

        consumed = avpkt->size;

        /* skip reported size */

        skip_bits_long(gb, 32);

    }

    /* get output buffer */

    frame->nb_samples = s->frame_len;

    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)

        return ret;

    if (decode_block(s, (float **)frame->extended_data,

                     avctx->codec->id == AV_CODEC_ID_BINKAUDIO_DCT)) {

        av_log(avctx, AV_LOG_ERROR, "Incomplete packet\n");

        return AVERROR_INVALIDDATA;

    }

    get_bits_align32(gb);

    frame->nb_samples = s->block_size / avctx->channels;

    *got_frame_ptr    = 1;

    return consumed;

}


static int decode_cabac_intra_mb_type(H264Context *h, int ctx_base, int intra_slice) {

    uint8_t *state= &h->cabac_state[ctx_base];

    int mb_type;

    if(intra_slice){

        MpegEncContext * const s = &h->s;

        const int mba_xy = h->left_mb_xy[0];

        const int mbb_xy = h->top_mb_xy;

        int ctx=0;

        if( h->slice_table[mba_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mba_xy] ) )

            ctx++;

        if( h->slice_table[mbb_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mbb_xy] ) )

            ctx++;

        if( get_cabac_noinline( &h->cabac, &state[ctx] ) == 0 )

            return 0;   /* I4x4 */

        state += 2;

    }else{

        if( get_cabac_noinline( &h->cabac, state ) == 0 )

            return 0;   /* I4x4 */

    }

    if( get_cabac_terminate( &h->cabac ) )

        return 25;  /* PCM */

    mb_type = 1; /* I16x16 */

    mb_type += 12 * get_cabac_noinline( &h->cabac, &state[1] ); /* cbp_luma != 0 */

    if( get_cabac_noinline( &h->cabac, &state[2] ) ) /* cbp_chroma */

        mb_type += 4 + 4 * get_cabac_noinline( &h->cabac, &state[2+intra_slice] );

    mb_type += 2 * get_cabac_noinline( &h->cabac, &state[3+intra_slice] );

    mb_type += 1 * get_cabac_noinline( &h->cabac, &state[3+2*intra_slice] );

    return mb_type;

}


static int decode_p_picture_header(VC9Context *v)

{

    /* INTERFRM, FRMCNT, RANGEREDFRM read in caller */

    int lowquant, pqindex;

    pqindex = get_bits(&v->gb, 5);

    if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)

        v->pq = pquant_table[0][pqindex];

    else

    {

        v->pq = pquant_table[v->quantizer_mode-1][pqindex];

    }

    if (pqindex < 9) v->halfpq = get_bits(&v->gb, 1);

    if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)

        v->pquantizer = get_bits(&v->gb, 1);

    av_log(v->avctx, AV_LOG_DEBUG, "P Frame: QP=%i (+%i/2)\n",

           v->pq, v->halfpq);

    if (v->extended_mv == 1) v->mvrange = get_prefix(&v->gb, 0, 3);

#if HAS_ADVANCED_PROFILE

    if (v->profile > PROFILE_MAIN)

    {

        if (v->postprocflag) v->postproc = get_bits(&v->gb, 1);

    }

    else

#endif

        if (v->multires) v->respic = get_bits(&v->gb, 2);

    lowquant = (v->pquantizer>12) ? 0 : 1;

    v->mv_mode = mv_pmode_table[lowquant][get_prefix(&v->gb, 1, 4)];

    if (v->mv_mode == MV_PMODE_INTENSITY_COMP)

    {

        v->mv_mode2 = mv_pmode_table[lowquant][get_prefix(&v->gb, 1, 3)];

        v->lumscale = get_bits(&v->gb, 6);

        v->lumshift = get_bits(&v->gb, 6);

    }

    if ((v->mv_mode == MV_PMODE_INTENSITY_COMP &&

         v->mv_mode2 == MV_PMODE_MIXED_MV)

        || v->mv_mode == MV_PMODE_MIXED_MV)

    {

        if (bitplane_decoding(v->mv_type_mb_plane, v->width_mb,

                                  v->height_mb, v) < 0)

            return -1;

    }

    if (bitplane_decoding(v->skip_mb_plane, v->width_mb,

                              v->height_mb, v) < 0)

        return -1;

    /* Hopefully this is correct for P frames */

    v->mv_diff_vlc = &vc9_mv_diff_vlc[get_bits(&v->gb, 2)];

    v->cbpcy_vlc = &vc9_cbpcy_p_vlc[get_bits(&v->gb, 2)];

    if (v->dquant)

    {

        av_log(v->avctx, AV_LOG_INFO, "VOP DQuant info\n");

        vop_dquant_decoding(v);

    }

    if (v->vstransform)

    {

        v->ttmbf = get_bits(&v->gb, 1);

        if (v->ttmbf)

        {

            v->ttfrm = get_bits(&v->gb, 2);

            av_log(v->avctx, AV_LOG_INFO, "Transform used: %ix%i\n",

                   (v->ttfrm & 2) ? 4 : 8, (v->ttfrm & 1) ? 4 : 8);

        }

    }

    /* Epilog should be done in caller */

    return 0;

}


void ff_avg_h264_qpel8_mc12_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_midh_qrt_and_aver_dst_8w_msa(src - (2 * stride) - 2,

                                          stride, dst, stride, 8, 0);

}


static void sbr_hf_assemble(float Y[2][38][64][2], const float X_high[64][40][2],

                            SpectralBandReplication *sbr, SBRData *ch_data,

                            const int e_a[2])

{

    int e, i, j, m;

    const int h_SL = 4 * !sbr->bs_smoothing_mode;

    const int kx = sbr->kx[1];

    const int m_max = sbr->m[1];

    static const float h_smooth[5] = {

        0.33333333333333,

        0.30150283239582,

        0.21816949906249,

        0.11516383427084,

        0.03183050093751,

    };

    static const int8_t phi[2][4] = {

        {  1,  0, -1,  0}, // real

        {  0,  1,  0, -1}, // imaginary

    };

    float (*g_temp)[48] = ch_data->g_temp, (*q_temp)[48] = ch_data->q_temp;

    int indexnoise = ch_data->f_indexnoise;

    int indexsine  = ch_data->f_indexsine;

    memcpy(Y[0], Y[1], sizeof(Y[0]));

    if (sbr->reset) {

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

            memcpy(g_temp[i + 2*ch_data->t_env[0]], sbr->gain[0], m_max * sizeof(sbr->gain[0][0]));

            memcpy(q_temp[i + 2*ch_data->t_env[0]], sbr->q_m[0],  m_max * sizeof(sbr->q_m[0][0]));

        }

    } else if (h_SL) {

        memcpy(g_temp[2*ch_data->t_env[0]], g_temp[2*ch_data->t_env_num_env_old], 4*sizeof(g_temp[0]));

        memcpy(q_temp[2*ch_data->t_env[0]], q_temp[2*ch_data->t_env_num_env_old], 4*sizeof(q_temp[0]));

    }

    for (e = 0; e < ch_data->bs_num_env; e++) {

        for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {

            memcpy(g_temp[h_SL + i], sbr->gain[e], m_max * sizeof(sbr->gain[0][0]));

            memcpy(q_temp[h_SL + i], sbr->q_m[e],  m_max * sizeof(sbr->q_m[0][0]));

        }

    }

    for (e = 0; e < ch_data->bs_num_env; e++) {

        for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {

            int phi_sign = (1 - 2*(kx & 1));

            if (h_SL && e != e_a[0] && e != e_a[1]) {

                for (m = 0; m < m_max; m++) {

                    const int idx1 = i + h_SL;

                    float g_filt = 0.0f;

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

                        g_filt += g_temp[idx1 - j][m] * h_smooth[j];

                    Y[1][i][m + kx][0] =

                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][0] * g_filt;

                    Y[1][i][m + kx][1] =

                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][1] * g_filt;

                }

            } else {

                for (m = 0; m < m_max; m++) {

                    const float g_filt = g_temp[i + h_SL][m];

                    Y[1][i][m + kx][0] =

                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][0] * g_filt;

                    Y[1][i][m + kx][1] =

                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][1] * g_filt;

                }

            }

            if (e != e_a[0] && e != e_a[1]) {

                for (m = 0; m < m_max; m++) {

                    indexnoise = (indexnoise + 1) & 0x1ff;

                    if (sbr->s_m[e][m]) {

                        Y[1][i][m + kx][0] +=

                            sbr->s_m[e][m] * phi[0][indexsine];

                        Y[1][i][m + kx][1] +=

                            sbr->s_m[e][m] * (phi[1][indexsine] * phi_sign);

                    } else {

                        float q_filt;

                        if (h_SL) {

                            const int idx1 = i + h_SL;

                            q_filt = 0.0f;

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

                                q_filt += q_temp[idx1 - j][m] * h_smooth[j];

                        } else {

                            q_filt = q_temp[i][m];

                        }

                        Y[1][i][m + kx][0] +=

                            q_filt * sbr_noise_table[indexnoise][0];

                        Y[1][i][m + kx][1] +=

                            q_filt * sbr_noise_table[indexnoise][1];

                    }

                    phi_sign = -phi_sign;

                }

            } else {

                indexnoise = (indexnoise + m_max) & 0x1ff;

                for (m = 0; m < m_max; m++) {

                    Y[1][i][m + kx][0] +=

                        sbr->s_m[e][m] * phi[0][indexsine];

                    Y[1][i][m + kx][1] +=

                        sbr->s_m[e][m] * (phi[1][indexsine] * phi_sign);

                    phi_sign = -phi_sign;

                }

            }

            indexsine = (indexsine + 1) & 3;

        }

    }

    ch_data->f_indexnoise = indexnoise;

    ch_data->f_indexsine  = indexsine;

}


int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)

{

    const SPS *sps = h->ps.sps;

    const int max_frame_num = 1 << sps->log2_max_frame_num;

    int field_poc[2];

    h->frame_num_offset = h->prev_frame_num_offset;

    if (h->frame_num < h->prev_frame_num)

        h->frame_num_offset += max_frame_num;

    if (sps->poc_type == 0) {

        const int max_poc_lsb = 1 << sps->log2_max_poc_lsb;

        if (h->poc_lsb < h->prev_poc_lsb &&

            h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)

            h->poc_msb = h->prev_poc_msb + max_poc_lsb;

        else if (h->poc_lsb > h->prev_poc_lsb &&

                 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)

            h->poc_msb = h->prev_poc_msb - max_poc_lsb;

        else

            h->poc_msb = h->prev_poc_msb;

        field_poc[0] =

        field_poc[1] = h->poc_msb + h->poc_lsb;

        if (h->picture_structure == PICT_FRAME)

            field_poc[1] += h->delta_poc_bottom;

    } else if (sps->poc_type == 1) {

        int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;

        int i;

        if (sps->poc_cycle_length != 0)

            abs_frame_num = h->frame_num_offset + h->frame_num;

        else

            abs_frame_num = 0;

        if (h->nal_ref_idc == 0 && abs_frame_num > 0)

            abs_frame_num--;

        expected_delta_per_poc_cycle = 0;

        for (i = 0; i < sps->poc_cycle_length; i++)

            // FIXME integrate during sps parse

            expected_delta_per_poc_cycle += sps->offset_for_ref_frame[i];

        if (abs_frame_num > 0) {

            int poc_cycle_cnt          = (abs_frame_num - 1) / sps->poc_cycle_length;

            int frame_num_in_poc_cycle = (abs_frame_num - 1) % sps->poc_cycle_length;

            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;

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

                expectedpoc = expectedpoc + sps->offset_for_ref_frame[i];

        } else

            expectedpoc = 0;

        if (h->nal_ref_idc == 0)

            expectedpoc = expectedpoc + sps->offset_for_non_ref_pic;

        field_poc[0] = expectedpoc + h->delta_poc[0];

        field_poc[1] = field_poc[0] + sps->offset_for_top_to_bottom_field;

        if (h->picture_structure == PICT_FRAME)

            field_poc[1] += h->delta_poc[1];

    } else {

        int poc = 2 * (h->frame_num_offset + h->frame_num);

        if (!h->nal_ref_idc)

            poc--;

        field_poc[0] = poc;

        field_poc[1] = poc;

    }

    if (h->picture_structure != PICT_BOTTOM_FIELD)

        pic_field_poc[0] = field_poc[0];

    if (h->picture_structure != PICT_TOP_FIELD)

        pic_field_poc[1] = field_poc[1];

    *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);

    return 0;

}


static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,

                            int64_t speed, int64_t granularity,

                            int64_t buf_size,

                            BlockdevOnError on_source_error,

                            BlockdevOnError on_target_error,

                            BlockDriverCompletionFunc *cb,

                            void *opaque, Error **errp,

                            const BlockJobDriver *driver,

                            bool is_none_mode, BlockDriverState *base)

{

    MirrorBlockJob *s;

    if (granularity == 0) {

        /* Choose the default granularity based on the target file's cluster

         * size, clamped between 4k and 64k.  */

        BlockDriverInfo bdi;

        if (bdrv_get_info(target, &bdi) >= 0 && bdi.cluster_size != 0) {

            granularity = MAX(4096, bdi.cluster_size);

            granularity = MIN(65536, granularity);

        } else {

            granularity = 65536;

        }

    }

    assert ((granularity & (granularity - 1)) == 0);

    if ((on_source_error == BLOCKDEV_ON_ERROR_STOP ||

         on_source_error == BLOCKDEV_ON_ERROR_ENOSPC) &&

        !bdrv_iostatus_is_enabled(bs)) {

        error_set(errp, QERR_INVALID_PARAMETER, "on-source-error");

        return;

    }

    s = block_job_create(driver, bs, speed, cb, opaque, errp);

    if (!s) {

        return;

    }

    s->on_source_error = on_source_error;

    s->on_target_error = on_target_error;

    s->target = target;

    s->is_none_mode = is_none_mode;

    s->base = base;

    s->granularity = granularity;

    s->buf_size = MAX(buf_size, granularity);

    s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity);

    bdrv_set_enable_write_cache(s->target, true);

    bdrv_set_on_error(s->target, on_target_error, on_target_error);

    bdrv_iostatus_enable(s->target);

    s->common.co = qemu_coroutine_create(mirror_run);

    trace_mirror_start(bs, s, s->common.co, opaque);

    qemu_coroutine_enter(s->common.co, s);

}


static int sdp_parse_rtpmap(AVFormatContext *s,

                            AVStream *st, RTSPStream *rtsp_st,

                            int payload_type, const char *p)

{

    AVCodecContext *codec = st->codec;

    char buf[256];

    int i;

    AVCodec *c;

    const char *c_name;

    /* See if we can handle this kind of payload.

     * The space should normally not be there but some Real streams or

     * particular servers ("RealServer Version 6.1.3.970", see issue 1658)

     * have a trailing space. */

    get_word_sep(buf, sizeof(buf), "/ ", &p);

    if (payload_type < RTP_PT_PRIVATE) {

        /* We are in a standard case

         * (from http://www.iana.org/assignments/rtp-parameters). */

        codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);

    }

    if (codec->codec_id == AV_CODEC_ID_NONE) {

        RTPDynamicProtocolHandler *handler =

            ff_rtp_handler_find_by_name(buf, codec->codec_type);

        init_rtp_handler(handler, rtsp_st, st);

        /* If no dynamic handler was found, check with the list of standard

         * allocated types, if such a stream for some reason happens to

         * use a private payload type. This isn't handled in rtpdec.c, since

         * the format name from the rtpmap line never is passed into rtpdec. */

        if (!rtsp_st->dynamic_handler)

            codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);

    }

    c = avcodec_find_decoder(codec->codec_id);

    if (c && c->name)

        c_name = c->name;

    else

        c_name = "(null)";

    get_word_sep(buf, sizeof(buf), "/", &p);

    i = atoi(buf);

    switch (codec->codec_type) {

    case AVMEDIA_TYPE_AUDIO:

        av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);

        codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;

        codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;

        if (i > 0) {

            codec->sample_rate = i;

            avpriv_set_pts_info(st, 32, 1, codec->sample_rate);

            get_word_sep(buf, sizeof(buf), "/", &p);

            i = atoi(buf);

            if (i > 0)

                codec->channels = i;

        }

        av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",

               codec->sample_rate);

        av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",

               codec->channels);

        break;

    case AVMEDIA_TYPE_VIDEO:

        av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);

        if (i > 0)

            avpriv_set_pts_info(st, 32, 1, i);

        break;

    default:

        break;

    }

    if (rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->init)

        rtsp_st->dynamic_handler->init(s, st->index,

                                       rtsp_st->dynamic_protocol_context);

    return 0;

}


void ff_dsputil_init_ppc(DSPContext* c, AVCodecContext *avctx)

{

    const int high_bit_depth = avctx->bits_per_raw_sample > 8;

    // Common optimizations whether AltiVec is available or not

    c->prefetch = prefetch_ppc;

    if (!high_bit_depth) {

    switch (check_dcbzl_effect()) {

        case 32:

            c->clear_blocks = clear_blocks_dcbz32_ppc;

            break;

        case 128:

            c->clear_blocks = clear_blocks_dcbz128_ppc;

            break;

        default:

            break;

    }

    }

#if HAVE_ALTIVEC

    if(CONFIG_H264_DECODER) ff_dsputil_h264_init_ppc(c, avctx);

    if (av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) {

        ff_dsputil_init_altivec(c, avctx);

        ff_float_init_altivec(c, avctx);

        ff_int_init_altivec(c, avctx);

        c->gmc1 = ff_gmc1_altivec;

#if CONFIG_ENCODERS

        if (avctx->bits_per_raw_sample <= 8 &&

            (avctx->dct_algo == FF_DCT_AUTO ||

             avctx->dct_algo == FF_DCT_ALTIVEC)) {

            c->fdct = ff_fdct_altivec;

        }

#endif //CONFIG_ENCODERS

        if (avctx->bits_per_raw_sample <= 8) {

            if ((avctx->idct_algo == FF_IDCT_AUTO) ||

                (avctx->idct_algo == FF_IDCT_ALTIVEC)) {

                c->idct_put = ff_idct_put_altivec;

                c->idct_add = ff_idct_add_altivec;

                c->idct_permutation_type = FF_TRANSPOSE_IDCT_PERM;

            }else if((CONFIG_VP3_DECODER || CONFIG_VP5_DECODER || CONFIG_VP6_DECODER) &&

                     avctx->idct_algo==FF_IDCT_VP3){

                c->idct_put = ff_vp3_idct_put_altivec;

                c->idct_add = ff_vp3_idct_add_altivec;

                c->idct     = ff_vp3_idct_altivec;

                c->idct_permutation_type = FF_TRANSPOSE_IDCT_PERM;

            }

        }

    }

#endif /* HAVE_ALTIVEC */

}


bool hbitmap_get(const HBitmap *hb, uint64_t item)

{

    /* Compute position and bit in the last layer.  */

    uint64_t pos = item >> hb->granularity;

    unsigned long bit = 1UL << (pos & (BITS_PER_LONG - 1));

    return (hb->levels[HBITMAP_LEVELS - 1][pos >> BITS_PER_LEVEL] & bit) != 0;

}


static int ffm_is_avail_data(AVFormatContext *s, int size)

{

    FFMContext *ffm = s->priv_data;

    int64_t pos, avail_size;

    int len;

    len = ffm->packet_end - ffm->packet_ptr;

    if (size <= len)

        return 1;

    pos = avio_tell(s->pb);

    if (!ffm->write_index) {

        if (pos == ffm->file_size)

            return AVERROR_EOF;

        avail_size = ffm->file_size - pos;

    } else {

    if (pos == ffm->write_index) {

        /* exactly at the end of stream */

        if (ffm->server_attached)

            return AVERROR(EAGAIN);

        else

            return AVERROR_INVALIDDATA;

    } else if (pos < ffm->write_index) {

        avail_size = ffm->write_index - pos;

    } else {

        avail_size = (ffm->file_size - pos) + (ffm->write_index - FFM_PACKET_SIZE);

    }

    }

    avail_size = (avail_size / ffm->packet_size) * (ffm->packet_size - FFM_HEADER_SIZE) + len;

    if (size <= avail_size)

        return 1;

    else if (ffm->server_attached)

        return AVERROR(EAGAIN);

    else

        return AVERROR_INVALIDDATA;

}


int fw_cfg_add_bytes(FWCfgState *s, uint16_t key, uint8_t *data, uint32_t len)

{

    int arch = !!(key & FW_CFG_ARCH_LOCAL);

    key &= FW_CFG_ENTRY_MASK;

    if (key >= FW_CFG_MAX_ENTRY)

        return 0;

    s->entries[arch][key].data = data;

    s->entries[arch][key].len = len;

    return 1;

}


static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)

{

    BDRVQcowState *s = bs->opaque;

    int flags = s->flags;

    AES_KEY aes_encrypt_key;

    AES_KEY aes_decrypt_key;

    uint32_t crypt_method = 0;

    QDict *options;

    Error *local_err = NULL;

    int ret;

    /*

     * Backing files are read-only which makes all of their metadata immutable,

     * that means we don't have to worry about reopening them here.

     */

    if (s->crypt_method) {

        crypt_method = s->crypt_method;

        memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));

        memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));

    }

    qcow2_close(bs);

    bdrv_invalidate_cache(bs->file, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    memset(s, 0, sizeof(BDRVQcowState));

    options = qdict_clone_shallow(bs->options);

    ret = qcow2_open(bs, options, flags, &local_err);

    QDECREF(options);

    if (local_err) {

        error_setg(errp, "Could not reopen qcow2 layer: %s",

                   error_get_pretty(local_err));

        error_free(local_err);

        return;

    } else if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");

        return;

    }

    if (crypt_method) {

        s->crypt_method = crypt_method;

        memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));

        memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));

    }

}


static void ppc_prep_init (ram_addr_t ram_size,

                           const char *boot_device,

                           const char *kernel_filename,

                           const char *kernel_cmdline,

                           const char *initrd_filename,

                           const char *cpu_model)

{

    CPUState *env = NULL, *envs[MAX_CPUS];

    char *filename;

    nvram_t nvram;

    m48t59_t *m48t59;

    int PPC_io_memory;

    int linux_boot, i, nb_nics1, bios_size;

    ram_addr_t ram_offset, bios_offset;

    uint32_t kernel_base, kernel_size, initrd_base, initrd_size;

    PCIBus *pci_bus;

    qemu_irq *i8259;

    int ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    DriveInfo *fd[MAX_FD];

    sysctrl = qemu_mallocz(sizeof(sysctrl_t));

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL)

        cpu_model = "602";

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

        env = cpu_init(cpu_model);

        if (!env) {

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

            exit(1);

        }

        if (env->flags & POWERPC_FLAG_RTC_CLK) {

            /* POWER / PowerPC 601 RTC clock frequency is 7.8125 MHz */

            cpu_ppc_tb_init(env, 7812500UL);

        } else {

            /* Set time-base frequency to 100 Mhz */

            cpu_ppc_tb_init(env, 100UL * 1000UL * 1000UL);

        }

        qemu_register_reset(&cpu_ppc_reset, env);

        envs[i] = env;

    }

    /* allocate RAM */

    ram_offset = qemu_ram_alloc(ram_size);

    cpu_register_physical_memory(0, ram_size, ram_offset);

    /* allocate and load BIOS */

    bios_offset = qemu_ram_alloc(BIOS_SIZE);

    if (bios_name == NULL)

        bios_name = BIOS_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    if (filename) {

        bios_size = get_image_size(filename);

    } else {

        bios_size = -1;

    }

    if (bios_size > 0 && bios_size <= BIOS_SIZE) {

        target_phys_addr_t bios_addr;

        bios_size = (bios_size + 0xfff) & ~0xfff;

        bios_addr = (uint32_t)(-bios_size);

        cpu_register_physical_memory(bios_addr, bios_size,

                                     bios_offset | IO_MEM_ROM);

        bios_size = load_image_targphys(filename, bios_addr, bios_size);

    }

    if (bios_size < 0 || bios_size > BIOS_SIZE) {

        hw_error("qemu: could not load PPC PREP bios '%s'\n", bios_name);

    }

    if (filename) {

        qemu_free(filename);

    }

    if (env->nip < 0xFFF80000 && bios_size < 0x00100000) {

        hw_error("PowerPC 601 / 620 / 970 need a 1MB BIOS\n");

    }

    if (linux_boot) {

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        kernel_size = load_image_targphys(kernel_filename, kernel_base,

                                          ram_size - kernel_base);

        if (kernel_size < 0) {

            hw_error("qemu: could not load kernel '%s'\n", kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                hw_error("qemu: could not load initial ram disk '%s'\n",

                          initrd_filename);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

        /* For now, OHW cannot boot from the network. */

        for (i = 0; boot_device[i] != '\0'; i++) {

            if (boot_device[i] >= 'a' && boot_device[i] <= 'f') {

                ppc_boot_device = boot_device[i];

                break;

            }

        }

        if (ppc_boot_device == '\0') {

            fprintf(stderr, "No valid boot device for Mac99 machine\n");

            exit(1);

        }

    }

    isa_mem_base = 0xc0000000;

    if (PPC_INPUT(env) != PPC_FLAGS_INPUT_6xx) {

        hw_error("Only 6xx bus is supported on PREP machine\n");

    }

    i8259 = i8259_init(first_cpu->irq_inputs[PPC6xx_INPUT_INT]);

    pci_bus = pci_prep_init(i8259);

    /* Hmm, prep has no pci-isa bridge ??? */

    isa_bus_new(NULL);

    isa_bus_irqs(i8259);

    //    pci_bus = i440fx_init();

    /* Register 8 MB of ISA IO space (needed for non-contiguous map) */

    PPC_io_memory = cpu_register_io_memory(PPC_prep_io_read,

                                           PPC_prep_io_write, sysctrl);

    cpu_register_physical_memory(0x80000000, 0x00800000, PPC_io_memory);

    /* init basic PC hardware */

    pci_vga_init(pci_bus, 0, 0);

    //    openpic = openpic_init(0x00000000, 0xF0000000, 1);

    //    pit = pit_init(0x40, i8259[0]);

    rtc_init(2000);

    if (serial_hds[0])

        serial_isa_init(0, serial_hds[0]);

    nb_nics1 = nb_nics;

    if (nb_nics1 > NE2000_NB_MAX)

        nb_nics1 = NE2000_NB_MAX;

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

        if (nd_table[i].model == NULL) {

	    nd_table[i].model = "ne2k_isa";

        }

        if (strcmp(nd_table[i].model, "ne2k_isa") == 0) {

            isa_ne2000_init(ne2000_io[i], ne2000_irq[i], &nd_table[i]);

        } else {

            pci_nic_init(&nd_table[i], "ne2k_pci", NULL);

        }

    }

    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {

        fprintf(stderr, "qemu: too many IDE bus\n");

        exit(1);

    }

    for(i = 0; i < MAX_IDE_BUS * MAX_IDE_DEVS; i++) {

        hd[i] = drive_get(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);

    }

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

        isa_ide_init(ide_iobase[i], ide_iobase2[i], ide_irq[i],

                     hd[2 * i],

		     hd[2 * i + 1]);

    }

    isa_create_simple("i8042");

    DMA_init(1);

    //    SB16_init();

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

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

    }

    fdctrl_init_isa(fd);

    /* Register speaker port */

    register_ioport_read(0x61, 1, 1, speaker_ioport_read, NULL);

    register_ioport_write(0x61, 1, 1, speaker_ioport_write, NULL);

    /* Register fake IO ports for PREP */

    sysctrl->reset_irq = first_cpu->irq_inputs[PPC6xx_INPUT_HRESET];

    register_ioport_read(0x398, 2, 1, &PREP_io_read, sysctrl);

    register_ioport_write(0x398, 2, 1, &PREP_io_write, sysctrl);

    /* System control ports */

    register_ioport_read(0x0092, 0x01, 1, &PREP_io_800_readb, sysctrl);

    register_ioport_write(0x0092, 0x01, 1, &PREP_io_800_writeb, sysctrl);

    register_ioport_read(0x0800, 0x52, 1, &PREP_io_800_readb, sysctrl);

    register_ioport_write(0x0800, 0x52, 1, &PREP_io_800_writeb, sysctrl);

    /* PCI intack location */

    PPC_io_memory = cpu_register_io_memory(PPC_intack_read,

                                           PPC_intack_write, NULL);

    cpu_register_physical_memory(0xBFFFFFF0, 0x4, PPC_io_memory);

    /* PowerPC control and status register group */

#if 0

    PPC_io_memory = cpu_register_io_memory(PPC_XCSR_read, PPC_XCSR_write,

                                           NULL);

    cpu_register_physical_memory(0xFEFF0000, 0x1000, PPC_io_memory);

#endif

    if (usb_enabled) {

        usb_ohci_init_pci(pci_bus, -1);

    }

    m48t59 = m48t59_init(i8259[8], 0, 0x0074, NVRAM_SIZE, 59);

    if (m48t59 == NULL)

        return;

    sysctrl->nvram = m48t59;

    /* Initialise NVRAM */

    nvram.opaque = m48t59;

    nvram.read_fn = &m48t59_read;

    nvram.write_fn = &m48t59_write;

    PPC_NVRAM_set_params(&nvram, NVRAM_SIZE, "PREP", ram_size, ppc_boot_device,

                         kernel_base, kernel_size,

                         kernel_cmdline,

                         initrd_base, initrd_size,

                         /* XXX: need an option to load a NVRAM image */

                         0,

                         graphic_width, graphic_height, graphic_depth);

    /* Special port to get debug messages from Open-Firmware */

    register_ioport_write(0x0F00, 4, 1, &PPC_debug_write, NULL);

}


static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
    MpegEncContext * const s = &h->s;
    int i, j;
    int current_ref_assigned=0;
    Picture *pic;
    if((s->avctx->debug&FF_DEBUG_MMCO) && mmco_count==0)
        av_log(h->s.avctx, AV_LOG_DEBUG, "no mmco here\n");
    for(i=0; i<mmco_count; i++){
        int structure, frame_num, unref_pic;
        if(s->avctx->debug&FF_DEBUG_MMCO)
            av_log(h->s.avctx, AV_LOG_DEBUG, "mmco:%d %d %d\n", h->mmco[i].opcode, h->mmco[i].short_pic_num, h->mmco[i].long_arg);
        switch(mmco[i].opcode){
        case MMCO_SHORT2UNUSED:
            if(s->avctx->debug&FF_DEBUG_MMCO)
                av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref short %d count %d\n", h->mmco[i].short_pic_num, h->short_ref_count);
            frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
            pic = find_short(h, frame_num, &j);
            if (pic) {
                if (unreference_pic(h, pic, structure ^ PICT_FRAME))
                    remove_short_at_index(h, j);
            } else if(s->avctx->debug&FF_DEBUG_MMCO)
                av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref short failure\n");
        case MMCO_SHORT2LONG:
            if (FIELD_PICTURE && mmco[i].long_arg < h->long_ref_count &&
                    h->long_ref[mmco[i].long_arg]->frame_num ==
                                              mmco[i].short_pic_num / 2) {
                /* do nothing, we've already moved this field pair. */
                int frame_num = mmco[i].short_pic_num >> FIELD_PICTURE;
                pic= remove_long(h, mmco[i].long_arg);
                if(pic) unreference_pic(h, pic, 0);
                h->long_ref[ mmco[i].long_arg ]= remove_short(h, frame_num);
                if (h->long_ref[ mmco[i].long_arg ]){
                    h->long_ref[ mmco[i].long_arg ]->long_ref=1;
                    h->long_ref_count++;
        case MMCO_LONG2UNUSED:
            j = pic_num_extract(h, mmco[i].long_arg, &structure);
            pic = h->long_ref[j];
            if (pic) {
                if (unreference_pic(h, pic, structure ^ PICT_FRAME))
                    remove_long_at_index(h, j);
            } else if(s->avctx->debug&FF_DEBUG_MMCO)
                av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
        case MMCO_LONG:
            unref_pic = 1;
            if (FIELD_PICTURE && !s->first_field) {
                if (h->long_ref[mmco[i].long_arg] == s->current_picture_ptr) {
                    /* Just mark second field as referenced */
                    unref_pic = 0;
                } else if (s->current_picture_ptr->reference) {
                    /* First field in pair is in short term list or
                     * at a different long term index.
                     * This is not allowed; see 7.4.3, notes 2 and 3.
                     * Report the problem and keep the pair where it is,
                     * and mark this field valid.
                        "illegal long term reference assignment for second "
                        "field in complementary field pair (first field is "
                        "short term or has non-matching long index)\n");
                    unref_pic = 0;
            if (unref_pic) {
                pic= remove_long(h, mmco[i].long_arg);
                if(pic) unreference_pic(h, pic, 0);
                h->long_ref[ mmco[i].long_arg ]= s->current_picture_ptr;
                h->long_ref[ mmco[i].long_arg ]->long_ref=1;
                h->long_ref_count++;
            s->current_picture_ptr->reference |= s->picture_structure;
            current_ref_assigned=1;
        case MMCO_SET_MAX_LONG:
            assert(mmco[i].long_arg <= 16);
            // just remove the long term which index is greater than new max
            for(j = mmco[i].long_arg; j<16; j++){
                pic = remove_long(h, j);
                if (pic) unreference_pic(h, pic, 0);
        case MMCO_RESET:
            while(h->short_ref_count){
                pic= remove_short(h, h->short_ref[0]->frame_num);
                if(pic) unreference_pic(h, pic, 0);
            for(j = 0; j < 16; j++) {
                pic= remove_long(h, j);
                if(pic) unreference_pic(h, pic, 0);
        default: assert(0);
    if (!current_ref_assigned && FIELD_PICTURE &&
            !s->first_field && s->current_picture_ptr->reference) {
        /* Second field of complementary field pair; the first field of
         * which is already referenced. If short referenced, it
         * should be first entry in short_ref. If not, it must exist
         * in long_ref; trying to put it on the short list here is an
         * error in the encoded bit stream (ref: 7.4.3, NOTE 2 and 3).
        if (h->short_ref_count && h->short_ref[0] == s->current_picture_ptr) {
            /* Just mark the second field valid */
            s->current_picture_ptr->reference = PICT_FRAME;
        } else if (s->current_picture_ptr->long_ref) {
            av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term reference "
                                             "assignment for second field "
                                             "in complementary field pair "
                                             "(first field is long term)\n");
            /*
             * First field in reference, but not in any sensible place on our
             * reference lists. This shouldn't happen unless reference
             * handling somewhere else is wrong.
            assert(0);
        current_ref_assigned = 1;
    if(!current_ref_assigned){
        pic= remove_short(h, s->current_picture_ptr->frame_num);
        if(pic){
            unreference_pic(h, pic, 0);
            av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
        if(h->short_ref_count)
            memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
        h->short_ref[0]= s->current_picture_ptr;
        h->short_ref[0]->long_ref=0;
        h->short_ref_count++;
        s->current_picture_ptr->reference |= s->picture_structure;
    print_short_term(h);
    print_long_term(h);
    return 0;


static void filter_samples(AVFilterLink *inlink, AVFilterBufferRef *samplesref)

{

    AVFilterContext *ctx = inlink->dst;

    ShowInfoContext *showinfo = ctx->priv;

    uint32_t plane_checksum[8] = {0}, checksum = 0;

    char chlayout_str[128];

    int plane;

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

        uint8_t *data = samplesref->data[plane];

        int linesize = samplesref->linesize[plane];

        plane_checksum[plane] = av_adler32_update(plane_checksum[plane],

                                                  data, linesize);

        checksum = av_adler32_update(checksum, data, linesize);

    }

    av_get_channel_layout_string(chlayout_str, sizeof(chlayout_str), -1,

                                 samplesref->audio->channel_layout);

    av_log(ctx, AV_LOG_INFO,

           "n:%d pts:%"PRId64" pts_time:%f pos:%"PRId64" "

           "fmt:%s chlayout:%s nb_samples:%d rate:%d planar:%d "

           "checksum:%u plane_checksum[%u %u %u %u %u %u %u %u]\n",

           showinfo->frame,

           samplesref->pts, samplesref->pts * av_q2d(inlink->time_base),

           samplesref->pos,

           av_get_sample_fmt_name(samplesref->format),

           chlayout_str,

           samplesref->audio->nb_samples,

           samplesref->audio->sample_rate,

           samplesref->audio->planar,

           checksum,

           plane_checksum[0], plane_checksum[1], plane_checksum[2], plane_checksum[3],

           plane_checksum[4], plane_checksum[5], plane_checksum[6], plane_checksum[7]);

    showinfo->frame++;

    avfilter_filter_samples(inlink->dst->outputs[0], samplesref);

}


static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)

{

    VAAPIEncodeContext *ctx = avctx->priv_data;

    int hrd_buffer_size;

    int hrd_initial_buffer_fullness;

    if (avctx->rc_buffer_size)

        hrd_buffer_size = avctx->rc_buffer_size;

    else

        hrd_buffer_size = avctx->bit_rate;

    if (avctx->rc_initial_buffer_occupancy)

        hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;

    else

        hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;

    ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;

    ctx->rc_params.rc = (VAEncMiscParameterRateControl) {

        .bits_per_second   = avctx->bit_rate,

        .target_percentage = 66,

        .window_size       = 1000,

        .initial_qp        = (avctx->qmax >= 0 ? avctx->qmax : 40),

        .min_qp            = (avctx->qmin >= 0 ? avctx->qmin : 18),

        .basic_unit_size   = 0,

    };

    ctx->global_params[ctx->nb_global_params] =

        &ctx->rc_params.misc;

    ctx->global_params_size[ctx->nb_global_params++] =

        sizeof(ctx->rc_params);

    ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;

    ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {

        .initial_buffer_fullness = hrd_initial_buffer_fullness,

        .buffer_size             = hrd_buffer_size,

    };

    ctx->global_params[ctx->nb_global_params] =

        &ctx->hrd_params.misc;

    ctx->global_params_size[ctx->nb_global_params++] =

        sizeof(ctx->hrd_params);

    return 0;

}


static void glib_pollfds_poll(void)

{

    GMainContext *context = g_main_context_default();

    GPollFD *pfds = &g_array_index(gpollfds, GPollFD, glib_pollfds_idx);

    if (g_main_context_check(context, max_priority, pfds, glib_n_poll_fds)) {

        g_main_context_dispatch(context);

    }

}


static int parse_drive(DeviceState *dev, const char *str, void **ptr)

{

    BlockDriverState *bs;

    bs = bdrv_find(str);

    if (bs == NULL) {

        return -ENOENT;

    }

    if (bdrv_attach_dev(bs, dev) < 0) {

        return -EEXIST;

    }

    *ptr = bs;

    return 0;

}


static void hda_audio_exit(HDACodecDevice *hda)

{

    HDAAudioState *a = HDA_AUDIO(hda);

    HDAAudioStream *st;

    int i;

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

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

        st = a->st + i;

        if (st->node == NULL) {

            continue;

        }

        if (st->output) {

            AUD_close_out(&a->card, st->voice.out);

        } else {

            AUD_close_in(&a->card, st->voice.in);

        }

    }

    AUD_remove_card(&a->card);

}


static void curl_block_init(void)

{

    bdrv_register(&bdrv_http);

    bdrv_register(&bdrv_https);

    bdrv_register(&bdrv_ftp);

    bdrv_register(&bdrv_ftps);

    bdrv_register(&bdrv_tftp);

}


static always_inline void gen_fcmov (void *func,

                                     int ra, int rb, int rc)

{

    int l1;

    TCGv tmp;

    if (unlikely(rc == 31))

        return;

    l1 = gen_new_label();

    tmp = tcg_temp_new(TCG_TYPE_I64);

    if (ra != 31) {

        tmp = tcg_temp_new(TCG_TYPE_I64);

        tcg_gen_helper_1_1(func, tmp, cpu_fir[ra]);

    } else  {

        tmp = tcg_const_i64(0);

        tcg_gen_helper_1_1(func, tmp, tmp);

    }

    tcg_gen_brcondi_i64(TCG_COND_EQ, tmp, 0, l1);

    if (rb != 31)

        tcg_gen_mov_i64(cpu_fir[rc], cpu_fir[ra]);

    else

        tcg_gen_movi_i64(cpu_fir[rc], 0);

    gen_set_label(l1);

}


static inline void gen_outs(DisasContext *s, int ot)

{

    gen_string_movl_A0_ESI(s);

    gen_op_ld_T0_A0(ot + s->mem_index);

    gen_op_mov_TN_reg(OT_WORD, 1, R_EDX);

    tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[1]);

    tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);

    tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T[0]);

    tcg_gen_helper_0_2(helper_out_func[ot], cpu_tmp2_i32, cpu_tmp3_i32);

    gen_op_movl_T0_Dshift[ot]();

#ifdef TARGET_X86_64

    if (s->aflag == 2) {

        gen_op_addq_ESI_T0();

    } else

#endif

    if (s->aflag) {

        gen_op_addl_ESI_T0();

    } else {

        gen_op_addw_ESI_T0();

    }

}


static void vscsi_command_complete(SCSIRequest *sreq, uint32_t status)

{

    VSCSIState *s = DO_UPCAST(VSCSIState, vdev.qdev, sreq->bus->qbus.parent);

    vscsi_req *req = sreq->hba_private;

    int32_t res_in = 0, res_out = 0;

    dprintf("VSCSI: SCSI cmd complete, r=0x%x tag=0x%x status=0x%x, req=%p\n",

            reason, sreq->tag, status, req);

    if (req == NULL) {

        fprintf(stderr, "VSCSI: Can't find request for tag 0x%x\n", sreq->tag);

        return;

    }

    if (status == CHECK_CONDITION) {

        req->senselen = scsi_req_get_sense(req->sreq, req->sense,

                                           sizeof(req->sense));

        status = 0;

        dprintf("VSCSI: Sense data, %d bytes:\n", len);

        dprintf("       %02x  %02x  %02x  %02x  %02x  %02x  %02x  %02x\n",

                req->sense[0], req->sense[1], req->sense[2], req->sense[3],

                req->sense[4], req->sense[5], req->sense[6], req->sense[7]);

        dprintf("       %02x  %02x  %02x  %02x  %02x  %02x  %02x  %02x\n",

                req->sense[8], req->sense[9], req->sense[10], req->sense[11],

                req->sense[12], req->sense[13], req->sense[14], req->sense[15]);

    }

    dprintf("VSCSI: Command complete err=%d\n", status);

    if (status == 0) {

        /* We handle overflows, not underflows for normal commands,

         * but hopefully nobody cares

         */

        if (req->writing) {

            res_out = req->data_len;

        } else {

            res_in = req->data_len;

        }

    }

    vscsi_send_rsp(s, req, status, res_in, res_out);

    vscsi_put_req(req);

}


static void virtio_blk_flush_complete(void *opaque, int ret)

{

    VirtIOBlockReq *req = opaque;

    if (ret) {

        if (virtio_blk_handle_rw_error(req, -ret, 0)) {

            return;

        }

    }

    virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);

    block_acct_done(bdrv_get_stats(req->dev->bs), &req->acct);

    virtio_blk_free_request(req);

}


void ppc_hw_interrupt (CPUState *env)

{

    env->exception_index = -1;

}


void qmp_ringbuf_write(const char *device, const char *data,

                       bool has_format, enum DataFormat format,

                       Error **errp)

{

    CharDriverState *chr;

    const uint8_t *write_data;

    int ret;

    gsize write_count;

    chr = qemu_chr_find(device);

    if (!chr) {

        error_setg(errp, "Device '%s' not found", device);

        return;

    }

    if (!chr_is_ringbuf(chr)) {

        error_setg(errp,"%s is not a ringbuf device", device);

        return;

    }

    if (has_format && (format == DATA_FORMAT_BASE64)) {

        write_data = g_base64_decode(data, &write_count);

    } else {

        write_data = (uint8_t *)data;

        write_count = strlen(data);

    }

    ret = ringbuf_chr_write(chr, write_data, write_count);

    if (write_data != (uint8_t *)data) {

        g_free((void *)write_data);

    }

    if (ret < 0) {

        error_setg(errp, "Failed to write to device %s", device);

        return;

    }

}


int do_migrate(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

    MigrationState *s = migrate_get_current();

    const char *p;

    int detach = qdict_get_try_bool(qdict, "detach", 0);

    int blk = qdict_get_try_bool(qdict, "blk", 0);

    int inc = qdict_get_try_bool(qdict, "inc", 0);

    const char *uri = qdict_get_str(qdict, "uri");

    int ret;

    if (s->state == MIG_STATE_ACTIVE) {

        monitor_printf(mon, "migration already in progress\n");

        return -1;

    }

    if (qemu_savevm_state_blocked(mon)) {

        return -1;

    }

    if (migration_blockers) {

        Error *err = migration_blockers->data;

        qerror_report_err(err);

        return -1;

    }

    s = migrate_init(mon, detach, blk, inc);

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

        ret = tcp_start_outgoing_migration(s, p);

#if !defined(WIN32)

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

        ret = exec_start_outgoing_migration(s, p);

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

        ret = unix_start_outgoing_migration(s, p);

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

        ret = fd_start_outgoing_migration(s, p);

#endif

    } else {

        monitor_printf(mon, "unknown migration protocol: %s\n", uri);

        ret  = -EINVAL;

    }

    if (ret < 0) {

        monitor_printf(mon, "migration failed: %s\n", strerror(-ret));

        return ret;

    }

    if (detach) {

        s->mon = NULL;

    }

    notifier_list_notify(&migration_state_notifiers, s);

    return 0;

}


void *laio_init(void)

{

    struct qemu_laio_state *s;

    s = qemu_mallocz(sizeof(*s));

    QLIST_INIT(&s->completed_reqs);

    s->efd = eventfd(0, 0);

    if (s->efd == -1)

        goto out_free_state;

    fcntl(s->efd, F_SETFL, O_NONBLOCK);

    if (io_setup(MAX_EVENTS, &s->ctx) != 0)

        goto out_close_efd;

    qemu_aio_set_fd_handler(s->efd, qemu_laio_completion_cb, NULL,

        qemu_laio_flush_cb, qemu_laio_process_requests, s);

    return s;

out_close_efd:

    close(s->efd);

out_free_state:

    qemu_free(s);

    return NULL;

}


static TileExcp decode_x1(DisasContext *dc, tilegx_bundle_bits bundle)

{

    unsigned opc = get_Opcode_X1(bundle);

    unsigned dest = get_Dest_X1(bundle);

    unsigned srca = get_SrcA_X1(bundle);

    unsigned ext, srcb;

    int imm;

    switch (opc) {

    case RRR_0_OPCODE_X1:

        ext = get_RRROpcodeExtension_X1(bundle);

        srcb = get_SrcB_X1(bundle);

        switch (ext) {

        case UNARY_RRR_0_OPCODE_X1:

            ext = get_UnaryOpcodeExtension_X1(bundle);

            return gen_rr_opcode(dc, OE(opc, ext, X1), dest, srca);

        case ST1_RRR_0_OPCODE_X1:

            return gen_st_opcode(dc, dest, srca, srcb, MO_UB, "st1");

        case ST2_RRR_0_OPCODE_X1:

            return gen_st_opcode(dc, dest, srca, srcb, MO_TEUW, "st2");

        case ST4_RRR_0_OPCODE_X1:

            return gen_st_opcode(dc, dest, srca, srcb, MO_TEUL, "st4");

        case STNT1_RRR_0_OPCODE_X1:

            return gen_st_opcode(dc, dest, srca, srcb, MO_UB, "stnt1");

        case STNT2_RRR_0_OPCODE_X1:

            return gen_st_opcode(dc, dest, srca, srcb, MO_TEUW, "stnt2");

        case STNT4_RRR_0_OPCODE_X1:

            return gen_st_opcode(dc, dest, srca, srcb, MO_TEUL, "stnt4");

        case STNT_RRR_0_OPCODE_X1:

            return gen_st_opcode(dc, dest, srca, srcb, MO_TEQ, "stnt");

        case ST_RRR_0_OPCODE_X1:

            return gen_st_opcode(dc, dest, srca, srcb, MO_TEQ, "st");

        }

        return gen_rrr_opcode(dc, OE(opc, ext, X1), dest, srca, srcb);

    case SHIFT_OPCODE_X1:

        ext = get_ShiftOpcodeExtension_X1(bundle);

        imm = get_ShAmt_X1(bundle);

        return gen_rri_opcode(dc, OE(opc, ext, X1), dest, srca, imm);

    case IMM8_OPCODE_X1:

        ext = get_Imm8OpcodeExtension_X1(bundle);

        imm = (int8_t)get_Dest_Imm8_X1(bundle);

        srcb = get_SrcB_X1(bundle);

        switch (ext) {

        case ST1_ADD_IMM8_OPCODE_X1:

            return gen_st_add_opcode(dc, srca, srcb, imm, MO_UB, "st1_add");

        case ST2_ADD_IMM8_OPCODE_X1:

            return gen_st_add_opcode(dc, srca, srcb, imm, MO_TEUW, "st2_add");

        case ST4_ADD_IMM8_OPCODE_X1:

            return gen_st_add_opcode(dc, srca, srcb, imm, MO_TEUL, "st4_add");

        case STNT1_ADD_IMM8_OPCODE_X1:

            return gen_st_add_opcode(dc, srca, srcb, imm, MO_UB, "stnt1_add");

        case STNT2_ADD_IMM8_OPCODE_X1:

            return gen_st_add_opcode(dc, srca, srcb, imm, MO_TEUW, "stnt2_add");

        case STNT4_ADD_IMM8_OPCODE_X1:

            return gen_st_add_opcode(dc, srca, srcb, imm, MO_TEUL, "stnt4_add");

        case STNT_ADD_IMM8_OPCODE_X1:

            return gen_st_add_opcode(dc, srca, srcb, imm, MO_TEQ, "stnt_add");

        case ST_ADD_IMM8_OPCODE_X1:

            return gen_st_add_opcode(dc, srca, srcb, imm, MO_TEQ, "st_add");

        case MFSPR_IMM8_OPCODE_X1:

            return gen_mfspr_x1(dc, dest, get_MF_Imm14_X1(bundle));

        case MTSPR_IMM8_OPCODE_X1:

            return gen_mtspr_x1(dc, get_MT_Imm14_X1(bundle), srca);

        }

        imm = (int8_t)get_Imm8_X1(bundle);

        return gen_rri_opcode(dc, OE(opc, ext, X1), dest, srca, imm);

    case BRANCH_OPCODE_X1:

        ext = get_BrType_X1(bundle);

        imm = sextract32(get_BrOff_X1(bundle), 0, 17);

        return gen_branch_opcode_x1(dc, ext, srca, imm);

    case JUMP_OPCODE_X1:

        ext = get_JumpOpcodeExtension_X1(bundle);

        imm = sextract32(get_JumpOff_X1(bundle), 0, 27);

        return gen_jump_opcode_x1(dc, ext, imm);

    case ADDLI_OPCODE_X1:

    case SHL16INSLI_OPCODE_X1:

    case ADDXLI_OPCODE_X1:

        imm = (int16_t)get_Imm16_X1(bundle);

        return gen_rri_opcode(dc, OE(opc, 0, X1), dest, srca, imm);

    default:

        return TILEGX_EXCP_OPCODE_UNIMPLEMENTED;

    }

}


static void compute_pkt_fields(AVFormatContext *s, AVStream *st,

                               AVCodecParserContext *pc, AVPacket *pkt)

{

    int num, den, presentation_delayed;

    /* handle wrapping */

    if(st->cur_dts != AV_NOPTS_VALUE){

        if(pkt->pts != AV_NOPTS_VALUE)

            pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);

        if(pkt->dts != AV_NOPTS_VALUE)

            pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);

    }

    if (pkt->duration == 0) {

        compute_frame_duration(&num, &den, s, st, pc, pkt);

        if (den && num) {

            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);

        }

    }

    /* do we have a video B frame ? */

    presentation_delayed = 0;

    if (st->codec.codec_type == CODEC_TYPE_VIDEO) {

        /* XXX: need has_b_frame, but cannot get it if the codec is

           not initialized */

        if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||

             st->codec.codec_id == CODEC_ID_MPEG2VIDEO ||

             st->codec.codec_id == CODEC_ID_MPEG4 ||

             st->codec.codec_id == CODEC_ID_H264) &&

            pc && pc->pict_type != FF_B_TYPE)

            presentation_delayed = 1;

        /* this may be redundant, but it shouldnt hurt */

        if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)

            presentation_delayed = 1;

    }

    if(st->cur_dts == AV_NOPTS_VALUE){

        if(presentation_delayed) st->cur_dts = -pkt->duration;

        else                     st->cur_dts = 0;

    }

//    av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%lld, dts:%lld cur_dts:%lld\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);

    /* interpolate PTS and DTS if they are not present */

    if (presentation_delayed) {

        /* DTS = decompression time stamp */

        /* PTS = presentation time stamp */

        if (pkt->dts == AV_NOPTS_VALUE) {

            /* if we know the last pts, use it */

            if(st->last_IP_pts != AV_NOPTS_VALUE)

                st->cur_dts = pkt->dts = st->last_IP_pts;

            else

                pkt->dts = st->cur_dts;

        } else {

            st->cur_dts = pkt->dts;

        }

        /* this is tricky: the dts must be incremented by the duration

           of the frame we are displaying, i.e. the last I or P frame */

        if (st->last_IP_duration == 0)

            st->cur_dts += pkt->duration;

        else

            st->cur_dts += st->last_IP_duration;

        st->last_IP_duration  = pkt->duration;

        st->last_IP_pts= pkt->pts;

        /* cannot compute PTS if not present (we can compute it only

           by knowing the futur */

    } else {

        /* presentation is not delayed : PTS and DTS are the same */

        if (pkt->pts == AV_NOPTS_VALUE) {

            if (pkt->dts == AV_NOPTS_VALUE) {

                pkt->pts = st->cur_dts;

                pkt->dts = st->cur_dts;

            }

            else {

                st->cur_dts = pkt->dts;

                pkt->pts = pkt->dts;

            }

        } else {

            st->cur_dts = pkt->pts;

            pkt->dts = pkt->pts;

        }

        st->cur_dts += pkt->duration;

    }

//    av_log(NULL, AV_LOG_DEBUG, "OUTdelayed:%d pts:%lld, dts:%lld cur_dts:%lld\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);

    /* update flags */

    if (pc) {

        pkt->flags = 0;

        /* key frame computation */

        switch(st->codec.codec_type) {

        case CODEC_TYPE_VIDEO:

            if (pc->pict_type == FF_I_TYPE)

                pkt->flags |= PKT_FLAG_KEY;

            break;

        case CODEC_TYPE_AUDIO:

            pkt->flags |= PKT_FLAG_KEY;

            break;

        default:

            break;

        }

    }

    /* convert the packet time stamp units */

    if(pkt->pts != AV_NOPTS_VALUE)

        pkt->pts = av_rescale(pkt->pts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);

    if(pkt->dts != AV_NOPTS_VALUE)

        pkt->dts = av_rescale(pkt->dts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);

    /* duration field */

    pkt->duration = av_rescale(pkt->duration, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);

}


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

{

    int size;

    FFMContext *ffm = s->priv_data;

    int duration, ret;

    switch(ffm->read_state) {

    case READ_HEADER:

        if ((ret = ffm_is_avail_data(s, FRAME_HEADER_SIZE+4)) < 0)

            return ret;

        av_dlog(s, "pos=%08"PRIx64" spos=%"PRIx64", write_index=%"PRIx64" size=%"PRIx64"\n",

               avio_tell(s->pb), s->pb->pos, ffm->write_index, ffm->file_size);

        if (ffm_read_data(s, ffm->header, FRAME_HEADER_SIZE, 1) !=

            FRAME_HEADER_SIZE)

            return -1;

        if (ffm->header[1] & FLAG_DTS)

            if (ffm_read_data(s, ffm->header+16, 4, 1) != 4)

                return -1;

        ffm->read_state = READ_DATA;

        /* fall thru */

    case READ_DATA:

        size = AV_RB24(ffm->header + 2);

        if ((ret = ffm_is_avail_data(s, size)) < 0)

            return ret;

        duration = AV_RB24(ffm->header + 5);

        av_new_packet(pkt, size);

        pkt->stream_index = ffm->header[0];

        if ((unsigned)pkt->stream_index >= s->nb_streams) {

            av_log(s, AV_LOG_ERROR, "invalid stream index %d\n", pkt->stream_index);

            av_free_packet(pkt);

            ffm->read_state = READ_HEADER;

            return -1;

        }

        pkt->pos = avio_tell(s->pb);

        if (ffm->header[1] & FLAG_KEY_FRAME)

            pkt->flags |= AV_PKT_FLAG_KEY;

        ffm->read_state = READ_HEADER;

        if (ffm_read_data(s, pkt->data, size, 0) != size) {

            /* bad case: desynchronized packet. we cancel all the packet loading */

            av_free_packet(pkt);

            return -1;

        }

        pkt->pts = AV_RB64(ffm->header+8);

        if (ffm->header[1] & FLAG_DTS)

            pkt->dts = pkt->pts - AV_RB32(ffm->header+16);

        else

            pkt->dts = pkt->pts;

        pkt->duration = duration;

        break;

    }

    return 0;

}


static int vda_h264_start_frame(AVCodecContext *avctx,

                                av_unused const uint8_t *buffer,

                                av_unused uint32_t size)

{

    VDAContext *vda = avctx->internal->hwaccel_priv_data;

    struct vda_context *vda_ctx         = avctx->hwaccel_context;

    if (!vda_ctx->decoder)

        return -1;

    vda->bitstream_size = 0;

    return 0;

}


static void colored_fputs(int level, int tint, const char *str)

{

    if (!*str)

        return;

    if (use_color < 0)

        check_color_terminal();

#if defined(_WIN32) && !defined(__MINGW32CE__) && HAVE_SETCONSOLETEXTATTRIBUTE

    if (use_color && level != AV_LOG_INFO/8)

        SetConsoleTextAttribute(con, background | color[level]);

    fputs(str, stderr);

    if (use_color && level != AV_LOG_INFO/8)

        SetConsoleTextAttribute(con, attr_orig);

#else

    if (use_color == 1 && level != AV_LOG_INFO/8) {

        fprintf(stderr,

                "\033[%d;3%dm%s\033[0m",

                (color[level] >> 4) & 15,

                color[level] & 15,

                str);

    } else if (tint && use_color == 256) {

        fprintf(stderr,

                "\033[48;5;%dm\033[38;5;%dm%s\033[0m",

                (color[level] >> 16) & 0xff,

                tint,

                str);

    } else if (use_color == 256 && level != AV_LOG_INFO/8) {

        fprintf(stderr,

                "\033[48;5;%dm\033[38;5;%dm%s\033[0m",

                (color[level] >> 16) & 0xff,

                (color[level] >> 8) & 0xff,

                str);

    } else

        fputs(str, stderr);

#endif

}


static int aasc_decode_frame(AVCodecContext *avctx,

                              void *data, int *got_frame,

                              AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    AascContext *s     = avctx->priv_data;

    int compr, i, stride, ret;

    s->frame.reference = 1;

    s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

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

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

        return ret;

    }

    compr     = AV_RL32(buf);

    buf      += 4;

    buf_size -= 4;

    switch (compr) {

    case 0:

        stride = (avctx->width * 3 + 3) & ~3;

        for (i = avctx->height - 1; i >= 0; i--) {

            memcpy(s->frame.data[0] + i * s->frame.linesize[0], buf, avctx->width * 3);

            buf += stride;

        }

        break;

    case 1:

        bytestream2_init(&s->gb, buf - 4, buf_size + 4);

        ff_msrle_decode(avctx, (AVPicture*)&s->frame, 8, &s->gb);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Unknown compression type %d\n", compr);

        return AVERROR_INVALIDDATA;

    }

    *got_frame = 1;

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

    /* report that the buffer was completely consumed */

    return buf_size;

}


static int rv10_decode_packet(AVCodecContext *avctx,

                             uint8_t *buf, int buf_size)

{

    MpegEncContext *s = avctx->priv_data;

    int i, mb_count, mb_pos, left;

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

#if 0

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

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

    printf("\n");

    return 0;

#endif

    if(s->codec_id ==CODEC_ID_RV10)

        mb_count = rv10_decode_picture_header(s);

    else

        mb_count = rv20_decode_picture_header(s);

    if (mb_count < 0) {

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

        return -1;

    }

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

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

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

        return -1;

    }

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

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

    if (mb_count > left) {

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

        return -1;

    }

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

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

        if(MPV_frame_start(s, avctx) < 0)

            return -1;

    }

#ifdef DEBUG

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

#endif

    /* default quantization values */

    if(s->codec_id== CODEC_ID_RV10){

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

    }else{

        s->first_slice_line=1;

        s->resync_mb_x= s->mb_x;

        s->resync_mb_y= s->mb_y;

    }

    if(s->h263_aic){

        s->y_dc_scale_table=

        s->c_dc_scale_table= ff_aic_dc_scale_table;

    }else{

        s->y_dc_scale_table=

        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;

    }

    if(s->modified_quant)

        s->chroma_qscale_table= ff_h263_chroma_qscale_table;

    ff_set_qscale(s, s->qscale);

    s->rv10_first_dc_coded[0] = 0;

    s->rv10_first_dc_coded[1] = 0;

    s->rv10_first_dc_coded[2] = 0;

    s->block_wrap[0]=

    s->block_wrap[1]=

    s->block_wrap[2]=

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

    s->block_wrap[4]=

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

    ff_init_block_index(s);

    /* decode each macroblock */

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

        int ret;

        ff_update_block_index(s);

#ifdef DEBUG

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

#endif

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

        s->mv_dir = MV_DIR_FORWARD;

        s->mv_type = MV_TYPE_16X16;

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

        if (ret == SLICE_ERROR) {

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

            return -1;

        }

        ff_h263_update_motion_val(s);

        MPV_decode_mb(s, s->block);

        if(s->loop_filter)

            ff_h263_loop_filter(s);

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

            s->mb_x = 0;

            s->mb_y++;

            ff_init_block_index(s);

        }

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

            s->first_slice_line=0;

        if(ret == SLICE_END) break;

    }

    return buf_size;

}


static bool memory_region_dispatch_write(MemoryRegion *mr,

                                         hwaddr addr,

                                         uint64_t data,

                                         unsigned size)

{

    if (!memory_region_access_valid(mr, addr, size, true)) {

        unassigned_mem_write(mr, addr, data, size);

        return true;

    }

    adjust_endianness(mr, &data, size);

    if (mr->ops->write) {

        access_with_adjusted_size(addr, &data, size,

                                  mr->ops->impl.min_access_size,

                                  mr->ops->impl.max_access_size,

                                  memory_region_write_accessor, mr);

    } else {

        access_with_adjusted_size(addr, &data, size, 1, 4,

                                  memory_region_oldmmio_write_accessor, mr);

    }

    return false;

}


static void complete_pdu(V9fsState *s, V9fsPDU *pdu, ssize_t len)

{

    int8_t id = pdu->id + 1; /* Response */

    if (len < 0) {

        int err = -len;

        len = 7;

        if (s->proto_version != V9FS_PROTO_2000L) {

            V9fsString str;

            str.data = strerror(err);

            str.size = strlen(str.data);

            len += pdu_marshal(pdu, len, "s", &str);

            id = P9_RERROR;

        }

        len += pdu_marshal(pdu, len, "d", err);

        if (s->proto_version == V9FS_PROTO_2000L) {

            id = P9_RLERROR;

        }

    }

    /* fill out the header */

    pdu_marshal(pdu, 0, "dbw", (int32_t)len, id, pdu->tag);

    /* keep these in sync */

    pdu->size = len;

    pdu->id = id;

    /* push onto queue and notify */

    virtqueue_push(s->vq, &pdu->elem, len);

    /* FIXME: we should batch these completions */

    virtio_notify(&s->vdev, s->vq);

    /* Now wakeup anybody waiting in flush for this request */

    qemu_co_queue_next(&pdu->complete);

    free_pdu(s, pdu);

}


static void gen_rsr(DisasContext *dc, TCGv_i32 d, uint32_t sr)

{

    static void (* const rsr_handler[256])(DisasContext *dc,

            TCGv_i32 d, uint32_t sr) = {

        [CCOUNT] = gen_rsr_ccount,

        [PTEVADDR] = gen_rsr_ptevaddr,

    };

    if (sregnames[sr]) {

        if (rsr_handler[sr]) {

            rsr_handler[sr](dc, d, sr);

        } else {

            tcg_gen_mov_i32(d, cpu_SR[sr]);

        }

    } else {

        qemu_log("RSR %d not implemented, ", sr);

    }

}


static inline uint64_t cksm_overflow(uint64_t cksm)

{

    if (cksm > 0xffffffffULL) {

        cksm &= 0xffffffffULL;

        cksm++;

    }

    return cksm;

}


int tcp_start_outgoing_migration(MigrationState *s, const char *host_port,

                                 Error **errp)

{

    s->get_error = socket_errno;

    s->write = socket_write;

    s->close = tcp_close;

    s->fd = inet_connect(host_port, false, NULL, errp);

    if (!error_is_set(errp)) {

        migrate_fd_connect(s);

    } else if (error_is_type(*errp, QERR_SOCKET_CONNECT_IN_PROGRESS)) {

        DPRINTF("connect in progress\n");

        qemu_set_fd_handler2(s->fd, NULL, NULL, tcp_wait_for_connect, s);

    } else if (error_is_type(*errp, QERR_SOCKET_CREATE_FAILED)) {

        DPRINTF("connect failed\n");

        return -1;

    } else if (error_is_type(*errp, QERR_SOCKET_CONNECT_FAILED)) {

        DPRINTF("connect failed\n");

        migrate_fd_error(s);

        return -1;

    } else {

        DPRINTF("unknown error\n");

        return -1;

    }

    return 0;

}


static int asf_read_simple_index(AVFormatContext *s, const GUIDParseTable *g)

{

    ASFContext *asf = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *st    = NULL;

    uint64_t interval; // index entry time interval in 100 ns units, usually it's 1s

    uint32_t pkt_num, nb_entries;

    int32_t prev_pkt_num = -1;

    int i, ret;

    uint64_t size = avio_rl64(pb);

    // simple index objects should be ordered by stream number, this loop tries to find

    // the first not indexed video stream

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

        if ((asf->asf_st[i]->type == AVMEDIA_TYPE_VIDEO) && !asf->asf_st[i]->indexed) {

            asf->asf_st[i]->indexed = 1;

            st = s->streams[asf->asf_st[i]->index];

            break;

        }

    }

    if (!st) {

        avio_skip(pb, size - 24); // if there's no video stream, skip index object

        return 0;

    }

    avio_skip(pb, 16); // skip File ID

    interval = avio_rl64(pb);

    avio_skip(pb, 4);

    nb_entries = avio_rl32(pb);

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

        pkt_num = avio_rl32(pb);

        ret = avio_skip(pb, 2);

        if (ret < 0) {

            av_log(s, AV_LOG_ERROR, "Skipping failed in asf_read_simple_index.\n");

            return ret;

        }

        if (prev_pkt_num != pkt_num) {

            av_add_index_entry(st, asf->first_packet_offset + asf->packet_size *

                               pkt_num, av_rescale(interval, i, 10000),

                               asf->packet_size, 0, AVINDEX_KEYFRAME);

            prev_pkt_num = pkt_num;

        }

    }

    asf->is_simple_index = 1;

    align_position(pb, asf->offset, size);

    return 0;

}


static void ehci_advance_async_state(EHCIState *ehci)

{

    const int async = 1;

    switch(ehci_get_state(ehci, async)) {

    case EST_INACTIVE:

        if (!(ehci->usbcmd & USBCMD_ASE)) {

            break;

        }

        ehci_set_usbsts(ehci, USBSTS_ASS);

        ehci_set_state(ehci, async, EST_ACTIVE);

        // No break, fall through to ACTIVE

    case EST_ACTIVE:

        if ( !(ehci->usbcmd & USBCMD_ASE)) {

            ehci_clear_usbsts(ehci, USBSTS_ASS);

            ehci_set_state(ehci, async, EST_INACTIVE);

            break;

        }

        /* If the doorbell is set, the guest wants to make a change to the

         * schedule. The host controller needs to release cached data.

         * (section 4.8.2)

         */

        if (ehci->usbcmd & USBCMD_IAAD) {

            DPRINTF("ASYNC: doorbell request acknowledged\n");

            ehci->usbcmd &= ~USBCMD_IAAD;

            ehci_set_interrupt(ehci, USBSTS_IAA);

            break;

        }

        /* make sure guest has acknowledged */

        /* TO-DO: is this really needed? */

        if (ehci->usbsts & USBSTS_IAA) {

            DPRINTF("IAA status bit still set.\n");

            break;

        }

        /* check that address register has been set */

        if (ehci->asynclistaddr == 0) {

            break;

        }

        ehci_set_state(ehci, async, EST_WAITLISTHEAD);

        ehci_advance_state(ehci, async);

        break;

    default:

        /* this should only be due to a developer mistake */

        fprintf(stderr, "ehci: Bad asynchronous state %d. "

                "Resetting to active\n", ehci->astate);

        assert(0);

    }

}


static uint32_t read_long(const unsigned char *p)

{

	return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];

}


PPC_OP(subfeo)

{

    do_subfeo();

    RETURN();

}


static void pci_bus_init(PCIBus *bus, DeviceState *parent,

                         const char *name,

                         MemoryRegion *address_space_mem,

                         MemoryRegion *address_space_io,

                         uint8_t devfn_min)

{

    assert(PCI_FUNC(devfn_min) == 0);

    bus->devfn_min = devfn_min;

    bus->address_space_mem = address_space_mem;

    bus->address_space_io = address_space_io;

    memory_region_init_io(&bus->master_abort_mem, OBJECT(bus),

                          &master_abort_mem_ops, bus, "pci-master-abort",

                          memory_region_size(bus->address_space_mem));

    memory_region_add_subregion_overlap(bus->address_space_mem,

                                        0, &bus->master_abort_mem,

                                        MASTER_ABORT_MEM_PRIORITY);

    /* host bridge */

    QLIST_INIT(&bus->child);

    pci_host_bus_register(bus, parent);

    vmstate_register(NULL, -1, &vmstate_pcibus, bus);

}


void qmp_change_blockdev(const char *device, const char *filename,

                         const char *format, Error **errp)

{

    BlockBackend *blk;

    BlockDriverState *bs;

    BlockDriver *drv = NULL;

    int bdrv_flags;

    Error *err = NULL;

    blk = blk_by_name(device);

    if (!blk) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    bs = blk_bs(blk);

    if (format) {

        drv = bdrv_find_whitelisted_format(format, bs->read_only);

        if (!drv) {

            error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);

            return;

        }

    }

    eject_device(blk, 0, &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;

    bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;

    qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);

}


static void do_video_out(AVFormatContext *s,

                         OutputStream *ost,

                         AVFrame *next_picture,

                         double sync_ipts)

{

    int ret, format_video_sync;

    AVPacket pkt;

    AVCodecContext *enc = ost->enc_ctx;

    AVCodecContext *mux_enc = ost->st->codec;

    int nb_frames, nb0_frames, i;

    double delta, delta0;

    double duration = 0;

    int frame_size = 0;

    InputStream *ist = NULL;

    AVFilterContext *filter = ost->filter->filter;

    if (ost->source_index >= 0)

        ist = input_streams[ost->source_index];

    if (filter->inputs[0]->frame_rate.num > 0 &&

        filter->inputs[0]->frame_rate.den > 0)

        duration = 1/(av_q2d(filter->inputs[0]->frame_rate) * av_q2d(enc->time_base));

    if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)

        duration = FFMIN(duration, 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base)));

    if (!ost->filters_script &&

        !ost->filters &&

        next_picture &&

        ist &&

        lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base)) > 0) {

        duration = lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base));

    }

    if (!next_picture) {

        //end, flushing

        nb0_frames = nb_frames = mid_pred(ost->last_nb0_frames[0],

                                          ost->last_nb0_frames[1],

                                          ost->last_nb0_frames[2]);

    } else {

        delta0 = sync_ipts - ost->sync_opts;

        delta  = delta0 + duration;

        /* by default, we output a single frame */

        nb0_frames = 0;

        nb_frames = 1;

        format_video_sync = video_sync_method;

        if (format_video_sync == VSYNC_AUTO) {

            if(!strcmp(s->oformat->name, "avi")) {

                format_video_sync = VSYNC_VFR;

            } else

                format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;

            if (   ist

                && format_video_sync == VSYNC_CFR

                && input_files[ist->file_index]->ctx->nb_streams == 1

                && input_files[ist->file_index]->input_ts_offset == 0) {

                format_video_sync = VSYNC_VSCFR;

            }

            if (format_video_sync == VSYNC_CFR && copy_ts) {

                format_video_sync = VSYNC_VSCFR;

            }

        }

        if (delta0 < 0 &&

            delta > 0 &&

            format_video_sync != VSYNC_PASSTHROUGH &&

            format_video_sync != VSYNC_DROP) {

            double cor = FFMIN(-delta0, duration);

            if (delta0 < -0.6) {

                av_log(NULL, AV_LOG_WARNING, "Past duration %f too large\n", -delta0);

            } else

                av_log(NULL, AV_LOG_DEBUG, "Cliping frame in rate conversion by %f\n", -delta0);

            sync_ipts += cor;

            duration -= cor;

            delta0 += cor;

        }

        switch (format_video_sync) {

        case VSYNC_VSCFR:

            if (ost->frame_number == 0 && delta - duration >= 0.5) {

                av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta - duration));

                delta = duration;

                delta0 = 0;

                ost->sync_opts = lrint(sync_ipts);

            }

        case VSYNC_CFR:

            // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c

            if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {

                nb_frames = 0;

            } else if (delta < -1.1)

                nb_frames = 0;

            else if (delta > 1.1) {

                nb_frames = lrintf(delta);

                if (delta0 > 1.1)

                    nb0_frames = lrintf(delta0 - 0.6);

            }

            break;

        case VSYNC_VFR:

            if (delta <= -0.6)

                nb_frames = 0;

            else if (delta > 0.6)

                ost->sync_opts = lrint(sync_ipts);

            break;

        case VSYNC_DROP:

        case VSYNC_PASSTHROUGH:

            ost->sync_opts = lrint(sync_ipts);

            break;

        default:

            av_assert0(0);

        }

    }

    nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);

    nb0_frames = FFMIN(nb0_frames, nb_frames);

    memmove(ost->last_nb0_frames + 1,

            ost->last_nb0_frames,

            sizeof(ost->last_nb0_frames[0]) * (FF_ARRAY_ELEMS(ost->last_nb0_frames) - 1));

    ost->last_nb0_frames[0] = nb0_frames;

    if (nb0_frames == 0 && ost->last_droped) {

        nb_frames_drop++;

        av_log(NULL, AV_LOG_VERBOSE,

               "*** dropping frame %d from stream %d at ts %"PRId64"\n",

               ost->frame_number, ost->st->index, ost->last_frame->pts);

    }

    if (nb_frames > (nb0_frames && ost->last_droped) + (nb_frames > nb0_frames)) {

        if (nb_frames > dts_error_threshold * 30) {

            av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);

            nb_frames_drop++;

            return;

        }

        nb_frames_dup += nb_frames - (nb0_frames && ost->last_droped) - (nb_frames > nb0_frames);

        av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);

    }

    ost->last_droped = nb_frames == nb0_frames && next_picture;

  /* duplicates frame if needed */

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

    AVFrame *in_picture;

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

    if (i < nb0_frames && ost->last_frame) {

        in_picture = ost->last_frame;

    } else

        in_picture = next_picture;

    if (!in_picture)

        return;

    in_picture->pts = ost->sync_opts;

#if 1

    if (!check_recording_time(ost))

#else

    if (ost->frame_number >= ost->max_frames)

#endif

        return;

    if (s->oformat->flags & AVFMT_RAWPICTURE &&

        enc->codec->id == AV_CODEC_ID_RAWVIDEO) {

        /* raw pictures are written as AVPicture structure to

           avoid any copies. We support temporarily the older

           method. */

        if (in_picture->interlaced_frame)

            mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;

        else

            mux_enc->field_order = AV_FIELD_PROGRESSIVE;

        pkt.data   = (uint8_t *)in_picture;

        pkt.size   =  sizeof(AVPicture);

        pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);

        pkt.flags |= AV_PKT_FLAG_KEY;

        write_frame(s, &pkt, ost);

    } else {

        int got_packet, forced_keyframe = 0;

        double pts_time;

        if (enc->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&

            ost->top_field_first >= 0)

            in_picture->top_field_first = !!ost->top_field_first;

        if (in_picture->interlaced_frame) {

            if (enc->codec->id == AV_CODEC_ID_MJPEG)

                mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;

            else

                mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;

        } else

            mux_enc->field_order = AV_FIELD_PROGRESSIVE;

        in_picture->quality = enc->global_quality;

        in_picture->pict_type = 0;

        pts_time = in_picture->pts != AV_NOPTS_VALUE ?

            in_picture->pts * av_q2d(enc->time_base) : NAN;

        if (ost->forced_kf_index < ost->forced_kf_count &&

            in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {

            ost->forced_kf_index++;

            forced_keyframe = 1;

        } else if (ost->forced_keyframes_pexpr) {

            double res;

            ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;

            res = av_expr_eval(ost->forced_keyframes_pexpr,

                               ost->forced_keyframes_expr_const_values, NULL);

            av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",

                    ost->forced_keyframes_expr_const_values[FKF_N],

                    ost->forced_keyframes_expr_const_values[FKF_N_FORCED],

                    ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],

                    ost->forced_keyframes_expr_const_values[FKF_T],

                    ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],

                    res);

            if (res) {

                forced_keyframe = 1;

                ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =

                    ost->forced_keyframes_expr_const_values[FKF_N];

                ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =

                    ost->forced_keyframes_expr_const_values[FKF_T];

                ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;

            }

            ost->forced_keyframes_expr_const_values[FKF_N] += 1;

        } else if (   ost->forced_keyframes

                   && !strncmp(ost->forced_keyframes, "source", 6)

                   && in_picture->key_frame==1) {

            forced_keyframe = 1;

        }

        if (forced_keyframe) {

            in_picture->pict_type = AV_PICTURE_TYPE_I;

            av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);

        }

        update_benchmark(NULL);

        if (debug_ts) {

            av_log(NULL, AV_LOG_INFO, "encoder <- type:video "

                   "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",

                   av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),

                   enc->time_base.num, enc->time_base.den);

        }

        ost->frames_encoded++;

        ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);

        update_benchmark("encode_video %d.%d", ost->file_index, ost->index);

        if (ret < 0) {

            av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");

            exit_program(1);

        }

        if (got_packet) {

            if (debug_ts) {

                av_log(NULL, AV_LOG_INFO, "encoder -> type:video "

                       "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",

                       av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),

                       av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));

            }

            if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))

                pkt.pts = ost->sync_opts;

            av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);

            if (debug_ts) {

                av_log(NULL, AV_LOG_INFO, "encoder -> type:video "

                    "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",

                    av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),

                    av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));

            }

            frame_size = pkt.size;

            write_frame(s, &pkt, ost);

            /* if two pass, output log */

            if (ost->logfile && enc->stats_out) {

                fprintf(ost->logfile, "%s", enc->stats_out);

            }

        }

    }

    ost->sync_opts++;

    /*

     * For video, number of frames in == number of packets out.

     * But there may be reordering, so we can't throw away frames on encoder

     * flush, we need to limit them here, before they go into encoder.

     */

    ost->frame_number++;

    if (vstats_filename && frame_size)

        do_video_stats(ost, frame_size);

  }

    if (!ost->last_frame)

        ost->last_frame = av_frame_alloc();

    av_frame_unref(ost->last_frame);

    if (next_picture)

        av_frame_ref(ost->last_frame, next_picture);

    else

        av_frame_free(&ost->last_frame);

}


static int read_header(AVFormatContext *s)

{

    BRSTMDemuxContext *b = s->priv_data;

    int bom, major, minor, codec, chunk;

    int64_t h1offset, pos, toffset;

    uint32_t size, asize, start = 0;

    AVStream *st;

    int ret = AVERROR_EOF;

    int loop = 0;

    int bfstm = !strcmp("bfstm", s->iformat->name);

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    avio_skip(s->pb, 4);

    bom = avio_rb16(s->pb);

    if (bom != 0xFEFF && bom != 0xFFFE) {

        av_log(s, AV_LOG_ERROR, "invalid byte order: %X\n", bom);

        return AVERROR_INVALIDDATA;

    }

    if (bom == 0xFFFE)

        b->little_endian = 1;

    if (!bfstm) {

        major = avio_r8(s->pb);

        minor = avio_r8(s->pb);

        avio_skip(s->pb, 4); // size of file

        size = read16(s);

        if (size < 14)

            return AVERROR_INVALIDDATA;

        avio_skip(s->pb, size - 14);

        pos = avio_tell(s->pb);

        if (avio_rl32(s->pb) != MKTAG('H','E','A','D'))

            return AVERROR_INVALIDDATA;

    } else {

        uint32_t info_offset = 0;

        uint16_t section_count, header_size, i;

        header_size = read16(s); // 6

        avio_skip(s->pb, 4); // Unknown constant 0x00030000

        avio_skip(s->pb, 4); // size of file

        section_count = read16(s);

        avio_skip(s->pb, 2); // padding

        for (i = 0; avio_tell(s->pb) < header_size

                    && !(start && info_offset)

                    && i < section_count; i++) {

            uint16_t flag = read16(s);

            avio_skip(s->pb, 2);

            switch (flag) {

            case 0x4000:

                info_offset = read32(s);

                /*info_size =*/ read32(s);

                break;

            case 0x4001:

                avio_skip(s->pb, 4); // seek offset

                avio_skip(s->pb, 4); // seek size

                break;

            case 0x4002:

                start = read32(s) + 8;

                avio_skip(s->pb, 4); //data_size = read32(s);

                break;

            case 0x4003:

                avio_skip(s->pb, 4); // REGN offset

                avio_skip(s->pb, 4); // REGN size

                break;

            }

        }

        if (!info_offset || !start)

            return AVERROR_INVALIDDATA;

        avio_skip(s->pb, info_offset - avio_tell(s->pb));

        pos = avio_tell(s->pb);

        if (avio_rl32(s->pb) != MKTAG('I','N','F','O'))

            return AVERROR_INVALIDDATA;

    }

    size = read32(s);

    if (size < 192)

        return AVERROR_INVALIDDATA;

    avio_skip(s->pb, 4); // unknown

    h1offset = read32(s);

    if (h1offset > size)

        return AVERROR_INVALIDDATA;

    avio_skip(s->pb, 12);

    toffset = read32(s) + 16LL;

    if (toffset > size)

        return AVERROR_INVALIDDATA;

    avio_skip(s->pb, pos + h1offset + 8 - avio_tell(s->pb));

    codec = avio_r8(s->pb);

    switch (codec) {

    case 0: codec = AV_CODEC_ID_PCM_S8_PLANAR;    break;

    case 1: codec = b->little_endian ?

                    AV_CODEC_ID_PCM_S16LE_PLANAR :

                    AV_CODEC_ID_PCM_S16BE_PLANAR; break;

    case 2: codec = b->little_endian ?

                    AV_CODEC_ID_ADPCM_THP_LE :

                    AV_CODEC_ID_ADPCM_THP;        break;

    default:

        avpriv_request_sample(s, "codec %d", codec);

        return AVERROR_PATCHWELCOME;

    }

    loop = avio_r8(s->pb); // loop flag

    st->codec->codec_id = codec;

    st->codec->channels = avio_r8(s->pb);

    if (!st->codec->channels)

        return AVERROR_INVALIDDATA;

    avio_skip(s->pb, 1); // padding

    st->codec->sample_rate = bfstm ? read32(s) : read16(s);

    if (!st->codec->sample_rate)

        return AVERROR_INVALIDDATA;

    if (!bfstm)

        avio_skip(s->pb, 2); // padding

    if (loop) {

        if (av_dict_set_int(&s->metadata, "loop_start",

                            av_rescale(read32(s), AV_TIME_BASE,

                                       st->codec->sample_rate),

                            0) < 0)

            return AVERROR(ENOMEM);

    } else {

        avio_skip(s->pb, 4);

    }

    st->start_time = 0;

    st->duration = read32(s);

    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);

    if (!bfstm)

        start = read32(s);

    b->current_block = 0;

    b->block_count = read32(s);

    if (b->block_count > UINT16_MAX) {

        av_log(s, AV_LOG_WARNING, "too many blocks: %u\n", b->block_count);

        return AVERROR_INVALIDDATA;

    }

    b->block_size = read32(s);

    if (b->block_size > UINT32_MAX / st->codec->channels)

        return AVERROR_INVALIDDATA;

    b->samples_per_block = read32(s);

    b->last_block_used_bytes = read32(s);

    b->last_block_samples = read32(s);

    b->last_block_size = read32(s);

    if (b->last_block_size > UINT32_MAX / st->codec->channels)

        return AVERROR_INVALIDDATA;

    if (b->last_block_used_bytes > b->last_block_size)

        return AVERROR_INVALIDDATA;

    if (codec == AV_CODEC_ID_ADPCM_THP || codec == AV_CODEC_ID_ADPCM_THP_LE) {

        int ch;

        avio_skip(s->pb, pos + toffset - avio_tell(s->pb));

        if (!bfstm)

            toffset = read32(s) + 16LL;

        else

            toffset = toffset + read32(s) + st->codec->channels * 8 - 8;

        if (toffset > size)

            return AVERROR_INVALIDDATA;

        avio_skip(s->pb, pos + toffset - avio_tell(s->pb));

        b->table = av_mallocz(32 * st->codec->channels);

        if (!b->table)

            return AVERROR(ENOMEM);

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

            if (avio_read(s->pb, b->table + ch * 32, 32) != 32) {

                ret = AVERROR_INVALIDDATA;

                goto fail;

            }

            avio_skip(s->pb, bfstm ? 14 : 24);

        }

    }

    if (size < (avio_tell(s->pb) - pos)) {

        ret = AVERROR_INVALIDDATA;

        goto fail;

    }

    avio_skip(s->pb, size - (avio_tell(s->pb) - pos));

    while (!avio_feof(s->pb)) {

        chunk = avio_rl32(s->pb);

        size  = read32(s);

        if (size < 8) {

            ret = AVERROR_INVALIDDATA;

            goto fail;

        }

        size -= 8;

        switch (chunk) {

        case MKTAG('S','E','E','K'):

        case MKTAG('A','D','P','C'):

            if (codec != AV_CODEC_ID_ADPCM_THP &&

                codec != AV_CODEC_ID_ADPCM_THP_LE)

                goto skip;

            asize = b->block_count * st->codec->channels * 4;

            if (size < asize) {

                ret = AVERROR_INVALIDDATA;

                goto fail;

            }

            if (b->adpc) {

                av_log(s, AV_LOG_WARNING, "skipping additional ADPC chunk\n");

                goto skip;

            } else {

                b->adpc = av_mallocz(asize);

                if (!b->adpc) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

                if (bfstm && codec != AV_CODEC_ID_ADPCM_THP_LE) {

                    // Big-endian BFSTMs have little-endian SEEK tables

                    // for some strange reason.

                    int i;

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

                        b->adpc[i+1] = avio_r8(s->pb);

                        b->adpc[i]   = avio_r8(s->pb);

                    }

                } else {

                    avio_read(s->pb, b->adpc, asize);

                }

                avio_skip(s->pb, size - asize);

            }

            break;

        case MKTAG('D','A','T','A'):

            if ((start < avio_tell(s->pb)) ||

                (!b->adpc && (codec == AV_CODEC_ID_ADPCM_THP ||

                              codec == AV_CODEC_ID_ADPCM_THP_LE))) {

                ret = AVERROR_INVALIDDATA;

                goto fail;

            }

            avio_skip(s->pb, start - avio_tell(s->pb));

            if (bfstm && (codec == AV_CODEC_ID_ADPCM_THP ||

                          codec == AV_CODEC_ID_ADPCM_THP_LE))

                avio_skip(s->pb, 24);

            b->data_start = avio_tell(s->pb);

            if (!bfstm && (major != 1 || minor))

                avpriv_request_sample(s, "Version %d.%d", major, minor);

            return 0;

        default:

            av_log(s, AV_LOG_WARNING, "skipping unknown chunk: %X\n", chunk);

skip:

            avio_skip(s->pb, size);

        }

    }

fail:

    read_close(s);

    return ret;

}


static inline void RENAME(rgb15to16)(const uint8_t *src,uint8_t *dst,unsigned src_size)

{

  register const uint8_t* s=src;

  register uint8_t* d=dst;

  register const uint8_t *end;

  const uint8_t *mm_end;

  end = s + src_size;

#ifdef HAVE_MMX

  __asm __volatile(PREFETCH"	%0"::"m"(*s));

  __asm __volatile("movq	%0, %%mm4"::"m"(mask15s));

  mm_end = end - 15;

  while(s<mm_end)

  {

	__asm __volatile(

		PREFETCH"	32%1\n\t"

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

		"movq	8%1, %%mm2\n\t"

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

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

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

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

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

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

		MOVNTQ"	%%mm0, %0\n\t"

		MOVNTQ"	%%mm2, 8%0"

		:"=m"(*d)

		:"m"(*s)

		);

	d+=16;

	s+=16;

  }

  __asm __volatile(SFENCE:::"memory");

  __asm __volatile(EMMS:::"memory");

#endif

    mm_end = end - 3;

    while(s < mm_end)

    {

	register unsigned x= *((uint32_t *)s);

	*((uint32_t *)d) = (x&0x7FFF7FFF) + (x&0x7FE07FE0);

	d+=4;

	s+=4;

    }

    if(s < end)

    {

	register unsigned short x= *((uint16_t *)s);

	*((uint16_t *)d) = (x&0x7FFF) + (x&0x7FE0);

    }

}


static void dec_sexth(DisasContext *dc)

{

    LOG_DIS("sexth r%d, r%d\n", dc->r2, dc->r0);

    if (!(dc->env->features & LM32_FEATURE_SIGN_EXTEND)) {

        cpu_abort(dc->env, "hardware sign extender is not available\n");

    }

    tcg_gen_ext16s_tl(cpu_R[dc->r2], cpu_R[dc->r0]);

}


static int X264_frame(AVCodecContext *ctx, AVPacket *pkt, const AVFrame *frame,

                      int *got_packet)

{

    X264Context *x4 = ctx->priv_data;

    x264_nal_t *nal;

    int nnal, i, ret;

    x264_picture_t pic_out;

    x264_picture_init( &x4->pic );

    x4->pic.img.i_csp   = x4->params.i_csp;

    if (x264_bit_depth > 8)

        x4->pic.img.i_csp |= X264_CSP_HIGH_DEPTH;

    x4->pic.img.i_plane = avfmt2_num_planes(ctx->pix_fmt);

    if (frame) {

        for (i = 0; i < x4->pic.img.i_plane; i++) {

            x4->pic.img.plane[i]    = frame->data[i];

            x4->pic.img.i_stride[i] = frame->linesize[i];

        }

        x4->pic.i_pts  = frame->pts;

        x4->pic.i_type =

            frame->pict_type == AV_PICTURE_TYPE_I ? X264_TYPE_KEYFRAME :

            frame->pict_type == AV_PICTURE_TYPE_P ? X264_TYPE_P :

            frame->pict_type == AV_PICTURE_TYPE_B ? X264_TYPE_B :

                                            X264_TYPE_AUTO;

        if (x4->params.b_interlaced && x4->params.b_tff != frame->top_field_first) {

            x4->params.b_tff = frame->top_field_first;

            x264_encoder_reconfig(x4->enc, &x4->params);

        }

        if (x4->params.vui.i_sar_height != ctx->sample_aspect_ratio.den ||

            x4->params.vui.i_sar_width  != ctx->sample_aspect_ratio.num) {

            x4->params.vui.i_sar_height = ctx->sample_aspect_ratio.den;

            x4->params.vui.i_sar_width  = ctx->sample_aspect_ratio.num;

            x264_encoder_reconfig(x4->enc, &x4->params);

        }

    }

    do {

        if (x264_encoder_encode(x4->enc, &nal, &nnal, frame? &x4->pic: NULL, &pic_out) < 0)

            return -1;

        ret = encode_nals(ctx, pkt, nal, nnal);

        if (ret < 0)

            return -1;

    } while (!ret && !frame && x264_encoder_delayed_frames(x4->enc));

    pkt->pts = pic_out.i_pts;

    pkt->dts = pic_out.i_dts;

    switch (pic_out.i_type) {

    case X264_TYPE_IDR:

    case X264_TYPE_I:

        x4->out_pic.pict_type = AV_PICTURE_TYPE_I;

        break;

    case X264_TYPE_P:

        x4->out_pic.pict_type = AV_PICTURE_TYPE_P;

        break;

    case X264_TYPE_B:

    case X264_TYPE_BREF:

        x4->out_pic.pict_type = AV_PICTURE_TYPE_B;

        break;

    }

    pkt->flags |= AV_PKT_FLAG_KEY*pic_out.b_keyframe;

    if (ret)

        x4->out_pic.quality = (pic_out.i_qpplus1 - 1) * FF_QP2LAMBDA;

    *got_packet = ret;

    return 0;

}


QCryptoHmac *qcrypto_hmac_new(QCryptoHashAlgorithm alg,

                              const uint8_t *key, size_t nkey,

                              Error **errp)

{

    QCryptoHmac *hmac;

    void *ctx = NULL;

    Error *err2 = NULL;

    QCryptoHmacDriver *drv = NULL;

#ifdef CONFIG_AF_ALG

    ctx = qcrypto_afalg_hmac_ctx_new(alg, key, nkey, &err2);

    if (ctx) {

        drv = &qcrypto_hmac_afalg_driver;

    }

#endif

    if (!ctx) {

        ctx = qcrypto_hmac_ctx_new(alg, key, nkey, errp);

        if (!ctx) {

            return NULL;

        }

        drv = &qcrypto_hmac_lib_driver;

        error_free(err2);

    }

    hmac = g_new0(QCryptoHmac, 1);

    hmac->alg = alg;

    hmac->opaque = ctx;

    hmac->driver = (void *)drv;

    return hmac;

}