int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
{
    int ret = 0;
    AVDictionary *tmp = NULL;
    if (avcodec_is_open(avctx))
        return 0;
    if ((!codec && !avctx->codec)) {
        av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
        return AVERROR(EINVAL);
    if ((codec && avctx->codec && codec != avctx->codec)) {
        av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
                                    "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
        return AVERROR(EINVAL);
    if (!codec)
        codec = avctx->codec;
    if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
        return AVERROR(EINVAL);
    if (options)
        av_dict_copy(&tmp, *options, 0);
    /* If there is a user-supplied mutex locking routine, call it. */
    if (!(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE) && codec->init) {
        if (lockmgr_cb) {
            if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
                return -1;
        entangled_thread_counter++;
        if (entangled_thread_counter != 1) {
            av_log(avctx, AV_LOG_ERROR,
                   "Insufficient thread locking. At least %d threads are "
                   "calling avcodec_open2() at the same time right now.\n",
                   entangled_thread_counter);
            ret = -1;
            goto end;
    avctx->internal = av_mallocz(sizeof(AVCodecInternal));
    if (!avctx->internal) {
        ret = AVERROR(ENOMEM);
        goto end;
    avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
    if (!avctx->internal->pool) {
        ret = AVERROR(ENOMEM);
    avctx->internal->to_free = av_frame_alloc();
    if (!avctx->internal->to_free) {
        ret = AVERROR(ENOMEM);
    avctx->internal->buffer_frame = av_frame_alloc();
    if (!avctx->internal->buffer_frame) {
        ret = AVERROR(ENOMEM);
    avctx->internal->buffer_pkt = av_packet_alloc();
    if (!avctx->internal->buffer_pkt) {
        ret = AVERROR(ENOMEM);
    if (codec->priv_data_size > 0) {
        if (!avctx->priv_data) {
            avctx->priv_data = av_mallocz(codec->priv_data_size);
            if (!avctx->priv_data) {
                ret = AVERROR(ENOMEM);
                goto end;
            if (codec->priv_class) {
                *(const AVClass **)avctx->priv_data = codec->priv_class;
                av_opt_set_defaults(avctx->priv_data);
        if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
    } else {
        avctx->priv_data = NULL;
    if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
    if (avctx->coded_width && avctx->coded_height && !avctx->width && !avctx->height)
        ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
    else if (avctx->width && avctx->height)
        ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
    if (ret < 0)
    if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
        && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
           || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
        av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
        ff_set_dimensions(avctx, 0, 0);
    if (avctx->width > 0 && avctx->height > 0) {
        if (av_image_check_sar(avctx->width, avctx->height,
                               avctx->sample_aspect_ratio) < 0) {
            av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
                   avctx->sample_aspect_ratio.num,
                   avctx->sample_aspect_ratio.den);
            avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
    /* if the decoder init function was already called previously,
     * free the already allocated subtitle_header before overwriting it */
    if (av_codec_is_decoder(codec))
        av_freep(&avctx->subtitle_header);
    if (avctx->channels > FF_SANE_NB_CHANNELS) {
    avctx->codec = codec;
    if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
        avctx->codec_id == AV_CODEC_ID_NONE) {
        avctx->codec_type = codec->type;
        avctx->codec_id   = codec->id;
    if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
                                         && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
        av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
    avctx->frame_number = 0;
    if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) &&
        avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
        ret = AVERROR_EXPERIMENTAL;
    if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
        (!avctx->time_base.num || !avctx->time_base.den)) {
        avctx->time_base.num = 1;
        avctx->time_base.den = avctx->sample_rate;
    if (HAVE_THREADS) {
        ret = ff_thread_init(avctx);
        if (ret < 0) {
    if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS))
        avctx->thread_count = 1;
    if (av_codec_is_encoder(avctx->codec)) {
        int i;
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
        avctx->coded_frame = av_frame_alloc();
        if (!avctx->coded_frame) {
            ret = AVERROR(ENOMEM);
FF_ENABLE_DEPRECATION_WARNINGS
#endif
        if (avctx->codec->sample_fmts) {
            for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
                if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
                    break;
                if (avctx->channels == 1 &&
                    av_get_planar_sample_fmt(avctx->sample_fmt) ==
                    av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
                    avctx->sample_fmt = avctx->codec->sample_fmts[i];
                    break;
            if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
                av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
        if (avctx->codec->pix_fmts) {
            for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
                if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
                    break;
            if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE) {
                av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
            if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
                avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
                avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
                avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
                avctx->color_range = AVCOL_RANGE_JPEG;
        if (avctx->codec->supported_samplerates) {
            for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
                if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
                    break;
            if (avctx->codec->supported_samplerates[i] == 0) {
                av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
        if (avctx->codec->channel_layouts) {
            if (!avctx->channel_layout) {
                av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
            } else {
                for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
                    if (avctx->channel_layout == avctx->codec->channel_layouts[i])
                        break;
                if (avctx->codec->channel_layouts[i] == 0) {
                    av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
        if (avctx->channel_layout && avctx->channels) {
            if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
                av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
        } else if (avctx->channel_layout) {
            avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
        if (!avctx->rc_initial_buffer_occupancy)
            avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
        if (avctx->ticks_per_frame &&
            avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) {
            av_log(avctx, AV_LOG_ERROR,
                   "ticks_per_frame %d too large for the timebase %d/%d.",
                   avctx->ticks_per_frame,
                   avctx->time_base.num,
                   avctx->time_base.den);
        if (avctx->hw_frames_ctx) {
            AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
            if (frames_ctx->format != avctx->pix_fmt) {
                av_log(avctx, AV_LOG_ERROR,
                       "Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n");
    if (avctx->codec->init && !(avctx->active_thread_type & FF_THREAD_FRAME)) {
        ret = avctx->codec->init(avctx);
        if (ret < 0) {
#if FF_API_AUDIOENC_DELAY
    if (av_codec_is_encoder(avctx->codec))
        avctx->delay = avctx->initial_padding;
#endif
    if (av_codec_is_decoder(avctx->codec)) {
        /* validate channel layout from the decoder */
        if (avctx->channel_layout) {
            int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
            if (!avctx->channels)
                avctx->channels = channels;
            else if (channels != avctx->channels) {
                av_log(avctx, AV_LOG_WARNING,
                       "channel layout does not match number of channels\n");
                avctx->channel_layout = 0;
        if (avctx->channels && avctx->channels < 0 ||
            avctx->channels > FF_SANE_NB_CHANNELS) {
#if FF_API_AVCTX_TIMEBASE
        if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
            avctx->time_base = av_inv_q(avctx->framerate);
#endif
end:
    if (!(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE) && codec->init) {
        entangled_thread_counter--;
        /* Release any user-supplied mutex. */
        if (lockmgr_cb) {
            (*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
    if (options) {
        av_dict_free(options);
        *options = tmp;
    return ret;
free_and_end:
    if (avctx->codec &&
        (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))
        avctx->codec->close(avctx);
    if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
        av_opt_free(avctx->priv_data);
    av_opt_free(avctx);
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
    av_frame_free(&avctx->coded_frame);
FF_ENABLE_DEPRECATION_WARNINGS
#endif
    av_dict_free(&tmp);
    av_freep(&avctx->priv_data);
    if (avctx->internal) {
        av_frame_free(&avctx->internal->to_free);
        av_freep(&avctx->internal->pool);
    av_freep(&avctx->internal);
    avctx->codec = NULL;
    goto end;


DECLARE_LOOP_FILTER(mmxext)

DECLARE_LOOP_FILTER(sse2)

DECLARE_LOOP_FILTER(ssse3)

DECLARE_LOOP_FILTER(sse4)

#endif /* HAVE_YASM */

#define VP8_LUMA_MC_FUNC(IDX, SIZE, OPT) \

    c->put_vp8_epel_pixels_tab[IDX][0][2] = ff_put_vp8_epel ## SIZE ## _h6_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][2][0] = ff_put_vp8_epel ## SIZE ## _v6_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][2][2] = ff_put_vp8_epel ## SIZE ## _h6v6_ ## OPT

#define VP8_MC_FUNC(IDX, SIZE, OPT) \

    c->put_vp8_epel_pixels_tab[IDX][0][1] = ff_put_vp8_epel ## SIZE ## _h4_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][1][0] = ff_put_vp8_epel ## SIZE ## _v4_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][1][1] = ff_put_vp8_epel ## SIZE ## _h4v4_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][1][2] = ff_put_vp8_epel ## SIZE ## _h6v4_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][2][1] = ff_put_vp8_epel ## SIZE ## _h4v6_ ## OPT; \

    VP8_LUMA_MC_FUNC(IDX, SIZE, OPT)

#define VP8_BILINEAR_MC_FUNC(IDX, SIZE, OPT) \

    c->put_vp8_bilinear_pixels_tab[IDX][0][1] = ff_put_vp8_bilinear ## SIZE ## _h_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][0][2] = ff_put_vp8_bilinear ## SIZE ## _h_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][1][0] = ff_put_vp8_bilinear ## SIZE ## _v_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][1][1] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][1][2] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][2][0] = ff_put_vp8_bilinear ## SIZE ## _v_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][2][1] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][2][2] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT

av_cold void ff_vp8dsp_init_x86(VP8DSPContext* c)

{

#if HAVE_YASM

    int mm_flags = av_get_cpu_flags();

    if (mm_flags & AV_CPU_FLAG_MMX) {

        c->vp8_idct_dc_add    = ff_vp8_idct_dc_add_mmx;

        c->vp8_idct_dc_add4uv = ff_vp8_idct_dc_add4uv_mmx;

#if ARCH_X86_32

        c->vp8_idct_dc_add4y  = ff_vp8_idct_dc_add4y_mmx;

        c->vp8_idct_add       = ff_vp8_idct_add_mmx;

        c->vp8_luma_dc_wht    = ff_vp8_luma_dc_wht_mmx;

        c->put_vp8_epel_pixels_tab[0][0][0]     =

        c->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_mmx;

#endif

        c->put_vp8_epel_pixels_tab[1][0][0]     =

        c->put_vp8_bilinear_pixels_tab[1][0][0] = ff_put_vp8_pixels8_mmx;

#if ARCH_X86_32

        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_mmx;

        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_mmx;

        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_mmx;

        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_mmx;

        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_mmx;

        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_mmx;

        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_mmx;

        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_mmx;

        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_mmx;

        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_mmx;

#endif

    }

    /* note that 4-tap width=16 functions are missing because w=16

     * is only used for luma, and luma is always a copy or sixtap. */

    if (mm_flags & AV_CPU_FLAG_MMXEXT) {

        VP8_MC_FUNC(2, 4, mmxext);

        VP8_BILINEAR_MC_FUNC(2, 4, mmxext);

#if ARCH_X86_32

        VP8_LUMA_MC_FUNC(0, 16, mmxext);

        VP8_MC_FUNC(1, 8, mmxext);

        VP8_BILINEAR_MC_FUNC(0, 16, mmxext);

        VP8_BILINEAR_MC_FUNC(1,  8, mmxext);

        c->vp8_v_loop_filter_simple   = ff_vp8_v_loop_filter_simple_mmxext;

        c->vp8_h_loop_filter_simple   = ff_vp8_h_loop_filter_simple_mmxext;

        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_mmxext;

        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_mmxext;

        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_mmxext;

        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_mmxext;

        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_mmxext;

        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_mmxext;

        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_mmxext;

        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_mmxext;

#endif

    }

    if (mm_flags & AV_CPU_FLAG_SSE) {

        c->vp8_idct_add                         = ff_vp8_idct_add_sse;

        c->vp8_luma_dc_wht                      = ff_vp8_luma_dc_wht_sse;

        c->put_vp8_epel_pixels_tab[0][0][0]     =

        c->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_sse;

    }

    if (mm_flags & (AV_CPU_FLAG_SSE2|AV_CPU_FLAG_SSE2SLOW)) {

        VP8_LUMA_MC_FUNC(0, 16, sse2);

        VP8_MC_FUNC(1, 8, sse2);

        VP8_BILINEAR_MC_FUNC(0, 16, sse2);

        VP8_BILINEAR_MC_FUNC(1, 8, sse2);

        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_sse2;

#if ARCH_X86_64 || HAVE_ALIGNED_STACK

        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_sse2;

        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_sse2;

        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_sse2;

        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_sse2;

#endif

    }

    if (mm_flags & AV_CPU_FLAG_SSE2) {

        c->vp8_idct_dc_add4y          = ff_vp8_idct_dc_add4y_sse2;

        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_sse2;

#if ARCH_X86_64 || HAVE_ALIGNED_STACK

        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_sse2;

        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_sse2;

        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_sse2;

        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_sse2;

#endif

    }

    if (mm_flags & AV_CPU_FLAG_SSSE3) {

        VP8_LUMA_MC_FUNC(0, 16, ssse3);

        VP8_MC_FUNC(1, 8, ssse3);

        VP8_MC_FUNC(2, 4, ssse3);

        VP8_BILINEAR_MC_FUNC(0, 16, ssse3);

        VP8_BILINEAR_MC_FUNC(1, 8, ssse3);

        VP8_BILINEAR_MC_FUNC(2, 4, ssse3);

        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_ssse3;

        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_ssse3;

#if ARCH_X86_64 || HAVE_ALIGNED_STACK

        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_ssse3;

        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_ssse3;

        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_ssse3;

        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_ssse3;

        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_ssse3;

        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_ssse3;

        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_ssse3;

        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_ssse3;

#endif

    }

    if (mm_flags & AV_CPU_FLAG_SSE4) {

        c->vp8_idct_dc_add                  = ff_vp8_idct_dc_add_sse4;

        c->vp8_h_loop_filter_simple   = ff_vp8_h_loop_filter_simple_sse4;

#if ARCH_X86_64 || HAVE_ALIGNED_STACK

        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_sse4;

        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_sse4;

#endif

    }

#endif /* HAVE_YASM */

}


static av_always_inline int get_dst_color_err(PaletteUseContext *s,

                                              uint32_t c, int *er, int *eg, int *eb,

                                              const enum color_search_method search_method)

{

    const uint8_t a = c >> 24 & 0xff;

    const uint8_t r = c >> 16 & 0xff;

    const uint8_t g = c >>  8 & 0xff;

    const uint8_t b = c       & 0xff;

    const int dstx = color_get(s, c, a, r, g, b, search_method);

    const uint32_t dstc = s->palette[dstx];

    *er = r - (dstc >> 16 & 0xff);

    *eg = g - (dstc >>  8 & 0xff);

    *eb = b - (dstc       & 0xff);

    return dstx;

}


static inline void put_symbol_inline(RangeCoder *c, uint8_t *state, int v, int is_signed){

    int i;

    if(v){

        const int a= FFABS(v);

        const int e= av_log2(a);

        put_rac(c, state+0, 0);

        assert(e<=9);

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

            put_rac(c, state+1+i, 1);  //1..10

        }

        put_rac(c, state+1+i, 0);

        for(i=e-1; i>=0; i--){

            put_rac(c, state+22+i, (a>>i)&1); //22..31

        }

        if(is_signed)

            put_rac(c, state+11 + e, v < 0); //11..21

    }else{

        put_rac(c, state+0, 1);

    }

}


static void rgb24_to_rgb555(AVPicture *dst, AVPicture *src,

                            int width, int height)

{

    const unsigned char *p;

    unsigned char *q;

    int r, g, b, dst_wrap, src_wrap;

    int x, y;

    p = src->data[0];

    src_wrap = src->linesize[0] - 3 * width;

    q = dst->data[0];

    dst_wrap = dst->linesize[0] - 2 * width;

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

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

            r = p[0];

            g = p[1];

            b = p[2];

            ((unsigned short *)q)[0] =

                ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3) | 0x8000;

            q += 2;

            p += 3;

        }

        p += src_wrap;

        q += dst_wrap;

    }

}


static void avc_wgt_8width_msa(uint8_t *data,

                               int32_t stride,

                               int32_t height,

                               int32_t log2_denom,

                               int32_t src_weight,

                               int32_t offset_in)

{

    uint8_t cnt;

    v16u8 zero = { 0 };

    v16u8 src0, src1, src2, src3;

    v8u16 src0_r, src1_r, src2_r, src3_r;

    v8u16 temp0, temp1, temp2, temp3;

    v8u16 wgt, denom, offset;

    offset_in <<= (log2_denom);

    if (log2_denom) {

        offset_in += (1 << (log2_denom - 1));

    }

    wgt = (v8u16) __msa_fill_h(src_weight);

    offset = (v8u16) __msa_fill_h(offset_in);

    denom = (v8u16) __msa_fill_h(log2_denom);

    for (cnt = height / 4; cnt--;) {

        LOAD_4VECS_UB(data, stride, src0, src1, src2, src3);

        ILVR_B_4VECS_UH(src0, src1, src2, src3, zero, zero, zero, zero,

                        src0_r, src1_r, src2_r, src3_r);

        temp0 = wgt * src0_r;

        temp1 = wgt * src1_r;

        temp2 = wgt * src2_r;

        temp3 = wgt * src3_r;

        ADDS_S_H_4VECS_UH(temp0, offset, temp1, offset,

                          temp2, offset, temp3, offset,

                          temp0, temp1, temp2, temp3);

        MAXI_S_H_4VECS_UH(temp0, temp1, temp2, temp3, 0);

        SRL_H_4VECS_UH(temp0, temp1, temp2, temp3,

                       temp0, temp1, temp2, temp3, denom);

        SAT_U_H_4VECS_UH(temp0, temp1, temp2, temp3, 7);

        PCKEV_B_STORE_8_BYTES_4(temp0, temp1, temp2, temp3, data, stride);

        data += (4 * stride);

    }

}


static void opt_frame_pad_left(const char *arg)

{

    frame_padleft = atoi(arg);

    if (frame_padleft < 0) {

        fprintf(stderr, "Incorrect left pad size\n");

        av_exit(1);

    }

}


ssize_t cpu_get_note_size(int class, int machine, int nr_cpus)

{

    int name_size = 8; /* "CORE" or "QEMU" rounded */

    size_t elf_note_size = 0;

    int note_head_size;

    const NoteFuncDesc *nf;

    assert(class == ELFCLASS64);

    assert(machine == EM_S390);

    note_head_size = sizeof(Elf64_Nhdr);

    for (nf = note_func; nf->note_contents_func; nf++) {

        elf_note_size = elf_note_size + note_head_size + name_size +

                        nf->contents_size;

    }

    return (elf_note_size) * nr_cpus;

}


static void add_query_tests(QmpSchema *schema)

{

    SchemaInfoList *tail;

    SchemaInfo *si, *arg_type, *ret_type;

    const char *test_name;

    /* Test the query-like commands */

    for (tail = schema->list; tail; tail = tail->next) {

        si = tail->value;

        if (si->meta_type != SCHEMA_META_TYPE_COMMAND) {

            continue;

        }

        if (query_is_blacklisted(si->name)) {

            continue;

        }

        arg_type = qmp_schema_lookup(schema, si->u.command.arg_type);

        if (object_type_has_mandatory_members(arg_type)) {

            continue;

        }

        ret_type = qmp_schema_lookup(schema, si->u.command.ret_type);

        if (ret_type->meta_type == SCHEMA_META_TYPE_OBJECT

            && !ret_type->u.object.members) {

            continue;

        }

        test_name = g_strdup_printf("qmp/%s", si->name);

        qtest_add_data_func(test_name, si->name, test_query);

    }

}


static void cpu_handle_guest_debug(CPUState *env)

{

    gdb_set_stop_cpu(env);

    qemu_system_debug_request();

#ifdef CONFIG_IOTHREAD

    env->stopped = 1;

#endif

}


vmxnet3_io_bar1_write(void *opaque,

                      hwaddr addr,

                      uint64_t val,

                      unsigned size)

{

    VMXNET3State *s = opaque;

    switch (addr) {

    /* Vmxnet3 Revision Report Selection */

    case VMXNET3_REG_VRRS:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_VRRS] = %" PRIx64 ", size %d",

                  val, size);

        break;

    /* UPT Version Report Selection */

    case VMXNET3_REG_UVRS:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_UVRS] = %" PRIx64 ", size %d",

                  val, size);

        break;

    /* Driver Shared Address Low */

    case VMXNET3_REG_DSAL:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_DSAL] = %" PRIx64 ", size %d",

                  val, size);

        /*

         * Guest driver will first write the low part of the shared

         * memory address. We save it to temp variable and set the

         * shared address only after we get the high part

         */

        if (val == 0) {

            s->device_active = false;

        }

        s->temp_shared_guest_driver_memory = val;

        s->drv_shmem = 0;

        break;

    /* Driver Shared Address High */

    case VMXNET3_REG_DSAH:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_DSAH] = %" PRIx64 ", size %d",

                  val, size);

        /*

         * Set the shared memory between guest driver and device.

         * We already should have low address part.

         */

        s->drv_shmem = s->temp_shared_guest_driver_memory | (val << 32);

        break;

    /* Command */

    case VMXNET3_REG_CMD:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_CMD] = %" PRIx64 ", size %d",

                  val, size);

        vmxnet3_handle_command(s, val);

        break;

    /* MAC Address Low */

    case VMXNET3_REG_MACL:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_MACL] = %" PRIx64 ", size %d",

                  val, size);

        s->temp_mac = val;

        break;

    /* MAC Address High */

    case VMXNET3_REG_MACH:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_MACH] = %" PRIx64 ", size %d",

                  val, size);

        vmxnet3_set_variable_mac(s, val, s->temp_mac);

        break;

    /* Interrupt Cause Register */

    case VMXNET3_REG_ICR:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_ICR] = %" PRIx64 ", size %d",

                  val, size);

        g_assert_not_reached();

        break;

    /* Event Cause Register */

    case VMXNET3_REG_ECR:

        VMW_CBPRN("Write BAR1 [VMXNET3_REG_ECR] = %" PRIx64 ", size %d",

                  val, size);

        vmxnet3_ack_events(s, val);

        break;

    default:

        VMW_CBPRN("Unknown Write to BAR1 [%" PRIx64 "] = %" PRIx64 ", size %d",

                  addr, val, size);

        break;

    }

}


static int64_t alloc_block(BlockDriverState* bs, int64_t offset)

{

    BDRVVPCState *s = bs->opaque;

    int64_t bat_offset;

    uint32_t index, bat_value;

    int ret;

    uint8_t bitmap[s->bitmap_size];

    /* Check if sector_num is valid */

    if ((offset < 0) || (offset > bs->total_sectors * BDRV_SECTOR_SIZE)) {

        return -EINVAL;

    }

    /* Write entry into in-memory BAT */

    index = offset / s->block_size;

    assert(s->pagetable[index] == 0xFFFFFFFF);

    s->pagetable[index] = s->free_data_block_offset / 512;

    /* Initialize the block's bitmap */

    memset(bitmap, 0xff, s->bitmap_size);

    ret = bdrv_pwrite_sync(bs->file, s->free_data_block_offset, bitmap,

        s->bitmap_size);

    if (ret < 0) {

        return ret;

    }

    /* Write new footer (the old one will be overwritten) */

    s->free_data_block_offset += s->block_size + s->bitmap_size;

    ret = rewrite_footer(bs);

    if (ret < 0)

        goto fail;

    /* Write BAT entry to disk */

    bat_offset = s->bat_offset + (4 * index);

    bat_value = cpu_to_be32(s->pagetable[index]);

    ret = bdrv_pwrite_sync(bs->file, bat_offset, &bat_value, 4);

    if (ret < 0)

        goto fail;

    return get_image_offset(bs, offset, false);

fail:

    s->free_data_block_offset -= (s->block_size + s->bitmap_size);

    return ret;

}


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

{

	const uint8_t *s = src;

	const uint8_t *end;

#ifdef HAVE_MMX

	const uint8_t *mm_end;

#endif

	uint16_t *d = (uint16_t *)dst;

	end = s + src_size;

#ifdef HAVE_MMX

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

	__asm __volatile(

	    "movq	%0, %%mm7\n\t"

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

	    ::"m"(red_16mask),"m"(green_16mask));

	mm_end = end - 15;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

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

		"movd	4%1, %%mm3\n\t"

		"punpckldq 8%1, %%mm0\n\t"

		"punpckldq 12%1, %%mm3\n\t"

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

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

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

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

		"psllq	$8, %%mm0\n\t"

		"psllq	$8, %%mm3\n\t"

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

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

		"psrlq	$5, %%mm1\n\t"

		"psrlq	$5, %%mm4\n\t"

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

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

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

		"psrlq	$19, %%mm5\n\t"

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

		"pand	%2, %%mm5\n\t"

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

		"por	%%mm4, %%mm3\n\t"

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

		"por	%%mm5, %%mm3\n\t"

		"psllq	$16, %%mm3\n\t"

		"por	%%mm3, %%mm0\n\t"

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

		:"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");

		d += 4;

		s += 16;

	}

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

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

#endif

	while(s < end)

	{

		// FIXME on bigendian

		const int src= *s; s += 4;

		*d++ = ((src&0xF8)<<8) + ((src&0xFC00)>>5) + ((src&0xF80000)>>19);

	}

}


int ff_h264_decode_mb_cavlc(const H264Context *h, H264SliceContext *sl)

{

    int mb_xy;

    int partition_count;

    unsigned int mb_type, cbp;

    int dct8x8_allowed= h->ps.pps->transform_8x8_mode;

    int decode_chroma = h->ps.sps->chroma_format_idc == 1 || h->ps.sps->chroma_format_idc == 2;

    const int pixel_shift = h->pixel_shift;

    mb_xy = sl->mb_xy = sl->mb_x + sl->mb_y*h->mb_stride;

    ff_tlog(h->avctx, "pic:%d mb:%d/%d\n", h->poc.frame_num, sl->mb_x, sl->mb_y);

    cbp = 0; /* avoid warning. FIXME: find a solution without slowing

                down the code */

    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {

        if (sl->mb_skip_run == -1)

            sl->mb_skip_run = get_ue_golomb_long(&sl->gb);

        if (sl->mb_skip_run--) {

            if (FRAME_MBAFF(h) && (sl->mb_y & 1) == 0) {

                if (sl->mb_skip_run == 0)

                    sl->mb_mbaff = sl->mb_field_decoding_flag = get_bits1(&sl->gb);

            }

            decode_mb_skip(h, sl);

            return 0;

        }

    }

    if (FRAME_MBAFF(h)) {

        if ((sl->mb_y & 1) == 0)

            sl->mb_mbaff = sl->mb_field_decoding_flag = get_bits1(&sl->gb);

    }

    sl->prev_mb_skipped = 0;

    mb_type= get_ue_golomb(&sl->gb);

    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {

        if(mb_type < 23){

            partition_count = ff_h264_b_mb_type_info[mb_type].partition_count;

            mb_type         = ff_h264_b_mb_type_info[mb_type].type;

        }else{

            mb_type -= 23;

            goto decode_intra_mb;

        }

    } else if (sl->slice_type_nos == AV_PICTURE_TYPE_P) {

        if(mb_type < 5){

            partition_count = ff_h264_p_mb_type_info[mb_type].partition_count;

            mb_type         = ff_h264_p_mb_type_info[mb_type].type;

        }else{

            mb_type -= 5;

            goto decode_intra_mb;

        }

    }else{

       av_assert2(sl->slice_type_nos == AV_PICTURE_TYPE_I);

        if (sl->slice_type == AV_PICTURE_TYPE_SI && mb_type)

            mb_type--;

decode_intra_mb:

        if(mb_type > 25){

            av_log(h->avctx, AV_LOG_ERROR, "mb_type %d in %c slice too large at %d %d\n", mb_type, av_get_picture_type_char(sl->slice_type), sl->mb_x, sl->mb_y);

            return -1;

        }

        partition_count=0;

        cbp                      = ff_h264_i_mb_type_info[mb_type].cbp;

        sl->intra16x16_pred_mode = ff_h264_i_mb_type_info[mb_type].pred_mode;

        mb_type                  = ff_h264_i_mb_type_info[mb_type].type;

    }

    if (MB_FIELD(sl))

        mb_type |= MB_TYPE_INTERLACED;

    h->slice_table[mb_xy] = sl->slice_num;

    if(IS_INTRA_PCM(mb_type)){

        const int mb_size = ff_h264_mb_sizes[h->ps.sps->chroma_format_idc] *

                            h->ps.sps->bit_depth_luma;

        // We assume these blocks are very rare so we do not optimize it.

        sl->intra_pcm_ptr = align_get_bits(&sl->gb);

        if (get_bits_left(&sl->gb) < mb_size) {

            av_log(h->avctx, AV_LOG_ERROR, "Not enough data for an intra PCM block.\n");

            return AVERROR_INVALIDDATA;

        }

        skip_bits_long(&sl->gb, mb_size);

        // In deblocking, the quantizer is 0

        h->cur_pic.qscale_table[mb_xy] = 0;

        // All coeffs are present

        memset(h->non_zero_count[mb_xy], 16, 48);

        h->cur_pic.mb_type[mb_xy] = mb_type;

        return 0;

    }

    fill_decode_neighbors(h, sl, mb_type);

    fill_decode_caches(h, sl, mb_type);

    //mb_pred

    if(IS_INTRA(mb_type)){

        int pred_mode;

//            init_top_left_availability(h);

        if(IS_INTRA4x4(mb_type)){

            int i;

            int di = 1;

            if(dct8x8_allowed && get_bits1(&sl->gb)){

                mb_type |= MB_TYPE_8x8DCT;

                di = 4;

            }

//                fill_intra4x4_pred_table(h);

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

                int mode = pred_intra_mode(h, sl, i);

                if(!get_bits1(&sl->gb)){

                    const int rem_mode= get_bits(&sl->gb, 3);

                    mode = rem_mode + (rem_mode >= mode);

                }

                if(di==4)

                    fill_rectangle(&sl->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1);

                else

                    sl->intra4x4_pred_mode_cache[scan8[i]] = mode;

            }

            write_back_intra_pred_mode(h, sl);

            if (ff_h264_check_intra4x4_pred_mode(sl->intra4x4_pred_mode_cache, h->avctx,

                                                 sl->top_samples_available, sl->left_samples_available) < 0)

                return -1;

        }else{

            sl->intra16x16_pred_mode = ff_h264_check_intra_pred_mode(h->avctx, sl->top_samples_available,

                                                                     sl->left_samples_available, sl->intra16x16_pred_mode, 0);

            if (sl->intra16x16_pred_mode < 0)

                return -1;

        }

        if(decode_chroma){

            pred_mode= ff_h264_check_intra_pred_mode(h->avctx, sl->top_samples_available,

                                                     sl->left_samples_available, get_ue_golomb_31(&sl->gb), 1);

            if(pred_mode < 0)

                return -1;

            sl->chroma_pred_mode = pred_mode;

        } else {

            sl->chroma_pred_mode = DC_128_PRED8x8;

        }

    }else if(partition_count==4){

        int i, j, sub_partition_count[4], list, ref[2][4];

        if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {

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

                sl->sub_mb_type[i]= get_ue_golomb_31(&sl->gb);

                if(sl->sub_mb_type[i] >=13){

                    av_log(h->avctx, AV_LOG_ERROR, "B sub_mb_type %u out of range at %d %d\n", sl->sub_mb_type[i], sl->mb_x, sl->mb_y);

                    return -1;

                }

                sub_partition_count[i] = ff_h264_b_sub_mb_type_info[sl->sub_mb_type[i]].partition_count;

                sl->sub_mb_type[i]     = ff_h264_b_sub_mb_type_info[sl->sub_mb_type[i]].type;

            }

            if( IS_DIRECT(sl->sub_mb_type[0]|sl->sub_mb_type[1]|sl->sub_mb_type[2]|sl->sub_mb_type[3])) {

                ff_h264_pred_direct_motion(h, sl, &mb_type);

                sl->ref_cache[0][scan8[4]] =

                sl->ref_cache[1][scan8[4]] =

                sl->ref_cache[0][scan8[12]] =

                sl->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;

            }

        }else{

            av_assert2(sl->slice_type_nos == AV_PICTURE_TYPE_P); //FIXME SP correct ?

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

                sl->sub_mb_type[i]= get_ue_golomb_31(&sl->gb);

                if(sl->sub_mb_type[i] >=4){

                    av_log(h->avctx, AV_LOG_ERROR, "P sub_mb_type %u out of range at %d %d\n", sl->sub_mb_type[i], sl->mb_x, sl->mb_y);

                    return -1;

                }

                sub_partition_count[i] = ff_h264_p_sub_mb_type_info[sl->sub_mb_type[i]].partition_count;

                sl->sub_mb_type[i]     = ff_h264_p_sub_mb_type_info[sl->sub_mb_type[i]].type;

            }

        }

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

            int ref_count = IS_REF0(mb_type) ? 1 : sl->ref_count[list] << MB_MBAFF(sl);

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

                if(IS_DIRECT(sl->sub_mb_type[i])) continue;

                if(IS_DIR(sl->sub_mb_type[i], 0, list)){

                    unsigned int tmp;

                    if(ref_count == 1){

                        tmp= 0;

                    }else if(ref_count == 2){

                        tmp= get_bits1(&sl->gb)^1;

                    }else{

                        tmp= get_ue_golomb_31(&sl->gb);

                        if(tmp>=ref_count){

                            av_log(h->avctx, AV_LOG_ERROR, "ref %u overflow\n", tmp);

                            return -1;

                        }

                    }

                    ref[list][i]= tmp;

                }else{

                 //FIXME

                    ref[list][i] = -1;

                }

            }

        }

        if(dct8x8_allowed)

            dct8x8_allowed = get_dct8x8_allowed(h, sl);

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

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

                if(IS_DIRECT(sl->sub_mb_type[i])) {

                    sl->ref_cache[list][ scan8[4*i] ] = sl->ref_cache[list][ scan8[4*i]+1 ];

                    continue;

                }

                sl->ref_cache[list][ scan8[4*i]   ]=sl->ref_cache[list][ scan8[4*i]+1 ]=

                sl->ref_cache[list][ scan8[4*i]+8 ]=sl->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];

                if(IS_DIR(sl->sub_mb_type[i], 0, list)){

                    const int sub_mb_type= sl->sub_mb_type[i];

                    const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;

                    for(j=0; j<sub_partition_count[i]; j++){

                        int mx, my;

                        const int index= 4*i + block_width*j;

                        int16_t (* mv_cache)[2]= &sl->mv_cache[list][ scan8[index] ];

                        pred_motion(h, sl, index, block_width, list, sl->ref_cache[list][ scan8[index] ], &mx, &my);

                        mx += get_se_golomb(&sl->gb);

                        my += get_se_golomb(&sl->gb);

                        ff_tlog(h->avctx, "final mv:%d %d\n", mx, my);

                        if(IS_SUB_8X8(sub_mb_type)){

                            mv_cache[ 1 ][0]=

                            mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;

                            mv_cache[ 1 ][1]=

                            mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;

                        }else if(IS_SUB_8X4(sub_mb_type)){

                            mv_cache[ 1 ][0]= mx;

                            mv_cache[ 1 ][1]= my;

                        }else if(IS_SUB_4X8(sub_mb_type)){

                            mv_cache[ 8 ][0]= mx;

                            mv_cache[ 8 ][1]= my;

                        }

                        mv_cache[ 0 ][0]= mx;

                        mv_cache[ 0 ][1]= my;

                    }

                }else{

                    uint32_t *p= (uint32_t *)&sl->mv_cache[list][ scan8[4*i] ][0];

                    p[0] = p[1]=

                    p[8] = p[9]= 0;

                }

            }

        }

    }else if(IS_DIRECT(mb_type)){

        ff_h264_pred_direct_motion(h, sl, &mb_type);

        dct8x8_allowed &= h->ps.sps->direct_8x8_inference_flag;

    }else{

        int list, mx, my, i;

         //FIXME we should set ref_idx_l? to 0 if we use that later ...

        if(IS_16X16(mb_type)){

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

                    unsigned int val;

                    if(IS_DIR(mb_type, 0, list)){

                        unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);

                        if (rc == 1) {

                            val= 0;

                        } else if (rc == 2) {

                            val= get_bits1(&sl->gb)^1;

                        }else{

                            val= get_ue_golomb_31(&sl->gb);

                            if (val >= rc) {

                                av_log(h->avctx, AV_LOG_ERROR, "ref %u overflow\n", val);

                                return -1;

                            }

                        }

                    fill_rectangle(&sl->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);

                    }

            }

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

                if(IS_DIR(mb_type, 0, list)){

                    pred_motion(h, sl, 0, 4, list, sl->ref_cache[list][ scan8[0] ], &mx, &my);

                    mx += get_se_golomb(&sl->gb);

                    my += get_se_golomb(&sl->gb);

                    ff_tlog(h->avctx, "final mv:%d %d\n", mx, my);

                    fill_rectangle(sl->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);

                }

            }

        }

        else if(IS_16X8(mb_type)){

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

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

                        unsigned int val;

                        if(IS_DIR(mb_type, i, list)){

                            unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);

                            if (rc == 1) {

                                val= 0;

                            } else if (rc == 2) {

                                val= get_bits1(&sl->gb)^1;

                            }else{

                                val= get_ue_golomb_31(&sl->gb);

                                if (val >= rc) {

                                    av_log(h->avctx, AV_LOG_ERROR, "ref %u overflow\n", val);

                                    return -1;

                                }

                            }

                        }else

                            val= LIST_NOT_USED&0xFF;

                        fill_rectangle(&sl->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);

                    }

            }

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

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

                    unsigned int val;

                    if(IS_DIR(mb_type, i, list)){

                        pred_16x8_motion(h, sl, 8*i, list, sl->ref_cache[list][scan8[0] + 16*i], &mx, &my);

                        mx += get_se_golomb(&sl->gb);

                        my += get_se_golomb(&sl->gb);

                        ff_tlog(h->avctx, "final mv:%d %d\n", mx, my);

                        val= pack16to32(mx,my);

                    }else

                        val=0;

                    fill_rectangle(sl->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 4);

                }

            }

        }else{

            av_assert2(IS_8X16(mb_type));

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

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

                        unsigned int val;

                        if(IS_DIR(mb_type, i, list)){ //FIXME optimize

                            unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);

                            if (rc == 1) {

                                val= 0;

                            } else if (rc == 2) {

                                val= get_bits1(&sl->gb)^1;

                            }else{

                                val= get_ue_golomb_31(&sl->gb);

                                if (val >= rc) {

                                    av_log(h->avctx, AV_LOG_ERROR, "ref %u overflow\n", val);

                                    return -1;

                                }

                            }

                        }else

                            val= LIST_NOT_USED&0xFF;

                        fill_rectangle(&sl->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);

                    }

            }

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

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

                    unsigned int val;

                    if(IS_DIR(mb_type, i, list)){

                        pred_8x16_motion(h, sl, i*4, list, sl->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);

                        mx += get_se_golomb(&sl->gb);

                        my += get_se_golomb(&sl->gb);

                        ff_tlog(h->avctx, "final mv:%d %d\n", mx, my);

                        val= pack16to32(mx,my);

                    }else

                        val=0;

                    fill_rectangle(sl->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 4);

                }

            }

        }

    }

    if(IS_INTER(mb_type))

        write_back_motion(h, sl, mb_type);

    if(!IS_INTRA16x16(mb_type)){

        cbp= get_ue_golomb(&sl->gb);

        if(decode_chroma){

            if(cbp > 47){

                av_log(h->avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, sl->mb_x, sl->mb_y);

                return -1;

            }

            if (IS_INTRA4x4(mb_type))

                cbp = ff_h264_golomb_to_intra4x4_cbp[cbp];

            else

                cbp = ff_h264_golomb_to_inter_cbp[cbp];

        }else{

            if(cbp > 15){

                av_log(h->avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, sl->mb_x, sl->mb_y);

                return -1;

            }

            if(IS_INTRA4x4(mb_type)) cbp= golomb_to_intra4x4_cbp_gray[cbp];

            else                     cbp= golomb_to_inter_cbp_gray[cbp];

        }

    } else {

        if (!decode_chroma && cbp>15) {

            av_log(h->avctx, AV_LOG_ERROR, "gray chroma\n");

            return AVERROR_INVALIDDATA;

        }

    }

    if(dct8x8_allowed && (cbp&15) && !IS_INTRA(mb_type)){

        mb_type |= MB_TYPE_8x8DCT*get_bits1(&sl->gb);

    }

    sl->cbp=

    h->cbp_table[mb_xy]= cbp;

    h->cur_pic.mb_type[mb_xy] = mb_type;

    if(cbp || IS_INTRA16x16(mb_type)){

        int i4x4, i8x8, chroma_idx;

        int dquant;

        int ret;

        GetBitContext *gb = &sl->gb;

        const uint8_t *scan, *scan8x8;

        const int max_qp = 51 + 6 * (h->ps.sps->bit_depth_luma - 8);

        if(IS_INTERLACED(mb_type)){

            scan8x8 = sl->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0;

            scan    = sl->qscale ? h->field_scan : h->field_scan_q0;

        }else{

            scan8x8 = sl->qscale ? h->zigzag_scan8x8_cavlc : h->zigzag_scan8x8_cavlc_q0;

            scan    = sl->qscale ? h->zigzag_scan : h->zigzag_scan_q0;

        }

        dquant= get_se_golomb(&sl->gb);

        sl->qscale += dquant;

        if (((unsigned)sl->qscale) > max_qp){

            if (sl->qscale < 0) sl->qscale += max_qp + 1;

            else                sl->qscale -= max_qp+1;

            if (((unsigned)sl->qscale) > max_qp){

                av_log(h->avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, sl->mb_x, sl->mb_y);

                return -1;

            }

        }

        sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, sl->qscale);

        sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, sl->qscale);

        if ((ret = decode_luma_residual(h, sl, gb, scan, scan8x8, pixel_shift, mb_type, cbp, 0)) < 0 ) {

            return -1;

        }

        h->cbp_table[mb_xy] |= ret << 12;

        if (CHROMA444(h)) {

            if (decode_luma_residual(h, sl, gb, scan, scan8x8, pixel_shift, mb_type, cbp, 1) < 0 ) {

                return -1;

            }

            if (decode_luma_residual(h, sl, gb, scan, scan8x8, pixel_shift, mb_type, cbp, 2) < 0 ) {

                return -1;

            }

        } else {

            const int num_c8x8 = h->ps.sps->chroma_format_idc;

            if(cbp&0x30){

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

                    if (decode_residual(h, sl, gb, sl->mb + ((256 + 16*16*chroma_idx) << pixel_shift),

                                        CHROMA_DC_BLOCK_INDEX + chroma_idx,

                                        CHROMA422(h) ? ff_h264_chroma422_dc_scan : ff_h264_chroma_dc_scan,

                                        NULL, 4 * num_c8x8) < 0) {

                        return -1;

                    }

            }

            if(cbp&0x20){

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

                    const uint32_t *qmul = h->ps.pps->dequant4_coeff[chroma_idx+1+(IS_INTRA( mb_type ) ? 0:3)][sl->chroma_qp[chroma_idx]];

                    int16_t *mb = sl->mb + (16*(16 + 16*chroma_idx) << pixel_shift);

                    for (i8x8 = 0; i8x8<num_c8x8; i8x8++) {

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

                            const int index = 16 + 16*chroma_idx + 8*i8x8 + i4x4;

                            if (decode_residual(h, sl, gb, mb, index, scan + 1, qmul, 15) < 0)

                                return -1;

                            mb += 16 << pixel_shift;

                        }

                    }

                }

            }else{

                fill_rectangle(&sl->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);

                fill_rectangle(&sl->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);

            }

        }

    }else{

        fill_rectangle(&sl->non_zero_count_cache[scan8[ 0]], 4, 4, 8, 0, 1);

        fill_rectangle(&sl->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);

        fill_rectangle(&sl->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);

    }

    h->cur_pic.qscale_table[mb_xy] = sl->qscale;

    write_back_non_zero_count(h, sl);

    return 0;

}


static void client_close(NBDClient *client)

{

    if (client->closing) {

        return;

    }

    client->closing = true;

    /* Force requests to finish.  They will drop their own references,

     * then we'll close the socket and free the NBDClient.

     */

    qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,

                         NULL);

    /* Also tell the client, so that they release their reference.  */

    if (client->close) {

        client->close(client);

    }

}


static int init_tile(Jpeg2000DecoderContext *s, int tileno)

{

    int compno;

    int tilex = tileno % s->numXtiles;

    int tiley = tileno / s->numXtiles;

    Jpeg2000Tile *tile = s->tile + tileno;

    if (!tile->comp)

        return AVERROR(ENOMEM);

    tile->coord[0][0] = FFMAX(tilex       * s->tile_width  + s->tile_offset_x, s->image_offset_x);

    tile->coord[0][1] = FFMIN((tilex + 1) * s->tile_width  + s->tile_offset_x, s->width);

    tile->coord[1][0] = FFMAX(tiley       * s->tile_height + s->tile_offset_y, s->image_offset_y);

    tile->coord[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height);

    for (compno = 0; compno < s->ncomponents; compno++) {

        Jpeg2000Component *comp = tile->comp + compno;

        Jpeg2000CodingStyle *codsty = tile->codsty + compno;

        Jpeg2000QuantStyle  *qntsty = tile->qntsty + compno;

        int ret; // global bandno

        comp->coord_o[0][0] = tile->coord[0][0];

        comp->coord_o[0][1] = tile->coord[0][1];

        comp->coord_o[1][0] = tile->coord[1][0];

        comp->coord_o[1][1] = tile->coord[1][1];

        if (compno) {

            comp->coord_o[0][0] /= s->cdx[compno];

            comp->coord_o[0][1] /= s->cdx[compno];

            comp->coord_o[1][0] /= s->cdy[compno];

            comp->coord_o[1][1] /= s->cdy[compno];

        }

        comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);

        comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);

        comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);

        comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);

        if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,

                                             s->cbps[compno], s->cdx[compno],

                                             s->cdy[compno], s->avctx))

            return ret;

    }

    return 0;

}


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

                                ptrdiff_t stride)

{

    avc_luma_hv_qrt_and_aver_dst_8x8_msa(src - 2,

                                         src - (stride * 2),

                                         stride, dst, stride);

}


int ff_h264_decode_picture_parameter_set(GetBitContext *gb, AVCodecContext *avctx,

                                         H264ParamSets *ps, int bit_length)

{

    AVBufferRef *pps_buf;

    const SPS *sps;

    unsigned int pps_id = get_ue_golomb(gb);

    PPS *pps;

    int qp_bd_offset;

    int bits_left;

    int ret;

    if (pps_id >= MAX_PPS_COUNT) {

        av_log(avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);

        return AVERROR_INVALIDDATA;

    pps_buf = av_buffer_allocz(sizeof(*pps));

    if (!pps_buf)

        return AVERROR(ENOMEM);

    pps = (PPS*)pps_buf->data;

    pps->data_size = gb->buffer_end - gb->buffer;

    if (pps->data_size > sizeof(pps->data)) {

        av_log(avctx, AV_LOG_WARNING, "Truncating likely oversized PPS "

               "(%"SIZE_SPECIFIER" > %"SIZE_SPECIFIER")\n",

               pps->data_size, sizeof(pps->data));

        pps->data_size = sizeof(pps->data);

    memcpy(pps->data, gb->buffer, pps->data_size);

    pps->sps_id = get_ue_golomb_31(gb);

    if ((unsigned)pps->sps_id >= MAX_SPS_COUNT ||

        !ps->sps_list[pps->sps_id]) {

        av_log(avctx, AV_LOG_ERROR, "sps_id %u out of range\n", pps->sps_id);

    sps = (const SPS*)ps->sps_list[pps->sps_id]->data;

    if (sps->bit_depth_luma > 14) {

        av_log(avctx, AV_LOG_ERROR,

               "Invalid luma bit depth=%d\n",

               sps->bit_depth_luma);

    } else if (sps->bit_depth_luma == 11 || sps->bit_depth_luma == 13) {

        av_log(avctx, AV_LOG_ERROR,

               "Unimplemented luma bit depth=%d\n",

               sps->bit_depth_luma);

        ret = AVERROR_PATCHWELCOME;

    pps->cabac             = get_bits1(gb);

    pps->pic_order_present = get_bits1(gb);

    pps->slice_group_count = get_ue_golomb(gb) + 1;

    if (pps->slice_group_count > 1) {

        pps->mb_slice_group_map_type = get_ue_golomb(gb);

        av_log(avctx, AV_LOG_ERROR, "FMO not supported\n");

        switch (pps->mb_slice_group_map_type) {

        case 0:

#if 0

    |       for (i = 0; i <= num_slice_groups_minus1; i++)  |   |      |

    |           run_length[i]                               |1  |ue(v) |

#endif

            break;

        case 2:

#if 0

    |       for (i = 0; i < num_slice_groups_minus1; i++) { |   |      |

    |           top_left_mb[i]                              |1  |ue(v) |

    |           bottom_right_mb[i]                          |1  |ue(v) |

    |       }                                               |   |      |

#endif

            break;

        case 3:

        case 4:

        case 5:

#if 0

    |       slice_group_change_direction_flag               |1  |u(1)  |

    |       slice_group_change_rate_minus1                  |1  |ue(v) |

#endif

            break;

        case 6:

#if 0

    |       slice_group_id_cnt_minus1                       |1  |ue(v) |

    |       for (i = 0; i <= slice_group_id_cnt_minus1; i++)|   |      |

    |           slice_group_id[i]                           |1  |u(v)  |

#endif

            break;

    pps->ref_count[0] = get_ue_golomb(gb) + 1;

    pps->ref_count[1] = get_ue_golomb(gb) + 1;

    if (pps->ref_count[0] - 1 > 32 - 1 || pps->ref_count[1] - 1 > 32 - 1) {

        av_log(avctx, AV_LOG_ERROR, "reference overflow (pps)\n");

    qp_bd_offset = 6 * (sps->bit_depth_luma - 8);

    pps->weighted_pred                        = get_bits1(gb);

    pps->weighted_bipred_idc                  = get_bits(gb, 2);

    pps->init_qp                              = get_se_golomb(gb) + 26 + qp_bd_offset;

    pps->init_qs                              = get_se_golomb(gb) + 26 + qp_bd_offset;

    pps->chroma_qp_index_offset[0]            = get_se_golomb(gb);

    if (pps->chroma_qp_index_offset[0] < -12 || pps->chroma_qp_index_offset[0] > 12) {

    pps->deblocking_filter_parameters_present = get_bits1(gb);

    pps->constrained_intra_pred               = get_bits1(gb);

    pps->redundant_pic_cnt_present            = get_bits1(gb);

    pps->transform_8x8_mode = 0;

    memcpy(pps->scaling_matrix4, sps->scaling_matrix4,

           sizeof(pps->scaling_matrix4));

    memcpy(pps->scaling_matrix8, sps->scaling_matrix8,

           sizeof(pps->scaling_matrix8));

    bits_left = bit_length - get_bits_count(gb);

    if (bits_left > 0 && more_rbsp_data_in_pps(sps, avctx)) {

        pps->transform_8x8_mode = get_bits1(gb);

        decode_scaling_matrices(gb, sps, pps, 0,

                                pps->scaling_matrix4, pps->scaling_matrix8);

        // second_chroma_qp_index_offset

        pps->chroma_qp_index_offset[1] = get_se_golomb(gb);

    } else {

        pps->chroma_qp_index_offset[1] = pps->chroma_qp_index_offset[0];

    build_qp_table(pps, 0, pps->chroma_qp_index_offset[0],

                   sps->bit_depth_luma);

    build_qp_table(pps, 1, pps->chroma_qp_index_offset[1],

                   sps->bit_depth_luma);

    init_dequant_tables(pps, sps);

    if (pps->chroma_qp_index_offset[0] != pps->chroma_qp_index_offset[1])

        pps->chroma_qp_diff = 1;

    if (avctx->debug & FF_DEBUG_PICT_INFO) {

        av_log(avctx, AV_LOG_DEBUG,

               "pps:%u sps:%u %s slice_groups:%d ref:%u/%u %s qp:%d/%d/%d/%d %s %s %s %s\n",

               pps_id, pps->sps_id,

               pps->cabac ? "CABAC" : "CAVLC",

               pps->slice_group_count,

               pps->ref_count[0], pps->ref_count[1],

               pps->weighted_pred ? "weighted" : "",

               pps->init_qp, pps->init_qs, pps->chroma_qp_index_offset[0], pps->chroma_qp_index_offset[1],

               pps->deblocking_filter_parameters_present ? "LPAR" : "",

               pps->constrained_intra_pred ? "CONSTR" : "",

               pps->redundant_pic_cnt_present ? "REDU" : "",

               pps->transform_8x8_mode ? "8x8DCT" : "");

    remove_pps(ps, pps_id);

    ps->pps_list[pps_id] = pps_buf;

    return 0;

fail:

    av_buffer_unref(&pps_buf);

    return ret;


static int vmdk_read(BlockDriverState *bs, int64_t sector_num,

                    uint8_t *buf, int nb_sectors)

{

    BDRVVmdkState *s = bs->opaque;

    int index_in_cluster, n, ret;

    uint64_t cluster_offset;

    while (nb_sectors > 0) {

        cluster_offset = get_cluster_offset(bs, sector_num << 9, 0);

        index_in_cluster = sector_num % s->cluster_sectors;

        n = s->cluster_sectors - index_in_cluster;

        if (n > nb_sectors)

            n = nb_sectors;

        if (!cluster_offset) {

            // try to read from parent image, if exist

            if (s->hd->backing_hd) {

                if (!vmdk_is_cid_valid(bs))

                    return -1;

                ret = bdrv_read(s->hd->backing_hd, sector_num, buf, n);

                if (ret < 0)

                    return -1;

            } else {

                memset(buf, 0, 512 * n);

            }

        } else {

            if(bdrv_pread(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512) != n * 512)

                return -1;

        }

        nb_sectors -= n;

        sector_num += n;

        buf += n * 512;

    }

    return 0;

}


int32_t ff_mlp_pack_output(int32_t lossless_check_data,

                           uint16_t blockpos,

                           int32_t (*sample_buffer)[MAX_CHANNELS],

                           void *data,

                           uint8_t *ch_assign,

                           int8_t *output_shift,

                           uint8_t max_matrix_channel,

                           int is32)

{

    unsigned int i, out_ch = 0;

    int32_t *data_32 = data;

    int16_t *data_16 = data;

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

        for (out_ch = 0; out_ch <= max_matrix_channel; out_ch++) {

            int mat_ch = ch_assign[out_ch];

            int32_t sample = sample_buffer[i][mat_ch]

                          << output_shift[mat_ch];

            lossless_check_data ^= (sample & 0xffffff) << mat_ch;

            if (is32)

                *data_32++ = sample << 8;

            else

                *data_16++ = sample >> 8;

        }

    }

    return lossless_check_data;

}


static void an5206_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    M68kCPU *cpu;

    CPUM68KState *env;

    int kernel_size;

    uint64_t elf_entry;

    hwaddr entry;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *sram = g_new(MemoryRegion, 1);

    if (!cpu_model) {

        cpu_model = "m5206";

    }

    cpu = M68K_CPU(cpu_generic_init(TYPE_M68K_CPU, cpu_model));

    if (!cpu) {

        error_report("Unable to find m68k CPU definition");

        exit(1);

    }

    env = &cpu->env;

    /* Initialize CPU registers.  */

    env->vbr = 0;

    /* TODO: allow changing MBAR and RAMBAR.  */

    env->mbar = AN5206_MBAR_ADDR | 1;

    env->rambar0 = AN5206_RAMBAR_ADDR | 1;

    /* DRAM at address zero */

    memory_region_allocate_system_memory(ram, NULL, "an5206.ram", ram_size);

    memory_region_add_subregion(address_space_mem, 0, ram);

    /* Internal SRAM.  */

    memory_region_init_ram(sram, NULL, "an5206.sram", 512, &error_fatal);

    memory_region_add_subregion(address_space_mem, AN5206_RAMBAR_ADDR, sram);

    mcf5206_init(address_space_mem, AN5206_MBAR_ADDR, cpu);

    /* Load kernel.  */

    if (!kernel_filename) {

        if (qtest_enabled()) {

            return;

        }

        fprintf(stderr, "Kernel image must be specified\n");

        exit(1);

    }

    kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,

                           NULL, NULL, 1, EM_68K, 0, 0);

    entry = elf_entry;

    if (kernel_size < 0) {

        kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL,

                                  NULL, NULL);

    }

    if (kernel_size < 0) {

        kernel_size = load_image_targphys(kernel_filename, KERNEL_LOAD_ADDR,

                                          ram_size - KERNEL_LOAD_ADDR);

        entry = KERNEL_LOAD_ADDR;

    }

    if (kernel_size < 0) {

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

        exit(1);

    }

    env->pc = entry;

}


static int mv_read_header(AVFormatContext *avctx)

{

    MvContext *mv = avctx->priv_data;

    AVIOContext *pb = avctx->pb;

    AVStream *ast = NULL, *vst = NULL; //initialization to suppress warning

    int version, i;

    avio_skip(pb, 4);

    version = avio_rb16(pb);

    if (version == 2) {

        uint64_t timestamp;

        int v;

        avio_skip(pb, 22);

        /* allocate audio track first to prevent unnecessary seeking

           (audio packet always precede video packet for a given frame) */

        ast = avformat_new_stream(avctx, NULL);

        if (!ast)

            return AVERROR(ENOMEM);

        vst = avformat_new_stream(avctx, NULL);

        if (!vst)

            return AVERROR(ENOMEM);

        vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        vst->time_base = (AVRational){1, 15};

        vst->nb_frames = avio_rb32(pb);

        v = avio_rb32(pb);

        switch (v) {

        case 1:

            vst->codec->codec_id = AV_CODEC_ID_MVC1;

            break;

        case 2:

            vst->codec->pix_fmt  = AV_PIX_FMT_ARGB;

            vst->codec->codec_id = AV_CODEC_ID_RAWVIDEO;

            break;

        default:

            av_log_ask_for_sample(avctx, "unknown video compression %i\n", v);

            break;

        }

        vst->codec->codec_tag = 0;

        vst->codec->width     = avio_rb32(pb);

        vst->codec->height    = avio_rb32(pb);

        avio_skip(pb, 12);

        ast->codec->codec_type     = AVMEDIA_TYPE_AUDIO;

        ast->nb_frames             = vst->nb_frames;

        ast->codec->sample_rate    = avio_rb32(pb);

        avpriv_set_pts_info(ast, 33, 1, ast->codec->sample_rate);

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

        ast->codec->channel_layout = (ast->codec->channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;

        v = avio_rb32(pb);

        if (v == AUDIO_FORMAT_SIGNED) {

            ast->codec->codec_id = AV_CODEC_ID_PCM_S16BE;

        } else {

            av_log_ask_for_sample(avctx, "unknown audio compression (format %i)\n", v);

        }

        avio_skip(pb, 12);

        var_read_metadata(avctx, "title", 0x80);

        var_read_metadata(avctx, "comment", 0x100);

        avio_skip(pb, 0x80);

        timestamp = 0;

        for (i = 0; i < vst->nb_frames; i++) {

            uint32_t pos   = avio_rb32(pb);

            uint32_t asize = avio_rb32(pb);

            uint32_t vsize = avio_rb32(pb);

            avio_skip(pb, 8);

            av_add_index_entry(ast, pos,         timestamp, asize, 0, AVINDEX_KEYFRAME);

            av_add_index_entry(vst, pos + asize, i,         vsize, 0, AVINDEX_KEYFRAME);

            timestamp += asize / (ast->codec->channels * 2);

        }

    } else if (!version && avio_rb16(pb) == 3) {

        avio_skip(pb, 4);

        read_table(avctx, NULL, parse_global_var);

        if (mv->nb_audio_tracks > 1) {

            av_log_ask_for_sample(avctx, "multiple audio streams\n");

            return AVERROR_PATCHWELCOME;

        } else if (mv->nb_audio_tracks) {

            ast = avformat_new_stream(avctx, NULL);

            if (!ast)

                return AVERROR(ENOMEM);

            ast->codec->codec_type = AVMEDIA_TYPE_AUDIO;

            /* temporarily store compression value in codec_tag; format value in codec_id */

            read_table(avctx, ast, parse_audio_var);

            if (ast->codec->codec_tag == 100 && ast->codec->codec_id == AUDIO_FORMAT_SIGNED && ast->codec->bits_per_coded_sample == 16) {

                ast->codec->codec_id = AV_CODEC_ID_PCM_S16BE;

            } else {

                av_log_ask_for_sample(avctx, "unknown audio compression %i (format %i, width %i)\n",

                    ast->codec->codec_tag, ast->codec->codec_id, ast->codec->bits_per_coded_sample);

                ast->codec->codec_id = AV_CODEC_ID_NONE;

            }

            ast->codec->codec_tag = 0;

        }

        if (mv->nb_video_tracks > 1) {

            av_log_ask_for_sample(avctx, "multiple video streams\n");

            return AVERROR_PATCHWELCOME;

        } else if (mv->nb_video_tracks) {

            vst = avformat_new_stream(avctx, NULL);

            if (!vst)

                return AVERROR(ENOMEM);

            vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

            read_table(avctx, vst, parse_video_var);

        }

        if (mv->nb_audio_tracks)

            read_index(pb, ast);

        if (mv->nb_video_tracks)

            read_index(pb, vst);

    } else {

        av_log_ask_for_sample(avctx, "unknown version %i\n", version);

        return AVERROR_PATCHWELCOME;

    }

    return 0;

}


void qsb_free(QEMUSizedBuffer *qsb)

{

    size_t i;

    if (!qsb) {

        return;

    }

    for (i = 0; i < qsb->n_iov; i++) {

        g_free(qsb->iov[i].iov_base);

    }

    g_free(qsb->iov);

    g_free(qsb);

}


static int decode_frame(AVCodecContext * avctx,

                        void *data, int *data_size,

                        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MPADecodeContext *s = avctx->priv_data;

    uint32_t header;

    int out_size;

    OUT_INT *out_samples = data;

    if(buf_size < HEADER_SIZE)

        return -1;

    header = AV_RB32(buf);

    if(ff_mpa_check_header(header) < 0){

        av_log(avctx, AV_LOG_ERROR, "Header missing\n");

        return -1;

    }

    if (ff_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {

        /* free format: prepare to compute frame size */

        s->frame_size = -1;

        return -1;

    }

    /* update codec info */

    avctx->channels = s->nb_channels;

    avctx->bit_rate = s->bit_rate;

    avctx->sub_id = s->layer;

    if(*data_size < 1152*avctx->channels*sizeof(OUT_INT))

        return -1;

    if(s->frame_size<=0 || s->frame_size > buf_size){

        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");

        return -1;

    }else if(s->frame_size < buf_size){

        av_log(avctx, AV_LOG_ERROR, "incorrect frame size\n");

        buf_size= s->frame_size;

    }

    out_size = mp_decode_frame(s, out_samples, buf, buf_size);

    if(out_size>=0){

        *data_size = out_size;

        avctx->sample_rate = s->sample_rate;

        //FIXME maybe move the other codec info stuff from above here too

    }else

        av_log(avctx, AV_LOG_DEBUG, "Error while decoding MPEG audio frame.\n"); //FIXME return -1 / but also return the number of bytes consumed

    s->frame_size = 0;

    return buf_size;

}


static struct omap_32khz_timer_s *omap_os_timer_init(MemoryRegion *memory,

                hwaddr base,

                qemu_irq irq, omap_clk clk)

{

    struct omap_32khz_timer_s *s = (struct omap_32khz_timer_s *)

            g_malloc0(sizeof(struct omap_32khz_timer_s));

    s->timer.irq = irq;

    s->timer.clk = clk;

    s->timer.timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, omap_timer_tick, &s->timer);

    omap_os_timer_reset(s);

    omap_timer_clk_setup(&s->timer);

    memory_region_init_io(&s->iomem, NULL, &omap_os_timer_ops, s,

                          "omap-os-timer", 0x800);

    memory_region_add_subregion(memory, base, &s->iomem);

    return s;

}


static bool check_irqchip_in_kernel(void)

{

    if (kvm_irqchip_in_kernel()) {

        return true;

    }

    error_report("pci-assign: error: requires KVM with in-kernel irqchip "

                 "enabled");

    return false;

}


static double get_qscale(MpegEncContext *s, RateControlEntry *rce, double rate_factor, int frame_num){

    RateControlContext *rcc= &s->rc_context;

    AVCodecContext *a= s->avctx;

    double q, bits;

    const int pict_type= rce->new_pict_type;

    const double mb_num= s->mb_num;

    int i;

    double const_values[]={

        M_PI,

        M_E,

        rce->i_tex_bits*rce->qscale,

        rce->p_tex_bits*rce->qscale,

        (rce->i_tex_bits + rce->p_tex_bits)*(double)rce->qscale,

        rce->mv_bits/mb_num,

        rce->pict_type == B_TYPE ? (rce->f_code + rce->b_code)*0.5 : rce->f_code,

        rce->i_count/mb_num,

        rce->mc_mb_var_sum/mb_num,

        rce->mb_var_sum/mb_num,

        rce->pict_type == I_TYPE,

        rce->pict_type == P_TYPE,

        rce->pict_type == B_TYPE,

        rcc->qscale_sum[pict_type] / (double)rcc->frame_count[pict_type],

        a->qcompress,

/*        rcc->last_qscale_for[I_TYPE],

        rcc->last_qscale_for[P_TYPE],

        rcc->last_qscale_for[B_TYPE],

        rcc->next_non_b_qscale,*/

        rcc->i_cplx_sum[I_TYPE] / (double)rcc->frame_count[I_TYPE],

        rcc->i_cplx_sum[P_TYPE] / (double)rcc->frame_count[P_TYPE],

        rcc->p_cplx_sum[P_TYPE] / (double)rcc->frame_count[P_TYPE],

        rcc->p_cplx_sum[B_TYPE] / (double)rcc->frame_count[B_TYPE],

        (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / (double)rcc->frame_count[pict_type],

        0

    };

    bits= ff_parse_eval(rcc->rc_eq_eval, const_values, rce);

    if (isnan(bits)) {

        av_log(s->avctx, AV_LOG_ERROR, "Error evaluating rc_eq \"%s\"\n", s->avctx->rc_eq);

        return -1;

    }

    rcc->pass1_rc_eq_output_sum+= bits;

    bits*=rate_factor;

    if(bits<0.0) bits=0.0;

    bits+= 1.0; //avoid 1/0 issues

    /* user override */

    for(i=0; i<s->avctx->rc_override_count; i++){

        RcOverride *rco= s->avctx->rc_override;

        if(rco[i].start_frame > frame_num) continue;

        if(rco[i].end_frame   < frame_num) continue;

        if(rco[i].qscale)

            bits= qp2bits(rce, rco[i].qscale); //FIXME move at end to really force it?

        else

            bits*= rco[i].quality_factor;

    }

    q= bits2qp(rce, bits);

    /* I/B difference */

    if     (pict_type==I_TYPE && s->avctx->i_quant_factor<0.0)

        q= -q*s->avctx->i_quant_factor + s->avctx->i_quant_offset;

    else if(pict_type==B_TYPE && s->avctx->b_quant_factor<0.0)

        q= -q*s->avctx->b_quant_factor + s->avctx->b_quant_offset;

    return q;

}


static int hpet_start_timer(struct qemu_alarm_timer *t)

{

    struct hpet_info info;

    int r, fd;

    fd = open("/dev/hpet", O_RDONLY);

    if (fd < 0)

        return -1;

    /* Set frequency */

    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);

    if (r < 0) {

        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"

                "error, but for better emulation accuracy type:\n"

                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");

        goto fail;

    }

    /* Check capabilities */

    r = ioctl(fd, HPET_INFO, &info);

    if (r < 0)

        goto fail;

    /* Enable periodic mode */

    r = ioctl(fd, HPET_EPI, 0);

    if (info.hi_flags && (r < 0))

        goto fail;

    /* Enable interrupt */

    r = ioctl(fd, HPET_IE_ON, 0);

    if (r < 0)

        goto fail;

    enable_sigio_timer(fd);

    t->priv = (void *)(long)fd;

    return 0;

fail:

    close(fd);

    return -1;

}


static void cmd_read_cd(IDEState *s, uint8_t* buf)

{

    int nb_sectors, lba, transfer_request;

    nb_sectors = (buf[6] << 16) | (buf[7] << 8) | buf[8];

    lba = ube32_to_cpu(buf + 2);

    if (nb_sectors == 0) {

        ide_atapi_cmd_ok(s);

        return;

    }

    transfer_request = buf[9];

    switch(transfer_request & 0xf8) {

    case 0x00:

        /* nothing */

        ide_atapi_cmd_ok(s);

        break;

    case 0x10:

        /* normal read */

        ide_atapi_cmd_read(s, lba, nb_sectors, 2048);

        break;

    case 0xf8:

        /* read all data */

        ide_atapi_cmd_read(s, lba, nb_sectors, 2352);

        break;

    default:

        ide_atapi_cmd_error(s, ILLEGAL_REQUEST,

                            ASC_INV_FIELD_IN_CMD_PACKET);

        break;

    }

}


static const char *srt_to_ass(AVCodecContext *avctx, char *out, char *out_end,

                              const char *in, int x1, int y1, int x2, int y2)

{

    char c, *param, buffer[128], tmp[128];

    int len, tag_close, sptr = 1, line_start = 1, an = 0, end = 0;

    SrtStack stack[16];

    stack[0].tag[0] = 0;

    strcpy(stack[0].param[PARAM_SIZE],  "{\\fs}");

    strcpy(stack[0].param[PARAM_COLOR], "{\\c}");

    strcpy(stack[0].param[PARAM_FACE],  "{\\fn}");

    if (x1 >= 0 && y1 >= 0) {

        if (x2 >= 0 && y2 >= 0 && (x2 != x1 || y2 != y1))

            out += snprintf(out, out_end-out,

                            "{\\an1}{\\move(%d,%d,%d,%d)}", x1, y1, x2, y2);

        else

            out += snprintf(out, out_end-out, "{\\an1}{\\pos(%d,%d)}", x1, y1);

    }

    for (; out < out_end && !end && *in; in++) {

        switch (*in) {

        case '\r':

            break;

        case '\n':

            if (line_start) {

                end = 1;

                break;

            }

            while (out[-1] == ' ')

                out--;

            out += snprintf(out, out_end-out, "\\N");

            line_start = 1;

            break;

        case ' ':

            if (!line_start)

                *out++ = *in;

            break;

        case '{':    /* skip all {\xxx} substrings except for {\an%d}

                        and all microdvd like styles such as {Y:xxx} */

            an += sscanf(in, "{\\an%*1u}%c", &c) == 1;

            if ((an != 1 && sscanf(in, "{\\%*[^}]}%n%c", &len, &c) > 0) ||

                sscanf(in, "{%*1[CcFfoPSsYy]:%*[^}]}%n%c", &len, &c) > 0) {

                in += len - 1;

            } else

                *out++ = *in;

            break;

        case '<':

            tag_close = in[1] == '/';

            if (sscanf(in+tag_close+1, "%127[^>]>%n%c", buffer, &len,&c) >= 2) {

                if ((param = strchr(buffer, ' ')))

                    *param++ = 0;

                if ((!tag_close && sptr < FF_ARRAY_ELEMS(stack)) ||

                    ( tag_close && sptr > 0 && !strcmp(stack[sptr-1].tag, buffer))) {

                    int i, j, unknown = 0;

                    in += len + tag_close;

                    if (!tag_close)

                        memset(stack+sptr, 0, sizeof(*stack));

                    if (!strcmp(buffer, "font")) {

                        if (tag_close) {

                            for (i=PARAM_NUMBER-1; i>=0; i--)

                                if (stack[sptr-1].param[i][0])

                                    for (j=sptr-2; j>=0; j--)

                                        if (stack[j].param[i][0]) {

                                            out += snprintf(out, out_end-out,

                                                            stack[j].param[i]);

                                            break;

                                        }

                        } else {

                            while (param) {

                                if (!strncmp(param, "size=", 5)) {

                                    unsigned font_size;

                                    param += 5 + (param[5] == '"');

                                    if (sscanf(param, "%u", &font_size) == 1) {

                                        snprintf(stack[sptr].param[PARAM_SIZE],

                                             sizeof(stack[0].param[PARAM_SIZE]),

                                             "{\\fs%u}", font_size);

                                    }

                                } else if (!strncmp(param, "color=", 6)) {

                                    param += 6 + (param[6] == '"');

                                    snprintf(stack[sptr].param[PARAM_COLOR],

                                         sizeof(stack[0].param[PARAM_COLOR]),

                                         "{\\c&H%X&}",

                                         html_color_parse(avctx, param));

                                } else if (!strncmp(param, "face=", 5)) {

                                    param += 5 + (param[5] == '"');

                                    len = strcspn(param,

                                                  param[-1] == '"' ? "\"" :" ");

                                    av_strlcpy(tmp, param,

                                               FFMIN(sizeof(tmp), len+1));

                                    param += len;

                                    snprintf(stack[sptr].param[PARAM_FACE],

                                             sizeof(stack[0].param[PARAM_FACE]),

                                             "{\\fn%s}", tmp);

                                }

                                if ((param = strchr(param, ' ')))

                                    param++;

                            }

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

                                if (stack[sptr].param[i][0])

                                    out += snprintf(out, out_end-out,

                                                    stack[sptr].param[i]);

                        }

                    } else if (!buffer[1] && strspn(buffer, "bisu") == 1) {

                        out += snprintf(out, out_end-out,

                                        "{\\%c%d}", buffer[0], !tag_close);

                    } else {

                        unknown = 1;

                        snprintf(tmp, sizeof(tmp), "</%s>", buffer);

                    }

                    if (tag_close) {

                        sptr--;

                    } else if (unknown && !strstr(in, tmp)) {

                        in -= len + tag_close;

                        *out++ = *in;

                    } else

                        av_strlcpy(stack[sptr++].tag, buffer,

                                   sizeof(stack[0].tag));

                    break;

                }

            }

        default:

            *out++ = *in;

            break;

        }

        if (*in != ' ' && *in != '\r' && *in != '\n')

            line_start = 0;

    }

    out = FFMIN(out, out_end-3);

    while (!strncmp(out-2, "\\N", 2))

        out -= 2;

    while (out[-1] == ' ')

        out--;

    out += snprintf(out, out_end-out, "\r\n");

    return in;

}


void tcg_prologue_init(TCGContext *s)
{
    /* init global prologue and epilogue */
    s->code_buf = s->code_gen_prologue;
    s->code_ptr = s->code_buf;
    tcg_target_qemu_prologue(s);
    flush_icache_range((tcg_target_ulong)s->code_buf,
                       (tcg_target_ulong)s->code_ptr);


static int decode_slice(AVCodecContext *c, void *arg)

{

    FFV1Context *fs = *(void **)arg;

    FFV1Context *f  = fs->avctx->priv_data;

    int width, height, x, y, ret;

    const int ps = (av_pix_fmt_desc_get(c->pix_fmt)->flags & AV_PIX_FMT_FLAG_PLANAR)

                   ? (c->bits_per_raw_sample > 8) + 1

                   : 4;

    AVFrame *const p = f->cur;

    if (f->version > 2) {

        if (decode_slice_header(f, fs) < 0) {

            fs->slice_damaged = 1;

            return AVERROR_INVALIDDATA;

        }

    }

    if ((ret = ffv1_init_slice_state(f, fs)) < 0)

        return ret;

    if (f->cur->key_frame)

        ffv1_clear_slice_state(f, fs);

    width  = fs->slice_width;

    height = fs->slice_height;

    x      = fs->slice_x;

    y      = fs->slice_y;

    if (!fs->ac) {

        if (f->version == 3 && f->minor_version > 1 || f->version > 3)

            get_rac(&fs->c, (uint8_t[]) { 129 });

        fs->ac_byte_count = f->version > 2 || (!x && !y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;

        init_get_bits(&fs->gb, fs->c.bytestream_start + fs->ac_byte_count,

                      (fs->c.bytestream_end - fs->c.bytestream_start -

                       fs->ac_byte_count) * 8);

    }

    av_assert1(width && height);

    if (f->colorspace == 0) {

        const int chroma_width  = -((-width) >> f->chroma_h_shift);

        const int chroma_height = -((-height) >> f->chroma_v_shift);

        const int cx            = x >> f->chroma_h_shift;

        const int cy            = y >> f->chroma_v_shift;

        decode_plane(fs, p->data[0] + ps * x + y * p->linesize[0], width,

                     height, p->linesize[0],

                     0);

        if (f->chroma_planes) {

            decode_plane(fs, p->data[1] + ps * cx + cy * p->linesize[1],

                         chroma_width, chroma_height, p->linesize[1],

                         1);

            decode_plane(fs, p->data[2] + ps * cx + cy * p->linesize[2],

                         chroma_width, chroma_height, p->linesize[2],

                         1);

        }

        if (fs->transparency)

            decode_plane(fs, p->data[3] + ps * x + y * p->linesize[3], width,

                         height, p->linesize[3],

                         2);

    } else {

        uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0],

                               p->data[1] + ps * x + y * p->linesize[1],

                               p->data[2] + ps * x + y * p->linesize[2] };

        decode_rgb_frame(fs, planes, width, height, p->linesize);

    }

    if (fs->ac && f->version > 2) {

        int v;

        get_rac(&fs->c, (uint8_t[]) { 129 });

        v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5 * f->ec;

        if (v) {

            av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n",

                   v);

            fs->slice_damaged = 1;

        }

    }

    emms_c();

    return 0;

}


int text_console_init(QemuOpts *opts, CharDriverState **_chr)

{

    CharDriverState *chr;

    TextConsole *s;

    unsigned width;

    unsigned height;

    chr = g_malloc0(sizeof(CharDriverState));

    if (n_text_consoles == 128) {

        fprintf(stderr, "Too many text consoles\n");

        exit(1);

    }

    text_consoles[n_text_consoles] = chr;

    n_text_consoles++;

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

    if (width == 0)

        width = qemu_opt_get_number(opts, "cols", 0) * FONT_WIDTH;

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

    if (height == 0)

        height = qemu_opt_get_number(opts, "rows", 0) * FONT_HEIGHT;

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

        s = new_console(NULL, TEXT_CONSOLE);

    } else {

        s = new_console(NULL, TEXT_CONSOLE_FIXED_SIZE);

    }

    if (!s) {

        g_free(chr);

        return -EBUSY;

    }

    s->chr = chr;

    s->g_width = width;

    s->g_height = height;

    chr->opaque = s;

    chr->chr_set_echo = text_console_set_echo;

    *_chr = chr;

    return 0;

}


_eth_get_rss_ex_dst_addr(const struct iovec *pkt, int pkt_frags,

                        size_t rthdr_offset,

                        struct ip6_ext_hdr *ext_hdr,

                        struct in6_address *dst_addr)

{

    struct ip6_ext_hdr_routing *rthdr = (struct ip6_ext_hdr_routing *) ext_hdr;

    if ((rthdr->rtype == 2) &&

        (rthdr->len == sizeof(struct in6_address) / 8) &&

        (rthdr->segleft == 1)) {

        size_t input_size = iov_size(pkt, pkt_frags);

        size_t bytes_read;

        if (input_size < rthdr_offset + sizeof(*ext_hdr)) {

            return false;

        }

        bytes_read = iov_to_buf(pkt, pkt_frags,

                                rthdr_offset + sizeof(*ext_hdr),

                                dst_addr, sizeof(*dst_addr));

        return bytes_read == sizeof(dst_addr);

    }

    return false;

}


USBPacket *usb_ep_find_packet_by_id(USBDevice *dev, int pid, int ep,

                                    uint64_t id)

{

    struct USBEndpoint *uep = usb_ep_get(dev, pid, ep);

    USBPacket *p;

    while ((p = QTAILQ_FIRST(&uep->queue)) != NULL) {

        if (p->id == id) {

            return p;

        }

    }

    return NULL;

}


void pci_bridge_exitfn(PCIDevice *pci_dev)

{

    PCIBridge *s = DO_UPCAST(PCIBridge, dev, pci_dev);

    assert(QLIST_EMPTY(&s->sec_bus.child));

    QLIST_REMOVE(&s->sec_bus, sibling);

    pci_bridge_region_cleanup(s);

    memory_region_destroy(&s->address_space_mem);

    memory_region_destroy(&s->address_space_io);

    /* qbus_free() is called automatically by qdev_free() */

}


static void superh_cpu_class_init(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    CPUClass *cc = CPU_CLASS(oc);

    SuperHCPUClass *scc = SUPERH_CPU_CLASS(oc);

    scc->parent_realize = dc->realize;

    dc->realize = superh_cpu_realizefn;

    scc->parent_reset = cc->reset;

    cc->reset = superh_cpu_reset;

    cc->class_by_name = superh_cpu_class_by_name;

    cc->has_work = superh_cpu_has_work;

    cc->do_interrupt = superh_cpu_do_interrupt;

    cc->cpu_exec_interrupt = superh_cpu_exec_interrupt;

    cc->dump_state = superh_cpu_dump_state;

    cc->set_pc = superh_cpu_set_pc;

    cc->synchronize_from_tb = superh_cpu_synchronize_from_tb;

    cc->gdb_read_register = superh_cpu_gdb_read_register;

    cc->gdb_write_register = superh_cpu_gdb_write_register;

#ifdef CONFIG_USER_ONLY

    cc->handle_mmu_fault = superh_cpu_handle_mmu_fault;

#else

    cc->get_phys_page_debug = superh_cpu_get_phys_page_debug;

#endif

    cc->disas_set_info = superh_cpu_disas_set_info;

    cc->gdb_num_core_regs = 59;

    dc->vmsd = &vmstate_sh_cpu;

    /*

     * Reason: superh_cpu_initfn() calls cpu_exec_init(), which saves

     * the object in cpus -> dangling pointer after final

     * object_unref().

     */

    dc->cannot_destroy_with_object_finalize_yet = true;

}


uint64_t HELPER(neon_abdl_u32)(uint32_t a, uint32_t b)

{

    uint64_t tmp;

    uint64_t result;

    DO_ABD(result, a, b, uint16_t);

    DO_ABD(tmp, a >> 16, b >> 16, uint16_t);

    return result | (tmp << 32);

}


void RENAME(swri_noise_shaping)(SwrContext *s, AudioData *dsts, const AudioData *srcs, const AudioData *noises, int count){

    int i, j, pos, ch;

    int taps  = s->dither.ns_taps;

    float S   = s->dither.ns_scale;

    float S_1 = s->dither.ns_scale_1;

    av_assert2((taps&3) != 2);

    av_assert2((taps&3) != 3 || s->dither.ns_coeffs[taps] == 0);

    for (ch=0; ch<srcs->ch_count; ch++) {

        const float *noise = ((const float *)noises->ch[ch]) + s->dither.noise_pos;

        const DELEM *src = (const DELEM*)srcs->ch[ch];

        DELEM *dst = (DELEM*)dsts->ch[ch];

        float *ns_errors = s->dither.ns_errors[ch];

        const float *ns_coeffs = s->dither.ns_coeffs;

        pos  = s->dither.ns_pos;

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

            double d1, d = src[i]*S_1;

            for(j=0; j<taps-2; j+=4) {

                d -= ns_coeffs[j    ] * ns_errors[pos + j    ]

                    +ns_coeffs[j + 1] * ns_errors[pos + j + 1]

                    +ns_coeffs[j + 2] * ns_errors[pos + j + 2]

                    +ns_coeffs[j + 3] * ns_errors[pos + j + 3];

            }

            if(j < taps)

                d -= ns_coeffs[j] * ns_errors[pos + j];

            pos = pos ? pos - 1 : taps - 1;

            d1 = rint(d + noise[i]);

            ns_errors[pos + taps] = ns_errors[pos] = d1 - d;

            d1 *= S;

            CLIP(d1);

            dst[i] = d1;

        }

    }

    s->dither.ns_pos = pos;

}


static int64_t expr_unary(Monitor *mon)

{

    int64_t n;

    char *p;

    int ret;

    switch(*pch) {

    case '+':

        next();

        n = expr_unary(mon);

        break;

    case '-':

        next();

        n = -expr_unary(mon);

        break;

    case '~':

        next();

        n = ~expr_unary(mon);

        break;

    case '(':

        next();

        n = expr_sum(mon);

        if (*pch != ')') {

            expr_error(mon, "')' expected");

        }

        next();

        break;

    case '\'':

        pch++;

        if (*pch == '\0')

            expr_error(mon, "character constant expected");

        n = *pch;

        pch++;

        if (*pch != '\'')

            expr_error(mon, "missing terminating \' character");

        next();

        break;

    case '$':

        {

            char buf[128], *q;

            target_long reg=0;

            pch++;

            q = buf;

            while ((*pch >= 'a' && *pch <= 'z') ||

                   (*pch >= 'A' && *pch <= 'Z') ||

                   (*pch >= '0' && *pch <= '9') ||

                   *pch == '_' || *pch == '.') {

                if ((q - buf) < sizeof(buf) - 1)

                    *q++ = *pch;

                pch++;

            }

            while (qemu_isspace(*pch))

                pch++;

            *q = 0;

            ret = get_monitor_def(&reg, buf);

            if (ret == -1)

                expr_error(mon, "unknown register");

            else if (ret == -2)

                expr_error(mon, "no cpu defined");

            n = reg;

        }

        break;

    case '\0':

        expr_error(mon, "unexpected end of expression");

        n = 0;

        break;

    default:

#if TARGET_PHYS_ADDR_BITS > 32

        n = strtoull(pch, &p, 0);

#else

        n = strtoul(pch, &p, 0);

#endif

        if (pch == p) {

            expr_error(mon, "invalid char in expression");

        }

        pch = p;

        while (qemu_isspace(*pch))

            pch++;

        break;

    }

    return n;

}


static av_cold void uninit(AVFilterContext *ctx)

{

    DynamicAudioNormalizerContext *s = ctx->priv;

    int c;

    av_freep(&s->prev_amplification_factor);

    av_freep(&s->dc_correction_value);

    av_freep(&s->compress_threshold);

    av_freep(&s->fade_factors[0]);

    av_freep(&s->fade_factors[1]);

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

        cqueue_free(s->gain_history_original[c]);

        cqueue_free(s->gain_history_minimum[c]);

        cqueue_free(s->gain_history_smoothed[c]);

    }

    av_freep(&s->gain_history_original);

    av_freep(&s->gain_history_minimum);

    av_freep(&s->gain_history_smoothed);

    av_freep(&s->weights);

    ff_bufqueue_discard_all(&s->queue);

}