av_cold int ff_MPV_encode_init(AVCodecContext *avctx)

{

    MpegEncContext *s = avctx->priv_data;

    int i, ret;

    MPV_encode_defaults(s);

    switch (avctx->codec_id) {

    case AV_CODEC_ID_MPEG2VIDEO:

        if (avctx->pix_fmt != AV_PIX_FMT_YUV420P &&

            avctx->pix_fmt != AV_PIX_FMT_YUV422P) {

            av_log(avctx, AV_LOG_ERROR,

                   "only YUV420 and YUV422 are supported\n");

            return -1;

        }

        break;

    case AV_CODEC_ID_MJPEG:

    case AV_CODEC_ID_AMV:

        if (avctx->pix_fmt != AV_PIX_FMT_YUVJ420P &&

            avctx->pix_fmt != AV_PIX_FMT_YUVJ422P &&

            avctx->pix_fmt != AV_PIX_FMT_YUVJ444P &&

            ((avctx->pix_fmt != AV_PIX_FMT_YUV420P &&

              avctx->pix_fmt != AV_PIX_FMT_YUV422P &&

              avctx->pix_fmt != AV_PIX_FMT_YUV444P) ||

             avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL)) {

            av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");

            return -1;

        }

        break;

    default:

        if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {

            av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");

            return -1;

        }

    }

    switch (avctx->pix_fmt) {

    case AV_PIX_FMT_YUVJ444P:

    case AV_PIX_FMT_YUV444P:

        s->chroma_format = CHROMA_444;

        break;

    case AV_PIX_FMT_YUVJ422P:

    case AV_PIX_FMT_YUV422P:

        s->chroma_format = CHROMA_422;

        break;

    case AV_PIX_FMT_YUVJ420P:

    case AV_PIX_FMT_YUV420P:

    default:

        s->chroma_format = CHROMA_420;

        break;

    }

    s->bit_rate = avctx->bit_rate;

    s->width    = avctx->width;

    s->height   = avctx->height;

    if (avctx->gop_size > 600 &&

        avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

        av_log(avctx, AV_LOG_WARNING,

               "keyframe interval too large!, reducing it from %d to %d\n",

               avctx->gop_size, 600);

        avctx->gop_size = 600;

    }

    s->gop_size     = avctx->gop_size;

    s->avctx        = avctx;

    s->flags        = avctx->flags;

    s->flags2       = avctx->flags2;

    if (avctx->max_b_frames > MAX_B_FRAMES) {

        av_log(avctx, AV_LOG_ERROR, "Too many B-frames requested, maximum "

               "is %d.\n", MAX_B_FRAMES);

        avctx->max_b_frames = MAX_B_FRAMES;

    }

    s->max_b_frames = avctx->max_b_frames;

    s->codec_id     = avctx->codec->id;

    s->strict_std_compliance = avctx->strict_std_compliance;

    s->quarter_sample     = (avctx->flags & CODEC_FLAG_QPEL) != 0;

    s->mpeg_quant         = avctx->mpeg_quant;

    s->rtp_mode           = !!avctx->rtp_payload_size;

    s->intra_dc_precision = avctx->intra_dc_precision;

    s->user_specified_pts = AV_NOPTS_VALUE;

    if (s->gop_size <= 1) {

        s->intra_only = 1;

        s->gop_size   = 12;

    } else {

        s->intra_only = 0;

    }

    s->me_method = avctx->me_method;

    /* Fixed QSCALE */

    s->fixed_qscale = !!(avctx->flags & CODEC_FLAG_QSCALE);

    s->adaptive_quant = (s->avctx->lumi_masking ||

                         s->avctx->dark_masking ||

                         s->avctx->temporal_cplx_masking ||

                         s->avctx->spatial_cplx_masking  ||

                         s->avctx->p_masking      ||

                         s->avctx->border_masking ||

                         (s->mpv_flags & FF_MPV_FLAG_QP_RD)) &&

                        !s->fixed_qscale;

    s->loop_filter      = !!(s->flags & CODEC_FLAG_LOOP_FILTER);

    if (avctx->rc_max_rate && !avctx->rc_buffer_size) {

        switch(avctx->codec_id) {

        case AV_CODEC_ID_MPEG1VIDEO:

        case AV_CODEC_ID_MPEG2VIDEO:

            avctx->rc_buffer_size = FFMAX(avctx->rc_max_rate, 15000000) * 112L / 15000000 * 16384;

            break;

        case AV_CODEC_ID_MPEG4:

        case AV_CODEC_ID_MSMPEG4V1:

        case AV_CODEC_ID_MSMPEG4V2:

        case AV_CODEC_ID_MSMPEG4V3:

            if       (avctx->rc_max_rate >= 15000000) {

                avctx->rc_buffer_size = 320 + (avctx->rc_max_rate - 15000000L) * (760-320) / (38400000 - 15000000);

            } else if(avctx->rc_max_rate >=  2000000) {

                avctx->rc_buffer_size =  80 + (avctx->rc_max_rate -  2000000L) * (320- 80) / (15000000 -  2000000);

            } else if(avctx->rc_max_rate >=   384000) {

                avctx->rc_buffer_size =  40 + (avctx->rc_max_rate -   384000L) * ( 80- 40) / ( 2000000 -   384000);

            } else

                avctx->rc_buffer_size = 40;

            avctx->rc_buffer_size *= 16384;

            break;

        }

        if (avctx->rc_buffer_size) {

            av_log(avctx, AV_LOG_INFO, "Automatically choosing VBV buffer size of %d kbyte\n", avctx->rc_buffer_size/8192);

        }

    }

    if ((!avctx->rc_max_rate) != (!avctx->rc_buffer_size)) {

        av_log(avctx, AV_LOG_ERROR, "Either both buffer size and max rate or neither must be specified\n");

        if (avctx->rc_max_rate && !avctx->rc_buffer_size)

            return -1;

    }

    if (avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate) {

        av_log(avctx, AV_LOG_INFO,

               "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");

    }

    if (avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate) {

        av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");

        return -1;

    }

    if (avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate) {

        av_log(avctx, AV_LOG_ERROR, "bitrate above max bitrate\n");

        return -1;

    }

    if (avctx->rc_max_rate &&

        avctx->rc_max_rate == avctx->bit_rate &&

        avctx->rc_max_rate != avctx->rc_min_rate) {

        av_log(avctx, AV_LOG_INFO,

               "impossible bitrate constraints, this will fail\n");

    }

    if (avctx->rc_buffer_size &&

        avctx->bit_rate * (int64_t)avctx->time_base.num >

            avctx->rc_buffer_size * (int64_t)avctx->time_base.den) {

        av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");

        return -1;

    }

    if (!s->fixed_qscale &&

        avctx->bit_rate * av_q2d(avctx->time_base) >

            avctx->bit_rate_tolerance) {

        av_log(avctx, AV_LOG_ERROR,

               "bitrate tolerance %d too small for bitrate %d\n", avctx->bit_rate_tolerance, avctx->bit_rate);

        return -1;

    }

    if (s->avctx->rc_max_rate &&

        s->avctx->rc_min_rate == s->avctx->rc_max_rate &&

        (s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||

         s->codec_id == AV_CODEC_ID_MPEG2VIDEO) &&

        90000LL * (avctx->rc_buffer_size - 1) >

            s->avctx->rc_max_rate * 0xFFFFLL) {

        av_log(avctx, AV_LOG_INFO,

               "Warning vbv_delay will be set to 0xFFFF (=VBR) as the "

               "specified vbv buffer is too large for the given bitrate!\n");

    }

    if ((s->flags & CODEC_FLAG_4MV)  && s->codec_id != AV_CODEC_ID_MPEG4 &&

        s->codec_id != AV_CODEC_ID_H263 && s->codec_id != AV_CODEC_ID_H263P &&

        s->codec_id != AV_CODEC_ID_FLV1) {

        av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");

        return -1;

    }

    if (s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE) {

        av_log(avctx, AV_LOG_ERROR,

               "OBMC is only supported with simple mb decision\n");

        return -1;

    }

    if (s->quarter_sample && s->codec_id != AV_CODEC_ID_MPEG4) {

        av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");

        return -1;

    }

    if (s->max_b_frames                    &&

        s->codec_id != AV_CODEC_ID_MPEG4      &&

        s->codec_id != AV_CODEC_ID_MPEG1VIDEO &&

        s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {

        av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");

        return -1;

    }

    if (s->max_b_frames < 0) {

        av_log(avctx, AV_LOG_ERROR,

               "max b frames must be 0 or positive for mpegvideo based encoders\n");

        return -1;

    }

    if ((s->codec_id == AV_CODEC_ID_MPEG4 ||

         s->codec_id == AV_CODEC_ID_H263  ||

         s->codec_id == AV_CODEC_ID_H263P) &&

        (avctx->sample_aspect_ratio.num > 255 ||

         avctx->sample_aspect_ratio.den > 255)) {

        av_log(avctx, AV_LOG_WARNING,

               "Invalid pixel aspect ratio %i/%i, limit is 255/255 reducing\n",

               avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);

        av_reduce(&avctx->sample_aspect_ratio.num, &avctx->sample_aspect_ratio.den,

                   avctx->sample_aspect_ratio.num,  avctx->sample_aspect_ratio.den, 255);

    }

    if ((s->codec_id == AV_CODEC_ID_H263  ||

         s->codec_id == AV_CODEC_ID_H263P) &&

        (avctx->width  > 2048 ||

         avctx->height > 1152 )) {

        av_log(avctx, AV_LOG_ERROR, "H.263 does not support resolutions above 2048x1152\n");

        return -1;

    }

    if ((s->codec_id == AV_CODEC_ID_H263  ||

         s->codec_id == AV_CODEC_ID_H263P) &&

        ((avctx->width &3) ||

         (avctx->height&3) )) {

        av_log(avctx, AV_LOG_ERROR, "w/h must be a multiple of 4\n");

        return -1;

    }

    if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO &&

        (avctx->width  > 4095 ||

         avctx->height > 4095 )) {

        av_log(avctx, AV_LOG_ERROR, "MPEG-1 does not support resolutions above 4095x4095\n");

        return -1;

    }

    if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO &&

        (avctx->width  > 16383 ||

         avctx->height > 16383 )) {

        av_log(avctx, AV_LOG_ERROR, "MPEG-2 does not support resolutions above 16383x16383\n");

        return -1;

    }

    if (s->codec_id == AV_CODEC_ID_RV10 &&

        (avctx->width &15 ||

         avctx->height&15 )) {

        av_log(avctx, AV_LOG_ERROR, "width and height must be a multiple of 16\n");

        return AVERROR(EINVAL);

    }

    if (s->codec_id == AV_CODEC_ID_RV20 &&

        (avctx->width &3 ||

         avctx->height&3 )) {

        av_log(avctx, AV_LOG_ERROR, "width and height must be a multiple of 4\n");

        return AVERROR(EINVAL);

    }

    if ((s->codec_id == AV_CODEC_ID_WMV1 ||

         s->codec_id == AV_CODEC_ID_WMV2) &&

         avctx->width & 1) {

         av_log(avctx, AV_LOG_ERROR, "width must be multiple of 2\n");

         return -1;

    }

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

        s->codec_id != AV_CODEC_ID_MPEG4 && s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {

        av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");

        return -1;

    }

    // FIXME mpeg2 uses that too

    if (s->mpeg_quant && (   s->codec_id != AV_CODEC_ID_MPEG4

                          && s->codec_id != AV_CODEC_ID_MPEG2VIDEO)) {

        av_log(avctx, AV_LOG_ERROR,

               "mpeg2 style quantization not supported by codec\n");

        return -1;

    }

    if ((s->mpv_flags & FF_MPV_FLAG_CBP_RD) && !avctx->trellis) {

        av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");

        return -1;

    }

    if ((s->mpv_flags & FF_MPV_FLAG_QP_RD) &&

        s->avctx->mb_decision != FF_MB_DECISION_RD) {

        av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");

        return -1;

    }

    if (s->avctx->scenechange_threshold < 1000000000 &&

        (s->flags & CODEC_FLAG_CLOSED_GOP)) {

        av_log(avctx, AV_LOG_ERROR,

               "closed gop with scene change detection are not supported yet, "

               "set threshold to 1000000000\n");

        return -1;

    }

    if (s->flags & CODEC_FLAG_LOW_DELAY) {

        if (s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {

            av_log(avctx, AV_LOG_ERROR,

                  "low delay forcing is only available for mpeg2\n");

            return -1;

        }

        if (s->max_b_frames != 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "b frames cannot be used with low delay\n");

            return -1;

        }

    }

    if (s->q_scale_type == 1) {

        if (avctx->qmax > 12) {

            av_log(avctx, AV_LOG_ERROR,

                   "non linear quant only supports qmax <= 12 currently\n");

            return -1;

        }

    }

    if (s->avctx->thread_count > 1         &&

        s->codec_id != AV_CODEC_ID_MPEG4      &&

        s->codec_id != AV_CODEC_ID_MPEG1VIDEO &&

        s->codec_id != AV_CODEC_ID_MPEG2VIDEO &&

        s->codec_id != AV_CODEC_ID_MJPEG      &&

        (s->codec_id != AV_CODEC_ID_H263P)) {

        av_log(avctx, AV_LOG_ERROR,

               "multi threaded encoding not supported by codec\n");

        return -1;

    }

    if (s->avctx->thread_count < 1) {

        av_log(avctx, AV_LOG_ERROR,

               "automatic thread number detection not supported by codec, "

               "patch welcome\n");

        return -1;

    }

    if (s->avctx->slices > 1 || s->avctx->thread_count > 1)

        s->rtp_mode = 1;

    if (s->avctx->thread_count > 1 && s->codec_id == AV_CODEC_ID_H263P)

        s->h263_slice_structured = 1;

    if (!avctx->time_base.den || !avctx->time_base.num) {

        av_log(avctx, AV_LOG_ERROR, "framerate not set\n");

        return -1;

    }

    i = (INT_MAX / 2 + 128) >> 8;

    if (avctx->mb_threshold >= i) {

        av_log(avctx, AV_LOG_ERROR, "mb_threshold too large, max is %d\n",

               i - 1);

        return -1;

    }

    if (avctx->b_frame_strategy && (avctx->flags & CODEC_FLAG_PASS2)) {

        av_log(avctx, AV_LOG_INFO,

               "notice: b_frame_strategy only affects the first pass\n");

        avctx->b_frame_strategy = 0;

    }

    i = av_gcd(avctx->time_base.den, avctx->time_base.num);

    if (i > 1) {

        av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");

        avctx->time_base.den /= i;

        avctx->time_base.num /= i;

        //return -1;

    }

    if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG1VIDEO || s->codec_id == AV_CODEC_ID_MPEG2VIDEO || s->codec_id == AV_CODEC_ID_MJPEG || s->codec_id==AV_CODEC_ID_AMV) {

        // (a + x * 3 / 8) / x

        s->intra_quant_bias = 3 << (QUANT_BIAS_SHIFT - 3);

        s->inter_quant_bias = 0;

    } else {

        s->intra_quant_bias = 0;

        // (a - x / 4) / x

        s->inter_quant_bias = -(1 << (QUANT_BIAS_SHIFT - 2));

    }

    if (avctx->qmin > avctx->qmax || avctx->qmin <= 0) {

        av_log(avctx, AV_LOG_ERROR, "qmin and or qmax are invalid, they must be 0 < min <= max\n");

        return AVERROR(EINVAL);

    }

    if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)

        s->intra_quant_bias = avctx->intra_quant_bias;

    if (avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)

        s->inter_quant_bias = avctx->inter_quant_bias;

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

    if (avctx->codec_id == AV_CODEC_ID_MPEG4 &&

        s->avctx->time_base.den > (1 << 16) - 1) {

        av_log(avctx, AV_LOG_ERROR,

               "timebase %d/%d not supported by MPEG 4 standard, "

               "the maximum admitted value for the timebase denominator "

               "is %d\n", s->avctx->time_base.num, s->avctx->time_base.den,

               (1 << 16) - 1);

        return -1;

    }

    s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;

    switch (avctx->codec->id) {

    case AV_CODEC_ID_MPEG1VIDEO:

        s->out_format = FMT_MPEG1;

        s->low_delay  = !!(s->flags & CODEC_FLAG_LOW_DELAY);

        avctx->delay  = s->low_delay ? 0 : (s->max_b_frames + 1);

        break;

    case AV_CODEC_ID_MPEG2VIDEO:

        s->out_format = FMT_MPEG1;

        s->low_delay  = !!(s->flags & CODEC_FLAG_LOW_DELAY);

        avctx->delay  = s->low_delay ? 0 : (s->max_b_frames + 1);

        s->rtp_mode   = 1;

        break;

    case AV_CODEC_ID_MJPEG:

    case AV_CODEC_ID_AMV:

        s->out_format = FMT_MJPEG;

        s->intra_only = 1; /* force intra only for jpeg */

        if (!CONFIG_MJPEG_ENCODER ||

            ff_mjpeg_encode_init(s) < 0)

            return -1;

        avctx->delay = 0;

        s->low_delay = 1;

        break;

    case AV_CODEC_ID_H261:

        if (!CONFIG_H261_ENCODER)

            return -1;

        if (ff_h261_get_picture_format(s->width, s->height) < 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "The specified picture size of %dx%d is not valid for the "

                   "H.261 codec.\nValid sizes are 176x144, 352x288\n",

                    s->width, s->height);

            return -1;

        }

        s->out_format = FMT_H261;

        avctx->delay  = 0;

        s->low_delay  = 1;

        break;

    case AV_CODEC_ID_H263:

        if (!CONFIG_H263_ENCODER)

            return -1;

        if (ff_match_2uint16(ff_h263_format, FF_ARRAY_ELEMS(ff_h263_format),

                             s->width, s->height) == 8) {

            av_log(avctx, AV_LOG_ERROR,

                   "The specified picture size of %dx%d is not valid for "

                   "the H.263 codec.\nValid sizes are 128x96, 176x144, "

                   "352x288, 704x576, and 1408x1152. "

                   "Try H.263+.\n", s->width, s->height);

            return -1;

        }

        s->out_format = FMT_H263;

        avctx->delay  = 0;

        s->low_delay  = 1;

        break;

    case AV_CODEC_ID_H263P:

        s->out_format = FMT_H263;

        s->h263_plus  = 1;

        /* Fx */

        s->h263_aic        = (avctx->flags & CODEC_FLAG_AC_PRED) ? 1 : 0;

        s->modified_quant  = s->h263_aic;

        s->loop_filter     = (avctx->flags & CODEC_FLAG_LOOP_FILTER) ? 1 : 0;

        s->unrestricted_mv = s->obmc || s->loop_filter || s->umvplus;

        /* /Fx */

        /* These are just to be sure */

        avctx->delay = 0;

        s->low_delay = 1;

        break;

    case AV_CODEC_ID_FLV1:

        s->out_format      = FMT_H263;

        s->h263_flv        = 2; /* format = 1; 11-bit codes */

        s->unrestricted_mv = 1;

        s->rtp_mode  = 0; /* don't allow GOB */

        avctx->delay = 0;

        s->low_delay = 1;

        break;

    case AV_CODEC_ID_RV10:

        s->out_format = FMT_H263;

        avctx->delay  = 0;

        s->low_delay  = 1;

        break;

    case AV_CODEC_ID_RV20:

        s->out_format      = FMT_H263;

        avctx->delay       = 0;

        s->low_delay       = 1;

        s->modified_quant  = 1;

        s->h263_aic        = 1;

        s->h263_plus       = 1;

        s->loop_filter     = 1;

        s->unrestricted_mv = 0;

        break;

    case AV_CODEC_ID_MPEG4:

        s->out_format      = FMT_H263;

        s->h263_pred       = 1;

        s->unrestricted_mv = 1;

        s->low_delay       = s->max_b_frames ? 0 : 1;

        avctx->delay       = s->low_delay ? 0 : (s->max_b_frames + 1);

        break;

    case AV_CODEC_ID_MSMPEG4V2:

        s->out_format      = FMT_H263;

        s->h263_pred       = 1;

        s->unrestricted_mv = 1;

        s->msmpeg4_version = 2;

        avctx->delay       = 0;

        s->low_delay       = 1;

        break;

    case AV_CODEC_ID_MSMPEG4V3:

        s->out_format        = FMT_H263;

        s->h263_pred         = 1;

        s->unrestricted_mv   = 1;

        s->msmpeg4_version   = 3;

        s->flipflop_rounding = 1;

        avctx->delay         = 0;

        s->low_delay         = 1;

        break;

    case AV_CODEC_ID_WMV1:

        s->out_format        = FMT_H263;

        s->h263_pred         = 1;

        s->unrestricted_mv   = 1;

        s->msmpeg4_version   = 4;

        s->flipflop_rounding = 1;

        avctx->delay         = 0;

        s->low_delay         = 1;

        break;

    case AV_CODEC_ID_WMV2:

        s->out_format        = FMT_H263;

        s->h263_pred         = 1;

        s->unrestricted_mv   = 1;

        s->msmpeg4_version   = 5;

        s->flipflop_rounding = 1;

        avctx->delay         = 0;

        s->low_delay         = 1;

        break;

    default:

        return -1;

    }

    avctx->has_b_frames = !s->low_delay;

    s->encoding = 1;

    s->progressive_frame    =

    s->progressive_sequence = !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT |

                                                CODEC_FLAG_INTERLACED_ME) ||

                                s->alternate_scan);

    /* init */

    if (ff_MPV_common_init(s) < 0)

        return -1;

    s->avctx->coded_frame = s->current_picture.f;

    if (s->msmpeg4_version) {

        FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_stats,

                          2 * 2 * (MAX_LEVEL + 1) *

                          (MAX_RUN + 1) * 2 * sizeof(int), fail);

    }

    FF_ALLOCZ_OR_GOTO(s->avctx, s->avctx->stats_out, 256, fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix,   64 * 32 * sizeof(int), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_chroma_intra_matrix, 64 * 32 * sizeof(int), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix,   64 * 32 * sizeof(int), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_chroma_intra_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->input_picture,

                      MAX_PICTURE_COUNT * sizeof(Picture *), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->reordered_input_picture,

                      MAX_PICTURE_COUNT * sizeof(Picture *), fail);

    if (s->avctx->noise_reduction) {

        FF_ALLOCZ_OR_GOTO(s->avctx, s->dct_offset,

                          2 * 64 * sizeof(uint16_t), fail);

    }

    ff_dct_encode_init(s);

    if ((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)

        s->chroma_qscale_table = ff_h263_chroma_qscale_table;

    s->quant_precision = 5;

    ff_set_cmp(&s->dsp, s->dsp.ildct_cmp, s->avctx->ildct_cmp);

    ff_set_cmp(&s->dsp, s->dsp.frame_skip_cmp, s->avctx->frame_skip_cmp);

    if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)

        ff_h261_encode_init(s);

    if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)

        ff_h263_encode_init(s);

    if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)

        ff_msmpeg4_encode_init(s);

    if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)

        && s->out_format == FMT_MPEG1)

        ff_mpeg1_encode_init(s);

    /* init q matrix */

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

        int j = s->dsp.idct_permutation[i];

        if (CONFIG_MPEG4_ENCODER && s->codec_id == AV_CODEC_ID_MPEG4 &&

            s->mpeg_quant) {

            s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];

            s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];

        } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {

            s->intra_matrix[j] =

            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];

        } else {

            /* mpeg1/2 */

            s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];

            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];

        }

        if (s->avctx->intra_matrix)

            s->intra_matrix[j] = s->avctx->intra_matrix[i];

        if (s->avctx->inter_matrix)

            s->inter_matrix[j] = s->avctx->inter_matrix[i];

    }

    /* precompute matrix */

    /* for mjpeg, we do include qscale in the matrix */

    if (s->out_format != FMT_MJPEG) {

        ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,

                          s->intra_matrix, s->intra_quant_bias, avctx->qmin,

                          31, 1);

        ff_convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16,

                          s->inter_matrix, s->inter_quant_bias, avctx->qmin,

                          31, 0);

    }

    if (ff_rate_control_init(s) < 0)

        return -1;

#if FF_API_ERROR_RATE

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->error_rate)

        s->error_rate = avctx->error_rate;

    FF_ENABLE_DEPRECATION_WARNINGS;

#endif

    if (avctx->b_frame_strategy == 2) {

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

            s->tmp_frames[i] = av_frame_alloc();

            if (!s->tmp_frames[i])

                return AVERROR(ENOMEM);

            s->tmp_frames[i]->format = AV_PIX_FMT_YUV420P;

            s->tmp_frames[i]->width  = s->width  >> avctx->brd_scale;

            s->tmp_frames[i]->height = s->height >> avctx->brd_scale;

            ret = av_frame_get_buffer(s->tmp_frames[i], 32);

            if (ret < 0)

                return ret;

        }

    }

    return 0;

fail:

    ff_MPV_encode_end(avctx);

    return AVERROR_UNKNOWN;

}


int pcnet_can_receive(NetClientState *nc)

{

    PCNetState *s = qemu_get_nic_opaque(nc);

    if (CSR_STOP(s) || CSR_SPND(s))

        return 0;

    return sizeof(s->buffer)-16;

}


void *kvmppc_create_spapr_tce(uint32_t liobn, uint32_t window_size, int *pfd,

                              bool vfio_accel)

{

    struct kvm_create_spapr_tce args = {

        .liobn = liobn,

        .window_size = window_size,

    };

    long len;

    int fd;

    void *table;

    /* Must set fd to -1 so we don't try to munmap when called for

     * destroying the table, which the upper layers -will- do

     */

    *pfd = -1;

    if (!cap_spapr_tce || (vfio_accel && !cap_spapr_vfio)) {

        return NULL;

    }

    fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_SPAPR_TCE, &args);

    if (fd < 0) {

        fprintf(stderr, "KVM: Failed to create TCE table for liobn 0x%x\n",

                liobn);

        return NULL;

    }

    len = (window_size / SPAPR_TCE_PAGE_SIZE) * sizeof(uint64_t);

    /* FIXME: round this up to page size */

    table = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

    if (table == MAP_FAILED) {

        fprintf(stderr, "KVM: Failed to map TCE table for liobn 0x%x\n",

                liobn);

        close(fd);

        return NULL;

    }

    *pfd = fd;

    return table;

}


static void exynos4210_pmu_write(void *opaque, target_phys_addr_t offset,

                                 uint64_t val, unsigned size)

{

    Exynos4210PmuState *s = (Exynos4210PmuState *)opaque;

    unsigned i;

    const Exynos4210PmuReg *reg_p = exynos4210_pmu_regs;

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

        if (reg_p->offset == offset) {

            PRINT_DEBUG_EXTEND("%s <0x%04x> <- 0x%04x\n", reg_p->name,

                    (uint32_t)offset, (uint32_t)val);

            s->reg[i] = val;

            return;

        }

        reg_p++;

    }

    PRINT_DEBUG("QEMU PMU ERROR: bad write offset 0x%04x\n", (uint32_t)offset);

}


static int omap_validate_emiff_addr(struct omap_mpu_state_s *s,

                target_phys_addr_t addr)

{

    return addr >= OMAP_EMIFF_BASE && addr < OMAP_EMIFF_BASE + s->sdram_size;

}


static int au_write_trailer(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    int64_t file_size;

    if (s->pb->seekable) {

        /* update file size */

        file_size = avio_tell(pb);

        avio_seek(pb, 8, SEEK_SET);

        avio_wb32(pb, (uint32_t)(file_size - 24));

        avio_seek(pb, file_size, SEEK_SET);

        avio_flush(pb);

    }

    return 0;

}


static const CPUArchIdList *pc_possible_cpu_arch_ids(MachineState *machine)

{

    assert(machine->possible_cpus);

    return machine->possible_cpus;

}


static void term_update(void)

{

    int i, delta;

    if (term_cmd_buf_size != term_last_cmd_buf_size ||

        memcmp(term_cmd_buf, term_last_cmd_buf, term_cmd_buf_size) != 0) {

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

            term_printf("\033[D");

        }

        term_cmd_buf[term_cmd_buf_size] = '\0';

        term_printf("%s", term_cmd_buf);

        term_printf("\033[K");

        memcpy(term_last_cmd_buf, term_cmd_buf, term_cmd_buf_size);

        term_last_cmd_buf_size = term_cmd_buf_size;

        term_last_cmd_buf_index = term_cmd_buf_size;

    }

    if (term_cmd_buf_index != term_last_cmd_buf_index) {

        delta = term_cmd_buf_index - term_last_cmd_buf_index;

        if (delta > 0) {

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

                term_printf("\033[C");

            }

        } else {

            delta = -delta;

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

                term_printf("\033[D");

            }

        }

        term_last_cmd_buf_index = term_cmd_buf_index;

    }

    term_flush();

}


static uint32_t qvirtio_pci_config_readl(QVirtioDevice *d, uint64_t off)

{

    QVirtioPCIDevice *dev = (QVirtioPCIDevice *)d;

    uint32_t value;

    value = qpci_io_readl(dev->pdev, CONFIG_BASE(dev) + off);

    if (qvirtio_is_big_endian(d)) {

        value = bswap32(value);

    }

    return value;

}


static int xa_read_packet(AVFormatContext *s,

                          AVPacket *pkt)

{

    MaxisXADemuxContext *xa = s->priv_data;

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

    ByteIOContext *pb = s->pb;

    unsigned int packet_size;

    int ret;

    if(xa->sent_bytes > xa->out_size)

        return AVERROR(EIO);

    /* 1 byte header and 14 bytes worth of samples * number channels per block */

    packet_size = 15*st->codec->channels;

    ret = av_get_packet(pb, pkt, packet_size);

    if(ret != packet_size)

        return AVERROR(EIO);

    pkt->stream_index = st->index;

    xa->sent_bytes += packet_size;

    pkt->pts = xa->audio_frame_counter;

    /* 14 bytes Samples per channel with 2 samples per byte */

    xa->audio_frame_counter += 28 * st->codec->channels;

    return ret;

}


int blk_mig_active(void)

{

    return !QSIMPLEQ_EMPTY(&block_mig_state.bmds_list);

}


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

{

    int superblock_starts[3] = {

        0, s->u_superblock_start, s->v_superblock_start

    };

    int bit = 0;

    int current_superblock = 0;

    int current_run = 0;

    int num_partial_superblocks = 0;

    int i, j;

    int current_fragment;

    int plane;

    if (s->keyframe) {

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

    } else {

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

        bit         = get_bits1(gb) ^ 1;

        current_run = 0;

        while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {

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

                bit = get_bits1(gb);

            else

                bit ^= 1;

            current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,

                                   6, 2) + 1;

            if (current_run == 34)

                current_run += get_bits(gb, 12);

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

                av_log(s->avctx, AV_LOG_ERROR,

                       "Invalid partially coded superblock run length\n");

                return -1;

            }

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

            current_superblock += current_run;

            if (bit)

                num_partial_superblocks += current_run;

        }

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

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

        if (num_partial_superblocks < s->superblock_count) {

            int superblocks_decoded = 0;

            current_superblock = 0;

            bit                = get_bits1(gb) ^ 1;

            current_run        = 0;

            while (superblocks_decoded < s->superblock_count - num_partial_superblocks &&

                   get_bits_left(gb) > 0) {

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

                    bit = get_bits1(gb);

                else

                    bit ^= 1;

                current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,

                                       6, 2) + 1;

                if (current_run == 34)

                    current_run += get_bits(gb, 12);

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

                    if (current_superblock >= s->superblock_count) {

                        av_log(s->avctx, AV_LOG_ERROR,

                               "Invalid fully coded superblock run length\n");

                        return -1;

                    }

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

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

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

                        j++;

                    }

                }

                superblocks_decoded += current_run;

            }

        }

        /* if there were partial blocks, initialize bitstream for

         * unpacking fragment codings */

        if (num_partial_superblocks) {

            current_run = 0;

            bit         = get_bits1(gb);

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

             * fetched the bit will be toggled again */

            bit ^= 1;

        }

    }

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

     * superblock (all planes) */

    s->total_num_coded_frags = 0;

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

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

        int sb_start = superblock_starts[plane];

        int sb_end   = sb_start + (plane ? s->c_superblock_count

                                         : s->y_superblock_count);

        int num_coded_frags = 0;

        for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {

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

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

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

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

                if (current_fragment != -1) {

                    int coded = s->superblock_coding[i];

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

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

                         * that cares about the fragment coding runs */

                        if (current_run-- == 0) {

                            bit        ^= 1;

                            current_run = get_vlc2(gb, s->fragment_run_length_vlc.table, 5, 2);

                        }

                        coded = bit;

                    }

                    if (coded) {

                        /* default mode; actual mode will be decoded in

                         * the next phase */

                        s->all_fragments[current_fragment].coding_method =

                            MODE_INTER_NO_MV;

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

                            current_fragment;

                    } else {

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

                        s->all_fragments[current_fragment].coding_method =

                            MODE_COPY;

                    }

                }

            }

        }

        s->total_num_coded_frags += num_coded_frags;

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

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

        if (plane < 2)

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

                                                num_coded_frags;

    }

    return 0;

}


static void isapc_machine_options(MachineClass *m)

{

    pc_common_machine_options(m);

    m->desc = "ISA-only PC";

    m->max_cpus = 1;

}


static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)

{

    float quant;

    int ret;

    ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);

    if (ret < 0)

        return AVERROR_BUG;

    q->param.mfx.CodecId = ret;

    q->width_align = avctx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16;

    if (avctx->level > 0)

        q->param.mfx.CodecLevel = avctx->level;

    q->param.mfx.CodecProfile       = q->profile;

    q->param.mfx.TargetUsage        = q->preset;

    q->param.mfx.GopPicSize         = FFMAX(0, avctx->gop_size);

    q->param.mfx.GopRefDist         = FFMAX(-1, avctx->max_b_frames) + 1;

    q->param.mfx.GopOptFlag         = avctx->flags & AV_CODEC_FLAG_CLOSED_GOP ?

                                      MFX_GOP_CLOSED : 0;

    q->param.mfx.IdrInterval        = q->idr_interval;

    q->param.mfx.NumSlice           = avctx->slices;

    q->param.mfx.NumRefFrame        = FFMAX(0, avctx->refs);

    q->param.mfx.EncodedOrder       = 0;

    q->param.mfx.BufferSizeInKB     = 0;

    q->param.mfx.FrameInfo.FourCC         = MFX_FOURCC_NV12;

    q->param.mfx.FrameInfo.Width          = FFALIGN(avctx->width, q->width_align);

    q->param.mfx.FrameInfo.Height         = FFALIGN(avctx->height, 32);

    q->param.mfx.FrameInfo.CropX          = 0;

    q->param.mfx.FrameInfo.CropY          = 0;

    q->param.mfx.FrameInfo.CropW          = avctx->width;

    q->param.mfx.FrameInfo.CropH          = avctx->height;

    q->param.mfx.FrameInfo.AspectRatioW   = avctx->sample_aspect_ratio.num;

    q->param.mfx.FrameInfo.AspectRatioH   = avctx->sample_aspect_ratio.den;

    q->param.mfx.FrameInfo.PicStruct      = MFX_PICSTRUCT_PROGRESSIVE;

    q->param.mfx.FrameInfo.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;

    q->param.mfx.FrameInfo.BitDepthLuma   = 8;

    q->param.mfx.FrameInfo.BitDepthChroma = 8;

    if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {

        q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;

        q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;

    } else {

        q->param.mfx.FrameInfo.FrameRateExtN  = avctx->time_base.den;

        q->param.mfx.FrameInfo.FrameRateExtD  = avctx->time_base.num;

    }

    ret = select_rc_mode(avctx, q);

    if (ret < 0)

        return ret;

    switch (q->param.mfx.RateControlMethod) {

    case MFX_RATECONTROL_CBR:

    case MFX_RATECONTROL_VBR:

#if QSV_HAVE_VCM

    case MFX_RATECONTROL_VCM:

#endif

        q->param.mfx.InitialDelayInKB = avctx->rc_initial_buffer_occupancy / 1000;

        q->param.mfx.TargetKbps       = avctx->bit_rate / 1000;

        q->param.mfx.MaxKbps          = avctx->rc_max_rate / 1000;

        break;

    case MFX_RATECONTROL_CQP:

        quant = avctx->global_quality / FF_QP2LAMBDA;

        q->param.mfx.QPI = av_clip(quant * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);

        q->param.mfx.QPP = av_clip(quant, 0, 51);

        q->param.mfx.QPB = av_clip(quant * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);

        break;

    case MFX_RATECONTROL_AVBR:

        q->param.mfx.TargetKbps  = avctx->bit_rate / 1000;

        q->param.mfx.Convergence = q->avbr_convergence;

        q->param.mfx.Accuracy    = q->avbr_accuracy;

        break;

#if QSV_HAVE_LA

    case MFX_RATECONTROL_LA:

        q->param.mfx.TargetKbps  = avctx->bit_rate / 1000;

        q->extco2.LookAheadDepth = q->la_depth;

        break;

#if QSV_HAVE_ICQ

    case MFX_RATECONTROL_LA_ICQ:

        q->extco2.LookAheadDepth = q->la_depth;

    case MFX_RATECONTROL_ICQ:

        q->param.mfx.ICQQuality  = avctx->global_quality;

        break;

#endif

#endif

    }

    // the HEVC encoder plugin currently fails if coding options

    // are provided

    if (avctx->codec_id != AV_CODEC_ID_HEVC) {

        q->extco.Header.BufferId      = MFX_EXTBUFF_CODING_OPTION;

        q->extco.Header.BufferSz      = sizeof(q->extco);

        q->extco.CAVLC                = avctx->coder_type == FF_CODER_TYPE_VLC ?

                                        MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;

        if (q->rdo >= 0)

            q->extco.RateDistortionOpt = q->rdo > 0 ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;

        if (avctx->codec_id == AV_CODEC_ID_H264) {

            if (avctx->strict_std_compliance != FF_COMPLIANCE_NORMAL)

                q->extco.NalHrdConformance = avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL ?

                                             MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;

            if (q->single_sei_nal_unit >= 0)

                q->extco.SingleSeiNalUnit = q->single_sei_nal_unit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;

            if (q->recovery_point_sei >= 0)

                q->extco.RecoveryPointSEI = q->recovery_point_sei ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;

            q->extco.MaxDecFrameBuffering = q->max_dec_frame_buffering;

        }

        q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco;

#if QSV_HAVE_CO2

        if (avctx->codec_id == AV_CODEC_ID_H264) {

            q->extco2.Header.BufferId     = MFX_EXTBUFF_CODING_OPTION2;

            q->extco2.Header.BufferSz     = sizeof(q->extco2);

            if (q->int_ref_type >= 0)

                q->extco2.IntRefType = q->int_ref_type;

            if (q->int_ref_cycle_size >= 0)

                q->extco2.IntRefCycleSize = q->int_ref_cycle_size;

            if (q->int_ref_qp_delta != INT16_MIN)

                q->extco2.IntRefQPDelta = q->int_ref_qp_delta;

            if (q->bitrate_limit >= 0)

                q->extco2.BitrateLimit = q->bitrate_limit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;

            if (q->mbbrc >= 0)

                q->extco2.MBBRC = q->mbbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;

            if (q->extbrc >= 0)

                q->extco2.ExtBRC = q->extbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;

            if (q->max_frame_size >= 0)

                q->extco2.MaxFrameSize = q->max_frame_size;

#if QSV_HAVE_MAX_SLICE_SIZE

            if (q->max_slice_size >= 0)

                q->extco2.MaxSliceSize = q->max_slice_size;

#endif

#if QSV_HAVE_TRELLIS

            q->extco2.Trellis = q->trellis;

#endif

#if QSV_HAVE_BREF_TYPE

            if (avctx->b_frame_strategy >= 0)

                q->extco2.BRefType = avctx->b_frame_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;

            if (q->adaptive_i >= 0)

                q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;

            if (q->adaptive_b >= 0)

                q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;

#endif

            q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;

        }

#endif

    }

    if (!rc_supported(q)) {

        av_log(avctx, AV_LOG_ERROR,

               "Selected ratecontrol mode is not supported by the QSV "

               "runtime. Choose a different mode.\n");

        return AVERROR(ENOSYS);

    }

    return 0;

}


static void lag_pred_line(LagarithContext *l, uint8_t *buf,

                          int width, int stride, int line)

{

    int L, TL;

    /* Left pixel is actually prev_row[width] */

    L = buf[width - stride - 1];

    if (!line) {

        /* Left prediction only for first line */

        L = l->dsp.add_hfyu_left_prediction(buf + 1, buf + 1,

                                            width - 1, buf[0]);

        return;

    } else if (line == 1) {

        /* Second line, left predict first pixel, the rest of the line is median predicted

         * NOTE: In the case of RGB this pixel is top predicted */

        TL = l->avctx->pix_fmt == PIX_FMT_YUV420P ? buf[-stride] : L;

    } else {

        /* Top left is 2 rows back, last pixel */

        TL = buf[width - (2 * stride) - 1];

    }

    add_lag_median_prediction(buf, buf - stride, buf,

                              width, &L, &TL);

}


static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,

                                    uint64_t oid, unsigned int data_len,

                                    uint64_t offset, uint8_t flags,

                                    uint64_t base_oid, unsigned int iov_offset)

{

    AIOReq *aio_req;

    aio_req = g_malloc(sizeof(*aio_req));

    aio_req->aiocb = acb;

    aio_req->iov_offset = iov_offset;

    aio_req->oid = oid;

    aio_req->base_oid = base_oid;

    aio_req->offset = offset;

    aio_req->data_len = data_len;

    aio_req->flags = flags;

    aio_req->id = s->aioreq_seq_num++;

    acb->nr_pending++;

    return aio_req;

}


static void ff_acelp_interpolatef_mips(float *out, const float *in,

                           const float *filter_coeffs, int precision,

                           int frac_pos, int filter_length, int length)

{

    int n, i;

    int prec = precision * 4;

    int fc_offset = precision - frac_pos;

    float in_val_p, in_val_m, fc_val_p, fc_val_m;

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

        /**

        * four pointers are defined in order to minimize number of

        * computations done in inner loop

        */

        const float *p_in_p = &in[n];

        const float *p_in_m = &in[n-1];

        const float *p_filter_coeffs_p = &filter_coeffs[frac_pos];

        const float *p_filter_coeffs_m = filter_coeffs + fc_offset;

        float v = 0;

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

            __asm__ volatile (

                "lwc1   %[in_val_p],           0(%[p_in_p])                    \n\t"

                "lwc1   %[fc_val_p],           0(%[p_filter_coeffs_p])         \n\t"

                "lwc1   %[in_val_m],           0(%[p_in_m])                    \n\t"

                "lwc1   %[fc_val_m],           0(%[p_filter_coeffs_m])         \n\t"

                "addiu  %[p_in_p],             %[p_in_p],              4       \n\t"

                "madd.s %[v],%[v],             %[in_val_p],%[fc_val_p]         \n\t"

                "addiu  %[p_in_m],             %[p_in_m],              -4      \n\t"

                "addu   %[p_filter_coeffs_p],  %[p_filter_coeffs_p],   %[prec] \n\t"

                "addu   %[p_filter_coeffs_m],  %[p_filter_coeffs_m],   %[prec] \n\t"

                "madd.s %[v],%[v],%[in_val_m], %[fc_val_m]                     \n\t"

                : [v] "=&f" (v),[p_in_p] "+r" (p_in_p), [p_in_m] "+r" (p_in_m),

                  [p_filter_coeffs_p] "+r" (p_filter_coeffs_p),

                  [in_val_p] "=&f" (in_val_p), [in_val_m] "=&f" (in_val_m),

                  [fc_val_p] "=&f" (fc_val_p), [fc_val_m] "=&f" (fc_val_m),

                  [p_filter_coeffs_m] "+r" (p_filter_coeffs_m)

                : [prec] "r" (prec)

                : "memory"

            );

        }

        out[n] = v;

    }

}


static int mpegts_push_data(MpegTSFilter *filter,

                            const uint8_t *buf, int buf_size, int is_start,

                            int64_t pos)

{

    PESContext *pes = filter->u.pes_filter.opaque;

    MpegTSContext *ts = pes->ts;

    const uint8_t *p;

    int len, code;

    if(!ts->pkt)

        return 0;

    if (is_start) {

        if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {

            new_pes_packet(pes, ts->pkt);

            ts->stop_parse = 1;

        }

        pes->state = MPEGTS_HEADER;

        pes->data_index = 0;

        pes->ts_packet_pos = pos;

    }

    p = buf;

    while (buf_size > 0) {

        switch(pes->state) {

        case MPEGTS_HEADER:

            len = PES_START_SIZE - pes->data_index;

            if (len > buf_size)

                len = buf_size;

            memcpy(pes->header + pes->data_index, p, len);

            pes->data_index += len;

            p += len;

            buf_size -= len;

            if (pes->data_index == PES_START_SIZE) {

                /* we got all the PES or section header. We can now

                   decide */

                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&

                    pes->header[2] == 0x01) {

                    /* it must be an mpeg2 PES stream */

                    code = pes->header[3] | 0x100;

                    av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);

                    if ((pes->st && pes->st->discard == AVDISCARD_ALL) ||

                        code == 0x1be) /* padding_stream */

                        goto skip;

                    /* stream not present in PMT */

                    if (!pes->st) {

                        pes->st = av_new_stream(ts->stream, pes->pid);

                        if (!pes->st)

                            return AVERROR(ENOMEM);

                        mpegts_set_stream_info(pes->st, pes, 0, 0);

                    }

                    pes->total_size = AV_RB16(pes->header + 4);

                    /* NOTE: a zero total size means the PES size is

                       unbounded */

                    if (!pes->total_size)

                        pes->total_size = MAX_PES_PAYLOAD;

                    /* allocate pes buffer */

                    pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);

                    if (!pes->buffer)

                        return AVERROR(ENOMEM);

                    if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */

                        code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */

                        code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */

                        code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */

                        pes->state = MPEGTS_PESHEADER;

                        if (pes->st->codec->codec_id == CODEC_ID_NONE) {

                            av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",

                                    pes->pid, pes->stream_type);

                            pes->st->codec->codec_id = CODEC_ID_PROBE;

                        }

                    } else {

                        pes->state = MPEGTS_PAYLOAD;

                        pes->data_index = 0;

                    }

                } else {

                    /* otherwise, it should be a table */

                    /* skip packet */

                skip:

                    pes->state = MPEGTS_SKIP;

                    continue;

                }

            }

            break;

            /**********************************************/

            /* PES packing parsing */

        case MPEGTS_PESHEADER:

            len = PES_HEADER_SIZE - pes->data_index;

            if (len < 0)

                return -1;

            if (len > buf_size)

                len = buf_size;

            memcpy(pes->header + pes->data_index, p, len);

            pes->data_index += len;

            p += len;

            buf_size -= len;

            if (pes->data_index == PES_HEADER_SIZE) {

                pes->pes_header_size = pes->header[8] + 9;

                pes->state = MPEGTS_PESHEADER_FILL;

            }

            break;

        case MPEGTS_PESHEADER_FILL:

            len = pes->pes_header_size - pes->data_index;

            if (len < 0)

                return -1;

            if (len > buf_size)

                len = buf_size;

            memcpy(pes->header + pes->data_index, p, len);

            pes->data_index += len;

            p += len;

            buf_size -= len;

            if (pes->data_index == pes->pes_header_size) {

                const uint8_t *r;

                unsigned int flags, pes_ext, skip;

                flags = pes->header[7];

                r = pes->header + 9;

                pes->pts = AV_NOPTS_VALUE;

                pes->dts = AV_NOPTS_VALUE;

                if ((flags & 0xc0) == 0x80) {

                    pes->dts = pes->pts = ff_parse_pes_pts(r);

                    r += 5;

                } else if ((flags & 0xc0) == 0xc0) {

                    pes->pts = ff_parse_pes_pts(r);

                    r += 5;

                    pes->dts = ff_parse_pes_pts(r);

                    r += 5;

                }

                pes->extended_stream_id = -1;

                if (flags & 0x01) { /* PES extension */

                    pes_ext = *r++;

                    /* Skip PES private data, program packet sequence counter and P-STD buffer */

                    skip = (pes_ext >> 4) & 0xb;

                    skip += skip & 0x9;

                    r += skip;

                    if ((pes_ext & 0x41) == 0x01 &&

                        (r + 2) <= (pes->header + pes->pes_header_size)) {

                        /* PES extension 2 */

                        if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)

                            pes->extended_stream_id = r[1];

                    }

                }

                /* we got the full header. We parse it and get the payload */

                pes->state = MPEGTS_PAYLOAD;

                pes->data_index = 0;

            }

            break;

        case MPEGTS_PAYLOAD:

            if (buf_size > 0 && pes->buffer) {

                if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {

                    new_pes_packet(pes, ts->pkt);

                    pes->total_size = MAX_PES_PAYLOAD;

                    pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);

                    if (!pes->buffer)

                        return AVERROR(ENOMEM);

                    ts->stop_parse = 1;

                } else if (pes->data_index == 0 && buf_size > pes->total_size) {

                    // pes packet size is < ts size packet and pes data is padded with 0xff

                    // not sure if this is legal in ts but see issue #2392

                    buf_size = pes->total_size;

                    pes->flags |= AV_PKT_FLAG_CORRUPT;

                }

                memcpy(pes->buffer+pes->data_index, p, buf_size);

                pes->data_index += buf_size;

            }

            buf_size = 0;

            /* emit complete packets with known packet size

             * decreases demuxer delay for infrequent packets like subtitles from

             * a couple of seconds to milliseconds for properly muxed files.

             * total_size is the number of bytes following pes_packet_length

             * in the pes header, i.e. not counting the first 6 bytes */

            if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&

                pes->pes_header_size + pes->data_index == pes->total_size + 6) {

                ts->stop_parse = 1;

                new_pes_packet(pes, ts->pkt);

            }

            break;

        case MPEGTS_SKIP:

            buf_size = 0;

            break;

        }

    }

    return 0;

}


static void mov_build_index(MOVContext *mov, AVStream *st)

{

    MOVStreamContext *sc = st->priv_data;

    int64_t current_offset;

    int64_t current_dts = 0;

    unsigned int stts_index = 0;

    unsigned int stsc_index = 0;

    unsigned int stss_index = 0;

    unsigned int stps_index = 0;

    unsigned int i, j;

    uint64_t stream_size = 0;

    /* adjust first dts according to edit list */

    if (sc->time_offset && mov->time_scale > 0) {

        if (sc->time_offset < 0)

            sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);

        current_dts = -sc->time_offset;

        if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&

            sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {

            /* more than 16 frames delay, dts are likely wrong

               this happens with files created by iMovie */

            sc->wrong_dts = 1;

            st->internal->avctx->has_b_frames = 1;

        }

    }

    /* only use old uncompressed audio chunk demuxing when stts specifies it */

    if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&

          sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {

        unsigned int current_sample = 0;

        unsigned int stts_sample = 0;

        unsigned int sample_size;

        unsigned int distance = 0;

        unsigned int rap_group_index = 0;

        unsigned int rap_group_sample = 0;

        int rap_group_present = sc->rap_group_count && sc->rap_group;

        int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);

        current_dts -= sc->dts_shift;

        if (!sc->sample_count)

            return;

        if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)

            return;

        if (av_reallocp_array(&st->index_entries,

                              st->nb_index_entries + sc->sample_count,

                              sizeof(*st->index_entries)) < 0) {

            st->nb_index_entries = 0;

            return;

        }

        st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);

        for (i = 0; i < sc->chunk_count; i++) {

            current_offset = sc->chunk_offsets[i];

            while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&

                i + 1 == sc->stsc_data[stsc_index + 1].first)

                stsc_index++;

            for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {

                int keyframe = 0;

                if (current_sample >= sc->sample_count) {

                    av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");

                    return;

                }

                if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {

                    keyframe = 1;

                    if (stss_index + 1 < sc->keyframe_count)

                        stss_index++;

                } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {

                    keyframe = 1;

                    if (stps_index + 1 < sc->stps_count)

                        stps_index++;

                }

                if (rap_group_present && rap_group_index < sc->rap_group_count) {

                    if (sc->rap_group[rap_group_index].index > 0)

                        keyframe = 1;

                    if (++rap_group_sample == sc->rap_group[rap_group_index].count) {

                        rap_group_sample = 0;

                        rap_group_index++;

                    }

                }

                if (keyframe)

                    distance = 0;

                sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];

                if (sc->pseudo_stream_id == -1 ||

                   sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {

                    AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];

                    e->pos = current_offset;

                    e->timestamp = current_dts;

                    e->size = sample_size;

                    e->min_distance = distance;

                    e->flags = keyframe ? AVINDEX_KEYFRAME : 0;

                    av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "

                            "size %d, distance %d, keyframe %d\n", st->index, current_sample,

                            current_offset, current_dts, sample_size, distance, keyframe);

                }

                current_offset += sample_size;

                stream_size += sample_size;

                current_dts += sc->stts_data[stts_index].duration;

                distance++;

                stts_sample++;

                current_sample++;

                if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {

                    stts_sample = 0;

                    stts_index++;

                }

            }

        }

        if (st->duration > 0)

            st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;

    } else {

        unsigned chunk_samples, total = 0;

        // compute total chunk count

        for (i = 0; i < sc->stsc_count; i++) {

            unsigned count, chunk_count;

            chunk_samples = sc->stsc_data[i].count;

            if (i != sc->stsc_count - 1 &&

                sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {

                av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");

                return;

            }

            if (sc->samples_per_frame >= 160) { // gsm

                count = chunk_samples / sc->samples_per_frame;

            } else if (sc->samples_per_frame > 1) {

                unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;

                count = (chunk_samples+samples-1) / samples;

            } else {

                count = (chunk_samples+1023) / 1024;

            }

            if (mov_stsc_index_valid(i, sc->stsc_count))

                chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;

            else

                chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);

            total += chunk_count * count;

        }

        av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);

        if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)

            return;

        if (av_reallocp_array(&st->index_entries,

                              st->nb_index_entries + total,

                              sizeof(*st->index_entries)) < 0) {

            st->nb_index_entries = 0;

            return;

        }

        st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);

        // populate index

        for (i = 0; i < sc->chunk_count; i++) {

            current_offset = sc->chunk_offsets[i];

            if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&

                i + 1 == sc->stsc_data[stsc_index + 1].first)

                stsc_index++;

            chunk_samples = sc->stsc_data[stsc_index].count;

            while (chunk_samples > 0) {

                AVIndexEntry *e;

                unsigned size, samples;

                if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {

                    avpriv_request_sample(mov->fc,

                           "Zero bytes per frame, but %d samples per frame",

                           sc->samples_per_frame);

                    return;

                }

                if (sc->samples_per_frame >= 160) { // gsm

                    samples = sc->samples_per_frame;

                    size = sc->bytes_per_frame;

                } else {

                    if (sc->samples_per_frame > 1) {

                        samples = FFMIN((1024 / sc->samples_per_frame)*

                                        sc->samples_per_frame, chunk_samples);

                        size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;

                    } else {

                        samples = FFMIN(1024, chunk_samples);

                        size = samples * sc->sample_size;

                    }

                }

                if (st->nb_index_entries >= total) {

                    av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);

                    return;

                }

                e = &st->index_entries[st->nb_index_entries++];

                e->pos = current_offset;

                e->timestamp = current_dts;

                e->size = size;

                e->min_distance = 0;

                e->flags = AVINDEX_KEYFRAME;

                av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "

                        "size %d, duration %d\n", st->index, i, current_offset, current_dts,

                        size, samples);

                current_offset += size;

                current_dts += samples;

                chunk_samples -= samples;

            }

        }

    }

}


static int32_t scsi_target_send_command(SCSIRequest *req, uint8_t *buf)

{

    SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);

    switch (buf[0]) {

    case REPORT_LUNS:

        if (!scsi_target_emulate_report_luns(r)) {

            goto illegal_request;

        }

        break;

    case INQUIRY:

        if (!scsi_target_emulate_inquiry(r)) {

            goto illegal_request;

        }

        break;

    case REQUEST_SENSE:

        scsi_target_alloc_buf(&r->req, scsi_sense_len(req));

        r->len = scsi_device_get_sense(r->req.dev, r->buf,

                                       MIN(req->cmd.xfer, r->buf_len),

                                       (req->cmd.buf[1] & 1) == 0);

        if (r->req.dev->sense_is_ua) {

            scsi_device_unit_attention_reported(req->dev);

            r->req.dev->sense_len = 0;

            r->req.dev->sense_is_ua = false;

        }

        break;

    case TEST_UNIT_READY:

        break;

    default:

        scsi_req_build_sense(req, SENSE_CODE(LUN_NOT_SUPPORTED));

        scsi_req_complete(req, CHECK_CONDITION);

        return 0;

    illegal_request:

        scsi_req_build_sense(req, SENSE_CODE(INVALID_FIELD));

        scsi_req_complete(req, CHECK_CONDITION);

        return 0;

    }

    if (!r->len) {

        scsi_req_complete(req, GOOD);

    }

    return r->len;

}


static inline int onenand_load_spare(OneNANDState *s, int sec, int secn,

                void *dest)

{

    uint8_t buf[512];

    if (s->bdrv_cur) {

        if (bdrv_read(s->bdrv_cur, s->secs_cur + (sec >> 5), buf, 1) < 0)

            return 1;

        memcpy(dest, buf + ((sec & 31) << 4), secn << 4);

    } else if (sec + secn > s->secs_cur)

        return 1;

    else

        memcpy(dest, s->current + (s->secs_cur << 9) + (sec << 4), secn << 4);

    return 0;

}


static inline void gen_op_fcmps(int fccno, TCGv_i32 r_rs1, TCGv_i32 r_rs2)

{

    switch (fccno) {

    case 0:

        gen_helper_fcmps(cpu_env, r_rs1, r_rs2);

        break;

    case 1:

        gen_helper_fcmps_fcc1(cpu_env, r_rs1, r_rs2);

        break;

    case 2:

        gen_helper_fcmps_fcc2(cpu_env, r_rs1, r_rs2);

        break;

    case 3:

        gen_helper_fcmps_fcc3(cpu_env, r_rs1, r_rs2);

        break;

    }

}


static void tpm_tis_receive_cb(TPMState *s, uint8_t locty)

{

    TPMTISEmuState *tis = &s->s.tis;

    assert(s->locty_number == locty);

    qemu_bh_schedule(tis->bh);

}


void cpu_physical_memory_unmap(void *buffer, target_phys_addr_t len,

                               int is_write, target_phys_addr_t access_len)

{

    if (buffer != bounce.buffer) {

        if (is_write) {

            ram_addr_t addr1 = qemu_ram_addr_from_host(buffer);

            while (access_len) {

                unsigned l;

                l = TARGET_PAGE_SIZE;

                if (l > access_len)

                    l = access_len;

                if (!cpu_physical_memory_is_dirty(addr1)) {

                    /* invalidate code */

                    tb_invalidate_phys_page_range(addr1, addr1 + l, 0);

                    /* set dirty bit */

                    phys_ram_dirty[addr1 >> TARGET_PAGE_BITS] |=

                        (0xff & ~CODE_DIRTY_FLAG);

                }

                addr1 += l;

                access_len -= l;

            }

        }

        return;

    }

    if (is_write) {

        cpu_physical_memory_write(bounce.addr, bounce.buffer, access_len);

    }

    qemu_vfree(bounce.buffer);

    bounce.buffer = NULL;

    cpu_notify_map_clients();

}


void qdev_prop_set_defaults(DeviceState *dev, Property *props)

{

    if (!props)

        return;

    while (props->name) {

        if (props->defval) {

            qdev_prop_cpy(dev, props, props->defval);

        }

        props++;

    }

}


static inline void gen_op_evabs(TCGv_i32 ret, TCGv_i32 arg1)

{

    int l1 = gen_new_label();

    int l2 = gen_new_label();

    tcg_gen_brcondi_i32(TCG_COND_GE, arg1, 0, l1);

    tcg_gen_neg_i32(ret, arg1);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_mov_i32(ret, arg1);

    gen_set_label(l2);

}


static void video_audio_display(VideoState *s)

{

    int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;

    int ch, channels, h, h2, bgcolor, fgcolor;

    int16_t time_diff;

    int rdft_bits, nb_freq;

    for (rdft_bits = 1; (1 << rdft_bits) < 2 * s->height; rdft_bits++)

        ;

    nb_freq = 1 << (rdft_bits - 1);

    /* compute display index : center on currently output samples */

    channels = s->audio_st->codec->channels;

    nb_display_channels = channels;

    if (!s->paused) {

        int data_used = s->show_audio == 1 ? s->width : (2 * nb_freq);

        n = 2 * channels;

        delay = audio_write_get_buf_size(s);

        delay /= n;

        /* to be more precise, we take into account the time spent since

           the last buffer computation */

        if (audio_callback_time) {

            time_diff = av_gettime() - audio_callback_time;

            delay -= (time_diff * s->audio_st->codec->sample_rate) / 1000000;

        }

        delay += 2 * data_used;

        if (delay < data_used)

            delay = data_used;

        i_start= x = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);

        if (s->show_audio == 1) {

            h = INT_MIN;

            for (i = 0; i < 1000; i += channels) {

                int idx = (SAMPLE_ARRAY_SIZE + x - i) % SAMPLE_ARRAY_SIZE;

                int a = s->sample_array[idx];

                int b = s->sample_array[(idx + 4 * channels) % SAMPLE_ARRAY_SIZE];

                int c = s->sample_array[(idx + 5 * channels) % SAMPLE_ARRAY_SIZE];

                int d = s->sample_array[(idx + 9 * channels) % SAMPLE_ARRAY_SIZE];

                int score = a - d;

                if (h < score && (b ^ c) < 0) {

                    h = score;

                    i_start = idx;

                }

            }

        }

        s->last_i_start = i_start;

    } else {

        i_start = s->last_i_start;

    }

    bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);

    if (s->show_audio == 1) {

        fill_rectangle(screen,

                       s->xleft, s->ytop, s->width, s->height,

                       bgcolor);

        fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);

        /* total height for one channel */

        h = s->height / nb_display_channels;

        /* graph height / 2 */

        h2 = (h * 9) / 20;

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

            i = i_start + ch;

            y1 = s->ytop + ch * h + (h / 2); /* position of center line */

            for (x = 0; x < s->width; x++) {

                y = (s->sample_array[i] * h2) >> 15;

                if (y < 0) {

                    y = -y;

                    ys = y1 - y;

                } else {

                    ys = y1;

                }

                fill_rectangle(screen,

                               s->xleft + x, ys, 1, y,

                               fgcolor);

                i += channels;

                if (i >= SAMPLE_ARRAY_SIZE)

                    i -= SAMPLE_ARRAY_SIZE;

            }

        }

        fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);

        for (ch = 1; ch < nb_display_channels; ch++) {

            y = s->ytop + ch * h;

            fill_rectangle(screen,

                           s->xleft, y, s->width, 1,

                           fgcolor);

        }

        SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);

    } else {

        nb_display_channels= FFMIN(nb_display_channels, 2);

        if (rdft_bits != s->rdft_bits) {

            av_rdft_end(s->rdft);

            av_free(s->rdft_data);

            s->rdft = av_rdft_init(rdft_bits, DFT_R2C);

            s->rdft_bits = rdft_bits;

            s->rdft_data = av_malloc(4 * nb_freq * sizeof(*s->rdft_data));

        }

        {

            FFTSample *data[2];

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

                data[ch] = s->rdft_data + 2 * nb_freq * ch;

                i = i_start + ch;

                for (x = 0; x < 2 * nb_freq; x++) {

                    double w = (x-nb_freq) * (1.0 / nb_freq);

                    data[ch][x] = s->sample_array[i] * (1.0 - w * w);

                    i += channels;

                    if (i >= SAMPLE_ARRAY_SIZE)

                        i -= SAMPLE_ARRAY_SIZE;

                }

                av_rdft_calc(s->rdft, data[ch]);

            }

            // least efficient way to do this, we should of course directly access it but its more than fast enough

            for (y = 0; y < s->height; y++) {

                double w = 1 / sqrt(nb_freq);

                int a = sqrt(w * sqrt(data[0][2 * y + 0] * data[0][2 * y + 0] + data[0][2 * y + 1] * data[0][2 * y + 1]));

                int b = (nb_display_channels == 2 ) ? sqrt(w * sqrt(data[1][2 * y + 0] * data[1][2 * y + 0]

                       + data[1][2 * y + 1] * data[1][2 * y + 1])) : a;

                a = FFMIN(a, 255);

                b = FFMIN(b, 255);

                fgcolor = SDL_MapRGB(screen->format, a, b, (a + b) / 2);

                fill_rectangle(screen,

                            s->xpos, s->height-y, 1, 1,

                            fgcolor);

            }

        }

        SDL_UpdateRect(screen, s->xpos, s->ytop, 1, s->height);

        s->xpos++;

        if (s->xpos >= s->width)

            s->xpos= s->xleft;

    }

}


static coroutine_fn int qemu_gluster_co_flush_to_disk(BlockDriverState *bs)

{

    int ret;

    GlusterAIOCB acb;

    BDRVGlusterState *s = bs->opaque;

    acb.size = 0;

    acb.ret = 0;

    acb.coroutine = qemu_coroutine_self();

    acb.aio_context = bdrv_get_aio_context(bs);

    ret = glfs_fsync_async(s->fd, gluster_finish_aiocb, &acb);

    if (ret < 0) {

        return -errno;

    }

    qemu_coroutine_yield();

    return acb.ret;

}


static DriveInfo *blockdev_init(QemuOpts *all_opts,

                                BlockInterfaceType block_default_type)

{

    const char *buf;

    const char *file = NULL;

    const char *serial;

    const char *mediastr = "";

    BlockInterfaceType type;

    enum { MEDIA_DISK, MEDIA_CDROM } media;

    int bus_id, unit_id;

    int cyls, heads, secs, translation;

    int max_devs;

    int index;

    int ro = 0;

    int bdrv_flags = 0;

    int on_read_error, on_write_error;

    const char *devaddr;

    DriveInfo *dinfo;

    ThrottleConfig cfg;

    int snapshot = 0;

    bool copy_on_read;

    int ret;

    Error *error = NULL;

    QemuOpts *opts;

    QDict *bs_opts;

    const char *id;

    bool has_driver_specific_opts;

    BlockDriver *drv = NULL;

    translation = BIOS_ATA_TRANSLATION_AUTO;

    media = MEDIA_DISK;

    /* Check common options by copying from all_opts to opts, all other options

     * are stored in bs_opts. */

    id = qemu_opts_id(all_opts);

    opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);

    if (error_is_set(&error)) {

        qerror_report_err(error);

        error_free(error);

        return NULL;

    }

    bs_opts = qdict_new();

    qemu_opts_to_qdict(all_opts, bs_opts);

    qemu_opts_absorb_qdict(opts, bs_opts, &error);

    if (error_is_set(&error)) {

        qerror_report_err(error);

        error_free(error);

        return NULL;

    }

    if (id) {

        qdict_del(bs_opts, "id");

    }

    has_driver_specific_opts = !!qdict_size(bs_opts);

    /* extract parameters */

    bus_id  = qemu_opt_get_number(opts, "bus", 0);

    unit_id = qemu_opt_get_number(opts, "unit", -1);

    index   = qemu_opt_get_number(opts, "index", -1);

    cyls  = qemu_opt_get_number(opts, "cyls", 0);

    heads = qemu_opt_get_number(opts, "heads", 0);

    secs  = qemu_opt_get_number(opts, "secs", 0);

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

    ro = qemu_opt_get_bool(opts, "read-only", 0);

    copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);

    file = qemu_opt_get(opts, "file");

    serial = qemu_opt_get(opts, "serial");

    if ((buf = qemu_opt_get(opts, "if")) != NULL) {

        for (type = 0; type < IF_COUNT && strcmp(buf, if_name[type]); type++)

            ;

        if (type == IF_COUNT) {

            error_report("unsupported bus type '%s'", buf);

            return NULL;

	}

    } else {

        type = block_default_type;

    }

    max_devs = if_max_devs[type];

    if (cyls || heads || secs) {

        if (cyls < 1) {

            error_report("invalid physical cyls number");

	    return NULL;

	}

        if (heads < 1) {

            error_report("invalid physical heads number");

	    return NULL;

	}

        if (secs < 1) {

            error_report("invalid physical secs number");

	    return NULL;

	}

    }

    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {

        if (!cyls) {

            error_report("'%s' trans must be used with cyls, heads and secs",

                         buf);

            return NULL;

        }

        if (!strcmp(buf, "none"))

            translation = BIOS_ATA_TRANSLATION_NONE;

        else if (!strcmp(buf, "lba"))

            translation = BIOS_ATA_TRANSLATION_LBA;

        else if (!strcmp(buf, "auto"))

            translation = BIOS_ATA_TRANSLATION_AUTO;

	else {

            error_report("'%s' invalid translation type", buf);

	    return NULL;

	}

    }

    if ((buf = qemu_opt_get(opts, "media")) != NULL) {

        if (!strcmp(buf, "disk")) {

	    media = MEDIA_DISK;

	} else if (!strcmp(buf, "cdrom")) {

            if (cyls || secs || heads) {

                error_report("CHS can't be set with media=%s", buf);

	        return NULL;

            }

	    media = MEDIA_CDROM;

	} else {

	    error_report("'%s' invalid media", buf);

	    return NULL;

	}

    }

    if ((buf = qemu_opt_get(opts, "discard")) != NULL) {

        if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {

            error_report("invalid discard option");

            return NULL;

        }

    }

    if (qemu_opt_get_bool(opts, "cache.writeback", true)) {

        bdrv_flags |= BDRV_O_CACHE_WB;

    }

    if (qemu_opt_get_bool(opts, "cache.direct", false)) {

        bdrv_flags |= BDRV_O_NOCACHE;

    }

    if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {

        bdrv_flags |= BDRV_O_NO_FLUSH;

    }

#ifdef CONFIG_LINUX_AIO

    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {

        if (!strcmp(buf, "native")) {

            bdrv_flags |= BDRV_O_NATIVE_AIO;

        } else if (!strcmp(buf, "threads")) {

            /* this is the default */

        } else {

           error_report("invalid aio option");

           return NULL;

        }

    }

#endif

    if ((buf = qemu_opt_get(opts, "format")) != NULL) {

        if (is_help_option(buf)) {

            error_printf("Supported formats:");

            bdrv_iterate_format(bdrv_format_print, NULL);

            error_printf("\n");

            return NULL;

        }

        drv = bdrv_find_whitelisted_format(buf, ro);

        if (!drv) {

            if (!ro && bdrv_find_whitelisted_format(buf, !ro)) {

                error_report("'%s' can be only used as read-only device.", buf);

            } else {

                error_report("'%s' invalid format", buf);

            }

            return NULL;

        }

    }

    /* disk I/O throttling */

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

    cfg.buckets[THROTTLE_BPS_TOTAL].avg =

        qemu_opt_get_number(opts, "throttling.bps-total", 0);

    cfg.buckets[THROTTLE_BPS_READ].avg  =

        qemu_opt_get_number(opts, "throttling.bps-read", 0);

    cfg.buckets[THROTTLE_BPS_WRITE].avg =

        qemu_opt_get_number(opts, "throttling.bps-write", 0);

    cfg.buckets[THROTTLE_OPS_TOTAL].avg =

        qemu_opt_get_number(opts, "throttling.iops-total", 0);

    cfg.buckets[THROTTLE_OPS_READ].avg =

        qemu_opt_get_number(opts, "throttling.iops-read", 0);

    cfg.buckets[THROTTLE_OPS_WRITE].avg =

        qemu_opt_get_number(opts, "throttling.iops-write", 0);

    cfg.buckets[THROTTLE_BPS_TOTAL].max =

        qemu_opt_get_number(opts, "throttling.bps-total-max", 0);

    cfg.buckets[THROTTLE_BPS_READ].max  =

        qemu_opt_get_number(opts, "throttling.bps-read-max", 0);

    cfg.buckets[THROTTLE_BPS_WRITE].max =

        qemu_opt_get_number(opts, "throttling.bps-write-max", 0);

    cfg.buckets[THROTTLE_OPS_TOTAL].max =

        qemu_opt_get_number(opts, "throttling.iops-total-max", 0);

    cfg.buckets[THROTTLE_OPS_READ].max =

        qemu_opt_get_number(opts, "throttling.iops-read-max", 0);

    cfg.buckets[THROTTLE_OPS_WRITE].max =

        qemu_opt_get_number(opts, "throttling.iops-write-max", 0);

    cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);

    if (!check_throttle_config(&cfg, &error)) {

        error_report("%s", error_get_pretty(error));

        error_free(error);

        return NULL;

    }

    if (qemu_opt_get(opts, "boot") != NULL) {

        fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "

                "ignored. Future versions will reject this parameter. Please "

                "update your scripts.\n");

    }

    on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;

    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {

        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {

            error_report("werror is not supported by this bus type");

            return NULL;

        }

        on_write_error = parse_block_error_action(buf, 0);

        if (on_write_error < 0) {

            return NULL;

        }

    }

    on_read_error = BLOCKDEV_ON_ERROR_REPORT;

    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {

        if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI && type != IF_NONE) {

            error_report("rerror is not supported by this bus type");

            return NULL;

        }

        on_read_error = parse_block_error_action(buf, 1);

        if (on_read_error < 0) {

            return NULL;

        }

    }

    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {

        if (type != IF_VIRTIO) {

            error_report("addr is not supported by this bus type");

            return NULL;

        }

    }

    /* compute bus and unit according index */

    if (index != -1) {

        if (bus_id != 0 || unit_id != -1) {

            error_report("index cannot be used with bus and unit");

            return NULL;

        }

        bus_id = drive_index_to_bus_id(type, index);

        unit_id = drive_index_to_unit_id(type, index);

    }

    /* if user doesn't specify a unit_id,

     * try to find the first free

     */

    if (unit_id == -1) {

       unit_id = 0;

       while (drive_get(type, bus_id, unit_id) != NULL) {

           unit_id++;

           if (max_devs && unit_id >= max_devs) {

               unit_id -= max_devs;

               bus_id++;

           }

       }

    }

    /* check unit id */

    if (max_devs && unit_id >= max_devs) {

        error_report("unit %d too big (max is %d)",

                     unit_id, max_devs - 1);

        return NULL;

    }

    /*

     * catch multiple definitions

     */

    if (drive_get(type, bus_id, unit_id) != NULL) {

        error_report("drive with bus=%d, unit=%d (index=%d) exists",

                     bus_id, unit_id, index);

        return NULL;

    }

    /* init */

    dinfo = g_malloc0(sizeof(*dinfo));

    if ((buf = qemu_opts_id(opts)) != NULL) {

        dinfo->id = g_strdup(buf);

    } else {

        /* no id supplied -> create one */

        dinfo->id = g_malloc0(32);

        if (type == IF_IDE || type == IF_SCSI)

            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";

        if (max_devs)

            snprintf(dinfo->id, 32, "%s%i%s%i",

                     if_name[type], bus_id, mediastr, unit_id);

        else

            snprintf(dinfo->id, 32, "%s%s%i",

                     if_name[type], mediastr, unit_id);

    }

    dinfo->bdrv = bdrv_new(dinfo->id);

    dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;

    dinfo->bdrv->read_only = ro;

    dinfo->devaddr = devaddr;

    dinfo->type = type;

    dinfo->bus = bus_id;

    dinfo->unit = unit_id;

    dinfo->cyls = cyls;

    dinfo->heads = heads;

    dinfo->secs = secs;

    dinfo->trans = translation;

    dinfo->opts = all_opts;

    dinfo->refcount = 1;

    if (serial != NULL) {

        dinfo->serial = g_strdup(serial);

    }

    QTAILQ_INSERT_TAIL(&drives, dinfo, next);

    bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);

    /* disk I/O throttling */

    if (throttle_enabled(&cfg)) {

        bdrv_io_limits_enable(dinfo->bdrv);

        bdrv_set_io_limits(dinfo->bdrv, &cfg);

    }

    switch(type) {

    case IF_IDE:

    case IF_SCSI:

    case IF_XEN:

    case IF_NONE:

        dinfo->media_cd = media == MEDIA_CDROM;

        break;

    case IF_SD:

    case IF_FLOPPY:

    case IF_PFLASH:

    case IF_MTD:

        break;

    case IF_VIRTIO:

    {

        /* add virtio block device */

        QemuOpts *devopts;

        devopts = qemu_opts_create_nofail(qemu_find_opts("device"));

        if (arch_type == QEMU_ARCH_S390X) {

            qemu_opt_set(devopts, "driver", "virtio-blk-s390");

        } else {

            qemu_opt_set(devopts, "driver", "virtio-blk-pci");

        }

        qemu_opt_set(devopts, "drive", dinfo->id);

        if (devaddr)

            qemu_opt_set(devopts, "addr", devaddr);

        break;

    }

    default:

        abort();

    }

    if (!file || !*file) {

        if (has_driver_specific_opts) {

            file = NULL;

        } else {

            return dinfo;

        }

    }

    if (snapshot) {

        /* always use cache=unsafe with snapshot */

        bdrv_flags &= ~BDRV_O_CACHE_MASK;

        bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);

    }

    if (copy_on_read) {

        bdrv_flags |= BDRV_O_COPY_ON_READ;

    }

    if (runstate_check(RUN_STATE_INMIGRATE)) {

        bdrv_flags |= BDRV_O_INCOMING;

    }

    if (media == MEDIA_CDROM) {

        /* CDROM is fine for any interface, don't check.  */

        ro = 1;

    } else if (ro == 1) {

        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY &&

            type != IF_NONE && type != IF_PFLASH) {

            error_report("read-only not supported by this bus type");

            goto err;

        }

    }

    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;

    if (ro && copy_on_read) {

        error_report("warning: disabling copy_on_read on read-only drive");

    }

    QINCREF(bs_opts);

    ret = bdrv_open(dinfo->bdrv, file, bs_opts, bdrv_flags, drv, &error);

    if (ret < 0) {

        error_report("could not open disk image %s: %s",

                     file ?: dinfo->id, error_get_pretty(error));

        goto err;

    }

    if (bdrv_key_required(dinfo->bdrv))

        autostart = 0;

    QDECREF(bs_opts);

    qemu_opts_del(opts);

    return dinfo;

err:

    qemu_opts_del(opts);

    QDECREF(bs_opts);

    bdrv_unref(dinfo->bdrv);

    g_free(dinfo->id);

    QTAILQ_REMOVE(&drives, dinfo, next);

    g_free(dinfo);

    return NULL;

}


int ff_get_cpu_flags_arm(void)
{
    int flags = CORE_CPU_FLAGS;
    uint32_t hwcap;
    if (get_hwcap(&hwcap) < 0)
        if (get_cpuinfo(&hwcap) < 0)
            return flags;
#define check_cap(cap, flag) do {               \
        if (hwcap & HWCAP_ ## cap)              \
            flags |= AV_CPU_FLAG_ ## flag;      \
    } while (0)
    /* No flags explicitly indicate v6 or v6T2 so check others which
       imply support. */
    check_cap(EDSP,    ARMV5TE);
    check_cap(TLS,     ARMV6);
    check_cap(THUMBEE, ARMV6T2);
    check_cap(VFP,     VFP);
    check_cap(VFPv3,   VFPV3);
    check_cap(NEON,    NEON);
    /* The v6 checks above are not reliable so let higher flags
       trickle down. */
    if (flags & (AV_CPU_FLAG_VFPV3 | AV_CPU_FLAG_NEON))
        flags |= AV_CPU_FLAG_ARMV6T2;
    if (flags & AV_CPU_FLAG_ARMV6T2)
        flags |= AV_CPU_FLAG_ARMV6;
    return flags;
}


static void avc_luma_vt_4w_msa(const uint8_t *src, int32_t src_stride,

                               uint8_t *dst, int32_t dst_stride,

                               int32_t height)

{

    int32_t loop_cnt;

    int16_t filt_const0 = 0xfb01;

    int16_t filt_const1 = 0x1414;

    int16_t filt_const2 = 0x1fb;

    v16i8 src0, src1, src2, src3, src4, src5, src6, src7, src8;

    v16i8 src10_r, src32_r, src54_r, src76_r, src21_r, src43_r, src65_r;

    v16i8 src87_r, src2110, src4332, src6554, src8776;

    v16i8 filt0, filt1, filt2;

    v8i16 out10, out32;

    v16u8 out;

    filt0 = (v16i8) __msa_fill_h(filt_const0);

    filt1 = (v16i8) __msa_fill_h(filt_const1);

    filt2 = (v16i8) __msa_fill_h(filt_const2);

    LD_SB5(src, src_stride, src0, src1, src2, src3, src4);

    src += (5 * src_stride);

    ILVR_B4_SB(src1, src0, src2, src1, src3, src2, src4, src3,

               src10_r, src21_r, src32_r, src43_r);

    ILVR_D2_SB(src21_r, src10_r, src43_r, src32_r, src2110, src4332);

    XORI_B2_128_SB(src2110, src4332);

    for (loop_cnt = (height >> 2); loop_cnt--;) {

        LD_SB4(src, src_stride, src5, src6, src7, src8);

        src += (4 * src_stride);

        ILVR_B4_SB(src5, src4, src6, src5, src7, src6, src8, src7,

                   src54_r, src65_r, src76_r, src87_r);

        ILVR_D2_SB(src65_r, src54_r, src87_r, src76_r, src6554, src8776);

        XORI_B2_128_SB(src6554, src8776);

        out10 = DPADD_SH3_SH(src2110, src4332, src6554, filt0, filt1, filt2);

        out32 = DPADD_SH3_SH(src4332, src6554, src8776, filt0, filt1, filt2);

        SRARI_H2_SH(out10, out32, 5);

        SAT_SH2_SH(out10, out32, 7);

        out = PCKEV_XORI128_UB(out10, out32);

        ST4x4_UB(out, out, 0, 1, 2, 3, dst, dst_stride);

        dst += (4 * dst_stride);

        src2110 = src6554;

        src4332 = src8776;

        src4 = src8;

    }

}


static inline uint32_t reloc_26_val(tcg_insn_unit *pc, tcg_insn_unit *target)

{

    assert((((uintptr_t)pc ^ (uintptr_t)target) & 0xf0000000) == 0);

    return ((uintptr_t)target >> 2) & 0x3ffffff;

}


static uint32_t openpic_iack(OpenPICState *opp, IRQDest *dst, int cpu)

{

    IRQSource *src;

    int retval, irq;

    DPRINTF("Lower OpenPIC INT output\n");

    qemu_irq_lower(dst->irqs[OPENPIC_OUTPUT_INT]);

    irq = IRQ_get_next(opp, &dst->raised);

    DPRINTF("IACK: irq=%d\n", irq);

    if (irq == -1) {

        /* No more interrupt pending */

        return opp->spve;

    }

    src = &opp->src[irq];

    if (!(src->ivpr & IVPR_ACTIVITY_MASK) ||

            !(IVPR_PRIORITY(src->ivpr) > dst->ctpr)) {

        /* - Spurious level-sensitive IRQ

         * - Priorities has been changed

         *   and the pending IRQ isn't allowed anymore

         */

        src->ivpr &= ~IVPR_ACTIVITY_MASK;

        retval = opp->spve;

    } else {

        /* IRQ enter servicing state */

        IRQ_setbit(&dst->servicing, irq);

        retval = IVPR_VECTOR(opp, src->ivpr);

    }

    IRQ_resetbit(&dst->raised, irq);

    if (!src->level) {

        /* edge-sensitive IRQ */

        src->ivpr &= ~IVPR_ACTIVITY_MASK;

        src->pending = 0;

    }

    if ((irq >= opp->irq_ipi0) &&  (irq < (opp->irq_ipi0 + MAX_IPI))) {

        src->idr &= ~(1 << cpu);

        if (src->idr && !src->level) {

            /* trigger on CPUs that didn't know about it yet */

            openpic_set_irq(opp, irq, 1);

            openpic_set_irq(opp, irq, 0);

            /* if all CPUs knew about it, set active bit again */

            src->ivpr |= IVPR_ACTIVITY_MASK;

        }

    }

    return retval;

}