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

                            int *got_frame_ptr, AVPacket *avpkt)

{

    AVFrame *frame     = data;

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    int lfe_samples;

    int num_core_channels = 0;

    int i, ret;

    float  **samples_flt;

    DCAContext *s = avctx->priv_data;

    int channels, full_channels;

    int core_ss_end;

    s->xch_present = 0;

    s->dca_buffer_size = ff_dca_convert_bitstream(buf, buf_size, s->dca_buffer,

                                                  DCA_MAX_FRAME_SIZE + DCA_MAX_EXSS_HEADER_SIZE);

    if (s->dca_buffer_size == AVERROR_INVALIDDATA) {

        av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");

        return AVERROR_INVALIDDATA;

    }

    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);

    if ((ret = dca_parse_frame_header(s)) < 0) {

        //seems like the frame is corrupt, try with the next one

        return ret;

    }

    //set AVCodec values with parsed data

    avctx->sample_rate = s->sample_rate;

    avctx->bit_rate    = s->bit_rate;

    s->profile = FF_PROFILE_DTS;

    for (i = 0; i < (s->sample_blocks / 8); i++) {

        if ((ret = dca_decode_block(s, 0, i))) {

            av_log(avctx, AV_LOG_ERROR, "error decoding block\n");

            return ret;

        }

    }

    /* record number of core channels incase less than max channels are requested */

    num_core_channels = s->prim_channels;

    if (s->ext_coding)

        s->core_ext_mask = dca_ext_audio_descr_mask[s->ext_descr];

    else

        s->core_ext_mask = 0;

    core_ss_end = FFMIN(s->frame_size, s->dca_buffer_size) * 8;

    /* only scan for extensions if ext_descr was unknown or indicated a

     * supported XCh extension */

    if (s->core_ext_mask < 0 || s->core_ext_mask & DCA_EXT_XCH) {

        /* if ext_descr was unknown, clear s->core_ext_mask so that the

         * extensions scan can fill it up */

        s->core_ext_mask = FFMAX(s->core_ext_mask, 0);

        /* extensions start at 32-bit boundaries into bitstream */

        skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);

        while (core_ss_end - get_bits_count(&s->gb) >= 32) {

            uint32_t bits = get_bits_long(&s->gb, 32);

            switch (bits) {

            case 0x5a5a5a5a: {

                int ext_amode, xch_fsize;

                s->xch_base_channel = s->prim_channels;

                /* validate sync word using XCHFSIZE field */

                xch_fsize = show_bits(&s->gb, 10);

                if ((s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize) &&

                    (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize + 1))

                    continue;

                /* skip length-to-end-of-frame field for the moment */

                skip_bits(&s->gb, 10);

                s->core_ext_mask |= DCA_EXT_XCH;

                /* extension amode(number of channels in extension) should be 1 */

                /* AFAIK XCh is not used for more channels */

                if ((ext_amode = get_bits(&s->gb, 4)) != 1) {

                    av_log(avctx, AV_LOG_ERROR, "XCh extension amode %d not"

                           " supported!\n", ext_amode);

                    continue;

                }

                /* much like core primary audio coding header */

                dca_parse_audio_coding_header(s, s->xch_base_channel);

                for (i = 0; i < (s->sample_blocks / 8); i++)

                    if ((ret = dca_decode_block(s, s->xch_base_channel, i))) {

                        av_log(avctx, AV_LOG_ERROR, "error decoding XCh extension\n");

                        continue;

                    }

                s->xch_present = 1;

                break;

            }

            case 0x47004a03:

                /* XXCh: extended channels */

                /* usually found either in core or HD part in DTS-HD HRA streams,

                 * but not in DTS-ES which contains XCh extensions instead */

                s->core_ext_mask |= DCA_EXT_XXCH;

                break;

            case 0x1d95f262: {

                int fsize96 = show_bits(&s->gb, 12) + 1;

                if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)

                    continue;

                av_log(avctx, AV_LOG_DEBUG, "X96 extension found at %d bits\n",

                       get_bits_count(&s->gb));

                skip_bits(&s->gb, 12);

                av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", fsize96);

                av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));

                s->core_ext_mask |= DCA_EXT_X96;

                break;

            }

            }

            skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);

        }

    } else {

        /* no supported extensions, skip the rest of the core substream */

        skip_bits_long(&s->gb, core_ss_end - get_bits_count(&s->gb));

    }

    if (s->core_ext_mask & DCA_EXT_X96)

        s->profile = FF_PROFILE_DTS_96_24;

    else if (s->core_ext_mask & (DCA_EXT_XCH | DCA_EXT_XXCH))

        s->profile = FF_PROFILE_DTS_ES;

    /* check for ExSS (HD part) */

    if (s->dca_buffer_size - s->frame_size > 32 &&

        get_bits_long(&s->gb, 32) == DCA_HD_MARKER)

        dca_exss_parse_header(s);

    avctx->profile = s->profile;

    full_channels = channels = s->prim_channels + !!s->lfe;

    if (s->amode < 16) {

        avctx->channel_layout = dca_core_channel_layout[s->amode];

        if (s->prim_channels + !!s->lfe > 2 &&

            avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {

            /*

             * Neither the core's auxiliary data nor our default tables contain

             * downmix coefficients for the additional channel coded in the XCh

             * extension, so when we're doing a Stereo downmix, don't decode it.

             */

            s->xch_disable = 1;

        }

#if FF_API_REQUEST_CHANNELS

FF_DISABLE_DEPRECATION_WARNINGS

        if (s->xch_present && !s->xch_disable &&

            (!avctx->request_channels ||

             avctx->request_channels > num_core_channels + !!s->lfe)) {

FF_ENABLE_DEPRECATION_WARNINGS

#else

        if (s->xch_present && !s->xch_disable) {

#endif

            avctx->channel_layout |= AV_CH_BACK_CENTER;

            if (s->lfe) {

                avctx->channel_layout |= AV_CH_LOW_FREQUENCY;

                s->channel_order_tab = dca_channel_reorder_lfe_xch[s->amode];

            } else {

                s->channel_order_tab = dca_channel_reorder_nolfe_xch[s->amode];

            }

        } else {

            channels = num_core_channels + !!s->lfe;

            s->xch_present = 0; /* disable further xch processing */

            if (s->lfe) {

                avctx->channel_layout |= AV_CH_LOW_FREQUENCY;

                s->channel_order_tab = dca_channel_reorder_lfe[s->amode];

            } else

                s->channel_order_tab = dca_channel_reorder_nolfe[s->amode];

        }

        if (channels > !!s->lfe &&

            s->channel_order_tab[channels - 1 - !!s->lfe] < 0)

            return AVERROR_INVALIDDATA;

        if (s->prim_channels + !!s->lfe > 2 &&

            avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {

            channels = 2;

            s->output = s->prim_channels == 2 ? s->amode : DCA_STEREO;

            avctx->channel_layout = AV_CH_LAYOUT_STEREO;

            /* Stereo downmix coefficients

             *

             * The decoder can only downmix to 2-channel, so we need to ensure

             * embedded downmix coefficients are actually targeting 2-channel.

             */

            if (s->core_downmix && (s->core_downmix_amode == DCA_STEREO ||

                                    s->core_downmix_amode == DCA_STEREO_TOTAL)) {

                int sign, code;

                for (i = 0; i < s->prim_channels + !!s->lfe; i++) {

                    sign = s->core_downmix_codes[i][0] & 0x100 ? 1 : -1;

                    code = s->core_downmix_codes[i][0] & 0x0FF;

                    s->downmix_coef[i][0] = (!code ? 0.0f :

                                             sign * dca_dmixtable[code - 1]);

                    sign = s->core_downmix_codes[i][1] & 0x100 ? 1 : -1;

                    code = s->core_downmix_codes[i][1] & 0x0FF;

                    s->downmix_coef[i][1] = (!code ? 0.0f :

                                             sign * dca_dmixtable[code - 1]);

                }

                s->output = s->core_downmix_amode;

            } else {

                int am = s->amode & DCA_CHANNEL_MASK;

                if (am >= FF_ARRAY_ELEMS(dca_default_coeffs)) {

                    av_log(s->avctx, AV_LOG_ERROR,

                           "Invalid channel mode %d\n", am);

                    return AVERROR_INVALIDDATA;

                }

                if (s->prim_channels + !!s->lfe >

                    FF_ARRAY_ELEMS(dca_default_coeffs[0])) {

                    avpriv_request_sample(s->avctx, "Downmixing %d channels",

                                          s->prim_channels + !!s->lfe);

                    return AVERROR_PATCHWELCOME;

                }

                for (i = 0; i < s->prim_channels + !!s->lfe; i++) {

                    s->downmix_coef[i][0] = dca_default_coeffs[am][i][0];

                    s->downmix_coef[i][1] = dca_default_coeffs[am][i][1];

                }

            }

            av_dlog(s->avctx, "Stereo downmix coeffs:\n");

            for (i = 0; i < s->prim_channels + !!s->lfe; i++) {

                av_dlog(s->avctx, "L, input channel %d = %f\n", i,

                        s->downmix_coef[i][0]);

                av_dlog(s->avctx, "R, input channel %d = %f\n", i,

                        s->downmix_coef[i][1]);

            }

            av_dlog(s->avctx, "\n");

        }

    } else {

        av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n", s->amode);

        return AVERROR_INVALIDDATA;

    }

    avctx->channels = channels;

    /* get output buffer */

    frame->nb_samples = 256 * (s->sample_blocks / 8);

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

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

        return ret;

    }

    samples_flt = (float **)frame->extended_data;

    /* allocate buffer for extra channels if downmixing */

    if (avctx->channels < full_channels) {

        ret = av_samples_get_buffer_size(NULL, full_channels - channels,

                                         frame->nb_samples,

                                         avctx->sample_fmt, 0);

        if (ret < 0)

            return ret;

        av_fast_malloc(&s->extra_channels_buffer,

                       &s->extra_channels_buffer_size, ret);

        if (!s->extra_channels_buffer)

            return AVERROR(ENOMEM);

        ret = av_samples_fill_arrays((uint8_t **)s->extra_channels, NULL,

                                     s->extra_channels_buffer,

                                     full_channels - channels,

                                     frame->nb_samples, avctx->sample_fmt, 0);

        if (ret < 0)

            return ret;

    }

    /* filter to get final output */

    for (i = 0; i < (s->sample_blocks / 8); i++) {

        int ch;

        for (ch = 0; ch < channels; ch++)

            s->samples_chanptr[ch] = samples_flt[ch] + i * 256;

        for (; ch < full_channels; ch++)

            s->samples_chanptr[ch] = s->extra_channels[ch - channels] + i * 256;

        dca_filter_channels(s, i);

        /* If this was marked as a DTS-ES stream we need to subtract back- */

        /* channel from SL & SR to remove matrixed back-channel signal */

        if ((s->source_pcm_res & 1) && s->xch_present) {

            float *back_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel]];

            float *lt_chan   = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 2]];

            float *rt_chan   = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 1]];

            s->fdsp.vector_fmac_scalar(lt_chan, back_chan, -M_SQRT1_2, 256);

            s->fdsp.vector_fmac_scalar(rt_chan, back_chan, -M_SQRT1_2, 256);

        }

    }

    /* update lfe history */

    lfe_samples = 2 * s->lfe * (s->sample_blocks / 8);

    for (i = 0; i < 2 * s->lfe * 4; i++)

        s->lfe_data[i] = s->lfe_data[i + lfe_samples];

    /* AVMatrixEncoding

     *

     * DCA_STEREO_TOTAL (Lt/Rt) is equivalent to Dolby Surround */

    ret = ff_side_data_update_matrix_encoding(frame,

                                              (s->output & ~DCA_LFE) == DCA_STEREO_TOTAL ?

                                              AV_MATRIX_ENCODING_DOLBY : AV_MATRIX_ENCODING_NONE);

    if (ret < 0)

        return ret;

    *got_frame_ptr = 1;

    return buf_size;

}


static unsigned do_stfle(CPUS390XState *env, uint64_t words[MAX_STFL_WORDS])

{

    S390CPU *cpu = s390_env_get_cpu(env);

    const unsigned long *features = cpu->model->features;

    unsigned max_bit = 0;

    S390Feat feat;

    memset(words, 0, sizeof(uint64_t) * MAX_STFL_WORDS);

    if (test_bit(S390_FEAT_ZARCH, features)) {

        /* z/Architecture is always active if around */

        words[0] = 1ull << (63 - 2);

    }

    for (feat = find_first_bit(features, S390_FEAT_MAX);

         feat < S390_FEAT_MAX;

         feat = find_next_bit(features, S390_FEAT_MAX, feat + 1)) {

        const S390FeatDef *def = s390_feat_def(feat);

        if (def->type == S390_FEAT_TYPE_STFL) {

            unsigned bit = def->bit;

            if (bit > max_bit) {

                max_bit = bit;

            }

            assert(bit / 64 < MAX_STFL_WORDS);

            words[bit / 64] |= 1ULL << (63 - bit % 64);

        }

    }

    return max_bit / 64;

}


static int nbd_establish_connection(BlockDriverState *bs)

{

    BDRVNBDState *s = bs->opaque;

    int sock;

    int ret;

    off_t size;

    size_t blocksize;

    if (s->host_spec[0] == '/') {

        sock = unix_socket_outgoing(s->host_spec);

    } else {

        sock = tcp_socket_outgoing_spec(s->host_spec);

    }

    /* Failed to establish connection */

    if (sock < 0) {

        logout("Failed to establish connection to NBD server\n");

        return -errno;

    }

    /* NBD handshake */

    ret = nbd_receive_negotiate(sock, s->export_name, &s->nbdflags, &size,

                                &blocksize);

    if (ret < 0) {

        logout("Failed to negotiate with the NBD server\n");

        closesocket(sock);

        return -errno;

    }

    /* Now that we're connected, set the socket to be non-blocking and

     * kick the reply mechanism.  */

    socket_set_nonblock(sock);

    qemu_aio_set_fd_handler(s->sock, nbd_reply_ready, NULL,

                            nbd_have_request, NULL, s);

    s->sock = sock;

    s->size = size;

    s->blocksize = blocksize;

    logout("Established connection with NBD server\n");

    return 0;

}


static av_cold int vc2_encode_init(AVCodecContext *avctx)

{

    Plane *p;

    SubBand *b;

    int i, j, level, o, shift;

    const AVPixFmtDescriptor *fmt = av_pix_fmt_desc_get(avctx->pix_fmt);

    const int depth = fmt->comp[0].depth;

    VC2EncContext *s = avctx->priv_data;

    s->picture_number = 0;

    /* Total allowed quantization range */

    s->q_ceil    = DIRAC_MAX_QUANT_INDEX;

    s->ver.major = 2;

    s->ver.minor = 0;

    s->profile   = 3;

    s->level     = 3;

    s->base_vf   = -1;

    s->strict_compliance = 1;

    s->q_avg = 0;

    s->slice_max_bytes = 0;

    s->slice_min_bytes = 0;

    /* Mark unknown as progressive */

    s->interlaced = !((avctx->field_order == AV_FIELD_UNKNOWN) ||

                      (avctx->field_order == AV_FIELD_PROGRESSIVE));

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

        const VC2BaseVideoFormat *fmt = &base_video_fmts[i];

        if (avctx->pix_fmt != fmt->pix_fmt)

            continue;

        if (avctx->time_base.num != fmt->time_base.num)

            continue;

        if (avctx->time_base.den != fmt->time_base.den)

            continue;

        if (avctx->width != fmt->width)

            continue;

        if (avctx->height != fmt->height)

            continue;

        if (s->interlaced != fmt->interlaced)

            continue;

        s->base_vf = i;

        s->level   = base_video_fmts[i].level;

        break;

    }

    if (s->interlaced)

        av_log(avctx, AV_LOG_WARNING, "Interlacing enabled!\n");

    if ((s->slice_width  & (s->slice_width  - 1)) ||

        (s->slice_height & (s->slice_height - 1))) {

        av_log(avctx, AV_LOG_ERROR, "Slice size is not a power of two!\n");

        return AVERROR_UNKNOWN;

    }

    if ((s->slice_width > avctx->width) ||

        (s->slice_height > avctx->height)) {

        av_log(avctx, AV_LOG_ERROR, "Slice size is bigger than the image!\n");

        return AVERROR_UNKNOWN;

    }

    if (s->base_vf <= 0) {

        if (avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {

            s->strict_compliance = s->base_vf = 0;

            av_log(avctx, AV_LOG_WARNING, "Disabling strict compliance\n");

        } else {

            av_log(avctx, AV_LOG_WARNING, "Given format does not strictly comply with "

                   "the specifications, please add a -strict -1 flag to use it\n");

            return AVERROR_UNKNOWN;

        }

    } else {

        av_log(avctx, AV_LOG_INFO, "Selected base video format = %i (%s)\n",

               s->base_vf, base_video_fmts[s->base_vf].name);

    }

    /* Chroma subsampling */

    avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);

    /* Bit depth and color range index */

    if (depth == 8 && avctx->color_range == AVCOL_RANGE_JPEG) {

        s->bpp = 1;

        s->bpp_idx = 1;

        s->diff_offset = 128;

    } else if (depth == 8 && (avctx->color_range == AVCOL_RANGE_MPEG ||

               avctx->color_range == AVCOL_RANGE_UNSPECIFIED)) {

        s->bpp = 1;

        s->bpp_idx = 2;

        s->diff_offset = 128;

    } else if (depth == 10) {

        s->bpp = 2;

        s->bpp_idx = 3;

        s->diff_offset = 512;

    } else {

        s->bpp = 2;

        s->bpp_idx = 4;

        s->diff_offset = 2048;

    }

    /* Planes initialization */

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

        int w, h;

        p = &s->plane[i];

        p->width      = avctx->width  >> (i ? s->chroma_x_shift : 0);

        p->height     = avctx->height >> (i ? s->chroma_y_shift : 0);

        if (s->interlaced)

            p->height >>= 1;

        p->dwt_width  = w = FFALIGN(p->width,  (1 << s->wavelet_depth));

        p->dwt_height = h = FFALIGN(p->height, (1 << s->wavelet_depth));

        p->coef_stride = FFALIGN(p->dwt_width, 32);

        p->coef_buf = av_malloc(p->coef_stride*p->dwt_height*sizeof(dwtcoef));

        if (!p->coef_buf)

            goto alloc_fail;

        for (level = s->wavelet_depth-1; level >= 0; level--) {

            w = w >> 1;

            h = h >> 1;

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

                b = &p->band[level][o];

                b->width  = w;

                b->height = h;

                b->stride = p->coef_stride;

                shift = (o > 1)*b->height*b->stride + (o & 1)*b->width;

                b->buf = p->coef_buf + shift;

            }

        }

        /* DWT init */

        if (ff_vc2enc_init_transforms(&s->transform_args[i].t,

                                      s->plane[i].coef_stride,

                                      s->plane[i].dwt_height))

            goto alloc_fail;

    }

    /* Slices */

    s->num_x = s->plane[0].dwt_width/s->slice_width;

    s->num_y = s->plane[0].dwt_height/s->slice_height;

    s->slice_args = av_calloc(s->num_x*s->num_y, sizeof(SliceArgs));

    if (!s->slice_args)

        goto alloc_fail;

    /* Lookup tables */

    s->coef_lut_len = av_malloc(COEF_LUT_TAB*(s->q_ceil+1)*sizeof(*s->coef_lut_len));

    if (!s->coef_lut_len)

        goto alloc_fail;

    s->coef_lut_val = av_malloc(COEF_LUT_TAB*(s->q_ceil+1)*sizeof(*s->coef_lut_val));

    if (!s->coef_lut_val)

        goto alloc_fail;

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

        uint8_t  *len_lut = &s->coef_lut_len[i*COEF_LUT_TAB];

        uint32_t *val_lut = &s->coef_lut_val[i*COEF_LUT_TAB];

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

            get_vc2_ue_uint(QUANT(j, ff_dirac_qscale_tab[i]),

                            &len_lut[j], &val_lut[j]);

            if (len_lut[j] != 1) {

                len_lut[j] += 1;

                val_lut[j] <<= 1;

            } else {

                val_lut[j] = 1;

            }

        }

    }

    return 0;

alloc_fail:

    vc2_encode_end(avctx);

    av_log(avctx, AV_LOG_ERROR, "Unable to allocate memory!\n");

    return AVERROR(ENOMEM);

}


void ff_fix_long_b_mvs(MpegEncContext * s, int16_t (*mv_table)[2], int f_code, int type)

{

    int y;

    uint8_t * fcode_tab= s->fcode_tab;

    // RAL: 8 in MPEG-1, 16 in MPEG-4

    int range = (((s->codec_id == CODEC_ID_MPEG1VIDEO) ? 8 : 16) << f_code);

    /* clip / convert to intra 16x16 type MVs */

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

        int x;

        int xy= (y+1)* (s->mb_width+2)+1;

        int i= y*s->mb_width;

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

            {

            if (s->mb_type[i] & type)    // RAL: "type" test added...

                {

                if (fcode_tab[mv_table[xy][0] + MAX_MV] > f_code || fcode_tab[mv_table[xy][0] + MAX_MV] == 0)

                    {

                    if(mv_table[xy][0]>0)

                        mv_table[xy][0]=  range-1;

                    else

                        mv_table[xy][0]= -range;

                    }

                if (fcode_tab[mv_table[xy][1] + MAX_MV] > f_code || fcode_tab[mv_table[xy][1] + MAX_MV] == 0)

                    {

                    if(mv_table[xy][1]>0)

                        mv_table[xy][1]=  range-1;

                    else

                        mv_table[xy][1]= -range;

            }

            }

            xy++;

            i++;

        }

    }

}


S390CPU *s390x_new_cpu(const char *cpu_model, uint32_t core_id, Error **errp)

{

    S390CPU *cpu;

    Error *err = NULL;

    cpu = cpu_s390x_create(cpu_model, &err);

    if (err != NULL) {

        goto out;

    }

    object_property_set_int(OBJECT(cpu), core_id, "core-id", &err);

    if (err != NULL) {

        goto out;

    }

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

out:

    if (err) {

        error_propagate(errp, err);

        object_unref(OBJECT(cpu));

        cpu = NULL;

    }

    return cpu;

}


aio_compute_timeout(AioContext *ctx)

{

    int64_t deadline;

    int timeout = -1;

    QEMUBH *bh;

    for (bh = atomic_rcu_read(&ctx->first_bh); bh;

         bh = atomic_rcu_read(&bh->next)) {

        if (bh->scheduled) {

            if (bh->idle) {

                /* idle bottom halves will be polled at least

                 * every 10ms */

                timeout = 10000000;

            } else {

                /* non-idle bottom halves will be executed

                 * immediately */

                return 0;

            }

        }

    }

    deadline = timerlistgroup_deadline_ns(&ctx->tlg);

    if (deadline == 0) {

        return 0;

    } else {

        return qemu_soonest_timeout(timeout, deadline);

    }

}


static void create_cel_evals(RoqContext *enc, RoqTempdata *tempData)

{

    int n=0, x, y, i;

    tempData->cel_evals = av_malloc(enc->width*enc->height/64 * sizeof(CelEvaluation));

    /* Map to the ROQ quadtree order */

    for (y=0; y<enc->height; y+=16)

        for (x=0; x<enc->width; x+=16)

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

                tempData->cel_evals[n  ].sourceX = x + (i&1)*8;

                tempData->cel_evals[n++].sourceY = y + (i&2)*4;

            }

}


static int ea_read_packet(AVFormatContext *s,

                          AVPacket *pkt)

{

    EaDemuxContext *ea = s->priv_data;

    AVIOContext *pb = s->pb;

    int ret = 0;

    int packet_read = 0;

    unsigned int chunk_type, chunk_size;

    int key = 0;

    int av_uninit(num_samples);

    while (!packet_read) {

        chunk_type = avio_rl32(pb);

        chunk_size = (ea->big_endian ? avio_rb32(pb) : avio_rl32(pb)) - 8;

        switch (chunk_type) {

        /* audio data */

        case ISNh_TAG:

            /* header chunk also contains data; skip over the header portion*/

            avio_skip(pb, 32);

            chunk_size -= 32;

        case ISNd_TAG:

        case SCDl_TAG:

        case SNDC_TAG:

        case SDEN_TAG:

            if (!ea->audio_codec) {

                avio_skip(pb, chunk_size);

                break;

            } else if (ea->audio_codec == CODEC_ID_PCM_S16LE_PLANAR ||

                       ea->audio_codec == CODEC_ID_MP3) {

                num_samples = avio_rl32(pb);

                avio_skip(pb, 8);

                chunk_size -= 12;

            }

            ret = av_get_packet(pb, pkt, chunk_size);

            if (ret < 0)

                return ret;

            pkt->stream_index = ea->audio_stream_index;

            switch (ea->audio_codec) {

            case CODEC_ID_ADPCM_EA:

            case CODEC_ID_ADPCM_EA_R1:

            case CODEC_ID_ADPCM_EA_R2:

            case CODEC_ID_ADPCM_IMA_EA_EACS:

                pkt->duration = AV_RL32(pkt->data);

                break;

            case CODEC_ID_ADPCM_EA_R3:

                pkt->duration = AV_RB32(pkt->data);

                break;

            case CODEC_ID_ADPCM_IMA_EA_SEAD:

                pkt->duration = ret * 2 / ea->num_channels;

                break;

            case CODEC_ID_PCM_S16LE_PLANAR:

            case CODEC_ID_MP3:

                pkt->duration = num_samples;

                break;

            default:

                pkt->duration = chunk_size / (ea->bytes * ea->num_channels);

            }

            packet_read = 1;

            break;

        /* ending tag */

        case 0:

        case ISNe_TAG:

        case SCEl_TAG:

        case SEND_TAG:

        case SEEN_TAG:

            ret = AVERROR(EIO);

            packet_read = 1;

            break;

        case MVIh_TAG:

        case kVGT_TAG:

        case pQGT_TAG:

        case TGQs_TAG:

        case MADk_TAG:

            key = AV_PKT_FLAG_KEY;

        case MVIf_TAG:

        case fVGT_TAG:

        case MADm_TAG:

        case MADe_TAG:

            avio_seek(pb, -8, SEEK_CUR);     // include chunk preamble

            chunk_size += 8;

            goto get_video_packet;

        case mTCD_TAG:

            avio_skip(pb, 8);  // skip ea dct header

            chunk_size -= 8;

            goto get_video_packet;

        case MV0K_TAG:

        case MPCh_TAG:

        case pIQT_TAG:

            key = AV_PKT_FLAG_KEY;

        case MV0F_TAG:

get_video_packet:

            ret = av_get_packet(pb, pkt, chunk_size);

            if (ret < 0)

                return ret;

            pkt->stream_index = ea->video_stream_index;

            pkt->flags |= key;

            packet_read = 1;

            break;

        default:

            avio_skip(pb, chunk_size);

            break;

        }

    }

    return ret;

}


static void type_initialize_interface(TypeImpl *ti, const char *parent)

{

    InterfaceClass *new_iface;

    TypeInfo info = { };

    TypeImpl *iface_impl;

    info.parent = parent;

    info.name = g_strdup_printf("%s::%s", ti->name, info.parent);

    info.abstract = true;

    iface_impl = type_register(&info);

    type_initialize(iface_impl);

    g_free((char *)info.name);

    new_iface = (InterfaceClass *)iface_impl->class;

    new_iface->concrete_class = ti->class;

    ti->class->interfaces = g_slist_append(ti->class->interfaces,

                                           iface_impl->class);

}


static int video_open(VideoState *is){

    int flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;

    int w,h;

    if(is_full_screen) flags |= SDL_FULLSCREEN;

    else               flags |= SDL_RESIZABLE;

    if (is_full_screen && fs_screen_width) {

        w = fs_screen_width;

        h = fs_screen_height;

    } else if(!is_full_screen && screen_width){

        w = screen_width;

        h = screen_height;

    }else if (is->video_st && is->video_st->codec->width){

        w = is->video_st->codec->width;

        h = is->video_st->codec->height;

    } else {

        w = 640;

        h = 480;

    }

#ifndef SYS_DARWIN

    screen = SDL_SetVideoMode(w, h, 0, flags);

#else

    /* setting bits_per_pixel = 0 or 32 causes blank video on OS X */

    screen = SDL_SetVideoMode(w, h, 24, flags);

#endif

    if (!screen) {

        fprintf(stderr, "SDL: could not set video mode - exiting\n");

        return -1;

    }

    SDL_WM_SetCaption("FFplay", "FFplay");

    is->width = screen->w;

    is->height = screen->h;

    return 0;

}


static uint64_t nand_read(void *opaque, target_phys_addr_t addr, unsigned size)

{

    struct nand_state_t *s = opaque;

    uint32_t r;

    int rdy;

    r = nand_getio(s->nand);

    nand_getpins(s->nand, &rdy);

    s->rdy = rdy;

    DNAND(printf("%s addr=%x r=%x\n", __func__, addr, r));

    return r;

}


void qmp_migrate_set_speed(int64_t value, Error **errp)

{

    MigrationState *s;

    if (value < 0) {

        value = 0;

    }

    s = migrate_get_current();

    s->bandwidth_limit = value;

    qemu_file_set_rate_limit(s->file, s->bandwidth_limit);

}


void block_job_resume_all(void)

{

    BlockJob *job = NULL;

    while ((job = block_job_next(job))) {

        AioContext *aio_context = blk_get_aio_context(job->blk);

        aio_context_acquire(aio_context);

        block_job_resume(job);

        aio_context_release(aio_context);

    }

}


static int write_option(void *optctx, const OptionDef *po, const char *opt,

                        const char *arg)

{

    /* new-style options contain an offset into optctx, old-style address of

     * a global var*/

    void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?

                (uint8_t *)optctx + po->u.off : po->u.dst_ptr;

    int *dstcount;

    if (po->flags & OPT_SPEC) {

        SpecifierOpt **so = dst;

        char *p = strchr(opt, ':');

        dstcount = (int *)(so + 1);

        *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);

        (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");

        dst = &(*so)[*dstcount - 1].u;

    }

    if (po->flags & OPT_STRING) {

        char *str;

        str = av_strdup(arg);

        av_freep(dst);

        *(char **)dst = str;

    } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {

        *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);

    } else if (po->flags & OPT_INT64) {

        *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);

    } else if (po->flags & OPT_TIME) {

        *(int64_t *)dst = parse_time_or_die(opt, arg, 1);

    } else if (po->flags & OPT_FLOAT) {

        *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);

    } else if (po->flags & OPT_DOUBLE) {

        *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);

    } else if (po->u.func_arg) {

        int ret = po->u.func_arg(optctx, opt, arg);

        if (ret < 0) {

            av_log(NULL, AV_LOG_ERROR,

                   "Failed to set value '%s' for option '%s'\n", arg, opt);

            return ret;

        }

    }

    if (po->flags & OPT_EXIT)

        exit_program(0);

    return 0;

}


static void put_uint8(QEMUFile *f, void *pv, size_t size)

{

    uint8_t *v = pv;

    qemu_put_8s(f, v);

}


static RemoveResult remove_hpte(PowerPCCPU *cpu, target_ulong ptex,

                                target_ulong avpn,

                                target_ulong flags,

                                target_ulong *vp, target_ulong *rp)

{

    CPUPPCState *env = &cpu->env;

    uint64_t token;

    target_ulong v, r, rb;

    if (!valid_pte_index(env, ptex)) {

        return REMOVE_PARM;

    }

    token = ppc_hash64_start_access(cpu, ptex);

    v = ppc_hash64_load_hpte0(cpu, token, 0);

    r = ppc_hash64_load_hpte1(cpu, token, 0);

    ppc_hash64_stop_access(token);

    if ((v & HPTE64_V_VALID) == 0 ||

        ((flags & H_AVPN) && (v & ~0x7fULL) != avpn) ||

        ((flags & H_ANDCOND) && (v & avpn) != 0)) {

        return REMOVE_NOT_FOUND;

    }

    *vp = v;

    *rp = r;

    ppc_hash64_store_hpte(cpu, ptex, HPTE64_V_HPTE_DIRTY, 0);

    rb = compute_tlbie_rb(v, r, ptex);

    ppc_tlb_invalidate_one(env, rb);

    return REMOVE_SUCCESS;

}


int pcie_aer_init(PCIDevice *dev, uint16_t offset, uint16_t size)

{

    PCIExpressDevice *exp;

    pcie_add_capability(dev, PCI_EXT_CAP_ID_ERR, PCI_ERR_VER,

                        offset, size);

    exp = &dev->exp;

    exp->aer_cap = offset;

    /* log_max is property */

    if (dev->exp.aer_log.log_max == PCIE_AER_LOG_MAX_UNSET) {

        dev->exp.aer_log.log_max = PCIE_AER_LOG_MAX_DEFAULT;

    }

    /* clip down the value to avoid unreasobale memory usage */

    if (dev->exp.aer_log.log_max > PCIE_AER_LOG_MAX_LIMIT) {

        return -EINVAL;

    }

    dev->exp.aer_log.log = g_malloc0(sizeof dev->exp.aer_log.log[0] *

                                        dev->exp.aer_log.log_max);

    pci_set_long(dev->w1cmask + offset + PCI_ERR_UNCOR_STATUS,

                 PCI_ERR_UNC_SUPPORTED);

    pci_set_long(dev->config + offset + PCI_ERR_UNCOR_SEVER,

                 PCI_ERR_UNC_SEVERITY_DEFAULT);

    pci_set_long(dev->wmask + offset + PCI_ERR_UNCOR_SEVER,

                 PCI_ERR_UNC_SUPPORTED);

    pci_long_test_and_set_mask(dev->w1cmask + offset + PCI_ERR_COR_STATUS,

                               PCI_ERR_COR_SUPPORTED);

    pci_set_long(dev->config + offset + PCI_ERR_COR_MASK,

                 PCI_ERR_COR_MASK_DEFAULT);

    pci_set_long(dev->wmask + offset + PCI_ERR_COR_MASK,

                 PCI_ERR_COR_SUPPORTED);

    /* capabilities and control. multiple header logging is supported */

    if (dev->exp.aer_log.log_max > 0) {

        pci_set_long(dev->config + offset + PCI_ERR_CAP,

                     PCI_ERR_CAP_ECRC_GENC | PCI_ERR_CAP_ECRC_CHKC |

                     PCI_ERR_CAP_MHRC);

        pci_set_long(dev->wmask + offset + PCI_ERR_CAP,

                     PCI_ERR_CAP_ECRC_GENE | PCI_ERR_CAP_ECRC_CHKE |

                     PCI_ERR_CAP_MHRE);

    } else {

        pci_set_long(dev->config + offset + PCI_ERR_CAP,

                     PCI_ERR_CAP_ECRC_GENC | PCI_ERR_CAP_ECRC_CHKC);

        pci_set_long(dev->wmask + offset + PCI_ERR_CAP,

                     PCI_ERR_CAP_ECRC_GENE | PCI_ERR_CAP_ECRC_CHKE);

    }

    switch (pcie_cap_get_type(dev)) {

    case PCI_EXP_TYPE_ROOT_PORT:

        /* this case will be set by pcie_aer_root_init() */

        /* fallthrough */

    case PCI_EXP_TYPE_DOWNSTREAM:

    case PCI_EXP_TYPE_UPSTREAM:

        pci_word_test_and_set_mask(dev->wmask + PCI_BRIDGE_CONTROL,

                                   PCI_BRIDGE_CTL_SERR);

        pci_long_test_and_set_mask(dev->w1cmask + PCI_STATUS,

                                   PCI_SEC_STATUS_RCV_SYSTEM_ERROR);

        break;

    default:

        /* nothing */

        break;

    }

    return 0;

}


static void qemu_tcg_init_vcpu(CPUState *cpu)

{

    char thread_name[VCPU_THREAD_NAME_SIZE];

    static QemuCond *tcg_halt_cond;

    static QemuThread *tcg_cpu_thread;

    /* share a single thread for all cpus with TCG */

    if (!tcg_cpu_thread) {

        cpu->thread = g_malloc0(sizeof(QemuThread));

        cpu->halt_cond = g_malloc0(sizeof(QemuCond));

        qemu_cond_init(cpu->halt_cond);

        tcg_halt_cond = cpu->halt_cond;

        snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/TCG",

                 cpu->cpu_index);

        qemu_thread_create(cpu->thread, thread_name, qemu_tcg_cpu_thread_fn,

                           cpu, QEMU_THREAD_JOINABLE);

#ifdef _WIN32

        cpu->hThread = qemu_thread_get_handle(cpu->thread);

#endif

        while (!cpu->created) {

            qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);

        }

        tcg_cpu_thread = cpu->thread;

    } else {

        cpu->thread = tcg_cpu_thread;

        cpu->halt_cond = tcg_halt_cond;

    }

}


ssize_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)

{

    ssize_t ret;

#ifdef CONFIG_VNC_TLS

    if (vs->tls.session) {

        ret = vnc_client_write_tls(&vs->tls.session, data, datalen);

    } else {

#endif /* CONFIG_VNC_TLS */

        ret = send(vs->csock, (const void *)data, datalen, 0);

#ifdef CONFIG_VNC_TLS

    }

#endif /* CONFIG_VNC_TLS */

    VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);

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

}


static av_cold int decode_init(AVCodecContext * avctx)

{

    MPADecodeContext *s = avctx->priv_data;

    static int init=0;

    int i, j, k;

    s->avctx = avctx;

    ff_mpadsp_init(&s->mpadsp);

    avctx->sample_fmt= OUT_FMT;

    s->error_recognition= avctx->error_recognition;

    if (!init && !avctx->parse_only) {

        int offset;

        /* scale factors table for layer 1/2 */

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

            int shift, mod;

            /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */

            shift = (i / 3);

            mod = i % 3;

            scale_factor_modshift[i] = mod | (shift << 2);

        }

        /* scale factor multiply for layer 1 */

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

            int n, norm;

            n = i + 2;

            norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);

            scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0          * 2.0), FRAC_BITS);

            scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);

            scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);

            av_dlog(avctx, "%d: norm=%x s=%x %x %x\n",

                    i, norm,

                    scale_factor_mult[i][0],

                    scale_factor_mult[i][1],

                    scale_factor_mult[i][2]);

        }

        RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));

        /* huffman decode tables */

        offset = 0;

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

            const HuffTable *h = &mpa_huff_tables[i];

            int xsize, x, y;

            uint8_t  tmp_bits [512];

            uint16_t tmp_codes[512];

            memset(tmp_bits , 0, sizeof(tmp_bits ));

            memset(tmp_codes, 0, sizeof(tmp_codes));

            xsize = h->xsize;

            j = 0;

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

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

                    tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j  ];

                    tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];

                }

            }

            /* XXX: fail test */

            huff_vlc[i].table = huff_vlc_tables+offset;

            huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];

            init_vlc(&huff_vlc[i], 7, 512,

                     tmp_bits, 1, 1, tmp_codes, 2, 2,

                     INIT_VLC_USE_NEW_STATIC);

            offset += huff_vlc_tables_sizes[i];

        }

        assert(offset == FF_ARRAY_ELEMS(huff_vlc_tables));

        offset = 0;

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

            huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;

            huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];

            init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,

                     mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,

                     INIT_VLC_USE_NEW_STATIC);

            offset += huff_quad_vlc_tables_sizes[i];

        }

        assert(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));

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

            k = 0;

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

                band_index_long[i][j] = k;

                k += band_size_long[i][j];

            }

            band_index_long[i][22] = k;

        }

        /* compute n ^ (4/3) and store it in mantissa/exp format */

        int_pow_init();

        mpegaudio_tableinit();

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

            if (ff_mpa_quant_bits[i] < 0)

                for (j = 0; j < (1<<(-ff_mpa_quant_bits[i]+1)); j++) {

                    int val1, val2, val3, steps;

                    int val = j;

                    steps  = ff_mpa_quant_steps[i];

                    val1 = val % steps;

                    val /= steps;

                    val2 = val % steps;

                    val3 = val / steps;

                    division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);

                }

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

            float f;

            INTFLOAT v;

            if (i != 6) {

                f = tan((double)i * M_PI / 12.0);

                v = FIXR(f / (1.0 + f));

            } else {

                v = FIXR(1.0);

            }

            is_table[0][i] = v;

            is_table[1][6 - i] = v;

        }

        /* invalid values */

        for(i=7;i<16;i++)

            is_table[0][i] = is_table[1][i] = 0.0;

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

            double f;

            int e, k;

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

                e = -(j + 1) * ((i + 1) >> 1);

                f = pow(2.0, e / 4.0);

                k = i & 1;

                is_table_lsf[j][k ^ 1][i] = FIXR(f);

                is_table_lsf[j][k][i] = FIXR(1.0);

                av_dlog(avctx, "is_table_lsf %d %d: %x %x\n",

                        i, j, is_table_lsf[j][0][i], is_table_lsf[j][1][i]);

            }

        }

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

            float ci, cs, ca;

            ci = ci_table[i];

            cs = 1.0 / sqrt(1.0 + ci * ci);

            ca = cs * ci;

            csa_table[i][0] = FIXHR(cs/4);

            csa_table[i][1] = FIXHR(ca/4);

            csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);

            csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);

            csa_table_float[i][0] = cs;

            csa_table_float[i][1] = ca;

            csa_table_float[i][2] = ca + cs;

            csa_table_float[i][3] = ca - cs;

        }

        /* compute mdct windows */

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

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

                double d;

                if(j==2 && i%3 != 1)

                    continue;

                d= sin(M_PI * (i + 0.5) / 36.0);

                if(j==1){

                    if     (i>=30) d= 0;

                    else if(i>=24) d= sin(M_PI * (i - 18 + 0.5) / 12.0);

                    else if(i>=18) d= 1;

                }else if(j==3){

                    if     (i<  6) d= 0;

                    else if(i< 12) d= sin(M_PI * (i -  6 + 0.5) / 12.0);

                    else if(i< 18) d= 1;

                }

                //merge last stage of imdct into the window coefficients

                d*= 0.5 / cos(M_PI*(2*i + 19)/72);

                if(j==2)

                    mdct_win[j][i/3] = FIXHR((d / (1<<5)));

                else

                    mdct_win[j][i  ] = FIXHR((d / (1<<5)));

            }

        }

        /* NOTE: we do frequency inversion adter the MDCT by changing

           the sign of the right window coefs */

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

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

                mdct_win[j + 4][i] = mdct_win[j][i];

                mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];

            }

        }

        init = 1;

    }

    if (avctx->codec_id == CODEC_ID_MP3ADU)

        s->adu_mode = 1;

    return 0;

}


static int libgsm_decode_frame(AVCodecContext *avctx,

                               void *data, int *data_size,

                               AVPacket *avpkt) {

    uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    int out_size = avctx->frame_size * av_get_bytes_per_sample(avctx->sample_fmt);

    if (*data_size < out_size) {

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

        return AVERROR(EINVAL);

    }

    if (buf_size < avctx->block_align) {

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

        return AVERROR_INVALIDDATA;

    }

    switch(avctx->codec_id) {

    case CODEC_ID_GSM:

        if(gsm_decode(avctx->priv_data,buf,data)) return -1;

        break;

    case CODEC_ID_GSM_MS:

        if(gsm_decode(avctx->priv_data,buf,data) ||

           gsm_decode(avctx->priv_data,buf+33,((int16_t*)data)+GSM_FRAME_SIZE)) return -1;

    }

    *data_size = out_size;

    return avctx->block_align;

}


static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)

{

    unsigned access_size_min = mr->ops->impl.min_access_size;

    unsigned access_size_max = mr->ops->impl.max_access_size;

    /* Regions are assumed to support 1-4 byte accesses unless

       otherwise specified.  */

    if (access_size_min == 0) {

        access_size_min = 1;

    }

    if (access_size_max == 0) {

        access_size_max = 4;

    }

    /* Bound the maximum access by the alignment of the address.  */

    if (!mr->ops->impl.unaligned) {

        unsigned align_size_max = addr & -addr;

        if (align_size_max != 0 && align_size_max < access_size_max) {

            access_size_max = align_size_max;

        }

    }

    /* Don't attempt accesses larger than the maximum.  */

    if (l > access_size_max) {

        l = access_size_max;

    }

    /* ??? The users of this function are wrong, not supporting minimums larger

       than the remaining length.  C.f. memory.c:access_with_adjusted_size.  */

    assert(l >= access_size_min);

    return l;

}


void fw_cfg_add_file_callback(FWCfgState *s,  const char *filename,

                              FWCfgCallback select_cb,

                              FWCfgWriteCallback write_cb,

                              void *callback_opaque,

                              void *data, size_t len, bool read_only)

{

    int i, index, count;

    size_t dsize;

    MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());

    int order = 0;

    if (!s->files) {

        dsize = sizeof(uint32_t) + sizeof(FWCfgFile) * fw_cfg_file_slots(s);

        s->files = g_malloc0(dsize);

        fw_cfg_add_bytes(s, FW_CFG_FILE_DIR, s->files, dsize);

    }

    count = be32_to_cpu(s->files->count);

    assert(count < fw_cfg_file_slots(s));

    /* Find the insertion point. */

    if (mc->legacy_fw_cfg_order) {

        /*

         * Sort by order. For files with the same order, we keep them

         * in the sequence in which they were added.

         */

        order = get_fw_cfg_order(s, filename);

        for (index = count;

             index > 0 && order < s->entry_order[index - 1];

             index--);

    } else {

        /* Sort by file name. */

        for (index = count;

             index > 0 && strcmp(filename, s->files->f[index - 1].name) < 0;

             index--);

    }

    /*

     * Move all the entries from the index point and after down one

     * to create a slot for the new entry.  Because calculations are

     * being done with the index, make it so that "i" is the current

     * index and "i - 1" is the one being copied from, thus the

     * unusual start and end in the for statement.

     */

    for (i = count + 1; i > index; i--) {

        s->files->f[i] = s->files->f[i - 1];

        s->files->f[i].select = cpu_to_be16(FW_CFG_FILE_FIRST + i);

        s->entries[0][FW_CFG_FILE_FIRST + i] =

            s->entries[0][FW_CFG_FILE_FIRST + i - 1];

        s->entry_order[i] = s->entry_order[i - 1];

    }

    memset(&s->files->f[index], 0, sizeof(FWCfgFile));

    memset(&s->entries[0][FW_CFG_FILE_FIRST + index], 0, sizeof(FWCfgEntry));

    pstrcpy(s->files->f[index].name, sizeof(s->files->f[index].name), filename);

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

        if (i != index &&

            strcmp(s->files->f[index].name, s->files->f[i].name) == 0) {

            error_report("duplicate fw_cfg file name: %s",

                         s->files->f[index].name);

            exit(1);

        }

    }

    fw_cfg_add_bytes_callback(s, FW_CFG_FILE_FIRST + index,

                              select_cb, write_cb,

                              callback_opaque, data, len,

                              read_only);

    s->files->f[index].size   = cpu_to_be32(len);

    s->files->f[index].select = cpu_to_be16(FW_CFG_FILE_FIRST + index);

    s->entry_order[index] = order;

    trace_fw_cfg_add_file(s, index, s->files->f[index].name, len);

    s->files->count = cpu_to_be32(count+1);

}


static void stellaris_enet_save(QEMUFile *f, void *opaque)

{

    stellaris_enet_state *s = (stellaris_enet_state *)opaque;

    int i;

    qemu_put_be32(f, s->ris);

    qemu_put_be32(f, s->im);

    qemu_put_be32(f, s->rctl);

    qemu_put_be32(f, s->tctl);

    qemu_put_be32(f, s->thr);

    qemu_put_be32(f, s->mctl);

    qemu_put_be32(f, s->mdv);

    qemu_put_be32(f, s->mtxd);

    qemu_put_be32(f, s->mrxd);

    qemu_put_be32(f, s->np);

    qemu_put_be32(f, s->tx_fifo_len);

    qemu_put_buffer(f, s->tx_fifo, sizeof(s->tx_fifo));

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

        qemu_put_be32(f, s->rx[i].len);

        qemu_put_buffer(f, s->rx[i].data, sizeof(s->rx[i].data));

    }

    qemu_put_be32(f, s->next_packet);

    qemu_put_be32(f, s->rx_fifo_offset);

}


static void exit_program(void)

{

    int i, j;

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

        avfilter_graph_free(&filtergraphs[i]->graph);

        for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {

            av_freep(&filtergraphs[i]->inputs[j]->name);

            av_freep(&filtergraphs[i]->inputs[j]);

        }

        av_freep(&filtergraphs[i]->inputs);

        for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {

            av_freep(&filtergraphs[i]->outputs[j]->name);

            av_freep(&filtergraphs[i]->outputs[j]);

        }

        av_freep(&filtergraphs[i]->outputs);

        av_freep(&filtergraphs[i]->graph_desc);

        av_freep(&filtergraphs[i]);

    }

    av_freep(&filtergraphs);

    /* close files */

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

        AVFormatContext *s = output_files[i]->ctx;

        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)

            avio_close(s->pb);

        avformat_free_context(s);

        av_dict_free(&output_files[i]->opts);

        av_freep(&output_files[i]);

    }

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

        AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;

        while (bsfc) {

            AVBitStreamFilterContext *next = bsfc->next;

            av_bitstream_filter_close(bsfc);

            bsfc = next;

        }

        output_streams[i]->bitstream_filters = NULL;

        avcodec_free_frame(&output_streams[i]->filtered_frame);

        av_freep(&output_streams[i]->forced_keyframes);

        av_freep(&output_streams[i]->avfilter);

        av_freep(&output_streams[i]->logfile_prefix);

        av_freep(&output_streams[i]);

    }

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

        avformat_close_input(&input_files[i]->ctx);

        av_freep(&input_files[i]);

    }

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

        av_frame_free(&input_streams[i]->decoded_frame);

        av_frame_free(&input_streams[i]->filter_frame);

        av_dict_free(&input_streams[i]->opts);

        av_freep(&input_streams[i]->filters);

        av_freep(&input_streams[i]);

    }

    if (vstats_file)

        fclose(vstats_file);

    av_free(vstats_filename);

    av_freep(&input_streams);

    av_freep(&input_files);

    av_freep(&output_streams);

    av_freep(&output_files);

    uninit_opts();

    avfilter_uninit();

    avformat_network_deinit();

    if (received_sigterm) {

        av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",

               (int) received_sigterm);

        exit (255);

    }

}


static int coroutine_fn cow_co_is_allocated(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors, int *num_same)

{

    int64_t bitnum = sector_num + sizeof(struct cow_header_v2) * 8;

    uint64_t offset = (bitnum / 8) & -BDRV_SECTOR_SIZE;

    uint8_t bitmap[BDRV_SECTOR_SIZE];

    int ret;

    int changed;

    ret = bdrv_pread(bs->file, offset, &bitmap, sizeof(bitmap));

    if (ret < 0) {

        return ret;

    }

    bitnum &= BITS_PER_BITMAP_SECTOR - 1;

    changed = cow_test_bit(bitnum, bitmap);

    *num_same = cow_find_streak(bitmap, changed, bitnum, nb_sectors);

    return changed;

}


bool timerlist_expired(QEMUTimerList *timer_list)

{

    int64_t expire_time;

    if (!atomic_read(&timer_list->active_timers)) {

        return false;

    }

    qemu_mutex_lock(&timer_list->active_timers_lock);

    if (!timer_list->active_timers) {

        qemu_mutex_unlock(&timer_list->active_timers_lock);

        return false;

    }

    expire_time = timer_list->active_timers->expire_time;

    qemu_mutex_unlock(&timer_list->active_timers_lock);

    return expire_time < qemu_clock_get_ns(timer_list->clock->type);

}


static void check_refcounts(BlockDriverState *bs)

{

    BDRVQcowState *s = bs->opaque;

    int64_t size;

    int nb_clusters, refcount1, refcount2, i;

    QCowSnapshot *sn;

    uint16_t *refcount_table;

    size = bdrv_getlength(s->hd);

    nb_clusters = size_to_clusters(s, size);

    refcount_table = qemu_mallocz(nb_clusters * sizeof(uint16_t));

    /* header */

    inc_refcounts(bs, refcount_table, nb_clusters,

                  0, s->cluster_size);

    check_refcounts_l1(bs, refcount_table, nb_clusters,

                       s->l1_table_offset, s->l1_size, 1);

    /* snapshots */

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

        sn = s->snapshots + i;

        check_refcounts_l1(bs, refcount_table, nb_clusters,

                           sn->l1_table_offset, sn->l1_size, 0);

    }

    inc_refcounts(bs, refcount_table, nb_clusters,

                  s->snapshots_offset, s->snapshots_size);

    /* refcount data */

    inc_refcounts(bs, refcount_table, nb_clusters,

                  s->refcount_table_offset,

                  s->refcount_table_size * sizeof(uint64_t));

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

        int64_t offset;

        offset = s->refcount_table[i];

        if (offset != 0) {

            inc_refcounts(bs, refcount_table, nb_clusters,

                          offset, s->cluster_size);

        }

    }

    /* compare ref counts */

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

        refcount1 = get_refcount(bs, i);

        refcount2 = refcount_table[i];

        if (refcount1 != refcount2)

            fprintf(stderr, "ERROR cluster %d refcount=%d reference=%d\n",

                   i, refcount1, refcount2);

    }

    qemu_free(refcount_table);

}


static int ipoctal_init(IPackDevice *ip)

{

    IPOctalState *s = IPOCTAL(ip);

    unsigned i;

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

        SCC2698Channel *ch = &s->ch[i];

        ch->ipoctal = s;

        /* Redirect IP-Octal channels to host character devices */

        if (ch->devpath) {

            const char chr_name[] = "ipoctal";

            char label[ARRAY_SIZE(chr_name) + 2];

            static int index;

            snprintf(label, sizeof(label), "%s%d", chr_name, index);

            ch->dev = qemu_chr_new(label, ch->devpath, NULL);

            if (ch->dev) {

                index++;

                qemu_chr_add_handlers(ch->dev, hostdev_can_receive,

                                      hostdev_receive, hostdev_event, ch);

                DPRINTF("Redirecting channel %u to %s (%s)\n",

                        i, ch->devpath, label);

            } else {

                DPRINTF("Could not redirect channel %u to %s\n",

                        i, ch->devpath);

            }

        }

    }

    return 0;

}


static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)

{

    uint64_t start = MAX(r1.start, r2.start);

    /* off-by-one arithmetic to prevent overflow */

    uint64_t end = MIN(addrrange_end(r1) - 1, addrrange_end(r2) - 1);

    return addrrange_make(start, end - start + 1);

}


static int wc3_read_header(AVFormatContext *s,

                           AVFormatParameters *ap)

{

    Wc3DemuxContext *wc3 = s->priv_data;

    ByteIOContext *pb = s->pb;

    unsigned int fourcc_tag;

    unsigned int size;

    AVStream *st;

    unsigned char preamble[WC3_PREAMBLE_SIZE];

    int ret = 0;

    int current_palette = 0;

    int bytes_to_read;

    int i;

    unsigned char rotate;

    /* default context members */

    wc3->width = WC3_DEFAULT_WIDTH;

    wc3->height = WC3_DEFAULT_HEIGHT;

    wc3->palettes = NULL;

    wc3->palette_count = 0;

    wc3->pts = 0;

    wc3->video_stream_index = wc3->audio_stream_index = 0;

    /* skip the first 3 32-bit numbers */

    url_fseek(pb, 12, SEEK_CUR);

    /* traverse through the chunks and load the header information before

     * the first BRCH tag */

    if ((ret = get_buffer(pb, preamble, WC3_PREAMBLE_SIZE)) !=

        WC3_PREAMBLE_SIZE)

        return AVERROR(EIO);

    fourcc_tag = AV_RL32(&preamble[0]);

    size = (AV_RB32(&preamble[4]) + 1) & (~1);

    do {

        switch (fourcc_tag) {

        case SOND_TAG:

        case INDX_TAG:

            /* SOND unknown, INDX unnecessary; ignore both */

            url_fseek(pb, size, SEEK_CUR);

            break;

        case _PC__TAG:

            /* need the number of palettes */

            url_fseek(pb, 8, SEEK_CUR);

            if ((ret = get_buffer(pb, preamble, 4)) != 4)

                return AVERROR(EIO);

            wc3->palette_count = AV_RL32(&preamble[0]);

            if((unsigned)wc3->palette_count >= UINT_MAX / PALETTE_SIZE){

                wc3->palette_count= 0;

                return -1;

            }

            wc3->palettes = av_malloc(wc3->palette_count * PALETTE_SIZE);

            break;

        case BNAM_TAG:

            /* load up the name */

            if ((unsigned)size < 512)

                bytes_to_read = size;

            else

                bytes_to_read = 512;

            if ((ret = get_buffer(pb, s->title, bytes_to_read)) != bytes_to_read)

                return AVERROR(EIO);

            break;

        case SIZE_TAG:

            /* video resolution override */

            if ((ret = get_buffer(pb, preamble, WC3_PREAMBLE_SIZE)) !=

                WC3_PREAMBLE_SIZE)

                return AVERROR(EIO);

            wc3->width = AV_RL32(&preamble[0]);

            wc3->height = AV_RL32(&preamble[4]);

            break;

        case PALT_TAG:

            /* one of several palettes */

            if ((unsigned)current_palette >= wc3->palette_count)

                return AVERROR_INVALIDDATA;

            if ((ret = get_buffer(pb,

                &wc3->palettes[current_palette * PALETTE_SIZE],

                PALETTE_SIZE)) != PALETTE_SIZE)

                return AVERROR(EIO);

            /* transform the current palette in place */

            for (i = current_palette * PALETTE_SIZE;

                 i < (current_palette + 1) * PALETTE_SIZE; i++) {

                /* rotate each palette component left by 2 and use the result

                 * as an index into the color component table */

                rotate = ((wc3->palettes[i] << 2) & 0xFF) |

                         ((wc3->palettes[i] >> 6) & 0xFF);

                wc3->palettes[i] = wc3_pal_lookup[rotate];

            }

            current_palette++;

            break;

        default:

            av_log(s, AV_LOG_ERROR, "  unrecognized WC3 chunk: %c%c%c%c (0x%02X%02X%02X%02X)\n",

                preamble[0], preamble[1], preamble[2], preamble[3],

                preamble[0], preamble[1], preamble[2], preamble[3]);

            return AVERROR_INVALIDDATA;

            break;

        }

        if ((ret = get_buffer(pb, preamble, WC3_PREAMBLE_SIZE)) !=

            WC3_PREAMBLE_SIZE)

            return AVERROR(EIO);

        fourcc_tag = AV_RL32(&preamble[0]);

        /* chunk sizes are 16-bit aligned */

        size = (AV_RB32(&preamble[4]) + 1) & (~1);

    } while (fourcc_tag != BRCH_TAG);

    /* initialize the decoder streams */

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR(ENOMEM);

    av_set_pts_info(st, 33, 1, 90000);

    wc3->video_stream_index = st->index;

    st->codec->codec_type = CODEC_TYPE_VIDEO;

    st->codec->codec_id = CODEC_ID_XAN_WC3;

    st->codec->codec_tag = 0;  /* no fourcc */

    st->codec->width = wc3->width;

    st->codec->height = wc3->height;

    /* palette considerations */

    st->codec->palctrl = &wc3->palette_control;

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR(ENOMEM);

    av_set_pts_info(st, 33, 1, 90000);

    wc3->audio_stream_index = st->index;

    st->codec->codec_type = CODEC_TYPE_AUDIO;

    st->codec->codec_id = CODEC_ID_PCM_S16LE;

    st->codec->codec_tag = 1;

    st->codec->channels = WC3_AUDIO_CHANNELS;

    st->codec->bits_per_sample = WC3_AUDIO_BITS;

    st->codec->sample_rate = WC3_SAMPLE_RATE;

    st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *

        st->codec->bits_per_sample;

    st->codec->block_align = WC3_AUDIO_BITS * WC3_AUDIO_CHANNELS;

    return 0;

}


static int64_t do_strtosz(const char *nptr, char **end,

                          const char default_suffix, int64_t unit)

{

    int64_t retval;

    char *endptr;

    unsigned char c;

    int mul_required = 0;

    double val, mul, integral, fraction;

    errno = 0;

    val = strtod(nptr, &endptr);

    if (isnan(val) || endptr == nptr || errno != 0) {

        retval = -EINVAL;

        goto out;

    }

    fraction = modf(val, &integral);

    if (fraction != 0) {

        mul_required = 1;

    }

    c = *endptr;

    mul = suffix_mul(c, unit);

    if (mul >= 0) {

        endptr++;

    } else {

        mul = suffix_mul(default_suffix, unit);

        assert(mul >= 0);

    }

    if (mul == 1 && mul_required) {

        retval = -EINVAL;

        goto out;

    }

    if ((val * mul >= INT64_MAX) || val < 0) {

        retval = -ERANGE;

        goto out;

    }

    retval = val * mul;

out:

    if (end) {

        *end = endptr;

    } else if (*endptr) {

        retval = -EINVAL;

    }

    return retval;

}


static int check_refcounts_l1(BlockDriverState *bs,

                              BdrvCheckResult *res,

                              uint16_t **refcount_table,

                              int64_t *refcount_table_size,

                              int64_t l1_table_offset, int l1_size,

                              int flags)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t *l1_table = NULL, l2_offset, l1_size2;

    int i, ret;

    l1_size2 = l1_size * sizeof(uint64_t);

    /* Mark L1 table as used */

    ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,

                        l1_table_offset, l1_size2);

    if (ret < 0) {

        goto fail;

    }

    /* Read L1 table entries from disk */

    if (l1_size2 > 0) {

        l1_table = g_try_malloc(l1_size2);

        if (l1_table == NULL) {

            ret = -ENOMEM;

            res->check_errors++;

            goto fail;

        }

        ret = bdrv_pread(bs->file, l1_table_offset, l1_table, l1_size2);

        if (ret < 0) {

            fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");

            res->check_errors++;

            goto fail;

        }

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

            be64_to_cpus(&l1_table[i]);

    }

    /* Do the actual checks */

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

        l2_offset = l1_table[i];

        if (l2_offset) {

            /* Mark L2 table as used */

            l2_offset &= L1E_OFFSET_MASK;

            ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,

                                l2_offset, s->cluster_size);

            if (ret < 0) {

                goto fail;

            }

            /* L2 tables are cluster aligned */

            if (offset_into_cluster(s, l2_offset)) {

                fprintf(stderr, "ERROR l2_offset=%" PRIx64 ": Table is not "

                    "cluster aligned; L1 entry corrupted\n", l2_offset);

                res->corruptions++;

            }

            /* Process and check L2 entries */

            ret = check_refcounts_l2(bs, res, refcount_table,

                                     refcount_table_size, l2_offset, flags);

            if (ret < 0) {

                goto fail;

            }

        }

    }

    g_free(l1_table);

    return 0;

fail:

    g_free(l1_table);

    return ret;

}


static uint32_t dcr_read_pob (void *opaque, int dcrn)

{

    ppc4xx_pob_t *pob;

    uint32_t ret;

    pob = opaque;

    switch (dcrn) {

    case POB0_BEAR:

        ret = pob->bear;

        break;

    case POB0_BESR0:

    case POB0_BESR1:

        ret = pob->besr[dcrn - POB0_BESR0];

        break;

    default:

        /* Avoid gcc warning */

        ret = 0;

        break;

    }

    return ret;

}


static inline int onenand_erase(OneNANDState *s, int sec, int num)

{

    uint8_t *blankbuf, *tmpbuf;

    blankbuf = g_malloc(512);

    if (!blankbuf) {

        return 1;

    }

    tmpbuf = g_malloc(512);

    if (!tmpbuf) {

        g_free(blankbuf);

        return 1;

    }

    memset(blankbuf, 0xff, 512);

    for (; num > 0; num--, sec++) {

        if (s->bdrv_cur) {

            int erasesec = s->secs_cur + (sec >> 5);

            if (bdrv_write(s->bdrv_cur, sec, blankbuf, 1) < 0) {

                goto fail;

            }

            if (bdrv_read(s->bdrv_cur, erasesec, tmpbuf, 1) < 0) {

                goto fail;

            }

            memcpy(tmpbuf + ((sec & 31) << 4), blankbuf, 1 << 4);

            if (bdrv_write(s->bdrv_cur, erasesec, tmpbuf, 1) < 0) {

                goto fail;

            }

        } else {

            if (sec + 1 > s->secs_cur) {

                goto fail;

            }

            memcpy(s->current + (sec << 9), blankbuf, 512);

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

                   blankbuf, 1 << 4);

        }

    }

    g_free(tmpbuf);

    g_free(blankbuf);

    return 0;

fail:

    g_free(tmpbuf);

    g_free(blankbuf);

    return 1;

}


static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,

                              const char *desc_file_path, Error **errp)

{

    int ret;

    char access[11];

    char type[11];

    char fname[512];

    const char *p = desc;

    int64_t sectors = 0;

    int64_t flat_offset;

    char extent_path[PATH_MAX];

    BlockDriverState *extent_file;

    BDRVVmdkState *s = bs->opaque;

    VmdkExtent *extent;

    while (*p) {

        /* parse extent line:

         * RW [size in sectors] FLAT "file-name.vmdk" OFFSET

         * or

         * RW [size in sectors] SPARSE "file-name.vmdk"

         */

        flat_offset = -1;

        ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,

                access, &sectors, type, fname, &flat_offset);

        if (ret < 4 || strcmp(access, "RW")) {

            goto next_line;

        } else if (!strcmp(type, "FLAT")) {

            if (ret != 5 || flat_offset < 0) {

                error_setg(errp, "Invalid extent lines: \n%s", p);

                return -EINVAL;

            }

        } else if (!strcmp(type, "VMFS")) {

            if (ret == 4) {

                flat_offset = 0;

            } else {

                error_setg(errp, "Invalid extent lines:\n%s", p);

                return -EINVAL;

            }

        } else if (ret != 4) {

            error_setg(errp, "Invalid extent lines:\n%s", p);

            return -EINVAL;

        }

        if (sectors <= 0 ||

            (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&

             strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||

            (strcmp(access, "RW"))) {

            goto next_line;

        }

        path_combine(extent_path, sizeof(extent_path),

                desc_file_path, fname);

        extent_file = NULL;

        ret = bdrv_open(&extent_file, extent_path, NULL, NULL,

                        bs->open_flags | BDRV_O_PROTOCOL, NULL, errp);

        if (ret) {

            return ret;

        }

        /* save to extents array */

        if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {

            /* FLAT extent */

            ret = vmdk_add_extent(bs, extent_file, true, sectors,

                            0, 0, 0, 0, 0, &extent, errp);

            if (ret < 0) {

                return ret;

            }

            extent->flat_start_offset = flat_offset << 9;

        } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {

            /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/

            char *buf = vmdk_read_desc(extent_file, 0, errp);

            if (!buf) {

                ret = -EINVAL;

            } else {

                ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf, errp);

            }

            if (ret) {

                g_free(buf);

                return ret;

            }

            extent = &s->extents[s->num_extents - 1];

        } else {

            error_setg(errp, "Unsupported extent type '%s'", type);

            return -ENOTSUP;

        }

        extent->type = g_strdup(type);

next_line:

        /* move to next line */

        while (*p) {

            if (*p == '\n') {

                p++;

                break;

            }

            p++;

        }

    }

    return 0;

}


static int default_lockmgr_cb(void **arg, enum AVLockOp op)

{

    void * volatile * mutex = arg;

    int err;

    switch (op) {

    case AV_LOCK_CREATE:

        return 0;

    case AV_LOCK_OBTAIN:

        if (!*mutex) {

            pthread_mutex_t *tmp = av_malloc(sizeof(pthread_mutex_t));

            if (!tmp)

                return AVERROR(ENOMEM);

            if ((err = pthread_mutex_init(tmp, NULL))) {

                av_free(tmp);

                return AVERROR(err);

            }

            if (avpriv_atomic_ptr_cas(mutex, NULL, tmp)) {

                pthread_mutex_destroy(tmp);

                av_free(tmp);

            }

        }

        if ((err = pthread_mutex_lock(*mutex)))

            return AVERROR(err);

        return 0;

    case AV_LOCK_RELEASE:

        if ((err = pthread_mutex_unlock(*mutex)))

            return AVERROR(err);

        return 0;

    case AV_LOCK_DESTROY:

        if (*mutex)

            pthread_mutex_destroy(*mutex);

        av_free(*mutex);

        avpriv_atomic_ptr_cas(mutex, *mutex, NULL);

        return 0;

    }

    return 1;

}


static inline int check_input_motion(MpegEncContext * s, int mb_x, int mb_y, int p_type){

    MotionEstContext * const c= &s->me;

    Picture *p= s->current_picture_ptr;

    int mb_xy= mb_x + mb_y*s->mb_stride;

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

    int mb_type= s->current_picture.mb_type[mb_xy];

    int flags= c->flags;

    int shift= (flags&FLAG_QPEL) + 1;

    int mask= (1<<shift)-1;

    int x, y, i;

    int d=0;

    me_cmp_func cmpf= s->dsp.sse[0];

    me_cmp_func chroma_cmpf= s->dsp.sse[1];

    assert(p_type==0 || !USES_LIST(mb_type, 1));

    assert(IS_INTRA(mb_type) || USES_LIST(mb_type,0) || USES_LIST(mb_type,1));

    if(IS_INTERLACED(mb_type)){

        int xy2= xy  + s->b8_stride;

        s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTRA;

        c->stride<<=1;

        c->uvstride<<=1;

        init_interlaced_ref(s, 2);

        assert(s->flags & CODEC_FLAG_INTERLACED_ME);

        if(USES_LIST(mb_type, 0)){

            int field_select0= p->ref_index[0][xy ];

            int field_select1= p->ref_index[0][xy2];

            assert(field_select0==0 ||field_select0==1);

            assert(field_select1==0 ||field_select1==1);

            if(p_type){

                s->p_field_select_table[0][mb_xy]= field_select0;

                s->p_field_select_table[1][mb_xy]= field_select1;

                *(uint32_t*)s->p_field_mv_table[0][field_select0][mb_xy]= *(uint32_t*)p->motion_val[0][xy ];

                *(uint32_t*)s->p_field_mv_table[1][field_select1][mb_xy]= *(uint32_t*)p->motion_val[0][xy2];

                s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTER_I;

            }else{

                s->b_field_select_table[0][0][mb_xy]= field_select0;

                s->b_field_select_table[0][1][mb_xy]= field_select1;

                *(uint32_t*)s->b_field_mv_table[0][0][field_select0][mb_xy]= *(uint32_t*)p->motion_val[0][xy ];

                *(uint32_t*)s->b_field_mv_table[0][1][field_select1][mb_xy]= *(uint32_t*)p->motion_val[0][xy2];

                s->mb_type[mb_xy]= CANDIDATE_MB_TYPE_FORWARD_I;

            }

            x= p->motion_val[0][xy ][0];

            y= p->motion_val[0][xy ][1];

            d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select0, 0, cmpf, chroma_cmpf, flags);

            x= p->motion_val[0][xy2][0];

            y= p->motion_val[0][xy2][1];

            d+= cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select1, 1, cmpf, chroma_cmpf, flags);

        }

        if(USES_LIST(mb_type, 1)){

            int field_select0= p->ref_index[1][xy ];

            int field_select1= p->ref_index[1][xy2];

            assert(field_select0==0 ||field_select0==1);

            assert(field_select1==0 ||field_select1==1);

            s->b_field_select_table[1][0][mb_xy]= field_select0;

            s->b_field_select_table[1][1][mb_xy]= field_select1;

            *(uint32_t*)s->b_field_mv_table[1][0][field_select0][mb_xy]= *(uint32_t*)p->motion_val[1][xy ];

            *(uint32_t*)s->b_field_mv_table[1][1][field_select1][mb_xy]= *(uint32_t*)p->motion_val[1][xy2];

            if(USES_LIST(mb_type, 0)){

                s->mb_type[mb_xy]= CANDIDATE_MB_TYPE_BIDIR_I;

            }else{

                s->mb_type[mb_xy]= CANDIDATE_MB_TYPE_BACKWARD_I;

            }

            x= p->motion_val[1][xy ][0];

            y= p->motion_val[1][xy ][1];

            d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select0+2, 0, cmpf, chroma_cmpf, flags);

            x= p->motion_val[1][xy2][0];

            y= p->motion_val[1][xy2][1];

            d+= cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select1+2, 1, cmpf, chroma_cmpf, flags);

            //FIXME bidir scores

        }

        c->stride>>=1;

        c->uvstride>>=1;

    }else if(IS_8X8(mb_type)){

        cmpf= s->dsp.sse[1];

        chroma_cmpf= s->dsp.sse[1];

        init_mv4_ref(s);

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

            xy= s->block_index[i];

            x= p->motion_val[0][xy][0];

            y= p->motion_val[0][xy][1];

            d+= cmp(s, x>>shift, y>>shift, x&mask, y&mask, 1, 8, i, i, cmpf, chroma_cmpf, flags);

        }

        s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTER4V;

    }else{

        if(USES_LIST(mb_type, 0)){

            if(p_type){

                *(uint32_t*)s->p_mv_table[mb_xy]= *(uint32_t*)p->motion_val[0][xy];

                s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTER;

            }else if(USES_LIST(mb_type, 1)){

                *(uint32_t*)s->b_bidir_forw_mv_table[mb_xy]= *(uint32_t*)p->motion_val[0][xy];

                *(uint32_t*)s->b_bidir_back_mv_table[mb_xy]= *(uint32_t*)p->motion_val[1][xy];

                s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_BIDIR;

            }else{

                *(uint32_t*)s->b_forw_mv_table[mb_xy]= *(uint32_t*)p->motion_val[0][xy];

                s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_FORWARD;

            }

            x= p->motion_val[0][xy][0];

            y= p->motion_val[0][xy][1];

            d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 16, 0, 0, cmpf, chroma_cmpf, flags);

        }else if(USES_LIST(mb_type, 1)){

            *(uint32_t*)s->b_back_mv_table[mb_xy]= *(uint32_t*)p->motion_val[1][xy];

            s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_BACKWARD;

            x= p->motion_val[1][xy][0];

            y= p->motion_val[1][xy][1];

            d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 16, 2, 0, cmpf, chroma_cmpf, flags);

        }else

            s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTRA;

    }

    return d;

}


void ff_estimate_p_frame_motion(MpegEncContext * s,

                                int mb_x, int mb_y)

{

    UINT8 *pix, *ppix;

    int sum, varc, vard, mx, my, range, dmin, xx, yy;

    int xmin, ymin, xmax, ymax;

    int rel_xmin, rel_ymin, rel_xmax, rel_ymax;

    int pred_x=0, pred_y=0;

    int P[6][2];

    const int shift= 1+s->quarter_sample;

    int mb_type=0;

    uint8_t *ref_picture= s->last_picture[0];

    get_limits(s, &range, &xmin, &ymin, &xmax, &ymax, s->f_code);

    switch(s->me_method) {

    case ME_ZERO:

    default:

	no_motion_search(s, &mx, &my);

        dmin = 0;

        break;

    case ME_FULL:

	dmin = full_motion_search(s, &mx, &my, range, xmin, ymin, xmax, ymax, ref_picture);

        break;

    case ME_LOG:

	dmin = log_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax, ref_picture);

        break;

    case ME_PHODS:

	dmin = phods_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax, ref_picture);

        break;

    case ME_X1:

    case ME_EPZS:

       {

            const int mot_stride = s->block_wrap[0];

            const int mot_xy = s->block_index[0];

            rel_xmin= xmin - mb_x*16;

            rel_xmax= xmax - mb_x*16;

            rel_ymin= ymin - mb_y*16;

            rel_ymax= ymax - mb_y*16;

            P[0][0] = s->motion_val[mot_xy    ][0];

            P[0][1] = s->motion_val[mot_xy    ][1];

            P[1][0] = s->motion_val[mot_xy - 1][0];

            P[1][1] = s->motion_val[mot_xy - 1][1];

            if(P[1][0] > (rel_xmax<<shift)) P[1][0]= (rel_xmax<<shift);

            /* special case for first line */

            if ((mb_y == 0 || s->first_slice_line || s->first_gob_line)) {

                P[4][0] = P[1][0];

                P[4][1] = P[1][1];

            } else {

                P[2][0] = s->motion_val[mot_xy - mot_stride             ][0];

                P[2][1] = s->motion_val[mot_xy - mot_stride             ][1];

                P[3][0] = s->motion_val[mot_xy - mot_stride + 2         ][0];

                P[3][1] = s->motion_val[mot_xy - mot_stride + 2         ][1];

                if(P[2][1] > (rel_ymax<<shift)) P[2][1]= (rel_ymax<<shift);

                if(P[3][0] < (rel_xmin<<shift)) P[3][0]= (rel_xmin<<shift);

                if(P[3][1] > (rel_ymax<<shift)) P[3][1]= (rel_ymax<<shift);

                P[4][0]= mid_pred(P[1][0], P[2][0], P[3][0]);

                P[4][1]= mid_pred(P[1][1], P[2][1], P[3][1]);

            }

            if(s->out_format == FMT_H263){

                pred_x = P[4][0];

                pred_y = P[4][1];

            }else { /* mpeg1 at least */

                pred_x= P[1][0];

                pred_y= P[1][1];

            }

        }

        dmin = epzs_motion_search(s, &mx, &my, P, pred_x, pred_y, rel_xmin, rel_ymin, rel_xmax, rel_ymax, ref_picture);

        mx+= mb_x*16;

        my+= mb_y*16;

        break;

    }

    if(s->flags&CODEC_FLAG_4MV){

        int block;

        mb_type|= MB_TYPE_INTER4V;

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

            int mx4, my4;

            int pred_x4, pred_y4;

            int dmin4;

            static const int off[4]= {2, 1, 1, -1};

            const int mot_stride = s->block_wrap[0];

            const int mot_xy = s->block_index[block];

            const int block_x= mb_x*2 + (block&1);

            const int block_y= mb_y*2 + (block>>1);

            const int rel_xmin4= xmin - block_x*8;

            const int rel_xmax4= xmax - block_x*8 + 8;

            const int rel_ymin4= ymin - block_y*8;

            const int rel_ymax4= ymax - block_y*8 + 8;

            P[0][0] = s->motion_val[mot_xy    ][0];

            P[0][1] = s->motion_val[mot_xy    ][1];

            P[1][0] = s->motion_val[mot_xy - 1][0];

            P[1][1] = s->motion_val[mot_xy - 1][1];

            if(P[1][0] > (rel_xmax4<<shift)) P[1][0]= (rel_xmax4<<shift);

            /* special case for first line */

            if ((mb_y == 0 || s->first_slice_line || s->first_gob_line) && block<2) {

                P[4][0] = P[1][0];

                P[4][1] = P[1][1];

            } else {

                P[2][0] = s->motion_val[mot_xy - mot_stride             ][0];

                P[2][1] = s->motion_val[mot_xy - mot_stride             ][1];

                P[3][0] = s->motion_val[mot_xy - mot_stride + off[block]][0];

                P[3][1] = s->motion_val[mot_xy - mot_stride + off[block]][1];

                if(P[2][1] > (rel_ymax4<<shift)) P[2][1]= (rel_ymax4<<shift);

                if(P[3][0] < (rel_xmin4<<shift)) P[3][0]= (rel_xmin4<<shift);

                if(P[3][0] > (rel_xmax4<<shift)) P[3][0]= (rel_xmax4<<shift);

                if(P[3][1] > (rel_ymax4<<shift)) P[3][1]= (rel_ymax4<<shift);

                P[4][0]= mid_pred(P[1][0], P[2][0], P[3][0]);

                P[4][1]= mid_pred(P[1][1], P[2][1], P[3][1]);

            }

            if(s->out_format == FMT_H263){

                pred_x4 = P[4][0];

                pred_y4 = P[4][1];

            }else { /* mpeg1 at least */

                pred_x4= P[1][0];

                pred_y4= P[1][1];

            }

            P[5][0]= mx - mb_x*16;

            P[5][1]= my - mb_y*16;

            dmin4 = epzs_motion_search4(s, block, &mx4, &my4, P, pred_x4, pred_y4, rel_xmin4, rel_ymin4, rel_xmax4, rel_ymax4, ref_picture);

            halfpel_motion_search4(s, &mx4, &my4, dmin4, rel_xmin4, rel_ymin4, rel_xmax4, rel_ymax4,

                                   pred_x4, pred_y4, block_x, block_y, ref_picture);

            s->motion_val[ s->block_index[block] ][0]= mx4;

            s->motion_val[ s->block_index[block] ][1]= my4;

        }

    }

    /* intra / predictive decision */

    xx = mb_x * 16;

    yy = mb_y * 16;

    pix = s->new_picture[0] + (yy * s->linesize) + xx;

    /* At this point (mx,my) are full-pell and the absolute displacement */

    ppix = ref_picture + (my * s->linesize) + mx;

    sum = pix_sum(pix, s->linesize);

#if 0

    varc = pix_dev(pix, s->linesize, (sum+128)>>8) + INTER_BIAS;

    vard = pix_abs16x16(pix, ppix, s->linesize);

#else

    sum= (sum+8)>>4;

    varc = ((pix_norm1(pix, s->linesize) - sum*sum + 128 + 500)>>8);

    vard = (pix_norm(pix, ppix, s->linesize)+128)>>8;

#endif

    s->mb_var[s->mb_width * mb_y + mb_x] = varc;

    s->avg_mb_var+= varc;

    s->mc_mb_var += vard;

#if 0

    printf("varc=%4d avg_var=%4d (sum=%4d) vard=%4d mx=%2d my=%2d\n",

	   varc, s->avg_mb_var, sum, vard, mx - xx, my - yy);

#endif

    if(s->flags&CODEC_FLAG_HQ){

        if (vard*2 + 200 > varc)

            mb_type|= MB_TYPE_INTRA;

        if (varc*2 + 200 > vard){

            mb_type|= MB_TYPE_INTER;

            halfpel_motion_search(s, &mx, &my, dmin, xmin, ymin, xmax, ymax, pred_x, pred_y, ref_picture);

        }else{

            mx = mx*2 - mb_x*32;

            my = my*2 - mb_y*32;

        }

    }else{

        if (vard <= 64 || vard < varc) {

            mb_type|= MB_TYPE_INTER;

            if (s->me_method != ME_ZERO) {

                halfpel_motion_search(s, &mx, &my, dmin, xmin, ymin, xmax, ymax, pred_x, pred_y, ref_picture);

            } else {

                mx -= 16 * mb_x;

                my -= 16 * mb_y;

            }

#if 0

            if (vard < 10) {

                skip++;

                fprintf(stderr,"\nEarly skip: %d vard: %2d varc: %5d dmin: %d",

                                skip, vard, varc, dmin);

            }

#endif

        }else{

            mb_type|= MB_TYPE_INTRA;

            mx = 0;//mx*2 - 32 * mb_x;

            my = 0;//my*2 - 32 * mb_y;

        }

    }

    s->mb_type[mb_y*s->mb_width + mb_x]= mb_type;

    set_p_mv_tables(s, mx, my);

}


av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)

{

    VAAPIEncodeContext *ctx = avctx->priv_data;

    VAAPIEncodePicture *pic, *next;

    for (pic = ctx->pic_start; pic; pic = next) {

        next = pic->next;

        vaapi_encode_free(avctx, pic);

    }

    if (ctx->va_context != VA_INVALID_ID) {

        vaDestroyContext(ctx->hwctx->display, ctx->va_context);

        ctx->va_context = VA_INVALID_ID;

    }

    if (ctx->va_config != VA_INVALID_ID) {

        vaDestroyConfig(ctx->hwctx->display, ctx->va_config);

        ctx->va_config = VA_INVALID_ID;

    }

    if (ctx->codec->close)

        ctx->codec->close(avctx);

    av_buffer_pool_uninit(&ctx->output_buffer_pool);

    av_freep(&ctx->codec_sequence_params);

    av_freep(&ctx->codec_picture_params);

    av_buffer_unref(&ctx->recon_frames_ref);

    av_buffer_unref(&ctx->input_frames_ref);

    av_buffer_unref(&ctx->device_ref);

    av_freep(&ctx->priv_data);

    return 0;

}


static ssize_t socket_read(int sockfd, void *buff, size_t size)

{

    ssize_t retval, total = 0;

    while (size) {

        retval = read(sockfd, buff, size);

        if (retval == 0) {

            return -EIO;

        }

        if (retval < 0) {

            if (errno == EINTR) {

                continue;

            }

            return -errno;

        }

        size -= retval;

        buff += retval;

        total += retval;

    }

    return total;

}


AioContext *blk_get_aio_context(BlockBackend *blk)

{

    return bdrv_get_aio_context(blk->bs);

}


static int vfio_load_rom(VFIODevice *vdev)

{

    uint64_t size = vdev->rom_size;

    char name[32];

    off_t off = 0, voff = vdev->rom_offset;

    ssize_t bytes;

    void *ptr;

    /* If loading ROM from file, pci handles it */

    if (vdev->pdev.romfile || !vdev->pdev.rom_bar || !size) {

        return 0;

    }

    DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,

            vdev->host.bus, vdev->host.slot, vdev->host.function);

    snprintf(name, sizeof(name), "vfio[%04x:%02x:%02x.%x].rom",

             vdev->host.domain, vdev->host.bus, vdev->host.slot,

             vdev->host.function);

    memory_region_init_ram(&vdev->pdev.rom, OBJECT(vdev), name, size);

    ptr = memory_region_get_ram_ptr(&vdev->pdev.rom);

    memset(ptr, 0xff, size);

    while (size) {

        bytes = pread(vdev->fd, ptr + off, size, voff + off);

        if (bytes == 0) {

            break; /* expect that we could get back less than the ROM BAR */

        } else if (bytes > 0) {

            off += bytes;

            size -= bytes;

        } else {

            if (errno == EINTR || errno == EAGAIN) {

                continue;

            }

            error_report("vfio: Error reading device ROM: %m");

            memory_region_destroy(&vdev->pdev.rom);

            return -errno;

        }

    }

    pci_register_bar(&vdev->pdev, PCI_ROM_SLOT, 0, &vdev->pdev.rom);

    vdev->pdev.has_rom = true;

    return 0;

}


UuidInfo *qmp_query_uuid(Error **errp)

{

    UuidInfo *info = g_malloc0(sizeof(*info));

    char uuid[64];

    snprintf(uuid, sizeof(uuid), UUID_FMT, qemu_uuid[0], qemu_uuid[1],

                   qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],

                   qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],

                   qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],

                   qemu_uuid[14], qemu_uuid[15]);

    info->UUID = g_strdup(uuid);

    return info;

}


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

                             int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size;

    MPCContext *c = avctx->priv_data;

    GetBitContext gb;

    int i, ch;

    int mb = -1;

    Band *bands = c->bands;

    int off, ret, last_frame, skip;

    int bits_used, bits_avail;

    memset(bands, 0, sizeof(*bands) * (c->maxbands + 1));

    buf_size = avpkt->size & ~3;

    if (buf_size <= 0) {

        av_log(avctx, AV_LOG_ERROR, "packet size is too small (%i bytes)\n",

               avpkt->size);

        return AVERROR_INVALIDDATA;

    }

    if (buf_size != avpkt->size) {

        av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "

               "extra bytes at the end will be skipped.\n");

    }

    skip       = buf[0];

    last_frame = buf[1];

    buf       += 4;

    buf_size  -= 4;

    /* get output buffer */

    c->frame.nb_samples = last_frame ? c->lastframelen : MPC_FRAME_SIZE;

    if ((ret = avctx->get_buffer(avctx, &c->frame)) < 0) {

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

        return ret;

    }

    av_fast_padded_malloc(&c->bits, &c->buf_size, buf_size);

    if (!c->bits)

        return AVERROR(ENOMEM);

    c->dsp.bswap_buf((uint32_t *)c->bits, (const uint32_t *)buf, buf_size >> 2);

    init_get_bits(&gb, c->bits, buf_size * 8);

    skip_bits_long(&gb, skip);

    /* read subband indexes */

    for(i = 0; i <= c->maxbands; i++){

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

            int t = 4;

            if(i) t = get_vlc2(&gb, hdr_vlc.table, MPC7_HDR_BITS, 1) - 5;

            if(t == 4) bands[i].res[ch] = get_bits(&gb, 4);

            else bands[i].res[ch] = bands[i-1].res[ch] + t;

        }

        if(bands[i].res[0] || bands[i].res[1]){

            mb = i;

            if(c->MSS) bands[i].msf = get_bits1(&gb);

        }

    }

    /* get scale indexes coding method */

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

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

            if(bands[i].res[ch]) bands[i].scfi[ch] = get_vlc2(&gb, scfi_vlc.table, MPC7_SCFI_BITS, 1);

    /* get scale indexes */

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

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

            if(bands[i].res[ch]){

                bands[i].scf_idx[ch][2] = c->oldDSCF[ch][i];

                bands[i].scf_idx[ch][0] = get_scale_idx(&gb, bands[i].scf_idx[ch][2]);

                switch(bands[i].scfi[ch]){

                case 0:

                    bands[i].scf_idx[ch][1] = get_scale_idx(&gb, bands[i].scf_idx[ch][0]);

                    bands[i].scf_idx[ch][2] = get_scale_idx(&gb, bands[i].scf_idx[ch][1]);

                    break;

                case 1:

                    bands[i].scf_idx[ch][1] = get_scale_idx(&gb, bands[i].scf_idx[ch][0]);

                    bands[i].scf_idx[ch][2] = bands[i].scf_idx[ch][1];

                    break;

                case 2:

                    bands[i].scf_idx[ch][1] = bands[i].scf_idx[ch][0];

                    bands[i].scf_idx[ch][2] = get_scale_idx(&gb, bands[i].scf_idx[ch][1]);

                    break;

                case 3:

                    bands[i].scf_idx[ch][2] = bands[i].scf_idx[ch][1] = bands[i].scf_idx[ch][0];

                    break;

                }

                c->oldDSCF[ch][i] = bands[i].scf_idx[ch][2];

            }

        }

    }

    /* get quantizers */

    memset(c->Q, 0, sizeof(c->Q));

    off = 0;

    for(i = 0; i < BANDS; i++, off += SAMPLES_PER_BAND)

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

            idx_to_quant(c, &gb, bands[i].res[ch], c->Q[ch] + off);

    ff_mpc_dequantize_and_synth(c, mb, c->frame.data[0], 2);

    bits_used = get_bits_count(&gb);

    bits_avail = buf_size * 8;

    if (!last_frame && ((bits_avail < bits_used) || (bits_used + 32 <= bits_avail))) {

        av_log(avctx, AV_LOG_ERROR, "Error decoding frame: used %i of %i bits\n", bits_used, bits_avail);

        return -1;

    }

    if(c->frames_to_skip){

        c->frames_to_skip--;

        *got_frame_ptr = 0;

        return avpkt->size;

    }

    *got_frame_ptr   = 1;

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

    return avpkt->size;

}


static int rle_unpack(const unsigned char *src, int src_len, int src_count,

                      unsigned char *dest, int dest_len)

{

    const unsigned char *ps;

    const unsigned char *ps_end;

    unsigned char *pd;

    int i, l;

    unsigned char *dest_end = dest + dest_len;

    ps = src;

    ps_end = src + src_len;

    pd = dest;

    if (src_count & 1) {

        if (ps_end - ps < 1)

            return 0;

        *pd++ = *ps++;

    }

    src_count >>= 1;

    i = 0;

    do {

        if (ps_end - ps < 1)

            break;

        l = *ps++;

        if (l & 0x80) {

            l = (l & 0x7F) * 2;

            if (pd + l > dest_end || ps_end - ps < l)

                return ps - src;

            memcpy(pd, ps, l);

            ps += l;

            pd += l;

        } else {

            if (pd + i > dest_end || ps_end - ps < 2)

                return ps - src;

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

                *pd++ = ps[0];

                *pd++ = ps[1];

            }

            ps += 2;

        }

        i += l;

    } while (i < src_count);

    return ps - src;

}


int vc1_decode_sequence_header(AVCodecContext *avctx, VC1Context *v, GetBitContext *gb)

{

    av_log(avctx, AV_LOG_DEBUG, "Header: %0X\n", show_bits(gb, 32));

    v->profile = get_bits(gb, 2);

    if (v->profile == PROFILE_COMPLEX)

    {

        av_log(avctx, AV_LOG_WARNING, "WMV3 Complex Profile is not fully supported\n");

    }

    if (v->profile == PROFILE_ADVANCED)

    {

        v->zz_8x4 = ff_vc1_adv_progressive_8x4_zz;

        v->zz_4x8 = ff_vc1_adv_progressive_4x8_zz;

        return decode_sequence_header_adv(v, gb);

    }

    else

    {

        v->zz_8x4 = wmv2_scantableA;

        v->zz_4x8 = wmv2_scantableB;

        v->res_y411   = get_bits1(gb);

        v->res_sprite = get_bits1(gb);

        if (v->res_y411)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "Old interlaced mode is not supported\n");

            return -1;

        }

        if (v->res_sprite) {

            av_log(avctx, AV_LOG_ERROR, "WMVP is not fully supported\n");

        }

    }

    // (fps-2)/4 (->30)

    v->frmrtq_postproc = get_bits(gb, 3); //common

    // (bitrate-32kbps)/64kbps

    v->bitrtq_postproc = get_bits(gb, 5); //common

    v->s.loop_filter = get_bits1(gb); //common

    if(v->s.loop_filter == 1 && v->profile == PROFILE_SIMPLE)

    {

        av_log(avctx, AV_LOG_ERROR,

               "LOOPFILTER shall not be enabled in Simple Profile\n");

    }

    if(v->s.avctx->skip_loop_filter >= AVDISCARD_ALL)

        v->s.loop_filter = 0;

    v->res_x8 = get_bits1(gb); //reserved

    v->multires = get_bits1(gb);

    v->res_fasttx = get_bits1(gb);

    if (!v->res_fasttx)

    {

        v->vc1dsp.vc1_inv_trans_8x8 = ff_simple_idct_8;

        v->vc1dsp.vc1_inv_trans_8x4 = ff_simple_idct84_add;

        v->vc1dsp.vc1_inv_trans_4x8 = ff_simple_idct48_add;

        v->vc1dsp.vc1_inv_trans_4x4 = ff_simple_idct44_add;

        v->vc1dsp.vc1_inv_trans_8x8_dc = ff_simple_idct_add_8;

        v->vc1dsp.vc1_inv_trans_8x4_dc = ff_simple_idct84_add;

        v->vc1dsp.vc1_inv_trans_4x8_dc = ff_simple_idct48_add;

        v->vc1dsp.vc1_inv_trans_4x4_dc = ff_simple_idct44_add;

    }

    v->fastuvmc =  get_bits1(gb); //common

    if (!v->profile && !v->fastuvmc)

    {

        av_log(avctx, AV_LOG_ERROR,

               "FASTUVMC unavailable in Simple Profile\n");

        return -1;

    }

    v->extended_mv =  get_bits1(gb); //common

    if (!v->profile && v->extended_mv)

    {

        av_log(avctx, AV_LOG_ERROR,

               "Extended MVs unavailable in Simple Profile\n");

        return -1;

    }

    v->dquant =  get_bits(gb, 2); //common

    v->vstransform =  get_bits1(gb); //common

    v->res_transtab = get_bits1(gb);

    if (v->res_transtab)

    {

        av_log(avctx, AV_LOG_ERROR,

               "1 for reserved RES_TRANSTAB is forbidden\n");

        return -1;

    }

    v->overlap = get_bits1(gb); //common

    v->s.resync_marker = get_bits1(gb);

    v->rangered = get_bits1(gb);

    if (v->rangered && v->profile == PROFILE_SIMPLE)

    {

        av_log(avctx, AV_LOG_INFO,

               "RANGERED should be set to 0 in Simple Profile\n");

    }

    v->s.max_b_frames = avctx->max_b_frames = get_bits(gb, 3); //common

    v->quantizer_mode = get_bits(gb, 2); //common

    v->finterpflag = get_bits1(gb); //common

    if (v->res_sprite) {

        v->s.avctx->width  = v->s.avctx->coded_width  = get_bits(gb, 11);

        v->s.avctx->height = v->s.avctx->coded_height = get_bits(gb, 11);

        skip_bits(gb, 5); //frame rate

        v->res_x8 = get_bits1(gb);

        if (get_bits1(gb)) { // something to do with DC VLC selection

            av_log(avctx, AV_LOG_ERROR, "Unsupported sprite feature\n");

            return -1;

        }

        skip_bits(gb, 3); //slice code

        v->res_rtm_flag = 0;

    } else {

        v->res_rtm_flag = get_bits1(gb); //reserved

    }

    if (!v->res_rtm_flag)

    {

//            av_log(avctx, AV_LOG_ERROR,

//                   "0 for reserved RES_RTM_FLAG is forbidden\n");

        av_log(avctx, AV_LOG_ERROR,

               "Old WMV3 version detected, some frames may be decoded incorrectly\n");

        //return -1;

    }

    //TODO: figure out what they mean (always 0x402F)

    if(!v->res_fasttx) skip_bits(gb, 16);

    av_log(avctx, AV_LOG_DEBUG,

               "Profile %i:\nfrmrtq_postproc=%i, bitrtq_postproc=%i\n"

               "LoopFilter=%i, MultiRes=%i, FastUVMC=%i, Extended MV=%i\n"

               "Rangered=%i, VSTransform=%i, Overlap=%i, SyncMarker=%i\n"

               "DQuant=%i, Quantizer mode=%i, Max B frames=%i\n",

               v->profile, v->frmrtq_postproc, v->bitrtq_postproc,

               v->s.loop_filter, v->multires, v->fastuvmc, v->extended_mv,

               v->rangered, v->vstransform, v->overlap, v->s.resync_marker,

               v->dquant, v->quantizer_mode, avctx->max_b_frames

               );

    return 0;

}


static int s390_virtio_rng_init(VirtIOS390Device *s390_dev)

{

    VirtIORNGS390 *dev = VIRTIO_RNG_S390(s390_dev);

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

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

    if (qdev_init(vdev) < 0) {

        return -1;

    }

    object_property_set_link(OBJECT(dev),

                             OBJECT(dev->vdev.conf.default_backend), "rng",

                             NULL);

    return s390_virtio_device_init(s390_dev, VIRTIO_DEVICE(vdev));

}


static void apic_update_irq(APICState *s)

{

    int irrv, ppr;

    if (!(s->spurious_vec & APIC_SV_ENABLE))

        return;

    irrv = get_highest_priority_int(s->irr);

    if (irrv < 0)

        return;

    ppr = apic_get_ppr(s);

    if (ppr && (irrv & 0xf0) <= (ppr & 0xf0))

        return;

    cpu_interrupt(s->cpu_env, CPU_INTERRUPT_HARD);

}