av_cold int ff_mpv_encode_init(AVCodecContext *avctx)

{

    MpegEncContext *s = avctx->priv_data;

    int i, ret, format_supported;

    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:

        format_supported = 0;

        /* JPEG color space */

        if (avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||

            avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||

            (avctx->color_range == AVCOL_RANGE_JPEG &&

             (avctx->pix_fmt == AV_PIX_FMT_YUV420P ||

              avctx->pix_fmt == AV_PIX_FMT_YUV422P)))

            format_supported = 1;

        /* MPEG color space */

        else if (avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL &&

                 (avctx->pix_fmt == AV_PIX_FMT_YUV420P ||

                  avctx->pix_fmt == AV_PIX_FMT_YUV422P))

            format_supported = 1;

        if (!format_supported) {

            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_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_ERROR,

               "Warning keyframe interval too large! reducing it ...\n");

        avctx->gop_size = 600;

    }

    s->gop_size     = avctx->gop_size;

    s->avctx        = avctx;

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

    }

    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 & AV_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;

    }

#if FF_API_MOTION_EST

FF_DISABLE_DEPRECATION_WARNINGS

    s->me_method = avctx->me_method;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    /* Fixed QSCALE */

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

#if FF_API_MPV_OPT

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->border_masking != 0.0)

        s->border_masking = avctx->border_masking;

    FF_ENABLE_DEPRECATION_WARNINGS

#endif

    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->border_masking ||

                         (s->mpv_flags & FF_MPV_FLAG_QP_RD)) &&

                        !s->fixed_qscale;

    s->loop_filter = !!(s->avctx->flags & AV_CODEC_FLAG_LOOP_FILTER);

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

        av_log(avctx, AV_LOG_ERROR,

               "a vbv buffer size is needed, "

               "for encoding with a maximum bitrate\n");

        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_INFO, "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 too small for bitrate\n");

        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->avctx->flags & AV_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->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_ERROR,

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

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

        return -1;

    }

    if ((s->avctx->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_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) {

        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->avctx->flags & AV_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->avctx->flags & AV_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 (avctx->slices > 1 &&

        (avctx->codec_id == AV_CODEC_ID_FLV1 || avctx->codec_id == AV_CODEC_ID_H261)) {

        av_log(avctx, AV_LOG_ERROR, "Multiple slices are not supported by this codec\n");

        return AVERROR(EINVAL);

    }

    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_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->thread_count > 1)

        s->rtp_mode = 1;

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

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

        return -1;

    }

    if (avctx->b_frame_strategy && (avctx->flags & AV_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) {

        // (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 FF_API_QUANT_BIAS

FF_DISABLE_DEPRECATION_WARNINGS

    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;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    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->avctx->flags & AV_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->avctx->flags & AV_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:

        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;

        s->rtp_mode   = 0; /* Sliced encoding not supported */

        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_INFO,

                   "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 & AV_CODEC_FLAG_AC_PRED) ? 1 : 0;

        s->modified_quant  = s->h263_aic;

        s->loop_filter     = (avctx->flags & AV_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 & (AV_CODEC_FLAG_INTERLACED_DCT |

                                                AV_CODEC_FLAG_INTERLACED_ME) ||

                                s->alternate_scan);

    /* init */

    ff_mpv_idct_init(s);

    if (ff_mpv_common_init(s) < 0)

        return -1;

    if (ARCH_X86)

        ff_mpv_encode_init_x86(s);

    ff_fdctdsp_init(&s->fdsp, avctx);

    ff_me_cmp_init(&s->mecc, avctx);

    ff_mpegvideoencdsp_init(&s->mpvencdsp, avctx);

    ff_pixblockdsp_init(&s->pdsp, avctx);

    ff_qpeldsp_init(&s->qdsp);

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

    }

    if (CONFIG_H263_ENCODER)

        ff_h263dsp_init(&s->h263dsp);

    if (!s->dct_quantize)

        s->dct_quantize = ff_dct_quantize_c;

    if (!s->denoise_dct)

        s->denoise_dct  = denoise_dct_c;

    s->fast_dct_quantize = s->dct_quantize;

    if (avctx->trellis)

        s->dct_quantize  = dct_quantize_trellis_c;

    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->mecc, s->mecc.ildct_cmp,      s->avctx->ildct_cmp);

    ff_set_cmp(&s->mecc, s->mecc.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)

        if ((ret = ff_msmpeg4_encode_init(s)) < 0)

            return ret;

    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->idsp.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, s->q_intra_matrix, s->q_intra_matrix16,

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

                          31, 1);

        ff_convert_matrix(s, 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 FF_API_NORMALIZE_AQP

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->flags & CODEC_FLAG_NORMALIZE_AQP)

        s->mpv_flags |= FF_MPV_FLAG_NAQ;

    FF_ENABLE_DEPRECATION_WARNINGS;

#endif

#if FF_API_MV0

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->flags & CODEC_FLAG_MV0)

        s->mpv_flags |= FF_MPV_FLAG_MV0;

    FF_ENABLE_DEPRECATION_WARNINGS

#endif

#if FF_API_MPV_OPT

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->rc_qsquish != 0.0)

        s->rc_qsquish = avctx->rc_qsquish;

    if (avctx->rc_qmod_amp != 0.0)

        s->rc_qmod_amp = avctx->rc_qmod_amp;

    if (avctx->rc_qmod_freq)

        s->rc_qmod_freq = avctx->rc_qmod_freq;

    if (avctx->rc_buffer_aggressivity != 1.0)

        s->rc_buffer_aggressivity = avctx->rc_buffer_aggressivity;

    if (avctx->rc_initial_cplx != 0.0)

        s->rc_initial_cplx = avctx->rc_initial_cplx;

    if (avctx->lmin)

        s->lmin = avctx->lmin;

    if (avctx->lmax)

        s->lmax = avctx->lmax;

    if (avctx->rc_eq) {

        av_freep(&s->rc_eq);

        s->rc_eq = av_strdup(avctx->rc_eq);

        if (!s->rc_eq)

            return AVERROR(ENOMEM);

    }

    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;

}


static int sbr_hf_gen(AACContext *ac, SpectralBandReplication *sbr,

                      float X_high[64][40][2], const float X_low[32][40][2],

                      const float (*alpha0)[2], const float (*alpha1)[2],

                      const float bw_array[5], const uint8_t *t_env,

                      int bs_num_env)

{

    int i, j, x;

    int g = 0;

    int k = sbr->kx[1];

    for (j = 0; j < sbr->num_patches; j++) {

        for (x = 0; x < sbr->patch_num_subbands[j]; x++, k++) {

            float alpha[4];

            const int p = sbr->patch_start_subband[j] + x;

            while (g <= sbr->n_q && k >= sbr->f_tablenoise[g])

                g++;

            g--;

            if (g < 0) {

                av_log(ac->avctx, AV_LOG_ERROR,

                       "ERROR : no subband found for frequency %d\n", k);

                return -1;

            }

            alpha[0] = alpha1[p][0] * bw_array[g] * bw_array[g];

            alpha[1] = alpha1[p][1] * bw_array[g] * bw_array[g];

            alpha[2] = alpha0[p][0] * bw_array[g];

            alpha[3] = alpha0[p][1] * bw_array[g];

            for (i = 2 * t_env[0]; i < 2 * t_env[bs_num_env]; i++) {

                const int idx = i + ENVELOPE_ADJUSTMENT_OFFSET;

                X_high[k][idx][0] =

                    X_low[p][idx - 2][0] * alpha[0] -

                    X_low[p][idx - 2][1] * alpha[1] +

                    X_low[p][idx - 1][0] * alpha[2] -

                    X_low[p][idx - 1][1] * alpha[3] +

                    X_low[p][idx][0];

                X_high[k][idx][1] =

                    X_low[p][idx - 2][1] * alpha[0] +

                    X_low[p][idx - 2][0] * alpha[1] +

                    X_low[p][idx - 1][1] * alpha[2] +

                    X_low[p][idx - 1][0] * alpha[3] +

                    X_low[p][idx][1];

            }

        }

    }

    if (k < sbr->m[1] + sbr->kx[1])

        memset(X_high + k, 0, (sbr->m[1] + sbr->kx[1] - k) * sizeof(*X_high));

    return 0;

}


static int find_image_range(int *pfirst_index, int *plast_index,

                            const char *path)

{

    char buf[1024];

    int range, last_index, range1, first_index;

    /* find the first image */

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

        if (av_get_frame_filename(buf, sizeof(buf), path, first_index) < 0){

            *pfirst_index =

            *plast_index = 1;

            if (avio_check(buf, AVIO_FLAG_READ) > 0)

                return 0;

            return -1;

        }

        if (avio_check(buf, AVIO_FLAG_READ) > 0)

            break;

    }

    if (first_index == 5)

        goto fail;

    /* find the last image */

    last_index = first_index;

    for(;;) {

        range = 0;

        for(;;) {

            if (!range)

                range1 = 1;

            else

                range1 = 2 * range;

            if (av_get_frame_filename(buf, sizeof(buf), path,

                                      last_index + range1) < 0)

                goto fail;

            if (avio_check(buf, AVIO_FLAG_READ) <= 0)

                break;

            range = range1;

            /* just in case... */

            if (range >= (1 << 30))

                goto fail;

        }

        /* we are sure than image last_index + range exists */

        if (!range)

            break;

        last_index += range;

    }

    *pfirst_index = first_index;

    *plast_index = last_index;

    return 0;

 fail:

    return -1;

}


av_cold void ff_MPV_common_init_x86(MpegEncContext *s)

{

#if HAVE_INLINE_ASM

    int cpu_flags = av_get_cpu_flags();

    if (cpu_flags & AV_CPU_FLAG_MMX) {

        s->dct_unquantize_h263_intra = dct_unquantize_h263_intra_mmx;

        s->dct_unquantize_h263_inter = dct_unquantize_h263_inter_mmx;

        s->dct_unquantize_mpeg1_intra = dct_unquantize_mpeg1_intra_mmx;

        s->dct_unquantize_mpeg1_inter = dct_unquantize_mpeg1_inter_mmx;

        if(!(s->flags & CODEC_FLAG_BITEXACT))

            s->dct_unquantize_mpeg2_intra = dct_unquantize_mpeg2_intra_mmx;

        s->dct_unquantize_mpeg2_inter = dct_unquantize_mpeg2_inter_mmx;

        if (cpu_flags & AV_CPU_FLAG_SSE2) {

            s->denoise_dct= denoise_dct_sse2;

        } else {

                s->denoise_dct= denoise_dct_mmx;

        }

    }

#endif /* HAVE_INLINE_ASM */

}


static int mjpegb_decode_frame(AVCodecContext *avctx,

                              void *data, int *data_size,

                              uint8_t *buf, int buf_size)

{

    MJpegDecodeContext *s = avctx->priv_data;

    uint8_t *buf_end, *buf_ptr;

    AVFrame *picture = data;

    GetBitContext hgb; /* for the header */

    uint32_t dqt_offs, dht_offs, sof_offs, sos_offs, second_field_offs;

    uint32_t field_size, sod_offs;

    /* no supplementary picture */

    if (buf_size == 0)

        return 0;

    buf_ptr = buf;

    buf_end = buf + buf_size;

read_header:

    /* reset on every SOI */

    s->restart_interval = 0;

    s->mjpb_skiptosod = 0;

    init_get_bits(&hgb, buf_ptr, /*buf_size*/(buf_end - buf_ptr)*8);

    skip_bits(&hgb, 32); /* reserved zeros */

    if (get_bits_long(&hgb, 32) != be2me_32(ff_get_fourcc("mjpg")))

    {

	dprintf("not mjpeg-b (bad fourcc)\n");

	return 0;

    }

    field_size = get_bits_long(&hgb, 32); /* field size */

    dprintf("field size: 0x%x\n", field_size);

    skip_bits(&hgb, 32); /* padded field size */

    second_field_offs = get_bits_long(&hgb, 32);

    dprintf("second field offs: 0x%x\n", second_field_offs);

    if (second_field_offs)

	s->interlaced = 1;

    dqt_offs = get_bits_long(&hgb, 32);

    dprintf("dqt offs: 0x%x\n", dqt_offs);

    if (dqt_offs)

    {

	init_get_bits(&s->gb, buf+dqt_offs, (buf_end - (buf+dqt_offs))*8);

	s->start_code = DQT;

	mjpeg_decode_dqt(s);

    }

    dht_offs = get_bits_long(&hgb, 32);

    dprintf("dht offs: 0x%x\n", dht_offs);

    if (dht_offs)

    {

	init_get_bits(&s->gb, buf+dht_offs, (buf_end - (buf+dht_offs))*8);

	s->start_code = DHT;

	mjpeg_decode_dht(s);

    }

    sof_offs = get_bits_long(&hgb, 32);

    dprintf("sof offs: 0x%x\n", sof_offs);

    if (sof_offs)

    {

	init_get_bits(&s->gb, buf+sof_offs, (buf_end - (buf+sof_offs))*8);

	s->start_code = SOF0;

	if (mjpeg_decode_sof(s) < 0)

	    return -1;

    }

    sos_offs = get_bits_long(&hgb, 32);

    dprintf("sos offs: 0x%x\n", sos_offs);

    sod_offs = get_bits_long(&hgb, 32);

    dprintf("sod offs: 0x%x\n", sod_offs);

    if (sos_offs)

    {

//	init_get_bits(&s->gb, buf+sos_offs, (buf_end - (buf+sos_offs))*8);

	init_get_bits(&s->gb, buf+sos_offs, field_size*8);

	s->mjpb_skiptosod = (sod_offs - sos_offs - show_bits(&s->gb, 16));

	s->start_code = SOS;

	mjpeg_decode_sos(s);

    }

    if (s->interlaced) {

        s->bottom_field ^= 1;

        /* if not bottom field, do not output image yet */

        if (s->bottom_field && second_field_offs)

	{

	    buf_ptr = buf + second_field_offs;

	    second_field_offs = 0;

	    goto read_header;

    	}

    }

    //XXX FIXME factorize, this looks very similar to the EOI code

    *picture= s->picture;

    *data_size = sizeof(AVFrame);

    if(!s->lossless){

        picture->quality= FFMAX(FFMAX(s->qscale[0], s->qscale[1]), s->qscale[2]);

        picture->qstride= 0;

        picture->qscale_table= s->qscale_table;

        memset(picture->qscale_table, picture->quality, (s->width+15)/16);

        if(avctx->debug & FF_DEBUG_QP)

            av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);

        picture->quality*= FF_QP2LAMBDA;

    }

    return buf_ptr - buf;

}


AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)

{

    AVStream *st;

    int i;

    AVStream **streams;

    if (s->nb_streams >= INT_MAX/sizeof(*streams))

    streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));

    if (!streams)

    s->streams = streams;

    st = av_mallocz(sizeof(AVStream));

    if (!st)

    if (!(st->info = av_mallocz(sizeof(*st->info)))) {

    st->info->last_dts = AV_NOPTS_VALUE;

    st->codec = avcodec_alloc_context3(c);

    if (s->iformat) {

        /* no default bitrate if decoding */

        st->codec->bit_rate = 0;

        /* default pts setting is MPEG-like */

        avpriv_set_pts_info(st, 33, 1, 90000);

    st->index      = s->nb_streams;

    st->start_time = AV_NOPTS_VALUE;

    st->duration   = AV_NOPTS_VALUE;

    /* we set the current DTS to 0 so that formats without any timestamps

     * but durations get some timestamps, formats with some unknown

     * timestamps have their first few packets buffered and the

     * timestamps corrected before they are returned to the user */

    st->cur_dts       = s->iformat ? RELATIVE_TS_BASE : 0;

    st->first_dts     = AV_NOPTS_VALUE;

    st->probe_packets = MAX_PROBE_PACKETS;

    st->pts_wrap_reference = AV_NOPTS_VALUE;

    st->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;

    st->last_IP_pts = AV_NOPTS_VALUE;

    st->last_dts_for_order_check = AV_NOPTS_VALUE;

    for (i = 0; i < MAX_REORDER_DELAY + 1; i++)

        st->pts_buffer[i] = AV_NOPTS_VALUE;

    st->sample_aspect_ratio = (AVRational) { 0, 1 };

#if FF_API_R_FRAME_RATE

    st->info->last_dts      = AV_NOPTS_VALUE;

#endif

    st->info->fps_first_dts = AV_NOPTS_VALUE;

    st->info->fps_last_dts  = AV_NOPTS_VALUE;

    st->inject_global_side_data = s->internal->inject_global_side_data;

    s->streams[s->nb_streams++] = st;

    return st;


static void monitor_parse(const char *optarg, const char *mode)

{

    static int monitor_device_index = 0;

    QemuOpts *opts;

    const char *p;

    char label[32];

    int def = 0;

    if (strstart(optarg, "chardev:", &p)) {

        snprintf(label, sizeof(label), "%s", p);

    } else {

        snprintf(label, sizeof(label), "compat_monitor%d",

                 monitor_device_index);

        if (monitor_device_index == 0) {

            def = 1;

        }

        opts = qemu_chr_parse_compat(label, optarg);

        if (!opts) {

            fprintf(stderr, "parse error: %s\n", optarg);

            exit(1);

        }

    }

    opts = qemu_opts_create(qemu_find_opts("mon"), label, 1);

    if (!opts) {

        fprintf(stderr, "duplicate chardev: %s\n", label);

        exit(1);

    }

    qemu_opt_set(opts, "mode", mode);

    qemu_opt_set(opts, "chardev", label);

    if (def)

        qemu_opt_set(opts, "default", "on");

    monitor_device_index++;

}


virtio_gpu_resource_attach_backing(VirtIOGPU *g,
                                   struct virtio_gpu_ctrl_command *cmd)
{
    struct virtio_gpu_simple_resource *res;
    struct virtio_gpu_resource_attach_backing ab;
    int ret;
    VIRTIO_GPU_FILL_CMD(ab);
    trace_virtio_gpu_cmd_res_back_attach(ab.resource_id);
    res = virtio_gpu_find_resource(g, ab.resource_id);
    if (!res) {
        qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal resource specified %d\n",
                      __func__, ab.resource_id);
        cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
    ret = virtio_gpu_create_mapping_iov(&ab, cmd, &res->addrs, &res->iov);
    if (ret != 0) {
    res->iov_cnt = ab.nr_entries;


static void qxl_create_guest_primary(PCIQXLDevice *qxl, int loadvm,
                                     qxl_async_io async)
{
    QXLDevSurfaceCreate surface;
    QXLSurfaceCreate *sc = &qxl->guest_primary.surface;
    int size;
    int requested_height = le32_to_cpu(sc->height);
    int requested_stride = le32_to_cpu(sc->stride);
    size = abs(requested_stride) * requested_height;
    if (size > qxl->vgamem_size) {
        qxl_set_guest_bug(qxl, "%s: requested primary larger then framebuffer"
                               " size", __func__);
    if (qxl->mode == QXL_MODE_NATIVE) {
        qxl_set_guest_bug(qxl, "%s: nop since already in QXL_MODE_NATIVE",
                      __func__);
    qxl_exit_vga_mode(qxl);
    surface.format     = le32_to_cpu(sc->format);
    surface.height     = le32_to_cpu(sc->height);
    surface.mem        = le64_to_cpu(sc->mem);
    surface.position   = le32_to_cpu(sc->position);
    surface.stride     = le32_to_cpu(sc->stride);
    surface.width      = le32_to_cpu(sc->width);
    surface.type       = le32_to_cpu(sc->type);
    surface.flags      = le32_to_cpu(sc->flags);
    trace_qxl_create_guest_primary(qxl->id, sc->width, sc->height, sc->mem,
                                   sc->format, sc->position);
    trace_qxl_create_guest_primary_rest(qxl->id, sc->stride, sc->type,
                                        sc->flags);
    surface.mouse_mode = true;
    surface.group_id   = MEMSLOT_GROUP_GUEST;
    if (loadvm) {
        surface.flags |= QXL_SURF_FLAG_KEEP_DATA;
    qxl->mode = QXL_MODE_NATIVE;
    qxl->cmdflags = 0;
    qemu_spice_create_primary_surface(&qxl->ssd, 0, &surface, async);
    if (async == QXL_SYNC) {
        qxl_create_guest_primary_complete(qxl);


pp_mode *pp_get_mode_by_name_and_quality(const char *name, int quality)

{

    char temp[GET_MODE_BUFFER_SIZE];

    char *p= temp;

    static const char filterDelimiters[] = ",/";

    static const char optionDelimiters[] = ":|";

    struct PPMode *ppMode;

    char *filterToken;

    if (!name)  {

        av_log(NULL, AV_LOG_ERROR, "pp: Missing argument\n");

        return NULL;

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

        const char *p;

        for (p = pp_help; strchr(p, '\n'); p = strchr(p, '\n') + 1) {

            av_strlcpy(temp, p, FFMIN(sizeof(temp), strchr(p, '\n') - p + 2));

            av_log(NULL, AV_LOG_INFO, "%s", temp);

        return NULL;

    ppMode= av_malloc(sizeof(PPMode));

    ppMode->lumMode= 0;

    ppMode->chromMode= 0;

    ppMode->maxTmpNoise[0]= 700;

    ppMode->maxTmpNoise[1]= 1500;

    ppMode->maxTmpNoise[2]= 3000;

    ppMode->maxAllowedY= 234;

    ppMode->minAllowedY= 16;

    ppMode->baseDcDiff= 256/8;

    ppMode->flatnessThreshold= 56-16-1;

    ppMode->maxClippedThreshold= 0.01;

    ppMode->error=0;

    memset(temp, 0, GET_MODE_BUFFER_SIZE);

    av_strlcpy(temp, name, GET_MODE_BUFFER_SIZE - 1);

    av_log(NULL, AV_LOG_DEBUG, "pp: %s\n", name);

    for(;;){

        char *filterName;

        int q= 1000000; //PP_QUALITY_MAX;

        int chrom=-1;

        int luma=-1;

        char *option;

        char *options[OPTIONS_ARRAY_SIZE];

        int i;

        int filterNameOk=0;

        int numOfUnknownOptions=0;

        int enable=1; //does the user want us to enabled or disabled the filter

        filterToken= strtok(p, filterDelimiters);

        if(filterToken == NULL) break;

        p+= strlen(filterToken) + 1; // p points to next filterToken

        filterName= strtok(filterToken, optionDelimiters);

        av_log(NULL, AV_LOG_DEBUG, "pp: %s::%s\n", filterToken, filterName);

        if(*filterName == '-'){

            enable=0;

            filterName++;

        for(;;){ //for all options

            option= strtok(NULL, optionDelimiters);

            if(option == NULL) break;

            av_log(NULL, AV_LOG_DEBUG, "pp: option: %s\n", option);

            if(!strcmp("autoq", option) || !strcmp("a", option)) q= quality;

            else if(!strcmp("nochrom", option) || !strcmp("y", option)) chrom=0;

            else if(!strcmp("chrom", option) || !strcmp("c", option)) chrom=1;

            else if(!strcmp("noluma", option) || !strcmp("n", option)) luma=0;

            else{

                options[numOfUnknownOptions] = option;

                numOfUnknownOptions++;

            if(numOfUnknownOptions >= OPTIONS_ARRAY_SIZE-1) break;

        options[numOfUnknownOptions] = NULL;

        /* replace stuff from the replace Table */

        for(i=0; replaceTable[2*i]!=NULL; i++){

            if(!strcmp(replaceTable[2*i], filterName)){

                int newlen= strlen(replaceTable[2*i + 1]);

                int plen;

                int spaceLeft;

                p--, *p=',';

                plen= strlen(p);

                spaceLeft= p - temp + plen;

                if(spaceLeft + newlen  >= GET_MODE_BUFFER_SIZE - 1){

                memmove(p + newlen, p, plen+1);

                memcpy(p, replaceTable[2*i + 1], newlen);

                filterNameOk=1;

        for(i=0; filters[i].shortName!=NULL; i++){

            if(   !strcmp(filters[i].longName, filterName)

               || !strcmp(filters[i].shortName, filterName)){

                ppMode->lumMode &= ~filters[i].mask;

                ppMode->chromMode &= ~filters[i].mask;

                filterNameOk=1;

                if(!enable) break; // user wants to disable it

                if(q >= filters[i].minLumQuality && luma)

                    ppMode->lumMode|= filters[i].mask;

                if(chrom==1 || (chrom==-1 && filters[i].chromDefault))

                    if(q >= filters[i].minChromQuality)

                            ppMode->chromMode|= filters[i].mask;

                if(filters[i].mask == LEVEL_FIX){

                    int o;

                    ppMode->minAllowedY= 16;

                    ppMode->maxAllowedY= 234;

                    for(o=0; options[o]!=NULL; o++){

                        if(  !strcmp(options[o],"fullyrange")

                           ||!strcmp(options[o],"f")){

                            ppMode->minAllowedY= 0;

                            ppMode->maxAllowedY= 255;

                            numOfUnknownOptions--;

                else if(filters[i].mask == TEMP_NOISE_FILTER)

                {

                    int o;

                    int numOfNoises=0;

                    for(o=0; options[o]!=NULL; o++){

                        char *tail;

                        ppMode->maxTmpNoise[numOfNoises]=

                            strtol(options[o], &tail, 0);

                        if(tail!=options[o]){

                            numOfNoises++;

                            numOfUnknownOptions--;

                            if(numOfNoises >= 3) break;

                else if(filters[i].mask == V_DEBLOCK   || filters[i].mask == H_DEBLOCK

                     || filters[i].mask == V_A_DEBLOCK || filters[i].mask == H_A_DEBLOCK){

                    int o;

                    for(o=0; options[o]!=NULL && o<2; o++){

                        char *tail;

                        int val= strtol(options[o], &tail, 0);

                        if(tail==options[o]) break;

                        numOfUnknownOptions--;

                        if(o==0) ppMode->baseDcDiff= val;

                        else ppMode->flatnessThreshold= val;

                else if(filters[i].mask == FORCE_QUANT){

                    int o;

                    ppMode->forcedQuant= 15;

                    for(o=0; options[o]!=NULL && o<1; o++){

                        char *tail;

                        int val= strtol(options[o], &tail, 0);

                        if(tail==options[o]) break;

                        numOfUnknownOptions--;

                        ppMode->forcedQuant= val;

        if(!filterNameOk) ppMode->error++;

        ppMode->error += numOfUnknownOptions;

    av_log(NULL, AV_LOG_DEBUG, "pp: lumMode=%X, chromMode=%X\n", ppMode->lumMode, ppMode->chromMode);

    if(ppMode->error){

        av_log(NULL, AV_LOG_ERROR, "%d errors in postprocess string \"%s\"\n", ppMode->error, name);

        av_free(ppMode);

        return NULL;

    return ppMode;


static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    uint64_t size;

    uint8_t *buf;

    int err;

    if (c->fc->nb_streams < 1) // will happen with jp2 files

        return 0;

    st= c->fc->streams[c->fc->nb_streams-1];

    size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;

    if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)

        return AVERROR_INVALIDDATA;

    if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {

        st->codec->extradata_size = 0;

        return err;

    }

    buf = st->codec->extradata + st->codec->extradata_size;

    st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;

    AV_WB32(       buf    , atom.size + 8);

    AV_WL32(       buf + 4, atom.type);

    avio_read(pb, buf + 8, atom.size);

    return 0;

}


static always_inline void gen_bcond (DisasContext *ctx, int type)

{

    uint32_t bo = BO(ctx->opcode);

    int l1 = gen_new_label();

    TCGv target;

    ctx->exception = POWERPC_EXCP_BRANCH;

    if (type == BCOND_LR || type == BCOND_CTR) {

        target = tcg_temp_local_new();

        if (type == BCOND_CTR)

            tcg_gen_mov_tl(target, cpu_ctr);

        else

            tcg_gen_mov_tl(target, cpu_lr);

    }

    if (LK(ctx->opcode))

        gen_setlr(ctx, ctx->nip);

    l1 = gen_new_label();

    if ((bo & 0x4) == 0) {

        /* Decrement and test CTR */

        TCGv temp = tcg_temp_new();

        if (unlikely(type == BCOND_CTR)) {

            gen_inval_exception(ctx, POWERPC_EXCP_INVAL_INVAL);

            return;

        }

        tcg_gen_subi_tl(cpu_ctr, cpu_ctr, 1);

#if defined(TARGET_PPC64)

        if (!ctx->sf_mode)

            tcg_gen_ext32u_tl(temp, cpu_ctr);

        else

#endif

            tcg_gen_mov_tl(temp, cpu_ctr);

        if (bo & 0x2) {

            tcg_gen_brcondi_tl(TCG_COND_NE, temp, 0, l1);

            tcg_gen_brcondi_tl(TCG_COND_EQ, temp, 0, l1);

        }

        tcg_temp_free(temp);

    }

    if ((bo & 0x10) == 0) {

        /* Test CR */

        uint32_t bi = BI(ctx->opcode);

        uint32_t mask = 1 << (3 - (bi & 0x03));

        TCGv_i32 temp = tcg_temp_new_i32();

        if (bo & 0x8) {

            tcg_gen_andi_i32(temp, cpu_crf[bi >> 2], mask);

            tcg_gen_brcondi_i32(TCG_COND_EQ, temp, 0, l1);

            tcg_gen_andi_i32(temp, cpu_crf[bi >> 2], mask);

            tcg_gen_brcondi_i32(TCG_COND_NE, temp, 0, l1);

        }

        tcg_temp_free_i32(temp);

    }

    if (type == BCOND_IM) {

        target_ulong li = (target_long)((int16_t)(BD(ctx->opcode)));

        if (likely(AA(ctx->opcode) == 0)) {

            gen_goto_tb(ctx, 0, ctx->nip + li - 4);

            gen_goto_tb(ctx, 0, li);

        }

        gen_set_label(l1);

        gen_goto_tb(ctx, 1, ctx->nip);

#if defined(TARGET_PPC64)

        if (!(ctx->sf_mode))

            tcg_gen_andi_tl(cpu_nip, target, (uint32_t)~3);

        else

#endif

            tcg_gen_andi_tl(cpu_nip, target, ~3);

        tcg_gen_exit_tb(0);

        gen_set_label(l1);

#if defined(TARGET_PPC64)

        if (!(ctx->sf_mode))

            tcg_gen_movi_tl(cpu_nip, (uint32_t)ctx->nip);

        else

#endif

            tcg_gen_movi_tl(cpu_nip, ctx->nip);

        tcg_gen_exit_tb(0);

    }

}


void slavio_serial_ms_kbd_init(target_phys_addr_t base, qemu_irq irq,

                               int disabled, int clock, int it_shift)

{

    DeviceState *dev;

    SysBusDevice *s;

    dev = qdev_create(NULL, "escc");

    qdev_prop_set_uint32(dev, "disabled", disabled);

    qdev_prop_set_uint32(dev, "frequency", clock);

    qdev_prop_set_uint32(dev, "it_shift", it_shift);

    qdev_prop_set_chr(dev, "chrB", NULL);

    qdev_prop_set_chr(dev, "chrA", NULL);

    qdev_prop_set_uint32(dev, "chnBtype", mouse);

    qdev_prop_set_uint32(dev, "chnAtype", kbd);

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    sysbus_connect_irq(s, 0, irq);

    sysbus_connect_irq(s, 1, irq);

    sysbus_mmio_map(s, 0, base);

}


static int v9fs_receive_response(V9fsProxy *proxy, int type,

                                 int *status, void *response)

{

    int retval;

    ProxyHeader header;

    struct iovec *reply = &proxy->in_iovec;

    *status = 0;

    reply->iov_len = 0;

    retval = socket_read(proxy->sockfd, reply->iov_base, PROXY_HDR_SZ);

    if (retval < 0) {

        return retval;

    }

    reply->iov_len = PROXY_HDR_SZ;

    proxy_unmarshal(reply, 0, "dd", &header.type, &header.size);

    /*

     * if response size > PROXY_MAX_IO_SZ, read the response but ignore it and

     * return -ENOBUFS

     */

    if (header.size > PROXY_MAX_IO_SZ) {

        int count;

        while (header.size > 0) {

            count = MIN(PROXY_MAX_IO_SZ, header.size);

            count = socket_read(proxy->sockfd, reply->iov_base, count);

            if (count < 0) {

                return count;

            }

            header.size -= count;

        }

        *status = -ENOBUFS;

        return 0;

    }

    retval = socket_read(proxy->sockfd,

                         reply->iov_base + PROXY_HDR_SZ, header.size);

    if (retval < 0) {

        return retval;

    }

    reply->iov_len += header.size;

    /* there was an error during processing request */

    if (header.type == T_ERROR) {

        int ret;

        ret = proxy_unmarshal(reply, PROXY_HDR_SZ, "d", status);

        if (ret < 0) {

            *status = ret;

        }

        return 0;

    }

    switch (type) {

    case T_LSTAT: {

        ProxyStat prstat;

        retval = proxy_unmarshal(reply, PROXY_HDR_SZ,

                                 "qqqdddqqqqqqqqqq", &prstat.st_dev,

                                 &prstat.st_ino, &prstat.st_nlink,

                                 &prstat.st_mode, &prstat.st_uid,

                                 &prstat.st_gid, &prstat.st_rdev,

                                 &prstat.st_size, &prstat.st_blksize,

                                 &prstat.st_blocks,

                                 &prstat.st_atim_sec, &prstat.st_atim_nsec,

                                 &prstat.st_mtim_sec, &prstat.st_mtim_nsec,

                                 &prstat.st_ctim_sec, &prstat.st_ctim_nsec);

        prstat_to_stat(response, &prstat);

        break;

    }

    case T_STATFS: {

        ProxyStatFS prstfs;

        retval = proxy_unmarshal(reply, PROXY_HDR_SZ,

                                 "qqqqqqqqqqq", &prstfs.f_type,

                                 &prstfs.f_bsize, &prstfs.f_blocks,

                                 &prstfs.f_bfree, &prstfs.f_bavail,

                                 &prstfs.f_files, &prstfs.f_ffree,

                                 &prstfs.f_fsid[0], &prstfs.f_fsid[1],

                                 &prstfs.f_namelen, &prstfs.f_frsize);

        prstatfs_to_statfs(response, &prstfs);

        break;

    }

    case T_READLINK: {

        V9fsString target;

        v9fs_string_init(&target);

        retval = proxy_unmarshal(reply, PROXY_HDR_SZ, "s", &target);

        strcpy(response, target.data);

        v9fs_string_free(&target);

        break;

    }

    case T_LGETXATTR:

    case T_LLISTXATTR: {

        V9fsString xattr;

        v9fs_string_init(&xattr);

        retval = proxy_unmarshal(reply, PROXY_HDR_SZ, "s", &xattr);

        memcpy(response, xattr.data, xattr.size);

        v9fs_string_free(&xattr);

        break;

    }

    case T_GETVERSION:

        proxy_unmarshal(reply, PROXY_HDR_SZ, "q", response);

        break;

    default:

        return -1;

    }

    if (retval < 0) {

        *status  = retval;

    }

    return 0;

}


static int nbd_opt_go(QIOChannel *ioc, const char *wantname,

                      NBDExportInfo *info, Error **errp)

{

    nbd_opt_reply reply;

    uint32_t len = strlen(wantname);

    uint16_t type;

    int error;

    char *buf;

    /* The protocol requires that the server send NBD_INFO_EXPORT with

     * a non-zero flags (at least NBD_FLAG_HAS_FLAGS must be set); so

     * flags still 0 is a witness of a broken server. */

    info->flags = 0;

    trace_nbd_opt_go_start(wantname);

    buf = g_malloc(4 + len + 2 + 2 * info->request_sizes + 1);

    stl_be_p(buf, len);

    memcpy(buf + 4, wantname, len);

    /* At most one request, everything else up to server */

    stw_be_p(buf + 4 + len, info->request_sizes);

    if (info->request_sizes) {

        stw_be_p(buf + 4 + len + 2, NBD_INFO_BLOCK_SIZE);

    }

    if (nbd_send_option_request(ioc, NBD_OPT_GO,

                                4 + len + 2 + 2 * info->request_sizes, buf,

                                errp) < 0) {

        return -1;

    }

    while (1) {

        if (nbd_receive_option_reply(ioc, NBD_OPT_GO, &reply, errp) < 0) {

            return -1;

        }

        error = nbd_handle_reply_err(ioc, &reply, errp);

        if (error <= 0) {

            return error;

        }

        len = reply.length;

        if (reply.type == NBD_REP_ACK) {

            /* Server is done sending info and moved into transmission

               phase, but make sure it sent flags */

            if (len) {

                error_setg(errp, "server sent invalid NBD_REP_ACK");

                nbd_send_opt_abort(ioc);

                return -1;

            }

            if (!info->flags) {

                error_setg(errp, "broken server omitted NBD_INFO_EXPORT");

                nbd_send_opt_abort(ioc);

                return -1;

            }

            trace_nbd_opt_go_success();

            return 1;

        }

        if (reply.type != NBD_REP_INFO) {

            error_setg(errp, "unexpected reply type %" PRIx32

                       " (%s), expected %x",

                       reply.type, nbd_rep_lookup(reply.type), NBD_REP_INFO);

            nbd_send_opt_abort(ioc);

            return -1;

        }

        if (len < sizeof(type)) {

            error_setg(errp, "NBD_REP_INFO length %" PRIu32 " is too short",

                       len);

            nbd_send_opt_abort(ioc);

            return -1;

        }

        if (nbd_read(ioc, &type, sizeof(type), errp) < 0) {

            error_prepend(errp, "failed to read info type");

            nbd_send_opt_abort(ioc);

            return -1;

        }

        len -= sizeof(type);

        be16_to_cpus(&type);

        switch (type) {

        case NBD_INFO_EXPORT:

            if (len != sizeof(info->size) + sizeof(info->flags)) {

                error_setg(errp, "remaining export info len %" PRIu32

                           " is unexpected size", len);

                nbd_send_opt_abort(ioc);

                return -1;

            }

            if (nbd_read(ioc, &info->size, sizeof(info->size), errp) < 0) {

                error_prepend(errp, "failed to read info size");

                nbd_send_opt_abort(ioc);

                return -1;

            }

            be64_to_cpus(&info->size);

            if (nbd_read(ioc, &info->flags, sizeof(info->flags), errp) < 0) {

                error_prepend(errp, "failed to read info flags");

                nbd_send_opt_abort(ioc);

                return -1;

            }

            be16_to_cpus(&info->flags);

            trace_nbd_receive_negotiate_size_flags(info->size, info->flags);

            break;

        case NBD_INFO_BLOCK_SIZE:

            if (len != sizeof(info->min_block) * 3) {

                error_setg(errp, "remaining export info len %" PRIu32

                           " is unexpected size", len);

                nbd_send_opt_abort(ioc);

                return -1;

            }

            if (nbd_read(ioc, &info->min_block, sizeof(info->min_block),

                         errp) < 0) {

                error_prepend(errp, "failed to read info minimum block size");

                nbd_send_opt_abort(ioc);

                return -1;

            }

            be32_to_cpus(&info->min_block);

            if (!is_power_of_2(info->min_block)) {

                error_setg(errp, "server minimum block size %" PRId32

                           "is not a power of two", info->min_block);

                nbd_send_opt_abort(ioc);

                return -1;

            }

            if (nbd_read(ioc, &info->opt_block, sizeof(info->opt_block),

                         errp) < 0) {

                error_prepend(errp, "failed to read info preferred block size");

                nbd_send_opt_abort(ioc);

                return -1;

            }

            be32_to_cpus(&info->opt_block);

            if (!is_power_of_2(info->opt_block) ||

                info->opt_block < info->min_block) {

                error_setg(errp, "server preferred block size %" PRId32

                           "is not valid", info->opt_block);

                nbd_send_opt_abort(ioc);

                return -1;

            }

            if (nbd_read(ioc, &info->max_block, sizeof(info->max_block),

                         errp) < 0) {

                error_prepend(errp, "failed to read info maximum block size");

                nbd_send_opt_abort(ioc);

                return -1;

            }

            be32_to_cpus(&info->max_block);

            trace_nbd_opt_go_info_block_size(info->min_block, info->opt_block,

                                             info->max_block);

            break;

        default:

            trace_nbd_opt_go_info_unknown(type, nbd_info_lookup(type));

            if (nbd_drop(ioc, len, errp) < 0) {

                error_prepend(errp, "Failed to read info payload");

                nbd_send_opt_abort(ioc);

                return -1;

            }

            break;

        }

    }

}


AVResampleContext *swr_resample_init(AVResampleContext *c, int out_rate, int in_rate, int filter_size, int phase_shift, int linear, double cutoff){

    double factor= FFMIN(out_rate * cutoff / in_rate, 1.0);

    int phase_count= 1<<phase_shift;

    if (!c || c->phase_shift != phase_shift || c->linear!=linear || c->factor != factor

           || c->filter_length != FFMAX((int)ceil(filter_size/factor), 1)) {

        c = av_mallocz(sizeof(AVResampleContext));

        if (!c)

            return NULL;

        c->phase_shift   = phase_shift;

        c->phase_mask    = phase_count - 1;

        c->linear        = linear;

        c->factor        = factor;

        c->filter_length = FFMAX((int)ceil(filter_size/factor), 1);

        c->filter_bank   = av_mallocz(c->filter_length*(phase_count+1)*sizeof(FELEM));

        if (!c->filter_bank)

            goto error;

        if (build_filter(c->filter_bank, factor, c->filter_length, phase_count, 1<<FILTER_SHIFT, WINDOW_TYPE))

            goto error;

        memcpy(&c->filter_bank[c->filter_length*phase_count+1], c->filter_bank, (c->filter_length-1)*sizeof(FELEM));

        c->filter_bank[c->filter_length*phase_count]= c->filter_bank[c->filter_length - 1];

    }

    c->compensation_distance= 0;

    c->src_incr= out_rate;

    c->ideal_dst_incr= c->dst_incr= in_rate * phase_count;

    c->index= -phase_count*((c->filter_length-1)/2);

    c->frac= 0;

    return c;

error:

    av_free(c->filter_bank);

    av_free(c);

    return NULL;

}


static void add_input_streams(OptionsContext *o, AVFormatContext *ic)

{

    int i;

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

        AVStream *st = ic->streams[i];

        AVCodecContext *dec = st->codec;

        InputStream *ist = av_mallocz(sizeof(*ist));

        char *framerate = NULL, *hwaccel = NULL, *hwaccel_device = NULL;

        if (!ist)

            exit_program(1);

        GROW_ARRAY(input_streams, nb_input_streams);

        input_streams[nb_input_streams - 1] = ist;

        ist->st = st;

        ist->file_index = nb_input_files;

        ist->discard = 1;

        st->discard  = AVDISCARD_ALL;

        ist->ts_scale = 1.0;

        MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);

        ist->dec = choose_decoder(o, ic, st);

        ist->opts = filter_codec_opts(o->g->codec_opts, ist->st->codec->codec_id, ic, st, ist->dec);

        switch (dec->codec_type) {

        case AVMEDIA_TYPE_VIDEO:

            ist->resample_height  = dec->height;

            ist->resample_width   = dec->width;

            ist->resample_pix_fmt = dec->pix_fmt;

            MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);

            if (framerate && av_parse_video_rate(&ist->framerate,

                                                 framerate) < 0) {

                av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",

                       framerate);

                exit_program(1);

            }

            MATCH_PER_STREAM_OPT(hwaccels, str, hwaccel, ic, st);

            if (hwaccel) {

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

                    ist->hwaccel_id = HWACCEL_NONE;

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

                    ist->hwaccel_id = HWACCEL_AUTO;

                else {

                    int i;

                    for (i = 0; hwaccels[i].name; i++) {

                        if (!strcmp(hwaccels[i].name, hwaccel)) {

                            ist->hwaccel_id = hwaccels[i].id;

                            break;

                        }

                    }

                    if (!ist->hwaccel_id) {

                        av_log(NULL, AV_LOG_FATAL, "Unrecognized hwaccel: %s.\n",

                               hwaccel);

                        av_log(NULL, AV_LOG_FATAL, "Supported hwaccels: ");

                        for (i = 0; hwaccels[i].name; i++)

                            av_log(NULL, AV_LOG_FATAL, "%s ", hwaccels[i].name);

                        av_log(NULL, AV_LOG_FATAL, "\n");

                        exit_program(1);

                    }

                }

            }

            MATCH_PER_STREAM_OPT(hwaccel_devices, str, hwaccel_device, ic, st);

            if (hwaccel_device) {

                ist->hwaccel_device = av_strdup(hwaccel_device);

                if (!ist->hwaccel_device)

                    exit_program(1);

            }

            break;

        case AVMEDIA_TYPE_AUDIO:

            guess_input_channel_layout(ist);

            ist->resample_sample_fmt     = dec->sample_fmt;

            ist->resample_sample_rate    = dec->sample_rate;

            ist->resample_channels       = dec->channels;

            ist->resample_channel_layout = dec->channel_layout;

            break;

        case AVMEDIA_TYPE_DATA:

        case AVMEDIA_TYPE_SUBTITLE:

        case AVMEDIA_TYPE_ATTACHMENT:

        case AVMEDIA_TYPE_UNKNOWN:

            break;

        default:

            abort();

        }

    }

}


static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt, int discard) {

    AviSynthContext *avs = s->priv_data;

    AVS_VideoFrame *frame;

    unsigned char *dst_p;

    const unsigned char *src_p;

    int n, i, plane, rowsize, planeheight, pitch, bits;

    const char *error;

    if (avs->curr_frame >= avs->vi->num_frames)

        return AVERROR_EOF;

    // This must happen even if the stream is discarded to prevent desync.

    n = avs->curr_frame++;

    if (discard)

        return 0;

    pkt->pts = n;

    pkt->dts = n;

    pkt->duration = 1;

    // Define the bpp values for the new AviSynth 2.6 colorspaces

    if (avs_is_yv24(avs->vi)) {

        bits = 24;

    } else if (avs_is_yv16(avs->vi)) {

        bits = 16;

    } else if (avs_is_yv411(avs->vi)) {

        bits = 12;

    } else if (avs_is_y8(avs->vi)) {

        bits = 8;

        bits = avs_bits_per_pixel(avs->vi);

    // Without cast to int64_t, calculation overflows at about 9k x 9k resolution.

    pkt->size = (((int64_t)avs->vi->width * (int64_t)avs->vi->height) * bits) / 8;

    if (!pkt->size)

    pkt->data = av_malloc(pkt->size);

    if (!pkt->data)

    frame = avs_library->avs_get_frame(avs->clip, n);

    error = avs_library->avs_clip_get_error(avs->clip);

    if (error) {

        av_log(s, AV_LOG_ERROR, "%s\n", error);

    dst_p = pkt->data;

    for (i = 0; i < avs->n_planes; i++) {

        plane = avs->planes[i];

        src_p = avs_get_read_ptr_p(frame, plane);

        rowsize = avs_get_row_size_p(frame, plane);

        planeheight = avs_get_height_p(frame, plane);

        pitch = avs_get_pitch_p(frame, plane);

        // Flip RGB video.

        if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {

            src_p = src_p + (planeheight - 1) * pitch;

            pitch = -pitch;

        dst_p += rowsize * planeheight;

    avs_library->avs_release_video_frame(frame);

    return 0;


static inline void out_reg(IVState *s, enum Reg reg, unsigned v)

{

    const char *name = reg2str(reg);

    QTestState *qtest = global_qtest;

    global_qtest = s->qtest;

    g_test_message("%x -> *%s\n", v, name);

    qpci_io_writel(s->dev, s->reg_base + reg, v);

    global_qtest = qtest;

}


void rgb15tobgr32(const uint8_t *src, uint8_t *dst, long src_size)

{

	const uint16_t *end;

	uint8_t *d = (uint8_t *)dst;

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

	end = s + src_size/2;

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

		#ifdef WORDS_BIGENDIAN

			*d++ = 0;

			*d++ = (bgr&0x1F)<<3;

			*d++ = (bgr&0x3E0)>>2;

			*d++ = (bgr&0x7C00)>>7;

		#else

			*d++ = (bgr&0x7C00)>>7;

			*d++ = (bgr&0x3E0)>>2;

			*d++ = (bgr&0x1F)<<3;

			*d++ = 0;

		#endif

	}

}


static inline int ff_fast_malloc(void *ptr, unsigned int *size, size_t min_size, int zero_realloc)

{

    void *val;

    if (min_size < *size)

        return 0;

    min_size = FFMAX(17 * min_size / 16 + 32, min_size);

    av_freep(ptr);

    val = zero_realloc ? av_mallocz(min_size) : av_malloc(min_size);

    memcpy(ptr, &val, sizeof(val));

    if (!val)

        min_size = 0;

    *size = min_size;

    return 1;

}


int qcow2_update_header(BlockDriverState *bs)

    BDRVQcowState *s = bs->opaque;

    QCowHeader *header;

    char *buf;

    size_t buflen = s->cluster_size;

    int ret;

    uint64_t total_size;

    uint32_t refcount_table_clusters;

    size_t header_length;

    Qcow2UnknownHeaderExtension *uext;

    buf = qemu_blockalign(bs, buflen);

    /* Header structure */

    header = (QCowHeader*) buf;

    if (buflen < sizeof(*header)) {

        ret = -ENOSPC;

        goto fail;

    }

    header_length = sizeof(*header) + s->unknown_header_fields_size;

    total_size = bs->total_sectors * BDRV_SECTOR_SIZE;

    refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);

    *header = (QCowHeader) {

        /* Version 2 fields */

        .magic                  = cpu_to_be32(QCOW_MAGIC),

        .version                = cpu_to_be32(s->qcow_version),

        .backing_file_offset    = 0,

        .backing_file_size      = 0,

        .cluster_bits           = cpu_to_be32(s->cluster_bits),

        .size                   = cpu_to_be64(total_size),

        .crypt_method           = cpu_to_be32(s->crypt_method_header),

        .l1_size                = cpu_to_be32(s->l1_size),

        .l1_table_offset        = cpu_to_be64(s->l1_table_offset),

        .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),

        .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),

        .nb_snapshots           = cpu_to_be32(s->nb_snapshots),

        .snapshots_offset       = cpu_to_be64(s->snapshots_offset),

        /* Version 3 fields */

        .incompatible_features  = cpu_to_be64(s->incompatible_features),

        .compatible_features    = cpu_to_be64(s->compatible_features),

        .autoclear_features     = cpu_to_be64(s->autoclear_features),

        .refcount_order         = cpu_to_be32(3 + REFCOUNT_SHIFT),

        .header_length          = cpu_to_be32(header_length),

    };

    /* For older versions, write a shorter header */

    switch (s->qcow_version) {

    case 2:

        ret = offsetof(QCowHeader, incompatible_features);

        break;

    case 3:

        ret = sizeof(*header);

        break;

    default:

        ret = -EINVAL;

        goto fail;

    }

    buf += ret;

    buflen -= ret;

    memset(buf, 0, buflen);

    /* Preserve any unknown field in the header */

    if (s->unknown_header_fields_size) {

        if (buflen < s->unknown_header_fields_size) {

            ret = -ENOSPC;

            goto fail;

        }

        memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);

        buf += s->unknown_header_fields_size;

        buflen -= s->unknown_header_fields_size;

    }

    /* Backing file format header extension */

    if (*bs->backing_format) {

        ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,

                             bs->backing_format, strlen(bs->backing_format),

                             buflen);

        if (ret < 0) {

            goto fail;

        }

        buf += ret;

        buflen -= ret;

    }

    /* Feature table */

    Qcow2Feature features[] = {

            .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,

            .name = "dirty bit",

            .type = QCOW2_FEAT_TYPE_COMPATIBLE,

            .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,

            .name = "lazy refcounts",

    };

    ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,

                         features, sizeof(features), buflen);

    if (ret < 0) {

        goto fail;

    }

    buf += ret;

    buflen -= ret;

    /* Keep unknown header extensions */

    QLIST_FOREACH(uext, &s->unknown_header_ext, next) {

        ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);

        if (ret < 0) {

            goto fail;

        }

        buf += ret;

        buflen -= ret;

    }

    /* End of header extensions */

    ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);

    if (ret < 0) {

        goto fail;

    }

    buf += ret;

    buflen -= ret;

    /* Backing file name */

    if (*bs->backing_file) {

        size_t backing_file_len = strlen(bs->backing_file);

        if (buflen < backing_file_len) {

            ret = -ENOSPC;

            goto fail;

        }

        /* Using strncpy is ok here, since buf is not NUL-terminated. */

        strncpy(buf, bs->backing_file, buflen);

        header->backing_file_offset = cpu_to_be64(buf - ((char*) header));

        header->backing_file_size   = cpu_to_be32(backing_file_len);

    }

    /* Write the new header */

    ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);

    if (ret < 0) {

        goto fail;

    }

    ret = 0;

fail:

    qemu_vfree(header);

    return ret;

}


void ff_float_dsp_init_x86(AVFloatDSPContext *fdsp)

{

#if HAVE_YASM

    int mm_flags = av_get_cpu_flags();

    if (mm_flags & AV_CPU_FLAG_SSE && HAVE_SSE) {

        fdsp->vector_fmul = ff_vector_fmul_sse;

        fdsp->vector_fmac_scalar = ff_vector_fmac_scalar_sse;

    }

    if (mm_flags & AV_CPU_FLAG_AVX && HAVE_AVX) {

        fdsp->vector_fmul = ff_vector_fmul_avx;

        fdsp->vector_fmac_scalar = ff_vector_fmac_scalar_avx;

    }

#endif

}


static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,

                                 Jpeg2000Component *comp,

                                 Jpeg2000T1Context *t1, Jpeg2000Band *band)

{

    int i, j;

    int w = cblk->coord[0][1] - cblk->coord[0][0];

    for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {

        float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];

        int *src = t1->data[j];

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

            datap[i] = src[i] * band->f_stepsize;

    }

}


static int read_extra_header(FFV1Context *f)

{

    RangeCoder *const c = &f->c;

    uint8_t state[CONTEXT_SIZE];

    int i, j, k, ret;

    uint8_t state2[32][CONTEXT_SIZE];

    memset(state2, 128, sizeof(state2));

    memset(state, 128, sizeof(state));

    ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);

    ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);

    f->version = get_symbol(c, state, 0);

    if (f->version < 2) {

        av_log(f->avctx, AV_LOG_ERROR, "Invalid version in global header\n");

        return AVERROR_INVALIDDATA;

    }

    if (f->version > 2) {

        c->bytestream_end -= 4;

        f->micro_version = get_symbol(c, state, 0);

        if (f->micro_version < 0)

            return AVERROR_INVALIDDATA;

    }

    f->ac = f->avctx->coder_type = get_symbol(c, state, 0);

    if (f->ac > 1) {

        for (i = 1; i < 256; i++)

            f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];

    }

    f->colorspace                 = get_symbol(c, state, 0); //YUV cs type

    f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);

    f->chroma_planes              = get_rac(c, state);

    f->chroma_h_shift             = get_symbol(c, state, 0);

    f->chroma_v_shift             = get_symbol(c, state, 0);

    f->transparency               = get_rac(c, state);

    f->plane_count                = 1 + (f->chroma_planes || f->version<4) + f->transparency;

    f->num_h_slices               = 1 + get_symbol(c, state, 0);

    f->num_v_slices               = 1 + get_symbol(c, state, 0);

    if (f->chroma_h_shift > 4U || f->chroma_v_shift > 4U) {

        av_log(f->avctx, AV_LOG_ERROR, "chroma shift parameters %d %d are invalid\n",

               f->chroma_h_shift, f->chroma_v_shift);

        return AVERROR_INVALIDDATA;

    }

    if (f->num_h_slices > (unsigned)f->width  || !f->num_h_slices ||

        f->num_v_slices > (unsigned)f->height || !f->num_v_slices

       ) {

        av_log(f->avctx, AV_LOG_ERROR, "slice count invalid\n");

        return AVERROR_INVALIDDATA;

    }

    f->quant_table_count = get_symbol(c, state, 0);

    if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES)

        return AVERROR_INVALIDDATA;

    for (i = 0; i < f->quant_table_count; i++) {

        f->context_count[i] = read_quant_tables(c, f->quant_tables[i]);

        if (f->context_count[i] < 0) {

            av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");

            return AVERROR_INVALIDDATA;

        }

    }

    if ((ret = ff_ffv1_allocate_initial_states(f)) < 0)

        return ret;

    for (i = 0; i < f->quant_table_count; i++)

        if (get_rac(c, state)) {

            for (j = 0; j < f->context_count[i]; j++)

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

                    int pred = j ? f->initial_states[i][j - 1][k] : 128;

                    f->initial_states[i][j][k] =

                        (pred + get_symbol(c, state2[k], 1)) & 0xFF;

                }

        }

    if (f->version > 2) {

        f->ec = get_symbol(c, state, 0);

        if (f->micro_version > 2)

            f->intra = get_symbol(c, state, 0);

    }

    if (f->version > 2) {

        unsigned v;

        v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0,

                   f->avctx->extradata, f->avctx->extradata_size);

        if (v) {

            av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);

            return AVERROR_INVALIDDATA;

        }

    }

    if (f->avctx->debug & FF_DEBUG_PICT_INFO)

        av_log(f->avctx, AV_LOG_DEBUG,

               "global: ver:%d.%d, coder:%d, colorspace: %d bpr:%d chroma:%d(%d:%d), alpha:%d slices:%dx%d qtabs:%d ec:%d intra:%d\n",

               f->version, f->micro_version,

               f->ac,

               f->colorspace,

               f->avctx->bits_per_raw_sample,

               f->chroma_planes, f->chroma_h_shift, f->chroma_v_shift,

               f->transparency,

               f->num_h_slices, f->num_v_slices,

               f->quant_table_count,

               f->ec,

               f->intra

              );

    return 0;

}


int ff_v4l2_m2m_codec_end(AVCodecContext *avctx)

{

    V4L2m2mContext* s = avctx->priv_data;

    int ret;

    ret = ff_v4l2_context_set_status(&s->output, VIDIOC_STREAMOFF);

    if (ret)

            av_log(avctx, AV_LOG_ERROR, "VIDIOC_STREAMOFF %s\n", s->output.name);

    ret = ff_v4l2_context_set_status(&s->capture, VIDIOC_STREAMOFF);

    if (ret)

        av_log(avctx, AV_LOG_ERROR, "VIDIOC_STREAMOFF %s\n", s->capture.name);

    ff_v4l2_context_release(&s->output);

    if (atomic_load(&s->refcount))

        av_log(avctx, AV_LOG_ERROR, "ff_v4l2m2m_codec_end leaving pending buffers\n");

    ff_v4l2_context_release(&s->capture);

    sem_destroy(&s->refsync);

    /* release the hardware */

    if (close(s->fd) < 0 )

        av_log(avctx, AV_LOG_ERROR, "failure closing %s (%s)\n", s->devname, av_err2str(AVERROR(errno)));

    s->fd = -1;

    return 0;

}


static void spr_read_tbl(DisasContext *ctx, int gprn, int sprn)

{

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_start();

    }

    gen_helper_load_tbl(cpu_gpr[gprn], cpu_env);

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_end();

        gen_stop_exception(ctx);

    }

}


void vnc_client_read(void *opaque)

{

    VncState *vs = opaque;

    long ret;

    buffer_reserve(&vs->input, 4096);

#ifdef CONFIG_VNC_TLS

    if (vs->tls.session) {

	ret = gnutls_read(vs->tls.session, buffer_end(&vs->input), 4096);

	if (ret < 0) {

	    if (ret == GNUTLS_E_AGAIN)

		errno = EAGAIN;

	    else

		errno = EIO;

	    ret = -1;

	}

    } else

#endif /* CONFIG_VNC_TLS */

	ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);

    ret = vnc_client_io_error(vs, ret, socket_error());

    if (!ret)

	return;

    vs->input.offset += ret;

    while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {

	size_t len = vs->read_handler_expect;

	int ret;

	ret = vs->read_handler(vs, vs->input.buffer, len);

	if (vs->csock == -1)

	    return;

	if (!ret) {

	    memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));

	    vs->input.offset -= len;

	} else {

	    vs->read_handler_expect = ret;

	}

    }

}


static void test_bmdma_short_prdt(void)

{

    QPCIDevice *dev;

    QPCIBar bmdma_bar, ide_bar;

    uint8_t status;

    PrdtEntry prdt[] = {

        {

            .addr = 0,

            .size = cpu_to_le32(0x10 | PRDT_EOT),

        },

    };

    dev = get_pci_device(&bmdma_bar, &ide_bar);

    /* Normal request */

    status = send_dma_request(CMD_READ_DMA, 0, 1,

                              prdt, ARRAY_SIZE(prdt), NULL);

    g_assert_cmphex(status, ==, 0);

    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);

    /* Abort the request before it completes */

    status = send_dma_request(CMD_READ_DMA | CMDF_ABORT, 0, 1,

                              prdt, ARRAY_SIZE(prdt), NULL);

    g_assert_cmphex(status, ==, 0);

    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);

}


int ff_mpeg4_decode_picture_header(MpegEncContext * s, GetBitContext *gb)

{

    int startcode, v;

    /* search next start code */

    align_get_bits(gb);

    if(s->avctx->codec_tag == ff_get_fourcc("WV1F") && show_bits(gb, 24) == 0x575630){

        skip_bits(gb, 24);

        if(get_bits(gb, 8) == 0xF0)

            return decode_vop_header(s, gb);

    }

    startcode = 0xff;

    for(;;) {

        v = get_bits(gb, 8);

        startcode = ((startcode << 8) | v) & 0xffffffff;

        if(get_bits_count(gb) >= gb->size_in_bits){

            if(gb->size_in_bits==8 && (s->divx_version || s->xvid_build)){

                av_log(s->avctx, AV_LOG_ERROR, "frame skip %d\n", gb->size_in_bits);

                return FRAME_SKIPPED; //divx bug

            }else

                return -1; //end of stream

        }

        if((startcode&0xFFFFFF00) != 0x100)

            continue; //no startcode

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

            av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);

            if     (startcode<=0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");

            else if(startcode<=0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");

            else if(startcode<=0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved");

            else if(startcode<=0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");

            else if(startcode<=0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved");

            else if(startcode==0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");

            else if(startcode==0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");

            else if(startcode==0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data");

            else if(startcode==0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");

            else if(startcode==0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");

            else if(startcode==0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");

            else if(startcode==0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");

            else if(startcode==0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start");

            else if(startcode==0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start");

            else if(startcode==0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start");

            else if(startcode==0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");

            else if(startcode==0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");

            else if(startcode==0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");

            else if(startcode==0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");

            else if(startcode==0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");

            else if(startcode==0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");

            else if(startcode==0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");

            else if(startcode==0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");

            else if(startcode==0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");

            else if(startcode==0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");

            else if(startcode<=0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved");

            else if(startcode<=0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start");

            av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));

        }

        if(startcode >= 0x120 && startcode <= 0x12F){

            if(decode_vol_header(s, gb) < 0)

                return -1;

        }

        else if(startcode == USER_DATA_STARTCODE){

            decode_user_data(s, gb);

        }

        else if(startcode == GOP_STARTCODE){

            mpeg4_decode_gop_header(s, gb);

        }

        else if(startcode == VOP_STARTCODE){

            return decode_vop_header(s, gb);

        }

        align_get_bits(gb);

        startcode = 0xff;

    }

}


SwsFunc yuv2rgb_init_altivec (SwsContext *c)

{

  if (!(c->flags & SWS_CPU_CAPS_ALTIVEC))

    return NULL;

  /*

    and this seems not to matter too much I tried a bunch of

    videos with abnormal widths and mplayer crashes else where.

    mplayer -vo x11 -rawvideo on:w=350:h=240 raw-350x240.eyuv

    boom with X11 bad match.

  */

  if ((c->srcW & 0xf) != 0)    return NULL;

  switch (c->srcFormat) {

  case PIX_FMT_YUV410P:

  case PIX_FMT_YUV420P:

  /*case IMGFMT_CLPL:	??? */

  case PIX_FMT_GRAY8:

  case PIX_FMT_NV12:

  case PIX_FMT_NV21:

    if ((c->srcH & 0x1) != 0)

      return NULL;

    switch(c->dstFormat){

    case PIX_FMT_RGB24:

      av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space RGB24\n");

      return altivec_yuv2_rgb24;

    case PIX_FMT_BGR24:

      av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space BGR24\n");

      return altivec_yuv2_bgr24;

    case PIX_FMT_ARGB:

      av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space ARGB\n");

      return altivec_yuv2_argb;

    case PIX_FMT_ABGR:

      av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space ABGR\n");

      return altivec_yuv2_abgr;

    case PIX_FMT_RGBA:

      av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space RGBA\n");

      return altivec_yuv2_rgba;

    case PIX_FMT_BGRA:

      av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space BGRA\n");

      return altivec_yuv2_bgra;

    default: return NULL;

    }

    break;

  case PIX_FMT_UYVY422:

    switch(c->dstFormat){

    case PIX_FMT_BGR32:

      av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space UYVY -> RGB32\n");

      return altivec_uyvy_rgb32;

    default: return NULL;

    }

    break;

  }

  return NULL;

}


static void string_output_append(StringOutputVisitor *sov, int64_t a)

{

    Range *r = g_malloc0(sizeof(*r));

    r->begin = a;

    r->end = a + 1;

    sov->ranges = g_list_insert_sorted_merged(sov->ranges, r, range_compare);

}


static void run_postproc(AVCodecContext *avctx, AVFrame *frame)

{

    DDSContext *ctx = avctx->priv_data;

    int i, x_off;

    switch (ctx->postproc) {

    case DDS_ALPHA_EXP:

        /* Alpha-exponential mode divides each channel by the maximum

         * R, G or B value, and stores the multiplying factor in the

         * alpha channel. */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing alpha exponent.\n");

        for (i = 0; i < frame->linesize[0] * frame->height; i += 4) {

            uint8_t *src = frame->data[0] + i;

            int r = src[0];

            int g = src[1];

            int b = src[2];

            int a = src[3];

            src[0] = r * a / 255;

            src[1] = g * a / 255;

            src[2] = b * a / 255;

            src[3] = 255;

        }

        break;

    case DDS_NORMAL_MAP:

        /* Normal maps work in the XYZ color space and they encode

         * X in R or in A, depending on the texture type, Y in G and

         * derive Z with a square root of the distance.

         *

         * http://www.realtimecollisiondetection.net/blog/?p=28 */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing normal map.\n");

        x_off = ctx->tex_ratio == 8 ? 0 : 3;

        for (i = 0; i < frame->linesize[0] * frame->height; i += 4) {

            uint8_t *src = frame->data[0] + i;

            int x = src[x_off];

            int y = src[1];

            int z = 127;

            int d = (255 * 255 - x * x - y * y) / 2;

            if (d > 0)

                z = rint(sqrtf(d));

            src[0] = x;

            src[1] = y;

            src[2] = z;

            src[3] = 255;

        }

        break;

    case DDS_RAW_YCOCG:

        /* Data is Y-Co-Cg-A and not RGBA, but they are represented

         * with the same masks in the DDPF header. */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing raw YCoCg.\n");

        for (i = 0; i < frame->linesize[0] * frame->height; i += 4) {

            uint8_t *src = frame->data[0] + i;

            int a  = src[0];

            int cg = src[1] - 128;

            int co = src[2] - 128;

            int y  = src[3];

            src[0] = av_clip_uint8(y + co - cg);

            src[1] = av_clip_uint8(y + cg);

            src[2] = av_clip_uint8(y - co - cg);

            src[3] = a;

        }

        break;

    case DDS_SWAP_ALPHA:

        /* Alpha and Luma are stored swapped. */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing swapped Luma/Alpha.\n");

        for (i = 0; i < frame->linesize[0] * frame->height; i += 2) {

            uint8_t *src = frame->data[0] + i;

            FFSWAP(uint8_t, src[0], src[1]);

        }

        break;

    case DDS_SWIZZLE_A2XY:

        /* Swap R and G, often used to restore a standard RGTC2. */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing A2XY swizzle.\n");

        do_swizzle(frame, 0, 1);

        break;

    case DDS_SWIZZLE_RBXG:

        /* Swap G and A, then B and new A (G). */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing RBXG swizzle.\n");

        do_swizzle(frame, 1, 3);

        do_swizzle(frame, 2, 3);

        break;

    case DDS_SWIZZLE_RGXB:

        /* Swap B and A. */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing RGXB swizzle.\n");

        do_swizzle(frame, 2, 3);

        break;

    case DDS_SWIZZLE_RXBG:

        /* Swap G and A. */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing RXBG swizzle.\n");

        do_swizzle(frame, 1, 3);

        break;

    case DDS_SWIZZLE_RXGB:

        /* Swap R and A (misleading name). */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing RXGB swizzle.\n");

        do_swizzle(frame, 0, 3);

        break;

    case DDS_SWIZZLE_XGBR:

        /* Swap B and A, then R and new A (B). */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing XGBR swizzle.\n");

        do_swizzle(frame, 2, 3);

        do_swizzle(frame, 0, 3);

        break;

    case DDS_SWIZZLE_XGXR:

        /* Swap G and A, then R and new A (G), then new R (G) and new G (A).

         * This variant does not store any B component. */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing XGXR swizzle.\n");

        do_swizzle(frame, 1, 3);

        do_swizzle(frame, 0, 3);

        do_swizzle(frame, 0, 1);

        break;

    case DDS_SWIZZLE_XRBG:

        /* Swap G and A, then R and new A (G). */

        av_log(avctx, AV_LOG_DEBUG, "Post-processing XRBG swizzle.\n");

        do_swizzle(frame, 1, 3);

        do_swizzle(frame, 0, 3);

        break;

    }

}


static void ipvideo_decode_format_10_opcodes(IpvideoContext *s, AVFrame *frame)

{

    int pass, x, y, changed_block;

    int16_t opcode, skip;

    GetByteContext decoding_map_ptr;

    GetByteContext skip_map_ptr;

    bytestream2_skip(&s->stream_ptr, 14); /* data starts 14 bytes in */

    /* this is PAL8, so make the palette available */

    memcpy(frame->data[1], s->pal, AVPALETTE_SIZE);

    s->stride = frame->linesize[0];

    s->line_inc = s->stride - 8;

    s->upper_motion_limit_offset = (s->avctx->height - 8) * frame->linesize[0]

                                  + (s->avctx->width - 8) * (1 + s->is_16bpp);

    bytestream2_init(&decoding_map_ptr, s->decoding_map, s->decoding_map_size);

    bytestream2_init(&skip_map_ptr, s->skip_map, s->skip_map_size);

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

        bytestream2_seek(&decoding_map_ptr, 0, SEEK_SET);

        bytestream2_seek(&skip_map_ptr, 0, SEEK_SET);

        skip = bytestream2_get_le16(&skip_map_ptr);

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

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

                s->pixel_ptr = s->cur_decode_frame->data[0] + x + y * s->cur_decode_frame->linesize[0];

                while (skip <= 0 && bytestream2_get_bytes_left(&decoding_map_ptr) > 1)  {

                    if (skip != -0x8000 && skip) {

                        opcode = bytestream2_get_le16(&decoding_map_ptr);

                        ipvideo_format_10_passes[pass](s, frame, opcode);

                        break;

                    }

                    skip = bytestream2_get_le16(&skip_map_ptr);

                }

                skip *= 2;

            }

        }

    }

    bytestream2_seek(&skip_map_ptr, 0, SEEK_SET);

    skip = bytestream2_get_le16(&skip_map_ptr);

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

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

            changed_block = 0;

            s->pixel_ptr = frame->data[0] + x + y*frame->linesize[0];

            while (skip <= 0)  {

                if (skip != -0x8000 && skip) {

                    changed_block = 1;

                    break;

                }

                if (bytestream2_get_bytes_left(&skip_map_ptr) < 2)

                    return;

                skip = bytestream2_get_le16(&skip_map_ptr);

            }

            if (changed_block) {

                copy_from(s, s->cur_decode_frame, frame, 0, 0);

            } else {

                /* Don't try to copy last_frame data on the first frame */

                if (s->avctx->frame_number)

                    copy_from(s, s->last_frame, frame, 0, 0);

            }

            skip *= 2;

        }

    }

    FFSWAP(AVFrame*, s->prev_decode_frame, s->cur_decode_frame);

    if (bytestream2_get_bytes_left(&s->stream_ptr) > 1) {

        av_log(s->avctx, AV_LOG_DEBUG,

               "decode finished with %d bytes left over\n",

               bytestream2_get_bytes_left(&s->stream_ptr));

    }

}


static uint64_t omap_clkm_read(void *opaque, target_phys_addr_t addr,

                               unsigned size)

{

    struct omap_mpu_state_s *s = (struct omap_mpu_state_s *) opaque;

    if (size != 2) {

        return omap_badwidth_read16(opaque, addr);

    }

    switch (addr) {

    case 0x00:	/* ARM_CKCTL */

        return s->clkm.arm_ckctl;

    case 0x04:	/* ARM_IDLECT1 */

        return s->clkm.arm_idlect1;

    case 0x08:	/* ARM_IDLECT2 */

        return s->clkm.arm_idlect2;

    case 0x0c:	/* ARM_EWUPCT */

        return s->clkm.arm_ewupct;

    case 0x10:	/* ARM_RSTCT1 */

        return s->clkm.arm_rstct1;

    case 0x14:	/* ARM_RSTCT2 */

        return s->clkm.arm_rstct2;

    case 0x18:	/* ARM_SYSST */

        return (s->clkm.clocking_scheme << 11) | s->clkm.cold_start;

    case 0x1c:	/* ARM_CKOUT1 */

        return s->clkm.arm_ckout1;

    case 0x20:	/* ARM_CKOUT2 */

        break;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static int xen_pt_msgaddr32_reg_write(XenPCIPassthroughState *s,

                                      XenPTReg *cfg_entry, uint32_t *val,

                                      uint32_t dev_value, uint32_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    uint32_t writable_mask = 0;

    uint32_t old_addr = cfg_entry->data;

    /* modify emulate register */

    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;

    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);

    s->msi->addr_lo = cfg_entry->data;

    /* create value for writing to I/O device register */

    *val = XEN_PT_MERGE_VALUE(*val, dev_value, 0);

    /* update MSI */

    if (cfg_entry->data != old_addr) {

        if (s->msi->mapped) {

            xen_pt_msi_update(s);

        }

    }

    return 0;

}


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

{

    BDRVQEDState *s = bs->opaque;

    bs->bl.write_zeroes_alignment = s->header.cluster_size >> BDRV_SECTOR_BITS;

}


int block_signals(void)

{

    TaskState *ts = (TaskState *)thread_cpu->opaque;

    sigset_t set;

    int pending;

    /* It's OK to block everything including SIGSEGV, because we won't

     * run any further guest code before unblocking signals in

     * process_pending_signals().

     */

    sigfillset(&set);

    sigprocmask(SIG_SETMASK, &set, 0);

    pending = atomic_xchg(&ts->signal_pending, 1);

    return pending;

}


static void poll_set_started(AioContext *ctx, bool started)

{

    AioHandler *node;

    if (started == ctx->poll_started) {

        return;

    }

    ctx->poll_started = started;

    qemu_lockcnt_inc(&ctx->list_lock);

    QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {

        IOHandler *fn;

        if (node->deleted) {

            continue;

        }

        if (started) {

            fn = node->io_poll_begin;

        } else {

            fn = node->io_poll_end;

        }

        if (fn) {

            fn(node->opaque);

        }

    }

    qemu_lockcnt_dec(&ctx->list_lock);

}


void qemu_iohandler_fill(GArray *pollfds)

{

    IOHandlerRecord *ioh;

    QLIST_FOREACH(ioh, &io_handlers, next) {

        int events = 0;

        if (ioh->deleted)

            continue;

        if (ioh->fd_read &&

            (!ioh->fd_read_poll ||

             ioh->fd_read_poll(ioh->opaque) != 0)) {

            events |= G_IO_IN | G_IO_HUP | G_IO_ERR;

        }

        if (ioh->fd_write) {

            events |= G_IO_OUT | G_IO_ERR;

        }

        if (events) {

            GPollFD pfd = {

                .fd = ioh->fd,

                .events = events,

            };

            ioh->pollfds_idx = pollfds->len;

            g_array_append_val(pollfds, pfd);

        } else {

            ioh->pollfds_idx = -1;

        }

    }

}


static void powernv_create_core_node(PnvChip *chip, PnvCore *pc, void *fdt)

{

    CPUState *cs = CPU(DEVICE(pc->threads));

    DeviceClass *dc = DEVICE_GET_CLASS(cs);

    PowerPCCPU *cpu = POWERPC_CPU(cs);

    int smt_threads = CPU_CORE(pc)->nr_threads;

    CPUPPCState *env = &cpu->env;

    PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cs);

    uint32_t servers_prop[smt_threads];

    int i;

    uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40),

                       0xffffffff, 0xffffffff};

    uint32_t tbfreq = PNV_TIMEBASE_FREQ;

    uint32_t cpufreq = 1000000000;

    uint32_t page_sizes_prop[64];

    size_t page_sizes_prop_size;

    const uint8_t pa_features[] = { 24, 0,

                                    0xf6, 0x3f, 0xc7, 0xc0, 0x80, 0xf0,

                                    0x80, 0x00, 0x00, 0x00, 0x00, 0x00,

                                    0x00, 0x00, 0x00, 0x00, 0x80, 0x00,

                                    0x80, 0x00, 0x80, 0x00, 0x80, 0x00 };

    int offset;

    char *nodename;

    int cpus_offset = get_cpus_node(fdt);

    nodename = g_strdup_printf("%s@%x", dc->fw_name, pc->pir);

    offset = fdt_add_subnode(fdt, cpus_offset, nodename);

    _FDT(offset);

    g_free(nodename);

    _FDT((fdt_setprop_cell(fdt, offset, "ibm,chip-id", chip->chip_id)));

    _FDT((fdt_setprop_cell(fdt, offset, "reg", pc->pir)));

    _FDT((fdt_setprop_cell(fdt, offset, "ibm,pir", pc->pir)));

    _FDT((fdt_setprop_string(fdt, offset, "device_type", "cpu")));

    _FDT((fdt_setprop_cell(fdt, offset, "cpu-version", env->spr[SPR_PVR])));

    _FDT((fdt_setprop_cell(fdt, offset, "d-cache-block-size",

                            env->dcache_line_size)));

    _FDT((fdt_setprop_cell(fdt, offset, "d-cache-line-size",

                            env->dcache_line_size)));

    _FDT((fdt_setprop_cell(fdt, offset, "i-cache-block-size",

                            env->icache_line_size)));

    _FDT((fdt_setprop_cell(fdt, offset, "i-cache-line-size",

                            env->icache_line_size)));

    if (pcc->l1_dcache_size) {

        _FDT((fdt_setprop_cell(fdt, offset, "d-cache-size",

                               pcc->l1_dcache_size)));

    } else {

        error_report("Warning: Unknown L1 dcache size for cpu");

    }

    if (pcc->l1_icache_size) {

        _FDT((fdt_setprop_cell(fdt, offset, "i-cache-size",

                               pcc->l1_icache_size)));

    } else {

        error_report("Warning: Unknown L1 icache size for cpu");

    }

    _FDT((fdt_setprop_cell(fdt, offset, "timebase-frequency", tbfreq)));

    _FDT((fdt_setprop_cell(fdt, offset, "clock-frequency", cpufreq)));

    _FDT((fdt_setprop_cell(fdt, offset, "ibm,slb-size", env->slb_nr)));

    _FDT((fdt_setprop_string(fdt, offset, "status", "okay")));

    _FDT((fdt_setprop(fdt, offset, "64-bit", NULL, 0)));

    if (env->spr_cb[SPR_PURR].oea_read) {

        _FDT((fdt_setprop(fdt, offset, "ibm,purr", NULL, 0)));

    }

    if (env->mmu_model & POWERPC_MMU_1TSEG) {

        _FDT((fdt_setprop(fdt, offset, "ibm,processor-segment-sizes",

                           segs, sizeof(segs))));

    }

    /* Advertise VMX/VSX (vector extensions) if available

     *   0 / no property == no vector extensions

     *   1               == VMX / Altivec available

     *   2               == VSX available */

    if (env->insns_flags & PPC_ALTIVEC) {

        uint32_t vmx = (env->insns_flags2 & PPC2_VSX) ? 2 : 1;

        _FDT((fdt_setprop_cell(fdt, offset, "ibm,vmx", vmx)));

    }

    /* Advertise DFP (Decimal Floating Point) if available

     *   0 / no property == no DFP

     *   1               == DFP available */

    if (env->insns_flags2 & PPC2_DFP) {

        _FDT((fdt_setprop_cell(fdt, offset, "ibm,dfp", 1)));

    }

    page_sizes_prop_size = ppc_create_page_sizes_prop(env, page_sizes_prop,

                                                  sizeof(page_sizes_prop));

    if (page_sizes_prop_size) {

        _FDT((fdt_setprop(fdt, offset, "ibm,segment-page-sizes",

                           page_sizes_prop, page_sizes_prop_size)));

    }

    _FDT((fdt_setprop(fdt, offset, "ibm,pa-features",

                       pa_features, sizeof(pa_features))));

    /* Build interrupt servers properties */

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

        servers_prop[i] = cpu_to_be32(pc->pir + i);

    }

    _FDT((fdt_setprop(fdt, offset, "ibm,ppc-interrupt-server#s",

                       servers_prop, sizeof(servers_prop))));

}


static void test_bh_flush(void)

{

    BHTestData data = { .n = 0 };

    data.bh = aio_bh_new(ctx, bh_test_cb, &data);

    qemu_bh_schedule(data.bh);

    g_assert_cmpint(data.n, ==, 0);

    wait_for_aio();

    g_assert_cmpint(data.n, ==, 1);

    g_assert(!aio_poll(ctx, false));

    g_assert_cmpint(data.n, ==, 1);

    qemu_bh_delete(data.bh);

}