static int overlay_opencl_blend(FFFrameSync *fs)

{

    AVFilterContext    *avctx = fs->parent;

    AVFilterLink     *outlink = avctx->outputs[0];

    OverlayOpenCLContext *ctx = avctx->priv;

    AVFrame *input_main, *input_overlay;

    AVFrame *output;

    cl_mem mem;

    cl_int cle, x, y;

    size_t global_work[2];

    int kernel_arg = 0;

    int err, plane;

    err = ff_framesync_get_frame(fs, 0, &input_main, 0);

    if (err < 0)

        return err;

    err = ff_framesync_get_frame(fs, 1, &input_overlay, 0);

    if (err < 0)

        return err;

    if (!ctx->initialised) {

        AVHWFramesContext *main_fc =

            (AVHWFramesContext*)input_main->hw_frames_ctx->data;

        AVHWFramesContext *overlay_fc =

            (AVHWFramesContext*)input_overlay->hw_frames_ctx->data;

        err = overlay_opencl_load(avctx, main_fc->sw_format,

                                  overlay_fc->sw_format);

        if (err < 0)

            return err;

    }

    output = ff_get_video_buffer(outlink, outlink->w, outlink->h);

    if (!output) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    for (plane = 0; plane < ctx->nb_planes; plane++) {

        kernel_arg = 0;

        mem = (cl_mem)output->data[plane];

        cle = clSetKernelArg(ctx->kernel, kernel_arg++, sizeof(cl_mem), &mem);

        if (cle != CL_SUCCESS)

            goto fail_kernel_arg;

        mem = (cl_mem)input_main->data[plane];

        cle = clSetKernelArg(ctx->kernel, kernel_arg++, sizeof(cl_mem), &mem);

        if (cle != CL_SUCCESS)

            goto fail_kernel_arg;

        mem = (cl_mem)input_overlay->data[plane];

        cle = clSetKernelArg(ctx->kernel, kernel_arg++, sizeof(cl_mem), &mem);

        if (cle != CL_SUCCESS)

            goto fail_kernel_arg;

        if (ctx->alpha_separate) {

            mem = (cl_mem)input_overlay->data[ctx->nb_planes];

            cle = clSetKernelArg(ctx->kernel, kernel_arg++, sizeof(cl_mem), &mem);

            if (cle != CL_SUCCESS)

                goto fail_kernel_arg;

        }

        x = ctx->x_position / (plane == 0 ? 1 : ctx->x_subsample);

        y = ctx->y_position / (plane == 0 ? 1 : ctx->y_subsample);

        cle = clSetKernelArg(ctx->kernel, kernel_arg++, sizeof(cl_int), &x);

        if (cle != CL_SUCCESS)

            goto fail_kernel_arg;

        cle = clSetKernelArg(ctx->kernel, kernel_arg++, sizeof(cl_int), &y);

        if (cle != CL_SUCCESS)

            goto fail_kernel_arg;

        if (ctx->alpha_separate) {

            cl_int alpha_adj_x = plane == 0 ? 1 : ctx->x_subsample;

            cl_int alpha_adj_y = plane == 0 ? 1 : ctx->y_subsample;

            cle = clSetKernelArg(ctx->kernel, kernel_arg++, sizeof(cl_int), &alpha_adj_x);

            if (cle != CL_SUCCESS)

                goto fail_kernel_arg;

            cle = clSetKernelArg(ctx->kernel, kernel_arg++, sizeof(cl_int), &alpha_adj_y);

            if (cle != CL_SUCCESS)

                goto fail_kernel_arg;

        }

        global_work[0] = output->width;

        global_work[1] = output->height;

        cle = clEnqueueNDRangeKernel(ctx->command_queue, ctx->kernel, 2, NULL,

                                     global_work, NULL, 0, NULL, NULL);

        if (cle != CL_SUCCESS) {

            av_log(avctx, AV_LOG_ERROR, "Failed to enqueue "

                   "overlay kernel for plane %d: %d.\n", cle, plane);

            err = AVERROR(EIO);

            goto fail;

        }

    }

    cle = clFinish(ctx->command_queue);

    if (cle != CL_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR, "Failed to finish "

               "command queue: %d.\n", cle);

        err = AVERROR(EIO);

        goto fail;

    }

    err = av_frame_copy_props(output, input_main);

    av_log(avctx, AV_LOG_DEBUG, "Filter output: %s, %ux%u (%"PRId64").\n",

           av_get_pix_fmt_name(output->format),

           output->width, output->height, output->pts);

    return ff_filter_frame(outlink, output);

fail_kernel_arg:

    av_log(avctx, AV_LOG_ERROR, "Failed to set kernel arg %d: %d.\n",

           kernel_arg, cle);

    err = AVERROR(EIO);

fail:

    return err;

}


static int oggvorbis_encode_frame(AVCodecContext *avccontext,

				  unsigned char *packets,

			   int buf_size, void *data)

{

    OggVorbisContext *context = avccontext->priv_data ;

    float **buffer ;

    ogg_packet op ;

    signed char *audio = data ;

    int l, samples = OGGVORBIS_FRAME_SIZE ;

    buffer = vorbis_analysis_buffer(&context->vd, samples) ;

    if(context->vi.channels == 1) {

	for(l = 0 ; l < samples ; l++)

	    buffer[0][l]=((audio[l*2+1]<<8)|(0x00ff&(int)audio[l*2]))/32768.f;

    } else {

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

	    buffer[0][l]=((audio[l*4+1]<<8)|(0x00ff&(int)audio[l*4]))/32768.f;

	    buffer[1][l]=((audio[l*4+3]<<8)|(0x00ff&(int)audio[l*4+2]))/32768.f;

	}

    }

    vorbis_analysis_wrote(&context->vd, samples) ;

    while(vorbis_analysis_blockout(&context->vd, &context->vb) == 1) {

	vorbis_analysis(&context->vb, NULL);

	vorbis_bitrate_addblock(&context->vb) ;

	while(vorbis_bitrate_flushpacket(&context->vd, &op)) {

            memcpy(context->buffer + context->buffer_index, &op, sizeof(ogg_packet));

            context->buffer_index += sizeof(ogg_packet);

            memcpy(context->buffer + context->buffer_index, op.packet, op.bytes);

            context->buffer_index += op.bytes;

//            av_log(avccontext, AV_LOG_DEBUG, "e%d / %d\n", context->buffer_index, op.bytes);

	}

    }

    if(context->buffer_index){

        ogg_packet *op2= (ogg_packet*)context->buffer;

        op2->packet = context->buffer + sizeof(ogg_packet);

        l=  op2->bytes;

        memcpy(packets, op2->packet, l);

        context->buffer_index -= l + sizeof(ogg_packet);

        memcpy(context->buffer, context->buffer + l + sizeof(ogg_packet), context->buffer_index);

//        av_log(avccontext, AV_LOG_DEBUG, "E%d\n", l);

        return l;

    }

    return 0;

}


static int mpegps_read_header(AVFormatContext *s)

{

    MpegDemuxContext *m = s->priv_data;

    char buffer[7];

    int64_t last_pos = avio_tell(s->pb);

    m->header_state = 0xff;

    s->ctx_flags   |= AVFMTCTX_NOHEADER;

    avio_get_str(s->pb, 6, buffer, sizeof(buffer));

    if (!memcmp("IMKH", buffer, 4)) {

        m->imkh_cctv = 1;

    } else if (!memcmp("Sofdec", buffer, 6)) {

        m->sofdec = 1;

    } else

       avio_seek(s->pb, last_pos, SEEK_SET);

    /* no need to do more */

    return 0;

}


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

                            int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MLPDecodeContext *m = avctx->priv_data;

    GetBitContext gb;

    unsigned int length, substr;

    unsigned int substream_start;

    unsigned int header_size = 4;

    unsigned int substr_header_size = 0;

    uint8_t substream_parity_present[MAX_SUBSTREAMS];

    uint16_t substream_data_len[MAX_SUBSTREAMS];

    uint8_t parity_bits;

    int ret;

    if (buf_size < 4)

        return 0;

    length = (AV_RB16(buf) & 0xfff) * 2;

    if (length < 4 || length > buf_size)

        return AVERROR_INVALIDDATA;

    init_get_bits(&gb, (buf + 4), (length - 4) * 8);

    m->is_major_sync_unit = 0;

    if (show_bits_long(&gb, 31) == (0xf8726fba >> 1)) {

        if (read_major_sync(m, &gb) < 0)

            goto error;

        m->is_major_sync_unit = 1;

        header_size += 28;

    }

    if (!m->params_valid) {

        av_log(m->avctx, AV_LOG_WARNING,

               "Stream parameters not seen; skipping frame.\n");

        *got_frame_ptr = 0;

        return length;

    }

    substream_start = 0;

    for (substr = 0; substr < m->num_substreams; substr++) {

        int extraword_present, checkdata_present, end, nonrestart_substr;

        extraword_present = get_bits1(&gb);

        nonrestart_substr = get_bits1(&gb);

        checkdata_present = get_bits1(&gb);

        skip_bits1(&gb);

        end = get_bits(&gb, 12) * 2;

        substr_header_size += 2;

        if (extraword_present) {

            if (m->avctx->codec_id == AV_CODEC_ID_MLP) {

                av_log(m->avctx, AV_LOG_ERROR, "There must be no extraword for MLP.\n");

                goto error;

            }

            skip_bits(&gb, 16);

            substr_header_size += 2;

        }

        if (!(nonrestart_substr ^ m->is_major_sync_unit)) {

            av_log(m->avctx, AV_LOG_ERROR, "Invalid nonrestart_substr.\n");

            goto error;

        }

        if (end + header_size + substr_header_size > length) {

            av_log(m->avctx, AV_LOG_ERROR,

                   "Indicated length of substream %d data goes off end of "

                   "packet.\n", substr);

            end = length - header_size - substr_header_size;

        }

        if (end < substream_start) {

            av_log(avctx, AV_LOG_ERROR,

                   "Indicated end offset of substream %d data "

                   "is smaller than calculated start offset.\n",

                   substr);

            goto error;

        }

        if (substr > m->max_decoded_substream)

            continue;

        substream_parity_present[substr] = checkdata_present;

        substream_data_len[substr] = end - substream_start;

        substream_start = end;

    }

    parity_bits  = ff_mlp_calculate_parity(buf, 4);

    parity_bits ^= ff_mlp_calculate_parity(buf + header_size, substr_header_size);

    if ((((parity_bits >> 4) ^ parity_bits) & 0xF) != 0xF) {

        av_log(avctx, AV_LOG_ERROR, "Parity check failed.\n");

        goto error;

    }

    buf += header_size + substr_header_size;

    for (substr = 0; substr <= m->max_decoded_substream; substr++) {

        SubStream *s = &m->substream[substr];

        init_get_bits(&gb, buf, substream_data_len[substr] * 8);

        m->matrix_changed = 0;

        memset(m->filter_changed, 0, sizeof(m->filter_changed));

        s->blockpos = 0;

        do {

            if (get_bits1(&gb)) {

                if (get_bits1(&gb)) {

                    /* A restart header should be present. */

                    if (read_restart_header(m, &gb, buf, substr) < 0)

                        goto next_substr;

                    s->restart_seen = 1;

                }

                if (!s->restart_seen)

                    goto next_substr;

                if (read_decoding_params(m, &gb, substr) < 0)

                    goto next_substr;

            }

            if (!s->restart_seen)

                goto next_substr;

            if ((ret = read_block_data(m, &gb, substr)) < 0)

                return ret;

            if (get_bits_count(&gb) >= substream_data_len[substr] * 8)

                goto substream_length_mismatch;

        } while (!get_bits1(&gb));

        skip_bits(&gb, (-get_bits_count(&gb)) & 15);

        if (substream_data_len[substr] * 8 - get_bits_count(&gb) >= 32) {

            int shorten_by;

            if (get_bits(&gb, 16) != 0xD234)

                return AVERROR_INVALIDDATA;

            shorten_by = get_bits(&gb, 16);

            if      (m->avctx->codec_id == AV_CODEC_ID_TRUEHD && shorten_by  & 0x2000)

                s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);

            else if (m->avctx->codec_id == AV_CODEC_ID_MLP    && shorten_by != 0xD234)

                return AVERROR_INVALIDDATA;

            if (substr == m->max_decoded_substream)

                av_log(m->avctx, AV_LOG_INFO, "End of stream indicated.\n");

        }

        if (substream_parity_present[substr]) {

            uint8_t parity, checksum;

            if (substream_data_len[substr] * 8 - get_bits_count(&gb) != 16)

                goto substream_length_mismatch;

            parity   = ff_mlp_calculate_parity(buf, substream_data_len[substr] - 2);

            checksum = ff_mlp_checksum8       (buf, substream_data_len[substr] - 2);

            if ((get_bits(&gb, 8) ^ parity) != 0xa9    )

                av_log(m->avctx, AV_LOG_ERROR, "Substream %d parity check failed.\n", substr);

            if ( get_bits(&gb, 8)           != checksum)

                av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed.\n"    , substr);

        }

        if (substream_data_len[substr] * 8 != get_bits_count(&gb))

            goto substream_length_mismatch;

next_substr:

        if (!s->restart_seen)

            av_log(m->avctx, AV_LOG_ERROR,

                   "No restart header present in substream %d.\n", substr);

        buf += substream_data_len[substr];

    }

    rematrix_channels(m, m->max_decoded_substream);

    if ((ret = output_data(m, m->max_decoded_substream, data, got_frame_ptr)) < 0)

        return ret;

    return length;

substream_length_mismatch:

    av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);

    return AVERROR_INVALIDDATA;

error:

    m->params_valid = 0;

    return AVERROR_INVALIDDATA;

}


static int ipmi_register_netfn(IPMIBmcSim *s, unsigned int netfn,

                               const IPMINetfn *netfnd)

{

    if ((netfn & 1) || (netfn > MAX_NETFNS) || (s->netfns[netfn / 2])) {

        return -1;

    }

    s->netfns[netfn / 2] = netfnd;

    return 0;

}


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

    }

    /* 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, s);

    s->sock = sock;

    s->size = size;

    s->blocksize = blocksize;

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

    return 0;

}


void memory_region_destroy(MemoryRegion *mr)

{

    assert(QTAILQ_EMPTY(&mr->subregions));

    mr->destructor(mr);

    memory_region_clear_coalescing(mr);

    g_free((char *)mr->name);

    g_free(mr->ioeventfds);

}


static av_cold int aac_decode_init(AVCodecContext * avccontext) {

    AACContext * ac = avccontext->priv_data;

    int i;

    ac->avccontext = avccontext;

    if (avccontext->extradata_size <= 0 ||

        decode_audio_specific_config(ac, avccontext->extradata, avccontext->extradata_size))

        return -1;

    avccontext->sample_fmt  = SAMPLE_FMT_S16;

    avccontext->sample_rate = ac->m4ac.sample_rate;

    avccontext->frame_size  = 1024;

    AAC_INIT_VLC_STATIC( 0, 144);

    AAC_INIT_VLC_STATIC( 1, 114);

    AAC_INIT_VLC_STATIC( 2, 188);

    AAC_INIT_VLC_STATIC( 3, 180);

    AAC_INIT_VLC_STATIC( 4, 172);

    AAC_INIT_VLC_STATIC( 5, 140);

    AAC_INIT_VLC_STATIC( 6, 168);

    AAC_INIT_VLC_STATIC( 7, 114);

    AAC_INIT_VLC_STATIC( 8, 262);

    AAC_INIT_VLC_STATIC( 9, 248);

    AAC_INIT_VLC_STATIC(10, 384);

    dsputil_init(&ac->dsp, avccontext);

    ac->random_state = 0x1f2e3d4c;

    // -1024 - Compensate wrong IMDCT method.

    // 32768 - Required to scale values to the correct range for the bias method

    //         for float to int16 conversion.

    if(ac->dsp.float_to_int16 == ff_float_to_int16_c) {

        ac->add_bias = 385.0f;

        ac->sf_scale = 1. / (-1024. * 32768.);

        ac->sf_offset = 0;

    } else {

        ac->add_bias = 0.0f;

        ac->sf_scale = 1. / -1024.;

        ac->sf_offset = 60;

    }

#ifndef CONFIG_HARDCODED_TABLES

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

        ff_aac_pow2sf_tab[i] = pow(2, (i - 200)/4.);

#endif /* CONFIG_HARDCODED_TABLES */

    INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),

        ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),

        ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),

        352);

    ff_mdct_init(&ac->mdct, 11, 1);

    ff_mdct_init(&ac->mdct_small, 8, 1);

    // window initialization

    ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);

    ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);

    ff_sine_window_init(ff_sine_1024, 1024);

    ff_sine_window_init(ff_sine_128, 128);

    return 0;

}


static void read_info_chunk(AVFormatContext *s, int64_t size)

{

    AVIOContext *pb = s->pb;

    unsigned int i;

    unsigned int nb_entries = avio_rb32(pb);

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

        char key[32];

        char value[1024];

        avio_get_str(pb, INT_MAX, key, sizeof(key));

        avio_get_str(pb, INT_MAX, value, sizeof(value));

        av_dict_set(&s->metadata, key, value, 0);

    }

}


static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts, int64_t *pkt_dts)

{

    AVFrame *decoded_frame, *filtered_frame = NULL;

    void *buffer_to_free = NULL;

    int i, ret = 0;

    float quality = 0;

#if CONFIG_AVFILTER

    int frame_available = 1;

#endif

    int duration=0;

    int64_t *best_effort_timestamp;

    AVRational *frame_sample_aspect;

    if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))

        return AVERROR(ENOMEM);

    else

        avcodec_get_frame_defaults(ist->decoded_frame);

    decoded_frame = ist->decoded_frame;

    pkt->pts  = *pkt_pts;

    pkt->dts  = *pkt_dts;

    *pkt_pts  = AV_NOPTS_VALUE;

    if (pkt->duration) {

        duration = av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);

    } else if(ist->st->codec->time_base.num != 0) {

        int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;

        duration = ((int64_t)AV_TIME_BASE *

                          ist->st->codec->time_base.num * ticks) /

                          ist->st->codec->time_base.den;

    }

    if(*pkt_dts != AV_NOPTS_VALUE && duration) {

        *pkt_dts += duration;

    }else

        *pkt_dts = AV_NOPTS_VALUE;

    ret = avcodec_decode_video2(ist->st->codec,

                                decoded_frame, got_output, pkt);

    if (ret < 0)

        return ret;

    quality = same_quant ? decoded_frame->quality : 0;

    if (!*got_output) {

        /* no picture yet */

        return ret;

    }

    best_effort_timestamp= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "best_effort_timestamp");

    if(*best_effort_timestamp != AV_NOPTS_VALUE)

        ist->next_pts = ist->pts = *best_effort_timestamp;

    ist->next_pts += duration;

    pkt->size = 0;

    pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);

#if CONFIG_AVFILTER

    frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");

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

        OutputStream *ost = ost = &output_streams[i];

        if(check_output_constraints(ist, ost)){

            if (!frame_sample_aspect->num)

                *frame_sample_aspect = ist->st->sample_aspect_ratio;

            decoded_frame->pts = ist->pts;

            if (ist->dr1) {

                FrameBuffer      *buf = decoded_frame->opaque;

                AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(

                                            decoded_frame->data, decoded_frame->linesize,

                                            AV_PERM_READ | AV_PERM_PRESERVE,

                                            ist->st->codec->width, ist->st->codec->height,

                                            ist->st->codec->pix_fmt);

                avfilter_copy_frame_props(fb, decoded_frame);

                fb->pts                 = ist->pts;

                fb->buf->priv           = buf;

                fb->buf->free           = filter_release_buffer;

                buf->refcount++;

                av_buffersrc_buffer(ost->input_video_filter, fb);

            } else

            if((av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE)) < 0){

                av_log(0, AV_LOG_FATAL, "Failed to inject frame into filter network\n");

                exit_program(1);

            }

        }

    }

#endif

    rate_emu_sleep(ist);

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

        OutputStream *ost = &output_streams[i];

        int frame_size;

        if (!check_output_constraints(ist, ost) || !ost->encoding_needed)

            continue;

#if CONFIG_AVFILTER

        if (ost->input_video_filter) {

            frame_available = av_buffersink_poll_frame(ost->output_video_filter);

        }

        while (frame_available) {

            if (ost->output_video_filter) {

                AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;

                if (av_buffersink_get_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0){

                    av_log(0, AV_LOG_WARNING, "AV Filter told us it has a frame available but failed to output one\n");

                    goto cont;

                }

                if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {

                    av_free(buffer_to_free);

                    return AVERROR(ENOMEM);

                } else

                    avcodec_get_frame_defaults(ist->filtered_frame);

                filtered_frame = ist->filtered_frame;

                *filtered_frame= *decoded_frame; //for me_threshold

                if (ost->picref) {

                    avfilter_fill_frame_from_video_buffer_ref(filtered_frame, ost->picref);

                    ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);

                }

            }

            if (ost->picref->video && !ost->frame_aspect_ratio)

                ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;

#else

            filtered_frame = decoded_frame;

#endif

            do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,

                         same_quant ? quality : ost->st->codec->global_quality);

            if (vstats_filename && frame_size)

                do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);

#if CONFIG_AVFILTER

            cont:

            frame_available = ost->output_video_filter && av_buffersink_poll_frame(ost->output_video_filter);

            avfilter_unref_buffer(ost->picref);

        }

#endif

    }

    av_free(buffer_to_free);

    return ret;

}


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

{

    AVStream *st;

    MOVStreamContext *sc;

    unsigned i, entries;

    if (c->fc->nb_streams < 1)

        return 0;

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

    sc = st->priv_data;

    avio_rb32(pb); // version + flags

    entries = avio_rb32(pb);

    if (entries >= UINT_MAX / sizeof(*sc->stps_data))

        return AVERROR_INVALIDDATA;

    sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));

    if (!sc->stps_data)

        return AVERROR(ENOMEM);

    sc->stps_count = entries;

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

        sc->stps_data[i] = avio_rb32(pb);

        //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);

    }

    return 0;

}


static int decode_frame(AVCodecContext * avctx,

			void *data, int *data_size,

			uint8_t * buf, int buf_size)

{

    MPADecodeContext *s = avctx->priv_data;

    uint32_t header;

    uint8_t *buf_ptr;

    int len, out_size;

    OUT_INT *out_samples = data;

    buf_ptr = buf;

    while (buf_size > 0) {

	len = s->inbuf_ptr - s->inbuf;

	if (s->frame_size == 0) {

            /* special case for next header for first frame in free

               format case (XXX: find a simpler method) */

            if (s->free_format_next_header != 0) {

                s->inbuf[0] = s->free_format_next_header >> 24;

                s->inbuf[1] = s->free_format_next_header >> 16;

                s->inbuf[2] = s->free_format_next_header >> 8;

                s->inbuf[3] = s->free_format_next_header;

                s->inbuf_ptr = s->inbuf + 4;

                s->free_format_next_header = 0;

                goto got_header;

            }

	    /* no header seen : find one. We need at least HEADER_SIZE

               bytes to parse it */

	    len = HEADER_SIZE - len;

	    if (len > buf_size)

		len = buf_size;

	    if (len > 0) {

		memcpy(s->inbuf_ptr, buf_ptr, len);

		buf_ptr += len;

		buf_size -= len;

		s->inbuf_ptr += len;

	    }

	    if ((s->inbuf_ptr - s->inbuf) >= HEADER_SIZE) {

            got_header:

		header = (s->inbuf[0] << 24) | (s->inbuf[1] << 16) |

		    (s->inbuf[2] << 8) | s->inbuf[3];

		if (ff_mpa_check_header(header) < 0) {

		    /* no sync found : move by one byte (inefficient, but simple!) */

		    memmove(s->inbuf, s->inbuf + 1, s->inbuf_ptr - s->inbuf - 1);

		    s->inbuf_ptr--;

                    dprintf("skip %x\n", header);

                    /* reset free format frame size to give a chance

                       to get a new bitrate */

                    s->free_format_frame_size = 0;

		} else {

		    if (decode_header(s, header) == 1) {

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

			s->frame_size = -1;

                    }

                    /* update codec info */

                    avctx->sample_rate = s->sample_rate;

                    avctx->channels = s->nb_channels;

                    avctx->bit_rate = s->bit_rate;

                    avctx->sub_id = s->layer;

                    switch(s->layer) {

                    case 1:

                        avctx->frame_size = 384;

                        break;

                    case 2:

                        avctx->frame_size = 1152;

                        break;

                    case 3:

                        if (s->lsf)

                            avctx->frame_size = 576;

                        else

                            avctx->frame_size = 1152;

                        break;

                    }

		}

	    }

        } else if (s->frame_size == -1) {

            /* free format : find next sync to compute frame size */

	    len = MPA_MAX_CODED_FRAME_SIZE - len;

	    if (len > buf_size)

		len = buf_size;

            if (len == 0) {

		/* frame too long: resync */

                s->frame_size = 0;

		memmove(s->inbuf, s->inbuf + 1, s->inbuf_ptr - s->inbuf - 1);

		s->inbuf_ptr--;

            } else {

                uint8_t *p, *pend;

                uint32_t header1;

                int padding;

                memcpy(s->inbuf_ptr, buf_ptr, len);

                /* check for header */

                p = s->inbuf_ptr - 3;

                pend = s->inbuf_ptr + len - 4;

                while (p <= pend) {

                    header = (p[0] << 24) | (p[1] << 16) |

                        (p[2] << 8) | p[3];

                    header1 = (s->inbuf[0] << 24) | (s->inbuf[1] << 16) |

                        (s->inbuf[2] << 8) | s->inbuf[3];

                    /* check with high probability that we have a

                       valid header */

                    if ((header & SAME_HEADER_MASK) ==

                        (header1 & SAME_HEADER_MASK)) {

                        /* header found: update pointers */

                        len = (p + 4) - s->inbuf_ptr;

                        buf_ptr += len;

                        buf_size -= len;

                        s->inbuf_ptr = p;

                        /* compute frame size */

                        s->free_format_next_header = header;

                        s->free_format_frame_size = s->inbuf_ptr - s->inbuf;

                        padding = (header1 >> 9) & 1;

                        if (s->layer == 1)

                            s->free_format_frame_size -= padding * 4;

                        else

                            s->free_format_frame_size -= padding;

                        dprintf("free frame size=%d padding=%d\n",

                                s->free_format_frame_size, padding);

                        decode_header(s, header1);

                        goto next_data;

                    }

                    p++;

                }

                /* not found: simply increase pointers */

                buf_ptr += len;

                s->inbuf_ptr += len;

                buf_size -= len;

            }

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

            if (s->frame_size > MPA_MAX_CODED_FRAME_SIZE)

                s->frame_size = MPA_MAX_CODED_FRAME_SIZE;

	    len = s->frame_size - len;

	    if (len > buf_size)

		len = buf_size;

	    memcpy(s->inbuf_ptr, buf_ptr, len);

	    buf_ptr += len;

	    s->inbuf_ptr += len;

	    buf_size -= len;

	}

    next_data:

        if (s->frame_size > 0 &&

            (s->inbuf_ptr - s->inbuf) >= s->frame_size) {

            if (avctx->parse_only) {

                /* simply return the frame data */

                *(uint8_t **)data = s->inbuf;

                out_size = s->inbuf_ptr - s->inbuf;

            } else {

                out_size = mp_decode_frame(s, out_samples);

            }

	    s->inbuf_ptr = s->inbuf;

	    s->frame_size = 0;

	    *data_size = out_size;

	    break;

	}

    }

    return buf_ptr - buf;

}


static av_cold void rv34_init_tables(void)

{

    int i, j, k;

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

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

            rv34_gen_vlc(rv34_table_intra_cbppat   [i][j], CBPPAT_VLC_SIZE,   &intra_vlcs[i].cbppattern[j],     NULL, 19*i + 0 + j);

            rv34_gen_vlc(rv34_table_intra_secondpat[i][j], OTHERBLK_VLC_SIZE, &intra_vlcs[i].second_pattern[j], NULL, 19*i + 2 + j);

            rv34_gen_vlc(rv34_table_intra_thirdpat [i][j], OTHERBLK_VLC_SIZE, &intra_vlcs[i].third_pattern[j],  NULL, 19*i + 4 + j);

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

                rv34_gen_vlc(rv34_table_intra_cbp[i][j+k*2],  CBP_VLC_SIZE,   &intra_vlcs[i].cbp[j][k],         rv34_cbp_code, 19*i + 6 + j*4 + k);

            }

        }

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

            rv34_gen_vlc(rv34_table_intra_firstpat[i][j], FIRSTBLK_VLC_SIZE, &intra_vlcs[i].first_pattern[j], NULL, 19*i + 14 + j);

        }

        rv34_gen_vlc(rv34_intra_coeff[i], COEFF_VLC_SIZE, &intra_vlcs[i].coefficient, NULL, 19*i + 18);

    }

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

        rv34_gen_vlc(rv34_inter_cbppat[i], CBPPAT_VLC_SIZE, &inter_vlcs[i].cbppattern[0], NULL, i*12 + 95);

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

            rv34_gen_vlc(rv34_inter_cbp[i][j], CBP_VLC_SIZE, &inter_vlcs[i].cbp[0][j], rv34_cbp_code, i*12 + 96 + j);

        }

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

            rv34_gen_vlc(rv34_table_inter_firstpat [i][j], FIRSTBLK_VLC_SIZE, &inter_vlcs[i].first_pattern[j],  NULL, i*12 + 100 + j);

            rv34_gen_vlc(rv34_table_inter_secondpat[i][j], OTHERBLK_VLC_SIZE, &inter_vlcs[i].second_pattern[j], NULL, i*12 + 102 + j);

            rv34_gen_vlc(rv34_table_inter_thirdpat [i][j], OTHERBLK_VLC_SIZE, &inter_vlcs[i].third_pattern[j],  NULL, i*12 + 104 + j);

        }

        rv34_gen_vlc(rv34_inter_coeff[i], COEFF_VLC_SIZE, &inter_vlcs[i].coefficient, NULL, i*12 + 106);

    }

}


static void ff_h264_idct_add8_sse2(uint8_t **dest, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){

    int i;

    for(i=16; i<16+8; i+=2){

        if(nnzc[ scan8[i+0] ]|nnzc[ scan8[i+1] ])

            ff_x264_add8x4_idct_sse2 (dest[(i&4)>>2] + block_offset[i], block + i*16, stride);

        else if(block[i*16]|block[i*16+16])

            ff_h264_idct_dc_add8_mmx2(dest[(i&4)>>2] + block_offset[i], block + i*16, stride);

    }

}


static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)

{

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

    MOVStreamContext *sc = st->priv_data;

    int entries, i, j;

    get_be32(pb); // version + flags

    entries = get_be32(pb);

    if (entries >= UINT_MAX / sizeof(*sc->drefs))

        return -1;

    sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));

    if (!sc->drefs)

        return AVERROR(ENOMEM);

    sc->drefs_count = entries;

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

        MOVDref *dref = &sc->drefs[i];

        uint32_t size = get_be32(pb);

        int64_t next = url_ftell(pb) + size - 4;

        dref->type = get_le32(pb);

        get_be32(pb); // version + flags

        dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);

        if (dref->type == MKTAG('a','l','i','s') && size > 150) {

            /* macintosh alias record */

            uint16_t volume_len, len;

            char volume[28];

            int16_t type;

            url_fskip(pb, 10);

            volume_len = get_byte(pb);

            volume_len = FFMIN(volume_len, 27);

            get_buffer(pb, volume, 27);

            volume[volume_len] = 0;

            av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", volume, volume_len);

            url_fskip(pb, 112);

            for (type = 0; type != -1 && url_ftell(pb) < next; ) {

                type = get_be16(pb);

                len = get_be16(pb);

                av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);

                if (len&1)

                    len += 1;

                if (type == 2) { // absolute path

                    av_free(dref->path);

                    dref->path = av_mallocz(len+1);

                    if (!dref->path)

                        return AVERROR(ENOMEM);

                    get_buffer(pb, dref->path, len);

                    if (len > volume_len && !strncmp(dref->path, volume, volume_len)) {

                        len -= volume_len;

                        memmove(dref->path, dref->path+volume_len, len);

                        dref->path[len] = 0;

                    }

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

                        if (dref->path[j] == ':')

                            dref->path[j] = '/';

                    av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);

                } else

                    url_fskip(pb, len);

            }

        }

        url_fseek(pb, next, SEEK_SET);

    }

    return 0;

}


void yuv2rgb_altivec_init_tables (SwsContext *c, const int inv_table[4])

{

  vector signed short CY, CRV, CBU, CGU, CGV, OY, Y0;

  int64_t crv __attribute__ ((aligned(16))) = inv_table[0];

  int64_t cbu __attribute__ ((aligned(16))) = inv_table[1];

  int64_t cgu __attribute__ ((aligned(16))) = inv_table[2];

  int64_t cgv __attribute__ ((aligned(16))) = inv_table[3];

  int64_t cy = (1<<16)-1;

  int64_t oy = 0;

  short tmp __attribute__ ((aligned(16)));

  if ((c->flags & SWS_CPU_CAPS_ALTIVEC) == 0)

    return;

  cy = (cy *c->contrast             )>>17;

  crv= (crv*c->contrast * c->saturation)>>32;

  cbu= (cbu*c->contrast * c->saturation)>>32;

  cgu= (cgu*c->contrast * c->saturation)>>32;

  cgv= (cgv*c->contrast * c->saturation)>>32;

  oy -= 256*c->brightness;

  tmp = cy;

  CY = vec_lde (0, &tmp);

  CY  = vec_splat (CY, 0);

  tmp = oy;

  OY = vec_lde (0, &tmp);

  OY  = vec_splat (OY, 0);

  tmp = crv>>3;

  CRV = vec_lde (0, &tmp);

  CRV  = vec_splat (CRV, 0);

  tmp = cbu>>3;

  CBU = vec_lde (0, &tmp);

  CBU  = vec_splat (CBU, 0);

  tmp = -(cgu>>1);

  CGU = vec_lde (0, &tmp);

  CGU  = vec_splat (CGU, 0);

  tmp = -(cgv>>1);

  CGV = vec_lde (0, &tmp);

  CGV  = vec_splat (CGV, 0);

  c->CSHIFT = (vector unsigned short)(2);

  c->CY = CY;

  c->OY = OY;

  c->CRV = CRV;

  c->CBU = CBU;

  c->CGU = CGU;

  c->CGV = CGV;

#if 0

  printf ("cy:  %hvx\n", CY);

  printf ("oy:  %hvx\n", OY);

  printf ("crv: %hvx\n", CRV);

  printf ("cbu: %hvx\n", CBU);

  printf ("cgv: %hvx\n", CGV);

  printf ("cgu: %hvx\n", CGU);

#endif

 return;

}


void mipsnet_init (int base, qemu_irq irq, NICInfo *nd)

{

    MIPSnetState *s;

    qemu_check_nic_model(nd, "mipsnet");

    s = qemu_mallocz(sizeof(MIPSnetState));

    register_ioport_write(base, 36, 1, mipsnet_ioport_write, s);

    register_ioport_read(base, 36, 1, mipsnet_ioport_read, s);

    register_ioport_write(base, 36, 2, mipsnet_ioport_write, s);

    register_ioport_read(base, 36, 2, mipsnet_ioport_read, s);

    register_ioport_write(base, 36, 4, mipsnet_ioport_write, s);

    register_ioport_read(base, 36, 4, mipsnet_ioport_read, s);

    s->io_base = base;

    s->irq = irq;

    if (nd && nd->vlan) {

        s->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name,

                                     mipsnet_can_receive, mipsnet_receive, NULL,

                                     mipsnet_cleanup, s);

    } else {

        s->vc = NULL;

    }

    qemu_format_nic_info_str(s->vc, nd->macaddr);

    mipsnet_reset(s);

    register_savevm("mipsnet", 0, 0, mipsnet_save, mipsnet_load, s);

}


static inline void hcscale_fast_c(SwsContext *c, int16_t *dst1, int16_t *dst2,

                                  int dstWidth, const uint8_t *src1,

                                  const uint8_t *src2, int srcW, int xInc)

{

    int i;

    unsigned int xpos=0;

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

        register unsigned int xx=xpos>>16;

        register unsigned int xalpha=(xpos&0xFFFF)>>9;

        dst1[i]=(src1[xx]*(xalpha^127)+src1[xx+1]*xalpha);

        dst2[i]=(src2[xx]*(xalpha^127)+src2[xx+1]*xalpha);

        xpos+=xInc;


static void apply_window_and_mdct(AACEncContext *s, SingleChannelElement *sce,

                                  float *audio)

{

    int i;

    float *output = sce->ret_buf;

    apply_window[sce->ics.window_sequence[0]](s->fdsp, sce, audio);

    if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE)

        s->mdct1024.mdct_calc(&s->mdct1024, sce->coeffs, output);

    else

        for (i = 0; i < 1024; i += 128)

            s->mdct128.mdct_calc(&s->mdct128, sce->coeffs + i, output + i*2);

    memcpy(audio, audio + 1024, sizeof(audio[0]) * 1024);

    memcpy(sce->pcoeffs, sce->coeffs, sizeof(sce->pcoeffs));

}


TPMVersion tpm_tis_get_tpm_version(Object *obj)
{
    TPMState *s = TPM(obj);
    return tpm_backend_get_tpm_version(s->be_driver);


vmxnet3_indicate_packet(VMXNET3State *s)

{

    struct Vmxnet3_RxDesc rxd;

    bool is_head = true;

    uint32_t rxd_idx;

    uint32_t rx_ridx;

    struct Vmxnet3_RxCompDesc rxcd;

    uint32_t new_rxcd_gen = VMXNET3_INIT_GEN;

    hwaddr new_rxcd_pa = 0;

    hwaddr ready_rxcd_pa = 0;

    struct iovec *data = vmxnet_rx_pkt_get_iovec(s->rx_pkt);

    size_t bytes_copied = 0;

    size_t bytes_left = vmxnet_rx_pkt_get_total_len(s->rx_pkt);

    uint16_t num_frags = 0;

    size_t chunk_size;

    vmxnet_rx_pkt_dump(s->rx_pkt);

    while (bytes_left > 0) {

        /* cannot add more frags to packet */

        if (num_frags == s->max_rx_frags) {

            break;

        }

        new_rxcd_pa = vmxnet3_pop_rxc_descr(s, RXQ_IDX, &new_rxcd_gen);

        if (!new_rxcd_pa) {

            break;

        }

        if (!vmxnet3_get_next_rx_descr(s, is_head, &rxd, &rxd_idx, &rx_ridx)) {

            break;

        }

        chunk_size = MIN(bytes_left, rxd.len);

        vmxnet3_physical_memory_writev(data, bytes_copied,

                                       le64_to_cpu(rxd.addr), chunk_size);

        bytes_copied += chunk_size;

        bytes_left -= chunk_size;

        vmxnet3_dump_rx_descr(&rxd);

        if (0 != ready_rxcd_pa) {

            cpu_physical_memory_write(ready_rxcd_pa, &rxcd, sizeof(rxcd));

        }

        memset(&rxcd, 0, sizeof(struct Vmxnet3_RxCompDesc));

        rxcd.rxdIdx = rxd_idx;

        rxcd.len = chunk_size;

        rxcd.sop = is_head;

        rxcd.gen = new_rxcd_gen;

        rxcd.rqID = RXQ_IDX + rx_ridx * s->rxq_num;

        if (0 == bytes_left) {

            vmxnet3_rx_update_descr(s->rx_pkt, &rxcd);

        }

        VMW_RIPRN("RX Completion descriptor: rxRing: %lu rxIdx %lu len %lu "

                  "sop %d csum_correct %lu",

                  (unsigned long) rx_ridx,

                  (unsigned long) rxcd.rxdIdx,

                  (unsigned long) rxcd.len,

                  (int) rxcd.sop,

                  (unsigned long) rxcd.tuc);

        is_head = false;

        ready_rxcd_pa = new_rxcd_pa;

        new_rxcd_pa = 0;

    }

    if (0 != ready_rxcd_pa) {

        rxcd.eop = 1;

        rxcd.err = (0 != bytes_left);

        cpu_physical_memory_write(ready_rxcd_pa, &rxcd, sizeof(rxcd));

        /* Flush RX descriptor changes */

        smp_wmb();

    }

    if (0 != new_rxcd_pa) {

        vmxnet3_revert_rxc_descr(s, RXQ_IDX);

    }

    vmxnet3_trigger_interrupt(s, s->rxq_descr[RXQ_IDX].intr_idx);

    if (bytes_left == 0) {

        vmxnet3_on_rx_done_update_stats(s, RXQ_IDX, VMXNET3_PKT_STATUS_OK);

        return true;

    } else if (num_frags == s->max_rx_frags) {

        vmxnet3_on_rx_done_update_stats(s, RXQ_IDX, VMXNET3_PKT_STATUS_ERROR);

        return false;

    } else {

        vmxnet3_on_rx_done_update_stats(s, RXQ_IDX,

                                        VMXNET3_PKT_STATUS_OUT_OF_BUF);

        return false;

    }

}


static void sp804_write(void *opaque, target_phys_addr_t offset,

                        uint64_t value, unsigned size)

{

    sp804_state *s = (sp804_state *)opaque;

    if (offset < 0x20) {

        arm_timer_write(s->timer[0], offset, value);

        return;

    }

    if (offset < 0x40) {

        arm_timer_write(s->timer[1], offset - 0x20, value);

        return;

    }

    /* Technically we could be writing to the Test Registers, but not likely */

    hw_error("%s: Bad offset %x\n", __func__, (int)offset);

}


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

{

    int sense;

    bool start = buf[4] & 1;

    bool loej = buf[4] & 2;     /* load on start, eject on !start */

    int pwrcnd = buf[4] & 0xf0;

    if (pwrcnd) {

        /* eject/load only happens for power condition == 0 */

        return;

    }

    if (loej) {

        if (!start && !s->tray_open && s->tray_locked) {

            sense = bdrv_is_inserted(s->bs)

                ? NOT_READY : ILLEGAL_REQUEST;

            ide_atapi_cmd_error(s, sense, ASC_MEDIA_REMOVAL_PREVENTED);

            return;

        }

        if (s->tray_open != !start) {

            bdrv_eject(s->bs, !start);

            s->tray_open = !start;

        }

    }

    ide_atapi_cmd_ok(s);

}


void migration_tls_channel_connect(MigrationState *s,

                                   QIOChannel *ioc,

                                   const char *hostname,

                                   Error **errp)

{

    QCryptoTLSCreds *creds;

    QIOChannelTLS *tioc;

    creds = migration_tls_get_creds(

        s, QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT, errp);

    if (!creds) {

        return;

    }

    if (s->parameters.tls_hostname) {

        hostname = s->parameters.tls_hostname;

    }

    if (!hostname) {

        error_setg(errp, "No hostname available for TLS");

        return;

    }

    tioc = qio_channel_tls_new_client(

        ioc, creds, hostname, errp);

    if (!tioc) {

        return;

    }

    trace_migration_tls_outgoing_handshake_start(hostname);

    qio_channel_set_name(QIO_CHANNEL(tioc), "migration-tls-outgoing");

    qio_channel_tls_handshake(tioc,

                              migration_tls_outgoing_handshake,

                              s,

                              NULL);

}


void bdrv_add_before_write_notifier(BlockDriverState *bs,

                                    NotifierWithReturn *notifier)

{

    notifier_with_return_list_add(&bs->before_write_notifiers, notifier);

}


static int qemu_savevm_state(Monitor *mon, QEMUFile *f)

{

    int ret;

    if (qemu_savevm_state_blocked(mon)) {

        ret = -EINVAL;

        goto out;

    }

    ret = qemu_savevm_state_begin(f, 0, 0);

    if (ret < 0)

        goto out;

    do {

        ret = qemu_savevm_state_iterate(f);

        if (ret < 0)

            goto out;

    } while (ret == 0);

    ret = qemu_savevm_state_complete(f);

out:

    if (ret == 0) {

        ret = qemu_file_get_error(f);

    }

    return ret;

}


static void s390_virtio_net_realize(VirtIOS390Device *s390_dev, Error **errp)

{

    DeviceState *qdev = DEVICE(s390_dev);

    VirtIONetS390 *dev = VIRTIO_NET_S390(s390_dev);

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

    Error *err = NULL;

    virtio_net_set_config_size(&dev->vdev, s390_dev->host_features);

    virtio_net_set_netclient_name(&dev->vdev, qdev->id,

                                  object_get_typename(OBJECT(qdev)));

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

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

    if (err) {

        error_propagate(errp, err);

        return;

    }

    s390_virtio_device_init(s390_dev, VIRTIO_DEVICE(vdev));

}


static void nvdimm_build_ssdt(GSList *device_list, GArray *table_offsets,

                              GArray *table_data, BIOSLinker *linker,

                              GArray *dsm_dma_arrea)

{

    Aml *ssdt, *sb_scope, *dev;

    int mem_addr_offset, nvdimm_ssdt;

    acpi_add_table(table_offsets, table_data);

    ssdt = init_aml_allocator();

    acpi_data_push(ssdt->buf, sizeof(AcpiTableHeader));

    sb_scope = aml_scope("\\_SB");

    dev = aml_device("NVDR");

    /*

     * ACPI 6.0: 9.20 NVDIMM Devices:

     *

     * The ACPI Name Space device uses _HID of ACPI0012 to identify the root

     * NVDIMM interface device. Platform firmware is required to contain one

     * such device in _SB scope if NVDIMMs support is exposed by platform to

     * OSPM.

     * For each NVDIMM present or intended to be supported by platform,

     * platform firmware also exposes an ACPI Namespace Device under the

     * root device.

     */

    aml_append(dev, aml_name_decl("_HID", aml_string("ACPI0012")));

    nvdimm_build_common_dsm(dev);

    /* 0 is reserved for root device. */

    nvdimm_build_device_dsm(dev, 0);

    nvdimm_build_nvdimm_devices(device_list, dev);

    aml_append(sb_scope, dev);

    aml_append(ssdt, sb_scope);

    nvdimm_ssdt = table_data->len;

    /* copy AML table into ACPI tables blob and patch header there */

    g_array_append_vals(table_data, ssdt->buf->data, ssdt->buf->len);

    mem_addr_offset = build_append_named_dword(table_data,

                                               NVDIMM_ACPI_MEM_ADDR);

    bios_linker_loader_alloc(linker,

                             NVDIMM_DSM_MEM_FILE, dsm_dma_arrea,

                             sizeof(NvdimmDsmIn), false /* high memory */);

    bios_linker_loader_add_pointer(linker,

        ACPI_BUILD_TABLE_FILE, mem_addr_offset, sizeof(uint32_t),

        NVDIMM_DSM_MEM_FILE, 0);

    build_header(linker, table_data,

        (void *)(table_data->data + nvdimm_ssdt),

        "SSDT", table_data->len - nvdimm_ssdt, 1, NULL, "NVDIMM");

    free_aml_allocator();

}


static av_cold int eightsvx_decode_init(AVCodecContext *avctx)

{

    EightSvxContext *esc = avctx->priv_data;

    if (avctx->channels < 1 || avctx->channels > 2) {

        av_log(avctx, AV_LOG_ERROR, "8SVX does not support more than 2 channels\n");

        return AVERROR_INVALIDDATA;

    }

    switch (avctx->codec->id) {

    case AV_CODEC_ID_8SVX_FIB: esc->table = fibonacci;    break;

    case AV_CODEC_ID_8SVX_EXP: esc->table = exponential;  break;

    case AV_CODEC_ID_PCM_S8_PLANAR:

    case AV_CODEC_ID_8SVX_RAW: esc->table = NULL;         break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Invalid codec id %d.\n", avctx->codec->id);

        return AVERROR_INVALIDDATA;

    }

    avctx->sample_fmt = AV_SAMPLE_FMT_U8P;

    avcodec_get_frame_defaults(&esc->frame);

    avctx->coded_frame = &esc->frame;

    return 0;

}


static av_cold int opus_encode_init(AVCodecContext *avctx)

{

    int i, ch, ret;

    OpusEncContext *s = avctx->priv_data;

    s->avctx = avctx;

    s->channels = avctx->channels;

    /* Opus allows us to change the framesize on each packet (and each packet may

     * have multiple frames in it) but we can't change the codec's frame size on

     * runtime, so fix it to the lowest possible number of samples and use a queue

     * to accumulate AVFrames until we have enough to encode whatever the encoder

     * decides is the best */

    avctx->frame_size = 120;

    /* Initial padding will change if SILK is ever supported */

    avctx->initial_padding = 120;

    avctx->cutoff = !avctx->cutoff ? 20000 : avctx->cutoff;

    if (!avctx->bit_rate) {

        int coupled = ff_opus_default_coupled_streams[s->channels - 1];

        avctx->bit_rate = coupled*(96000) + (s->channels - coupled*2)*(48000);

    } else if (avctx->bit_rate < 6000 || avctx->bit_rate > 255000 * s->channels) {

        int64_t clipped_rate = av_clip(avctx->bit_rate, 6000, 255000 * s->channels);

        av_log(avctx, AV_LOG_ERROR, "Unsupported bitrate %"PRId64" kbps, clipping to %"PRId64" kbps\n",

               avctx->bit_rate/1000, clipped_rate/1000);

        avctx->bit_rate = clipped_rate;

    }

    /* Frame structs and range coder buffers */

    s->frame = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(CeltFrame));

    if (!s->frame)

        return AVERROR(ENOMEM);

    s->rc = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(OpusRangeCoder));

    if (!s->rc)

        return AVERROR(ENOMEM);

    /* Extradata */

    avctx->extradata_size = 19;

    avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);

    if (!avctx->extradata)

        return AVERROR(ENOMEM);

    opus_write_extradata(avctx);

    ff_af_queue_init(avctx, &s->afq);

    if (!(s->dsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT)))

        return AVERROR(ENOMEM);

    /* I have no idea why a base scaling factor of 68 works, could be the twiddles */

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

        if ((ret = ff_mdct15_init(&s->mdct[i], 0, i + 3, 68 << (CELT_BLOCK_NB - 1 - i))))

            return AVERROR(ENOMEM);

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

        s->frame[i].block[0].emph_coeff = s->frame[i].block[1].emph_coeff = 0.0f;

    /* Zero out previous energy (matters for inter first frame) */

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

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

            s->last_quantized_energy[ch][i] = 0.0f;

    /* Allocate an empty frame to use as overlap for the first frame of audio */

    ff_bufqueue_add(avctx, &s->bufqueue, spawn_empty_frame(s));

    if (!ff_bufqueue_peek(&s->bufqueue, 0))

        return AVERROR(ENOMEM);

    return 0;

}


static void scsi_destroy(SCSIDevice *s)

{

    scsi_device_purge_requests(s, SENSE_CODE(NO_SENSE));

    blockdev_mark_auto_del(s->conf.bs);

}


static void init_event_facility_class(ObjectClass *klass, void *data)

{

    SysBusDeviceClass *sbdc = SYS_BUS_DEVICE_CLASS(klass);

    DeviceClass *dc = DEVICE_CLASS(sbdc);

    SCLPEventFacilityClass *k = EVENT_FACILITY_CLASS(dc);

    dc->reset = reset_event_facility;

    dc->vmsd = &vmstate_event_facility;

    set_bit(DEVICE_CATEGORY_MISC, dc->categories);

    k->init = init_event_facility;

    k->command_handler = command_handler;

    k->event_pending = event_pending;

}


static void set_pixel_format(VncState *vs,

			     int bits_per_pixel, int depth,

			     int big_endian_flag, int true_color_flag,

			     int red_max, int green_max, int blue_max,

			     int red_shift, int green_shift, int blue_shift)

{

    int host_big_endian_flag;

#ifdef WORDS_BIGENDIAN

    host_big_endian_flag = 1;

#else

    host_big_endian_flag = 0;

#endif

    if (!true_color_flag) {

    fail:

	vnc_client_error(vs);

        return;

    }

    if (bits_per_pixel == 32 &&

        host_big_endian_flag == big_endian_flag &&

        red_max == 0xff && green_max == 0xff && blue_max == 0xff &&

        red_shift == 16 && green_shift == 8 && blue_shift == 0) {

        vs->depth = 4;

        vs->write_pixels = vnc_write_pixels_copy;

        vs->send_hextile_tile = send_hextile_tile_32;

    } else

    if (bits_per_pixel == 16 &&

        host_big_endian_flag == big_endian_flag &&

        red_max == 31 && green_max == 63 && blue_max == 31 &&

        red_shift == 11 && green_shift == 5 && blue_shift == 0) {

        vs->depth = 2;

        vs->write_pixels = vnc_write_pixels_copy;

        vs->send_hextile_tile = send_hextile_tile_16;

    } else

    if (bits_per_pixel == 8 &&

        red_max == 7 && green_max == 7 && blue_max == 3 &&

        red_shift == 5 && green_shift == 2 && blue_shift == 0) {

        vs->depth = 1;

        vs->write_pixels = vnc_write_pixels_copy;

        vs->send_hextile_tile = send_hextile_tile_8;

    } else

    {

        /* generic and slower case */

        if (bits_per_pixel != 8 &&

            bits_per_pixel != 16 &&

            bits_per_pixel != 32)

            goto fail;

        vs->depth = 4;

        vs->red_shift = red_shift;

        vs->red_max = red_max;

        vs->red_shift1 = 24 - compute_nbits(red_max);

        vs->green_shift = green_shift;

        vs->green_max = green_max;

        vs->green_shift1 = 16 - compute_nbits(green_max);

        vs->blue_shift = blue_shift;

        vs->blue_max = blue_max;

        vs->blue_shift1 = 8 - compute_nbits(blue_max);

        vs->pix_bpp = bits_per_pixel / 8;

        vs->pix_big_endian = big_endian_flag;

        vs->write_pixels = vnc_write_pixels_generic;

        vs->send_hextile_tile = send_hextile_tile_generic;

    }

    vnc_dpy_resize(vs->ds, vs->ds->width, vs->ds->height);

    memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));

    memset(vs->old_data, 42, vs->ds->linesize * vs->ds->height);

    vga_hw_invalidate();

    vga_hw_update();

}


void do_info_vnc(Monitor *mon)

{

    if (vnc_display == NULL || vnc_display->display == NULL)

        monitor_printf(mon, "VNC server disabled\n");

    else {

        monitor_printf(mon, "VNC server active on: ");

        monitor_print_filename(mon, vnc_display->display);

        monitor_printf(mon, "\n");

	if (vnc_display->clients == NULL)

            monitor_printf(mon, "No client connected\n");

	else

	    monitor_printf(mon, "Client connected\n");

    }

}


void qemu_chr_generic_open(CharDriverState *s)

{

    if (s->open_timer == NULL) {

        s->open_timer = qemu_new_timer_ms(rt_clock,

                                          qemu_chr_fire_open_event, s);

        qemu_mod_timer(s->open_timer, qemu_get_clock_ms(rt_clock) - 1);

    }

}


static int pci_piix4_ide_initfn(PCIDevice *dev)

{

    PCIIDEState *d = DO_UPCAST(PCIIDEState, dev, dev);

    pci_config_set_vendor_id(d->dev.config, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(d->dev.config, PCI_DEVICE_ID_INTEL_82371AB);

    return pci_piix_ide_initfn(d);

}


static void block_job_defer_to_main_loop_bh(void *opaque)

{

    BlockJobDeferToMainLoopData *data = opaque;

    AioContext *aio_context;

    /* Prevent race with block_job_defer_to_main_loop() */

    aio_context_acquire(data->aio_context);

    /* Fetch BDS AioContext again, in case it has changed */

    aio_context = blk_get_aio_context(data->job->blk);

    if (aio_context != data->aio_context) {

        aio_context_acquire(aio_context);

    }

    data->job->deferred_to_main_loop = false;

    data->fn(data->job, data->opaque);

    if (aio_context != data->aio_context) {

        aio_context_release(aio_context);

    }

    aio_context_release(data->aio_context);

    g_free(data);

}


static void virtio_blk_handle_read(VirtIOBlockReq *req)

{

    uint64_t sector;

    sector = virtio_ldq_p(VIRTIO_DEVICE(req->dev), &req->out.sector);

    bdrv_acct_start(req->dev->bs, &req->acct, req->qiov.size, BDRV_ACCT_READ);

    trace_virtio_blk_handle_read(req, sector, req->qiov.size / 512);

    if (sector & req->dev->sector_mask) {

        virtio_blk_rw_complete(req, -EIO);

        return;

    }

    if (req->qiov.size % req->dev->conf->logical_block_size) {

        virtio_blk_rw_complete(req, -EIO);

        return;

    }

    bdrv_aio_readv(req->dev->bs, sector, &req->qiov,

                   req->qiov.size / BDRV_SECTOR_SIZE,

                   virtio_blk_rw_complete, req);

}


envlist_unsetenv(envlist_t *envlist, const char *env)

{

	struct envlist_entry *entry;

	size_t envname_len;

	if ((envlist == NULL) || (env == NULL))

		return (EINVAL);

	/* env is not allowed to contain '=' */

	if (strchr(env, '=') != NULL)

		return (EINVAL);

	/*

	 * Find out the requested entry and remove

	 * it from the list.

	 */

	envname_len = strlen(env);

	for (entry = envlist->el_entries.lh_first; entry != NULL;

	    entry = entry->ev_link.le_next) {

		if (strncmp(entry->ev_var, env, envname_len) == 0)

			break;

	}

	if (entry != NULL) {

		LIST_REMOVE(entry, ev_link);

		free((char *)entry->ev_var);

		free(entry);

		envlist->el_count--;

	}

	return (0);

}


static int ehci_state_fetchitd(EHCIState *ehci, int async)

{

    uint32_t entry;

    EHCIitd itd;

    assert(!async);

    entry = ehci_get_fetch_addr(ehci, async);

    get_dwords(NLPTR_GET(entry),(uint32_t *) &itd,

               sizeof(EHCIitd) >> 2);

    ehci_trace_itd(ehci, entry, &itd);

    if (ehci_process_itd(ehci, &itd) != 0) {

        return -1;

    }

    put_dwords(NLPTR_GET(entry), (uint32_t *) &itd,

                sizeof(EHCIitd) >> 2);

    ehci_set_fetch_addr(ehci, async, itd.next);

    ehci_set_state(ehci, async, EST_FETCHENTRY);

    return 1;

}


static int decode_b_mbs(VC9Context *v)

{

    int x, y, current_mb = 0 , last_mb = v->height_mb*v->width_mb,

        i /* MB / B postion information */;

    int direct_b_bit = 0, skip_mb_bit = 0;

    int ac_pred;

    int b_mv1 = 0, b_mv2 = 0, b_mv_type = 0;

    int mquant, mqdiff; /* MB quant stuff */

    int tt_block; /* Block transform type */

    for (y=0; y<v->height_mb; y++)

    {

        for (x=0; x<v->width_mb; x++)

        {

            if (v->direct_mb_plane[current_mb])

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

            if (1 /* Skip mode is raw */)

            {

                /* FIXME getting tired commenting */

#if 0

                skip_mb_bit = get_bits(&v->gb, n); //vlc

#endif

            }

            if (!direct_b_bit)

            {

                if (skip_mb_bit)

                {

                    /* FIXME getting tired commenting */

#if 0

                    b_mv_type = get_bits(&v->gb, n); //vlc

#endif

                }

                else

                {

                    /* FIXME getting tired commenting */

#if 0

                    b_mv1 = get_bits(&v->gb, n); //VLC

#endif

                    if (1 /* b_mv1 isn't intra */)

                    {

                        /* FIXME: actually read it */

                        b_mv_type = 0; //vlc

                    }

                }

            }

            if (!skip_mb_bit)

            {

                if (b_mv1 != last_mb)

                {

                    GET_MQUANT();

                    if (1 /* intra mb */)

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

                }

                else

                {

                    if (1 /* forward_mb is interpolate */)

                    {

                        /* FIXME: actually read it */

                        b_mv2 = 0; //vlc

                    }

                    if (1 /* b_mv2 isn't the last */)

                    {

                        if (1 /* intra_mb */)

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

                        GET_MQUANT();

                    }

                }

            }

            //End1

            /* FIXME getting tired, commenting */

#if 0

            if (v->ttmbf)

                v->ttmb = get_bits(&v->gb, n); //vlc

#endif

        }

        //End2

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

        {

            /* FIXME: process the block */

        }

        current_mb++;

    }

    return 0;

}


static int ram_save_iterate(QEMUFile *f, void *opaque)

{

    int ret;

    int i;

    int64_t t0;

    int total_sent = 0;

    qemu_mutex_lock_ramlist();

    if (ram_list.version != last_version) {

        reset_ram_globals();

    }

    ram_control_before_iterate(f, RAM_CONTROL_ROUND);

    t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);

    i = 0;

    while ((ret = qemu_file_rate_limit(f)) == 0) {

        int bytes_sent;

        bytes_sent = ram_save_block(f, false);

        /* no more blocks to sent */

        if (bytes_sent == 0) {

            break;

        }

        total_sent += bytes_sent;

        acct_info.iterations++;

        check_guest_throttling();

        /* we want to check in the 1st loop, just in case it was the 1st time

           and we had to sync the dirty bitmap.

           qemu_get_clock_ns() is a bit expensive, so we only check each some

           iterations

        */

        if ((i & 63) == 0) {

            uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) / 1000000;

            if (t1 > MAX_WAIT) {

                DPRINTF("big wait: %" PRIu64 " milliseconds, %d iterations\n",

                        t1, i);

                break;

            }

        }

        i++;

    }

    qemu_mutex_unlock_ramlist();

    /*

     * Must occur before EOS (or any QEMUFile operation)

     * because of RDMA protocol.

     */

    ram_control_after_iterate(f, RAM_CONTROL_ROUND);

    if (ret < 0) {

        bytes_transferred += total_sent;

        return ret;

    }

    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);

    total_sent += 8;

    bytes_transferred += total_sent;

    return total_sent;

}


static void *file_ram_alloc(RAMBlock *block,

                            ram_addr_t memory,

                            const char *path,

                            Error **errp)

{

    char *filename;

    char *sanitized_name;

    char *c;

    void *area;

    int fd;

    uint64_t hpagesize;

    Error *local_err = NULL;

    hpagesize = gethugepagesize(path, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto error;

    }

    block->mr->align = hpagesize;

    if (memory < hpagesize) {

        error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "

                   "or larger than huge page size 0x%" PRIx64,

                   memory, hpagesize);

        goto error;

    }

    if (kvm_enabled() && !kvm_has_sync_mmu()) {

        error_setg(errp,

                   "host lacks kvm mmu notifiers, -mem-path unsupported");

        goto error;

    }

    /* Make name safe to use with mkstemp by replacing '/' with '_'. */

    sanitized_name = g_strdup(memory_region_name(block->mr));

    for (c = sanitized_name; *c != '\0'; c++) {

        if (*c == '/')

            *c = '_';

    }

    filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,

                               sanitized_name);

    g_free(sanitized_name);

    fd = mkstemp(filename);

    if (fd < 0) {

        error_setg_errno(errp, errno,

                         "unable to create backing store for hugepages");

        g_free(filename);

        goto error;

    }

    unlink(filename);

    g_free(filename);

    memory = ROUND_UP(memory, hpagesize);

    /*

     * ftruncate is not supported by hugetlbfs in older

     * hosts, so don't bother bailing out on errors.

     * If anything goes wrong with it under other filesystems,

     * mmap will fail.

     */

    if (ftruncate(fd, memory)) {

        perror("ftruncate");

    }

    area = qemu_ram_mmap(fd, memory, hpagesize, block->flags & RAM_SHARED);

    if (area == MAP_FAILED) {

        error_setg_errno(errp, errno,

                         "unable to map backing store for hugepages");

        close(fd);

        goto error;

    }

    if (mem_prealloc) {

        os_mem_prealloc(fd, area, memory);

    }

    block->fd = fd;

    return area;

error:

    return NULL;

}


static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockDriverCompletionFunc *cb, void *opaque)

{

    RawAIOCB *acb;

    acb = raw_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque);

    if (!acb)

        return NULL;

    if (qemu_paio_read(&acb->aiocb) < 0) {

        raw_aio_remove(acb);

        return NULL;

    }

    return &acb->common;

}


void ff_ivi_inverse_haar_8x8(const int32_t *in, int16_t *out, ptrdiff_t pitch,

                             const uint8_t *flags)

{

    int     i, shift, sp1, sp2, sp3, sp4;

    const int32_t *src;

    int32_t *dst;

    int     tmp[64];

    int     t0, t1, t2, t3, t4, t5, t6, t7, t8;

    /* apply the InvHaar8 to all columns */

#define COMPENSATE(x) (x)

    src = in;

    dst = tmp;

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

        if (flags[i]) {

            /* pre-scaling */

            shift = !(i & 4);

            sp1 = src[ 0] << shift;

            sp2 = src[ 8] << shift;

            sp3 = src[16] << shift;

            sp4 = src[24] << shift;

            INV_HAAR8(    sp1,     sp2,     sp3,     sp4,

                      src[32], src[40], src[48], src[56],

                      dst[ 0], dst[ 8], dst[16], dst[24],

                      dst[32], dst[40], dst[48], dst[56],

                      t0, t1, t2, t3, t4, t5, t6, t7, t8);

        } else

            dst[ 0] = dst[ 8] = dst[16] = dst[24] =

            dst[32] = dst[40] = dst[48] = dst[56] = 0;

        src++;

        dst++;

    }

#undef  COMPENSATE

    /* apply the InvHaar8 to all rows */

#define COMPENSATE(x) (x)

    src = tmp;

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

        if (   !src[0] && !src[1] && !src[2] && !src[3]

            && !src[4] && !src[5] && !src[6] && !src[7]) {

            memset(out, 0, 8 * sizeof(out[0]));

        } else {

            INV_HAAR8(src[0], src[1], src[2], src[3],

                      src[4], src[5], src[6], src[7],

                      out[0], out[1], out[2], out[3],

                      out[4], out[5], out[6], out[7],

                      t0, t1, t2, t3, t4, t5, t6, t7, t8);

        }

        src += 8;

        out += pitch;

    }

#undef  COMPENSATE

}


av_cold void ff_flacdsp_init_x86(FLACDSPContext *c, enum AVSampleFormat fmt,

                                 int bps)

{

#if HAVE_YASM

    int cpu_flags = av_get_cpu_flags();

    if (EXTERNAL_SSE4(cpu_flags)) {

        if (bps > 16 && CONFIG_FLAC_DECODER)

            c->lpc = ff_flac_lpc_32_sse4;

    }

    if (EXTERNAL_XOP(cpu_flags)) {

        if (bps > 16)

            c->lpc = ff_flac_lpc_32_xop;

    }

#endif

}


static void up_heap(uint32_t val, uint32_t *heap, uint32_t *weights)

{

    uint32_t initial_val = heap[val];

    while (weights[initial_val] < weights[heap[val >> 1]]) {

        heap[val] = heap[val >> 1];

        val     >>= 1;

    }

    heap[val] = initial_val;

}


static int vmstate_size(void *opaque, VMStateField *field)

{

    int size = field->size;

    if (field->flags & VMS_VBUFFER) {

        size = *(int32_t *)(opaque+field->size_offset);

        if (field->flags & VMS_MULTIPLY) {

            size *= field->size;

        }

    }

    return size;

}


void ff_simple_idct84_add(uint8_t *dest, int line_size, DCTELEM *block)

{

    int i;

    /* IDCT8 on each line */

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

        idctRowCondDC_8(block + i*8);

    }

    /* IDCT4 and store */

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

        idct4col_add(dest + i, line_size, block + i);

    }

}


int net_handle_fd_param(Monitor *mon, const char *param)

{

    if (!qemu_isdigit(param[0])) {

        int fd;

        fd = monitor_get_fd(mon, param);

        if (fd == -1) {

            error_report("No file descriptor named %s found", param);

            return -1;

        }

        return fd;

    } else {

        return strtol(param, NULL, 0);

    }

}


static int tee_write_trailer(AVFormatContext *avf)

{

    TeeContext *tee = avf->priv_data;

    AVFormatContext *avf2;

    int ret_all = 0, ret;

    unsigned i;

    for (i = 0; i < tee->nb_slaves; i++) {

        avf2 = tee->slaves[i].avf;

        if ((ret = av_write_trailer(avf2)) < 0)

            if (!ret_all)

                ret_all = ret;

        if (!(avf2->oformat->flags & AVFMT_NOFILE))

            ff_format_io_close(avf2, &avf2->pb);

    }

    close_slaves(avf);

    return ret_all;

}


static int write_trailer(AVFormatContext *s){

    NUTContext *nut= s->priv_data;

    AVIOContext *bc= s->pb;

    while(nut->header_count<3)

        write_headers(s, bc);

    avio_flush(bc);

    ff_nut_free_sp(nut);

    av_freep(&nut->stream);

    av_freep(&nut->time_base);

    return 0;

}


static void vmgenid_set_guid_test(void)

{

    QemuUUID expected, measured;

    gchar *cmd;

    g_assert(qemu_uuid_parse(VGID_GUID, &expected) == 0);

    cmd = g_strdup_printf("-machine accel=tcg -device vmgenid,id=testvgid,"

                          "guid=%s", VGID_GUID);

    qtest_start(cmd);

    /* Read the GUID from accessing guest memory */

    read_guid_from_memory(&measured);

    g_assert(memcmp(measured.data, expected.data, sizeof(measured.data)) == 0);

    qtest_quit(global_qtest);

    g_free(cmd);

}


static int rtp_write(URLContext *h, const uint8_t *buf, int size)
{
    RTPContext *s = h->priv_data;
    int ret;
    URLContext *hd;
    if (RTP_PT_IS_RTCP(buf[1])) {
        /* RTCP payload type */
        hd = s->rtcp_hd;
    } else {
        /* RTP payload type */
        hd = s->rtp_hd;
    }
    ret = ffurl_write(hd, buf, size);
    return ret;
}


static unsigned int dec_addi_acr(DisasContext *dc)

{

	TCGv t0;

	DIS(fprintf (logfile, "addi.%c $r%u, $r%u, $acr\n",

		  memsize_char(memsize_zz(dc)), dc->op2, dc->op1));

	cris_cc_mask(dc, 0);

	t0 = tcg_temp_new(TCG_TYPE_TL);

	tcg_gen_shl_tl(t0, cpu_R[dc->op2], tcg_const_tl(dc->zzsize));

	tcg_gen_add_tl(cpu_R[R_ACR], cpu_R[dc->op1], t0);

	return 2;

}


int ff_insert_pad(unsigned idx, unsigned *count, size_t padidx_off,

                   AVFilterPad **pads, AVFilterLink ***links,

                   AVFilterPad *newpad)

{

    AVFilterLink **newlinks;

    AVFilterPad *newpads;

    unsigned i;

    idx = FFMIN(idx, *count);

    newpads  = av_realloc_array(*pads,  *count + 1, sizeof(AVFilterPad));

    newlinks = av_realloc_array(*links, *count + 1, sizeof(AVFilterLink*));

    if (newpads)

        *pads  = newpads;

    if (newlinks)

        *links = newlinks;

    if (!newpads || !newlinks)

        return AVERROR(ENOMEM);

    memmove(*pads  + idx + 1, *pads  + idx, sizeof(AVFilterPad)   * (*count - idx));

    memmove(*links + idx + 1, *links + idx, sizeof(AVFilterLink*) * (*count - idx));

    memcpy(*pads + idx, newpad, sizeof(AVFilterPad));

    (*links)[idx] = NULL;

    (*count)++;

    for (i = idx + 1; i < *count; i++)

        if (*links[i])

            (*(unsigned *)((uint8_t *) *links[i] + padidx_off))++;

    return 0;

}


sbappend(struct socket *so, struct mbuf *m)

{

	int ret = 0;

	DEBUG_CALL("sbappend");

	DEBUG_ARG("so = %p", so);

	DEBUG_ARG("m = %p", m);

	DEBUG_ARG("m->m_len = %d", m->m_len);

	/* Shouldn't happen, but...  e.g. foreign host closes connection */

	if (m->m_len <= 0) {

		m_free(m);

		return;

	}

	/*

	 * If there is urgent data, call sosendoob

	 * if not all was sent, sowrite will take care of the rest

	 * (The rest of this function is just an optimisation)

	 */

	if (so->so_urgc) {

		sbappendsb(&so->so_rcv, m);

		m_free(m);

		sosendoob(so);

		return;

	}

	/*

	 * We only write if there's nothing in the buffer,

	 * ottherwise it'll arrive out of order, and hence corrupt

	 */

	if (!so->so_rcv.sb_cc)

	   ret = slirp_send(so, m->m_data, m->m_len, 0);

	if (ret <= 0) {

		/*

		 * Nothing was written

		 * It's possible that the socket has closed, but

		 * we don't need to check because if it has closed,

		 * it will be detected in the normal way by soread()

		 */

		sbappendsb(&so->so_rcv, m);

	} else if (ret != m->m_len) {

		/*

		 * Something was written, but not everything..

		 * sbappendsb the rest

		 */

		m->m_len -= ret;

		m->m_data += ret;

		sbappendsb(&so->so_rcv, m);

	} /* else */

	/* Whatever happened, we free the mbuf */

	m_free(m);

}


static int xan_decode_chroma(AVCodecContext *avctx, unsigned chroma_off)

{

    XanContext *s = avctx->priv_data;

    uint8_t *U, *V;

    int val, uval, vval;

    int i, j;

    const uint8_t *src, *src_end;

    const uint8_t *table;

    int mode, offset, dec_size;

    if (!chroma_off)

        return 0;

    if (chroma_off + 4 >= bytestream2_get_bytes_left(&s->gb)) {

        av_log(avctx, AV_LOG_ERROR, "Invalid chroma block position\n");

        return -1;

    }

    bytestream2_seek(&s->gb, chroma_off + 4, SEEK_SET);

    mode   = bytestream2_get_le16(&s->gb);

    table  = s->gb.buffer;

    offset = bytestream2_get_le16(&s->gb) * 2;

    if (offset >= bytestream2_get_bytes_left(&s->gb)) {

        av_log(avctx, AV_LOG_ERROR, "Invalid chroma block offset\n");

        return -1;

    }

    bytestream2_skip(&s->gb, offset);

    memset(s->scratch_buffer, 0, s->buffer_size);

    dec_size = xan_unpack(s, s->scratch_buffer, s->buffer_size);

    if (dec_size < 0) {

        av_log(avctx, AV_LOG_ERROR, "Chroma unpacking failed\n");

        return -1;

    }

    U = s->pic.data[1];

    V = s->pic.data[2];

    src     = s->scratch_buffer;

    src_end = src + dec_size;

    if (mode) {

        for (j = 0; j < avctx->height >> 1; j++) {

            for (i = 0; i < avctx->width >> 1; i++) {

                val = *src++;

                if (val) {

                    val  = AV_RL16(table + (val << 1));

                    uval = (val >> 3) & 0xF8;

                    vval = (val >> 8) & 0xF8;

                    U[i] = uval | (uval >> 5);

                    V[i] = vval | (vval >> 5);

                }

                if (src == src_end)

                    return 0;

            }

            U += s->pic.linesize[1];

            V += s->pic.linesize[2];

        }

    } else {

        uint8_t *U2 = U + s->pic.linesize[1];

        uint8_t *V2 = V + s->pic.linesize[2];

        for (j = 0; j < avctx->height >> 2; j++) {

            for (i = 0; i < avctx->width >> 1; i += 2) {

                val = *src++;

                if (val) {

                    val  = AV_RL16(table + (val << 1));

                    uval = (val >> 3) & 0xF8;

                    vval = (val >> 8) & 0xF8;

                    U[i] = U[i+1] = U2[i] = U2[i+1] = uval | (uval >> 5);

                    V[i] = V[i+1] = V2[i] = V2[i+1] = vval | (vval >> 5);

                }

            }

            U  += s->pic.linesize[1] * 2;

            V  += s->pic.linesize[2] * 2;

            U2 += s->pic.linesize[1] * 2;

            V2 += s->pic.linesize[2] * 2;

        }

    }

    return 0;

}


void filter_mb(VP8Context *s, uint8_t *dst[3], VP8FilterStrength *f,

               int mb_x, int mb_y)

{

    int mbedge_lim, bedge_lim, hev_thresh;

    int filter_level = f->filter_level;

    int inner_limit = f->inner_limit;

    int inner_filter = f->inner_filter;

    int linesize = s->linesize;

    int uvlinesize = s->uvlinesize;

    static const uint8_t hev_thresh_lut[2][64] = {

        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,

          2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,

          3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,

          3, 3, 3, 3 },

        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,

          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,

          2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,

          2, 2, 2, 2 }

    };

    if (!filter_level)

        return;

    bedge_lim  = 2 * filter_level + inner_limit;

    mbedge_lim = bedge_lim + 4;

    hev_thresh = hev_thresh_lut[s->keyframe][filter_level];

    if (mb_x) {

        s->vp8dsp.vp8_h_loop_filter16y(dst[0], linesize,

                                       mbedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_h_loop_filter8uv(dst[1], dst[2], uvlinesize,

                                       mbedge_lim, inner_limit, hev_thresh);

    }

    if (inner_filter) {

        s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0] +  4, linesize, bedge_lim,

                                             inner_limit, hev_thresh);

        s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0] +  8, linesize, bedge_lim,

                                             inner_limit, hev_thresh);

        s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0] + 12, linesize, bedge_lim,

                                             inner_limit, hev_thresh);

        s->vp8dsp.vp8_h_loop_filter8uv_inner(dst[1] +  4, dst[2] + 4,

                                             uvlinesize, bedge_lim,

                                             inner_limit, hev_thresh);

    }

    if (mb_y) {

        s->vp8dsp.vp8_v_loop_filter16y(dst[0], linesize,

                                       mbedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_v_loop_filter8uv(dst[1], dst[2], uvlinesize,

                                       mbedge_lim, inner_limit, hev_thresh);

    }

    if (inner_filter) {

        s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0] +  4 * linesize,

                                             linesize, bedge_lim,

                                             inner_limit, hev_thresh);

        s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0] +  8 * linesize,

                                             linesize, bedge_lim,

                                             inner_limit, hev_thresh);

        s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0] + 12 * linesize,

                                             linesize, bedge_lim,

                                             inner_limit, hev_thresh);

        s->vp8dsp.vp8_v_loop_filter8uv_inner(dst[1] +  4 * uvlinesize,

                                             dst[2] +  4 * uvlinesize,

                                             uvlinesize, bedge_lim,

                                             inner_limit, hev_thresh);

    }

}


static void migrate_check_parameter(QTestState *who, const char *parameter,

                                    const char *value)

{

    QDict *rsp, *rsp_return;

    const char *result;

    rsp = wait_command(who, "{ 'execute': 'query-migrate-parameters' }");

    rsp_return = qdict_get_qdict(rsp, "return");

    result = g_strdup_printf("%" PRId64,

                             qdict_get_try_int(rsp_return,  parameter, -1));

    g_assert_cmpstr(result, ==, value);

    QDECREF(rsp);

}


int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)

{

    AVCodecContext *avctx = h->s.avctx;

    if (!buf || size <= 0)

        return -1;

    if (buf[0] == 1) {

        int i, cnt, nalsize;

        const unsigned char *p = buf;

        h->is_avc = 1;

        if (size < 7) {

            av_log(avctx, AV_LOG_ERROR, "avcC too short\n");

            return -1;

        }

        /* sps and pps in the avcC always have length coded with 2 bytes,

         * so put a fake nal_length_size = 2 while parsing them */

        h->nal_length_size = 2;

        // Decode sps from avcC

        cnt = *(p + 5) & 0x1f; // Number of sps

        p  += 6;

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

            nalsize = AV_RB16(p) + 2;

            if(nalsize > size - (p-buf))

                return -1;

            if (decode_nal_units(h, p, nalsize) < 0) {

                av_log(avctx, AV_LOG_ERROR,

                       "Decoding sps %d from avcC failed\n", i);

                return -1;

            }

            p += nalsize;

        }

        // Decode pps from avcC

        cnt = *(p++); // Number of pps

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

            nalsize = AV_RB16(p) + 2;

            if(nalsize > size - (p-buf))

                return -1;

            if (decode_nal_units(h, p, nalsize) < 0) {

                av_log(avctx, AV_LOG_ERROR,

                       "Decoding pps %d from avcC failed\n", i);

                return -1;

            }

            p += nalsize;

        }

        // Now store right nal length size, that will be used to parse all other nals

        h->nal_length_size = (buf[4] & 0x03) + 1;

    } else {

        h->is_avc = 0;

        if (decode_nal_units(h, buf, size) < 0)

            return -1;

    }

    return size;

}


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

{

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

        gen_io_start();

    }

    gen_helper_store_hdecr(cpu_env, cpu_gpr[gprn]);

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

        gen_io_end();

        gen_stop_exception(ctx);

    }

}


static int ioreq_parse(struct ioreq *ioreq)

{

    struct XenBlkDev *blkdev = ioreq->blkdev;

    uintptr_t mem;

    size_t len;

    int i;

    xen_be_printf(&blkdev->xendev, 3,

		  "op %d, nr %d, handle %d, id %" PRId64 ", sector %" PRId64 "\n",

		  ioreq->req.operation, ioreq->req.nr_segments,

		  ioreq->req.handle, ioreq->req.id, ioreq->req.sector_number);

    switch (ioreq->req.operation) {

    case BLKIF_OP_READ:

	ioreq->prot = PROT_WRITE; /* to memory */

        if (ioreq->req.operation != BLKIF_OP_READ && blkdev->mode[0] != 'w') {

	    xen_be_printf(&blkdev->xendev, 0, "error: write req for ro device\n");

	    goto err;

	}

	break;

    case BLKIF_OP_WRITE_BARRIER:

	if (!syncwrite)

	    ioreq->presync = ioreq->postsync = 1;

	/* fall through */

    case BLKIF_OP_WRITE:

	ioreq->prot = PROT_READ; /* from memory */

	if (syncwrite)

	    ioreq->postsync = 1;

	break;

    default:

	xen_be_printf(&blkdev->xendev, 0, "error: unknown operation (%d)\n",

		      ioreq->req.operation);

	goto err;

    };

    ioreq->start = ioreq->req.sector_number * blkdev->file_blk;

    for (i = 0; i < ioreq->req.nr_segments; i++) {

	if (i == BLKIF_MAX_SEGMENTS_PER_REQUEST) {

	    xen_be_printf(&blkdev->xendev, 0, "error: nr_segments too big\n");

	    goto err;

	}

	if (ioreq->req.seg[i].first_sect > ioreq->req.seg[i].last_sect) {

	    xen_be_printf(&blkdev->xendev, 0, "error: first > last sector\n");

	    goto err;

	}

	if (ioreq->req.seg[i].last_sect * BLOCK_SIZE >= XC_PAGE_SIZE) {

	    xen_be_printf(&blkdev->xendev, 0, "error: page crossing\n");

	    goto err;

	}

	ioreq->domids[i] = blkdev->xendev.dom;

	ioreq->refs[i]   = ioreq->req.seg[i].gref;

	mem = ioreq->req.seg[i].first_sect * blkdev->file_blk;

	len = (ioreq->req.seg[i].last_sect - ioreq->req.seg[i].first_sect + 1) * blkdev->file_blk;

        qemu_iovec_add(&ioreq->v, (void*)mem, len);

    }

    if (ioreq->start + ioreq->v.size > blkdev->file_size) {

	xen_be_printf(&blkdev->xendev, 0, "error: access beyond end of file\n");

	goto err;

    }

    return 0;

err:

    ioreq->status = BLKIF_RSP_ERROR;

    return -1;

}


static void test_qemu_strtoul_full_empty(void)

{

    const char *str = "";

    unsigned long res = 999;

    int err;

    err = qemu_strtoul(str, NULL, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 0);

}


static void xen_sysdev_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);

    k->init = xen_sysdev_init;

    dc->props = xen_sysdev_properties;

    dc->bus_type = TYPE_XENSYSBUS;

}


static int vqf_read_header(AVFormatContext *s)

{

    VqfContext *c = s->priv_data;

    AVStream *st  = avformat_new_stream(s, NULL);

    int chunk_tag;

    int rate_flag = -1;

    int header_size;

    int read_bitrate = 0;

    int size;

    uint8_t comm_chunk[12];

    if (!st)

        return AVERROR(ENOMEM);

    avio_skip(s->pb, 12);

    header_size = avio_rb32(s->pb);

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_id   = AV_CODEC_ID_TWINVQ;

    st->start_time = 0;

    do {

        int len;

        chunk_tag = avio_rl32(s->pb);

        if (chunk_tag == MKTAG('D','A','T','A'))

            break;

        len = avio_rb32(s->pb);

        if ((unsigned) len > INT_MAX/2) {

            av_log(s, AV_LOG_ERROR, "Malformed header\n");

        header_size -= 8;

        switch(chunk_tag){

        case MKTAG('C','O','M','M'):

            avio_read(s->pb, comm_chunk, 12);

            st->codec->channels = AV_RB32(comm_chunk    ) + 1;

            read_bitrate        = AV_RB32(comm_chunk + 4);

            rate_flag           = AV_RB32(comm_chunk + 8);

            avio_skip(s->pb, len-12);

            st->codec->bit_rate              = read_bitrate*1000;

            break;

        case MKTAG('D','S','I','Z'): // size of compressed data

        {

            char buf[8] = {0};

            int size = avio_rb32(s->pb);

            snprintf(buf, sizeof(buf), "%d", size);

            av_dict_set(&s->metadata, "size", buf, 0);

            break;

        case MKTAG('Y','E','A','R'): // recording date

        case MKTAG('E','N','C','D'): // compression date

        case MKTAG('E','X','T','R'): // reserved

        case MKTAG('_','Y','M','H'): // reserved

        case MKTAG('_','N','T','T'): // reserved

        case MKTAG('_','I','D','3'): // reserved for ID3 tags

            avio_skip(s->pb, FFMIN(len, header_size));

            break;

        default:

            add_metadata(s, chunk_tag, len, header_size);

            break;

        header_size -= len;

    } while (header_size >= 0);

    switch (rate_flag) {

    case -1:

        av_log(s, AV_LOG_ERROR, "COMM tag not found!\n");

    case 44:

        st->codec->sample_rate = 44100;

        break;

    case 22:

        st->codec->sample_rate = 22050;

        break;

    case 11:

        st->codec->sample_rate = 11025;

        break;

    default:

        st->codec->sample_rate = rate_flag*1000;

        break;

    switch (((st->codec->sample_rate/1000) << 8) +

            read_bitrate/st->codec->channels) {

    case (11<<8) + 8 :

    case (8 <<8) + 8 :

    case (11<<8) + 10:

    case (22<<8) + 32:

        size = 512;

        break;

    case (16<<8) + 16:

    case (22<<8) + 20:

    case (22<<8) + 24:

        size = 1024;

        break;

    case (44<<8) + 40:

    case (44<<8) + 48:

        size = 2048;

        break;

    default:

        av_log(s, AV_LOG_ERROR, "Mode not suported: %d Hz, %d kb/s.\n",

               st->codec->sample_rate, st->codec->bit_rate);

    c->frame_bit_len = st->codec->bit_rate*size/st->codec->sample_rate;

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

    /* put first 12 bytes of COMM chunk in extradata */

    if (!(st->codec->extradata = av_malloc(12 + FF_INPUT_BUFFER_PADDING_SIZE)))

        return AVERROR(ENOMEM);

    st->codec->extradata_size = 12;

    memcpy(st->codec->extradata, comm_chunk, 12);

    ff_metadata_conv_ctx(s, NULL, vqf_metadata_conv);

    return 0;


int qemu_sendv(int sockfd, struct iovec *iov, int len, int iov_offset)

{

    return do_sendv_recvv(sockfd, iov, len, iov_offset, 1);

}


static int gdb_handle_vcont(GDBState *s, const char *p)

{

    int res, idx, signal = 0;

    char cur_action;

    char *newstates;

    unsigned long tmp;

    CPUState *cpu;

#ifdef CONFIG_USER_ONLY

    int max_cpus = 1; /* global variable max_cpus exists only in system mode */

    CPU_FOREACH(cpu) {

        max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;

    }

#endif

    /* uninitialised CPUs stay 0 */

    newstates = g_new0(char, max_cpus);

    /* mark valid CPUs with 1 */

    CPU_FOREACH(cpu) {

        newstates[cpu->cpu_index] = 1;

    }

    /*

     * res keeps track of what error we are returning, with -ENOTSUP meaning

     * that the command is unknown or unsupported, thus returning an empty

     * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,

     *  or incorrect parameters passed.

     */

    res = 0;

    while (*p) {

        if (*p++ != ';') {

            res = -ENOTSUP;

            goto out;

        }

        cur_action = *p++;

        if (cur_action == 'C' || cur_action == 'S') {

            cur_action = tolower(cur_action);

            res = qemu_strtoul(p + 1, &p, 16, &tmp);

            if (res) {

                goto out;

            }

            signal = gdb_signal_to_target(tmp);

        } else if (cur_action != 'c' && cur_action != 's') {

            /* unknown/invalid/unsupported command */

            res = -ENOTSUP;

            goto out;

        }

        /* thread specification. special values: (none), -1 = all; 0 = any */

        if ((p[0] == ':' && p[1] == '-' && p[2] == '1') || (p[0] != ':')) {

            if (*p == ':') {

                p += 3;

            }

            for (idx = 0; idx < max_cpus; idx++) {

                if (newstates[idx] == 1) {

                    newstates[idx] = cur_action;

                }

            }

        } else if (*p == ':') {

            p++;

            res = qemu_strtoul(p, &p, 16, &tmp);

            if (res) {

                goto out;

            }

            /* 0 means any thread, so we pick the first valid CPU */

            cpu = tmp ? find_cpu(tmp) : first_cpu;

            /* invalid CPU/thread specified */

            if (!cpu) {

                res = -EINVAL;

                goto out;

            }

            /* only use if no previous match occourred */

            if (newstates[cpu->cpu_index] == 1) {

                newstates[cpu->cpu_index] = cur_action;

            }

        }

    }

    s->signal = signal;

    gdb_continue_partial(s, newstates);

out:

    g_free(newstates);

    return res;

}


static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)

{

    AVFormatContext *s = of->ctx;

    AVStream *st = ost->st;

    int ret;

    if (!of->header_written) {

        AVPacket tmp_pkt;

        /* the muxer is not initialized yet, buffer the packet */

        if (!av_fifo_space(ost->muxing_queue)) {

            int new_size = FFMIN(2 * av_fifo_size(ost->muxing_queue),

                                 ost->max_muxing_queue_size);

            if (new_size <= av_fifo_size(ost->muxing_queue)) {

                av_log(NULL, AV_LOG_ERROR,

                       "Too many packets buffered for output stream %d:%d.\n",

                       ost->file_index, ost->st->index);

                exit_program(1);

            }

            ret = av_fifo_realloc2(ost->muxing_queue, new_size);

            if (ret < 0)

                exit_program(1);

        }

        av_packet_move_ref(&tmp_pkt, pkt);

        av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);

        return;

    }

    if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||

        (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))

        pkt->pts = pkt->dts = AV_NOPTS_VALUE;

    /*

     * Audio encoders may split the packets --  #frames in != #packets out.

     * But there is no reordering, so we can limit the number of output packets

     * by simply dropping them here.

     * Counting encoded video frames needs to be done separately because of

     * reordering, see do_video_out()

     */

    if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed)) {

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

            av_packet_unref(pkt);

            return;

        }

        ost->frame_number++;

    }

    if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {

        int i;

        uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,

                                              NULL);

        ost->quality = sd ? AV_RL32(sd) : -1;

        ost->pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;

        for (i = 0; i<FF_ARRAY_ELEMS(ost->error); i++) {

            if (sd && i < sd[5])

                ost->error[i] = AV_RL64(sd + 8 + 8*i);

            else

                ost->error[i] = -1;

        }

        if (ost->frame_rate.num && ost->is_cfr) {

            if (pkt->duration > 0)

                av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");

            pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),

                                         ost->st->time_base);

        }

    }

    if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {

        if (pkt->dts != AV_NOPTS_VALUE &&

            pkt->pts != AV_NOPTS_VALUE &&

            pkt->dts > pkt->pts) {

            av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",

                   pkt->dts, pkt->pts,

                   ost->file_index, ost->st->index);

            pkt->pts =

            pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1

                     - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)

                     - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);

        }

        if ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&

            pkt->dts != AV_NOPTS_VALUE &&

            !(st->codecpar->codec_id == AV_CODEC_ID_VP9 && ost->stream_copy) &&

            ost->last_mux_dts != AV_NOPTS_VALUE) {

            int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);

            if (pkt->dts < max) {

                int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;

                av_log(s, loglevel, "Non-monotonous DTS in output stream "

                       "%d:%d; previous: %"PRId64", current: %"PRId64"; ",

                       ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);

                if (exit_on_error) {

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

                    exit_program(1);

                }

                av_log(s, loglevel, "changing to %"PRId64". This may result "

                       "in incorrect timestamps in the output file.\n",

                       max);

                if (pkt->pts >= pkt->dts)

                    pkt->pts = FFMAX(pkt->pts, max);

                pkt->dts = max;

            }

        }

    }

    ost->last_mux_dts = pkt->dts;

    ost->data_size += pkt->size;

    ost->packets_written++;

    pkt->stream_index = ost->index;

    if (debug_ts) {

        av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "

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

                av_get_media_type_string(ost->enc_ctx->codec_type),

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

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

                pkt->size

              );

    }

    ret = av_interleaved_write_frame(s, pkt);

    if (ret < 0) {

        print_error("av_interleaved_write_frame()", ret);

        main_return_code = 1;

        close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);

    }

    av_packet_unref(pkt);

}


void bdrv_commit_all(void)

{

    BlockDriverState *bs;

    QTAILQ_FOREACH(bs, &bdrv_states, list) {

        bdrv_commit(bs);

    }

}


static int event_qdev_exit(DeviceState *qdev)

{

    SCLPEvent *event = DO_UPCAST(SCLPEvent, qdev, qdev);

    SCLPEventClass *child = SCLP_EVENT_GET_CLASS(event);

    if (child->exit) {

        child->exit(event);

    }

    return 0;

}


static av_cold int amr_wb_encode_init(AVCodecContext *avctx)

{

    AMRWBContext *s = avctx->priv_data;

    if (avctx->sample_rate != 16000) {

        av_log(avctx, AV_LOG_ERROR, "Only 16000Hz sample rate supported\n");

        return AVERROR(ENOSYS);

    }

    if (avctx->channels != 1) {

        av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");

        return AVERROR(ENOSYS);

    }

    s->mode            = get_wb_bitrate_mode(avctx->bit_rate, avctx);

    s->last_bitrate    = avctx->bit_rate;

    avctx->frame_size  = 320;

    avctx->delay       =  80;

    s->state     = E_IF_init();

    return 0;

}