static int roq_read_packet(AVFormatContext *s,

                           AVPacket *pkt)

{

    RoqDemuxContext *roq = s->priv_data;

    AVIOContext *pb = s->pb;

    int ret = 0;

    unsigned int chunk_size;

    unsigned int chunk_type;

    unsigned int codebook_size;

    unsigned char preamble[RoQ_CHUNK_PREAMBLE_SIZE];

    int packet_read = 0;

    int64_t codebook_offset;

    while (!packet_read) {

        if (avio_feof(s->pb))

            return AVERROR(EIO);

        /* get the next chunk preamble */

        if ((ret = avio_read(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE)) !=

            RoQ_CHUNK_PREAMBLE_SIZE)

            return AVERROR(EIO);

        chunk_type = AV_RL16(&preamble[0]);

        chunk_size = AV_RL32(&preamble[2]);

        if(chunk_size > INT_MAX)

            return AVERROR_INVALIDDATA;

        chunk_size = ffio_limit(pb, chunk_size);

        switch (chunk_type) {

        case RoQ_INFO:

            if (roq->video_stream_index == -1) {

                AVStream *st = avformat_new_stream(s, NULL);

                if (!st)

                    return AVERROR(ENOMEM);

                avpriv_set_pts_info(st, 63, 1, roq->frame_rate);

                roq->video_stream_index = st->index;

                st->codecpar->codec_type   = AVMEDIA_TYPE_VIDEO;

                st->codecpar->codec_id     = AV_CODEC_ID_ROQ;

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

                if (avio_read(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) != RoQ_CHUNK_PREAMBLE_SIZE)

                    return AVERROR(EIO);

                st->codecpar->width  = roq->width  = AV_RL16(preamble);

                st->codecpar->height = roq->height = AV_RL16(preamble + 2);

                break;

            }

            /* don't care about this chunk anymore */

            avio_skip(pb, RoQ_CHUNK_PREAMBLE_SIZE);

            break;

        case RoQ_QUAD_CODEBOOK:

            if (roq->video_stream_index < 0)

                return AVERROR_INVALIDDATA;

            /* packet needs to contain both this codebook and next VQ chunk */

            codebook_offset = avio_tell(pb) - RoQ_CHUNK_PREAMBLE_SIZE;

            codebook_size = chunk_size;

            avio_skip(pb, codebook_size);

            if (avio_read(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=

                RoQ_CHUNK_PREAMBLE_SIZE)

                return AVERROR(EIO);

            chunk_size = AV_RL32(&preamble[2]) + RoQ_CHUNK_PREAMBLE_SIZE * 2 +

                codebook_size;

            if (chunk_size > INT_MAX)

                return AVERROR_INVALIDDATA;

            /* rewind */

            avio_seek(pb, codebook_offset, SEEK_SET);

            /* load up the packet */

            ret= av_get_packet(pb, pkt, chunk_size);

            if (ret != chunk_size)

                return AVERROR(EIO);

            pkt->stream_index = roq->video_stream_index;

            pkt->pts = roq->video_pts++;

            packet_read = 1;

            break;

        case RoQ_SOUND_MONO:

        case RoQ_SOUND_STEREO:

            if (roq->audio_stream_index == -1) {

                AVStream *st = avformat_new_stream(s, NULL);

                if (!st)

                    return AVERROR(ENOMEM);

                avpriv_set_pts_info(st, 32, 1, RoQ_AUDIO_SAMPLE_RATE);

                roq->audio_stream_index = st->index;

                st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;

                st->codecpar->codec_id = AV_CODEC_ID_ROQ_DPCM;

                st->codecpar->codec_tag = 0;  /* no tag */

                if (chunk_type == RoQ_SOUND_STEREO) {

                    st->codecpar->channels       = 2;

                    st->codecpar->channel_layout = AV_CH_LAYOUT_STEREO;

                } else {

                    st->codecpar->channels       = 1;

                    st->codecpar->channel_layout = AV_CH_LAYOUT_MONO;

                }

                roq->audio_channels    = st->codecpar->channels;

                st->codecpar->sample_rate = RoQ_AUDIO_SAMPLE_RATE;

                st->codecpar->bits_per_coded_sample = 16;

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

                    st->codecpar->bits_per_coded_sample;

                st->codecpar->block_align = st->codecpar->channels * st->codecpar->bits_per_coded_sample;

            }

        case RoQ_QUAD_VQ:

            if (chunk_type == RoQ_QUAD_VQ) {

                if (roq->video_stream_index < 0)

                    return AVERROR_INVALIDDATA;

            }

            /* load up the packet */

            if (av_new_packet(pkt, chunk_size + RoQ_CHUNK_PREAMBLE_SIZE))

                return AVERROR(EIO);

            /* copy over preamble */

            memcpy(pkt->data, preamble, RoQ_CHUNK_PREAMBLE_SIZE);

            if (chunk_type == RoQ_QUAD_VQ) {

                pkt->stream_index = roq->video_stream_index;

                pkt->pts = roq->video_pts++;

            } else {

                pkt->stream_index = roq->audio_stream_index;

                pkt->pts = roq->audio_frame_count;

                roq->audio_frame_count += (chunk_size / roq->audio_channels);

            }

            pkt->pos= avio_tell(pb);

            ret = avio_read(pb, pkt->data + RoQ_CHUNK_PREAMBLE_SIZE,

                chunk_size);

            if (ret != chunk_size)

                ret = AVERROR(EIO);

            packet_read = 1;

            break;

        default:

            av_log(s, AV_LOG_ERROR, "  unknown RoQ chunk (%04X)\n", chunk_type);

            return AVERROR_INVALIDDATA;

        }

    }

    return ret;

}


static inline void RENAME(hScale)(int16_t *dst, int dstW, uint8_t *src, int srcW, int xInc,

				  int16_t *filter, int16_t *filterPos, int filterSize)

{

#ifdef HAVE_MMX

	assert(filterSize % 4 == 0 && filterSize>0);

	if(filterSize==4) // allways true for upscaling, sometimes for down too

	{

		long counter= -2*dstW;

		filter-= counter*2;

		filterPos-= counter/2;

		dst-= counter/2;

		asm volatile(

			"pxor %%mm7, %%mm7		\n\t"

			"movq "MANGLE(w02)", %%mm6	\n\t"

			"push %%"REG_BP"		\n\t" // we use 7 regs here ...

			"mov %%"REG_a", %%"REG_BP"	\n\t"

			".balign 16			\n\t"

			"1:				\n\t"

			"movzwl (%2, %%"REG_BP"), %%eax	\n\t"

			"movzwl 2(%2, %%"REG_BP"), %%ebx\n\t"

			"movq (%1, %%"REG_BP", 4), %%mm1\n\t"

			"movq 8(%1, %%"REG_BP", 4), %%mm3\n\t"

			"movd (%3, %%"REG_a"), %%mm0	\n\t"

			"movd (%3, %%"REG_b"), %%mm2	\n\t"

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

			"punpcklbw %%mm7, %%mm2		\n\t"

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

			"pmaddwd %%mm2, %%mm3		\n\t"

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

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

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

			"pmaddwd %%mm6, %%mm0		\n\t"

			"packssdw %%mm0, %%mm0		\n\t"

			"movd %%mm0, (%4, %%"REG_BP")	\n\t"

			"add $4, %%"REG_BP"		\n\t"

			" jnc 1b			\n\t"

			"pop %%"REG_BP"			\n\t"

			: "+a" (counter)

			: "c" (filter), "d" (filterPos), "S" (src), "D" (dst)

			: "%"REG_b

		);

	}

	else if(filterSize==8)

	{

		long counter= -2*dstW;

		filter-= counter*4;

		filterPos-= counter/2;

		dst-= counter/2;

		asm volatile(

			"pxor %%mm7, %%mm7		\n\t"

			"movq "MANGLE(w02)", %%mm6	\n\t"

			"push %%"REG_BP"		\n\t" // we use 7 regs here ...

			"mov %%"REG_a", %%"REG_BP"	\n\t"

			".balign 16			\n\t"

			"1:				\n\t"

			"movzwl (%2, %%"REG_BP"), %%eax	\n\t"

			"movzwl 2(%2, %%"REG_BP"), %%ebx\n\t"

			"movq (%1, %%"REG_BP", 8), %%mm1\n\t"

			"movq 16(%1, %%"REG_BP", 8), %%mm3\n\t"

			"movd (%3, %%"REG_a"), %%mm0	\n\t"

			"movd (%3, %%"REG_b"), %%mm2	\n\t"

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

			"punpcklbw %%mm7, %%mm2		\n\t"

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

			"pmaddwd %%mm2, %%mm3		\n\t"

			"movq 8(%1, %%"REG_BP", 8), %%mm1\n\t"

			"movq 24(%1, %%"REG_BP", 8), %%mm5\n\t"

			"movd 4(%3, %%"REG_a"), %%mm4	\n\t"

			"movd 4(%3, %%"REG_b"), %%mm2	\n\t"

			"punpcklbw %%mm7, %%mm4		\n\t"

			"punpcklbw %%mm7, %%mm2		\n\t"

			"pmaddwd %%mm1, %%mm4		\n\t"

			"pmaddwd %%mm2, %%mm5		\n\t"

			"paddd %%mm4, %%mm0		\n\t"

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

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

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

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

			"pmaddwd %%mm6, %%mm0		\n\t"

			"packssdw %%mm0, %%mm0		\n\t"

			"movd %%mm0, (%4, %%"REG_BP")	\n\t"

			"add $4, %%"REG_BP"		\n\t"

			" jnc 1b			\n\t"

			"pop %%"REG_BP"			\n\t"

			: "+a" (counter)

			: "c" (filter), "d" (filterPos), "S" (src), "D" (dst)

			: "%"REG_b

		);

	}

	else

	{

		uint8_t *offset = src+filterSize;

		long counter= -2*dstW;

//		filter-= counter*filterSize/2;

		filterPos-= counter/2;

		dst-= counter/2;

		asm volatile(

			"pxor %%mm7, %%mm7		\n\t"

			"movq "MANGLE(w02)", %%mm6	\n\t"

			".balign 16			\n\t"

			"1:				\n\t"

			"mov %2, %%"REG_c"		\n\t"

			"movzwl (%%"REG_c", %0), %%eax	\n\t"

			"movzwl 2(%%"REG_c", %0), %%ebx	\n\t"

			"mov %5, %%"REG_c"		\n\t"

			"pxor %%mm4, %%mm4		\n\t"

			"pxor %%mm5, %%mm5		\n\t"

			"2:				\n\t"

			"movq (%1), %%mm1		\n\t"

			"movq (%1, %6), %%mm3		\n\t"

			"movd (%%"REG_c", %%"REG_a"), %%mm0\n\t"

			"movd (%%"REG_c", %%"REG_b"), %%mm2\n\t"

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

			"punpcklbw %%mm7, %%mm2		\n\t"

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

			"pmaddwd %%mm2, %%mm3		\n\t"

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

			"paddd %%mm0, %%mm4		\n\t"

			"add $8, %1			\n\t"

			"add $4, %%"REG_c"		\n\t"

			"cmp %4, %%"REG_c"		\n\t"

			" jb 2b				\n\t"

			"add %6, %1			\n\t"

			"psrad $8, %%mm4		\n\t"

			"psrad $8, %%mm5		\n\t"

			"packssdw %%mm5, %%mm4		\n\t"

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

			"packssdw %%mm4, %%mm4		\n\t"

			"mov %3, %%"REG_a"		\n\t"

			"movd %%mm4, (%%"REG_a", %0)	\n\t"

			"add $4, %0			\n\t"

			" jnc 1b			\n\t"

			: "+r" (counter), "+r" (filter)

			: "m" (filterPos), "m" (dst), "m"(offset),

			  "m" (src), "r" ((long)filterSize*2)

			: "%"REG_b, "%"REG_a, "%"REG_c

		);

	}

#else

#ifdef HAVE_ALTIVEC

	hScale_altivec_real(dst, dstW, src, srcW, xInc, filter, filterPos, filterSize);

#else

	int i;

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

	{

		int j;

		int srcPos= filterPos[i];

		int val=0;

//		printf("filterPos: %d\n", filterPos[i]);

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

		{

//			printf("filter: %d, src: %d\n", filter[i], src[srcPos + j]);

			val += ((int)src[srcPos + j])*filter[filterSize*i + j];

		}

//		filter += hFilterSize;

		dst[i] = MIN(MAX(0, val>>7), (1<<15)-1); // the cubic equation does overflow ...

//		dst[i] = val>>7;

	}

#endif

#endif

}


void qemu_file_set_error(QEMUFile *f, int ret)

{

    if (f->last_error == 0) {

        f->last_error = ret;

    }

}


static int encode_picture_lossless(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data){

    MpegEncContext * const s = avctx->priv_data;

    MJpegContext * const m = s->mjpeg_ctx;

    AVFrame *pict = data;

    const int width= s->width;

    const int height= s->height;

    AVFrame * const p= (AVFrame*)&s->current_picture;

    const int predictor= avctx->prediction_method+1;

    init_put_bits(&s->pb, buf, buf_size);

    *p = *pict;

    p->pict_type= FF_I_TYPE;

    p->key_frame= 1;

    ff_mjpeg_encode_picture_header(s);

    s->header_bits= put_bits_count(&s->pb);

    if(avctx->pix_fmt == PIX_FMT_RGB32){

        int x, y, i;

        const int linesize= p->linesize[0];

        uint16_t (*buffer)[4]= (void *) s->rd_scratchpad;

        int left[3], top[3], topleft[3];

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

            buffer[0][i]= 1 << (9 - 1);

        }

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

            const int modified_predictor= y ? predictor : 1;

            uint8_t *ptr = p->data[0] + (linesize * y);

            if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < width*3*4){

                av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");

                return -1;

            }

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

                top[i]= left[i]= topleft[i]= buffer[0][i];

            }

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

                buffer[x][1] = ptr[4*x+0] - ptr[4*x+1] + 0x100;

                buffer[x][2] = ptr[4*x+2] - ptr[4*x+1] + 0x100;

                buffer[x][0] = (ptr[4*x+0] + 2*ptr[4*x+1] + ptr[4*x+2])>>2;

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

                    int pred, diff;

                    PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);

                    topleft[i]= top[i];

                    top[i]= buffer[x+1][i];

                    left[i]= buffer[x][i];

                    diff= ((left[i] - pred + 0x100)&0x1FF) - 0x100;

                    if(i==0)

                        ff_mjpeg_encode_dc(s, diff, m->huff_size_dc_luminance, m->huff_code_dc_luminance); //FIXME ugly

                    else

                        ff_mjpeg_encode_dc(s, diff, m->huff_size_dc_chrominance, m->huff_code_dc_chrominance);

                }

            }

        }

    }else{

        int mb_x, mb_y, i;

        const int mb_width  = (width  + s->mjpeg_hsample[0] - 1) / s->mjpeg_hsample[0];

        const int mb_height = (height + s->mjpeg_vsample[0] - 1) / s->mjpeg_vsample[0];

        for(mb_y = 0; mb_y < mb_height; mb_y++) {

            if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < mb_width * 4 * 3 * s->mjpeg_hsample[0] * s->mjpeg_vsample[0]){

                av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");

                return -1;

            }

            for(mb_x = 0; mb_x < mb_width; mb_x++) {

                if(mb_x==0 || mb_y==0){

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

                        uint8_t *ptr;

                        int x, y, h, v, linesize;

                        h = s->mjpeg_hsample[i];

                        v = s->mjpeg_vsample[i];

                        linesize= p->linesize[i];

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

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

                                int pred;

                                ptr = p->data[i] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap

                                if(y==0 && mb_y==0){

                                    if(x==0 && mb_x==0){

                                        pred= 128;

                                    }else{

                                        pred= ptr[-1];

                                    }

                                }else{

                                    if(x==0 && mb_x==0){

                                        pred= ptr[-linesize];

                                    }else{

                                        PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);

                                    }

                                }

                                if(i==0)

                                    ff_mjpeg_encode_dc(s, (int8_t)(*ptr - pred), m->huff_size_dc_luminance, m->huff_code_dc_luminance); //FIXME ugly

                                else

                                    ff_mjpeg_encode_dc(s, (int8_t)(*ptr - pred), m->huff_size_dc_chrominance, m->huff_code_dc_chrominance);

                            }

                        }

                    }

                }else{

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

                        uint8_t *ptr;

                        int x, y, h, v, linesize;

                        h = s->mjpeg_hsample[i];

                        v = s->mjpeg_vsample[i];

                        linesize= p->linesize[i];

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

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

                                int pred;

                                ptr = p->data[i] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap

//printf("%d %d %d %d %8X\n", mb_x, mb_y, x, y, ptr);

                                PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);

                                if(i==0)

                                    ff_mjpeg_encode_dc(s, (int8_t)(*ptr - pred), m->huff_size_dc_luminance, m->huff_code_dc_luminance); //FIXME ugly

                                else

                                    ff_mjpeg_encode_dc(s, (int8_t)(*ptr - pred), m->huff_size_dc_chrominance, m->huff_code_dc_chrominance);

                            }

                        }

                    }

                }

            }

        }

    }

    emms_c();

    ff_mjpeg_encode_picture_trailer(s);

    s->picture_number++;

    flush_put_bits(&s->pb);

    return pbBufPtr(&s->pb) - s->pb.buf;

//    return (put_bits_count(&f->pb)+7)/8;

}


static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)

{

    AVFormatContext *ic;

    AVInputFormat *file_iformat = NULL;

    int err, i, ret;

    int64_t timestamp;

    uint8_t buf[128];

    AVDictionary **opts;

    int orig_nb_streams;                     // number of streams before avformat_find_stream_info

    if (o->format) {

        if (!(file_iformat = av_find_input_format(o->format))) {

            av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);

            exit_program(1);

        }

    }

    if (!strcmp(filename, "-"))

        filename = "pipe:";

    using_stdin |= !strncmp(filename, "pipe:", 5) ||

                    !strcmp(filename, "/dev/stdin");

    /* get default parameters from command line */

    ic = avformat_alloc_context();

    if (!ic) {

        print_error(filename, AVERROR(ENOMEM));

        exit_program(1);

    }

    if (o->nb_audio_sample_rate) {

        snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);

        av_dict_set(&format_opts, "sample_rate", buf, 0);

    }

    if (o->nb_audio_channels) {

        snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);

        av_dict_set(&format_opts, "channels", buf, 0);

    }

    if (o->nb_frame_rates) {

        av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);

    }

    if (o->nb_frame_sizes) {

        av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);

    }

    if (o->nb_frame_pix_fmts)

        av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);

    ic->video_codec_id   = video_codec_name ?

        find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0)->id : CODEC_ID_NONE;

    ic->audio_codec_id   = audio_codec_name ?

        find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0)->id : CODEC_ID_NONE;

    ic->subtitle_codec_id= subtitle_codec_name ?

        find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0)->id : CODEC_ID_NONE;

    ic->flags |= AVFMT_FLAG_NONBLOCK;

    ic->interrupt_callback = int_cb;

    if (loop_input) {

        av_log(NULL, AV_LOG_WARNING, "-loop_input is deprecated, use -loop 1\n");

        ic->loop_input = loop_input;

    }

    /* open the input file with generic avformat function */

    err = avformat_open_input(&ic, filename, file_iformat, &format_opts);

    if (err < 0) {

        print_error(filename, err);

        exit_program(1);

    }

    assert_avoptions(format_opts);

    /* apply forced codec ids */

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

        choose_decoder(o, ic, ic->streams[i]);

    /* Set AVCodecContext options for avformat_find_stream_info */

    opts = setup_find_stream_info_opts(ic, codec_opts);

    orig_nb_streams = ic->nb_streams;

    /* If not enough info to get the stream parameters, we decode the

       first frames to get it. (used in mpeg case for example) */

    ret = avformat_find_stream_info(ic, opts);

    if (ret < 0) {

        av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);

        av_close_input_file(ic);

        exit_program(1);

    }

    timestamp = o->start_time;

    /* add the stream start time */

    if (ic->start_time != AV_NOPTS_VALUE)

        timestamp += ic->start_time;

    /* if seeking requested, we execute it */

    if (o->start_time != 0) {

        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);

        if (ret < 0) {

            av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",

                   filename, (double)timestamp / AV_TIME_BASE);

        }

    }

    /* update the current parameters so that they match the one of the input stream */

    add_input_streams(o, ic);

    /* dump the file content */

    av_dump_format(ic, nb_input_files, filename, 0);

    input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);

    input_files[nb_input_files - 1].ctx        = ic;

    input_files[nb_input_files - 1].ist_index  = nb_input_streams - ic->nb_streams;

    input_files[nb_input_files - 1].ts_offset  = o->input_ts_offset - (copy_ts ? 0 : timestamp);

    input_files[nb_input_files - 1].nb_streams = ic->nb_streams;

    input_files[nb_input_files - 1].rate_emu   = o->rate_emu;

    for (i = 0; i < o->nb_dump_attachment; i++) {

        int j;

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

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

            if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)

                dump_attachment(st, o->dump_attachment[i].u.str);

        }

    }

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

        av_dict_free(&opts[i]);

    av_freep(&opts);

    reset_options(o, 1);

    return 0;

}


uint64_t helper_efdctuidz (uint64_t val)

{

    CPU_DoubleU u;

    u.ll = val;

    /* NaN are not treated the same way IEEE 754 does */

    if (unlikely(float64_is_nan(u.d)))

        return 0;

    return float64_to_uint64_round_to_zero(u.d, &env->vec_status);

}


void bios_linker_loader_add_checksum(BIOSLinker *linker, const char *file_name,

                                     void *start, unsigned size,

                                     uint8_t *checksum)

{

    BiosLinkerLoaderEntry entry;

    const BiosLinkerFileEntry *file = bios_linker_find_file(linker, file_name);

    ptrdiff_t checksum_offset = (gchar *)checksum - file->blob->data;

    ptrdiff_t start_offset = (gchar *)start - file->blob->data;

    assert(checksum_offset >= 0);

    assert(start_offset >= 0);

    assert(checksum_offset + 1 <= file->blob->len);

    assert(start_offset + size <= file->blob->len);

    assert(*checksum == 0x0);

    memset(&entry, 0, sizeof entry);

    strncpy(entry.cksum.file, file_name, sizeof entry.cksum.file - 1);

    entry.command = cpu_to_le32(BIOS_LINKER_LOADER_COMMAND_ADD_CHECKSUM);

    entry.cksum.offset = cpu_to_le32(checksum_offset);

    entry.cksum.start = cpu_to_le32(start_offset);

    entry.cksum.length = cpu_to_le32(size);

    g_array_append_vals(linker->cmd_blob, &entry, sizeof entry);

}


void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)

{

    PerThreadContext *p = avctx->internal->thread_ctx;

    FrameThreadContext *fctx;

    AVFrame *dst, *tmp;

FF_DISABLE_DEPRECATION_WARNINGS

    int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||

                          avctx->thread_safe_callbacks                   ||

                          (

#if FF_API_GET_BUFFER

                           !avctx->get_buffer &&

#endif

                           avctx->get_buffer2 == avcodec_default_get_buffer2);

FF_ENABLE_DEPRECATION_WARNINGS

    if (!f->f->buf[0])

        return;

    if (avctx->debug & FF_DEBUG_BUFFERS)

        av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);

    av_buffer_unref(&f->progress);

    f->owner    = NULL;

    if (can_direct_free) {

        av_frame_unref(f->f);

        return;

    }

    fctx = p->parent;

    pthread_mutex_lock(&fctx->buffer_mutex);

    if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))

        goto fail;

    tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,

                          (p->num_released_buffers + 1) *

                          sizeof(*p->released_buffers));

    if (!tmp)

        goto fail;

    p->released_buffers = tmp;

    dst = &p->released_buffers[p->num_released_buffers];

    av_frame_move_ref(dst, f->f);

    p->num_released_buffers++;

fail:

    pthread_mutex_unlock(&fctx->buffer_mutex);

}


void ff_schro_queue_free(FFSchroQueue *queue, void (*free_func)(void *))

{

    while (queue->p_head)

        free_func(ff_schro_queue_pop(queue));

}


void qemu_mutex_lock_iothread(void)

{

    if (!tcg_enabled()) {

        qemu_mutex_lock(&qemu_global_mutex);

    } else {

        iothread_requesting_mutex = true;

        if (qemu_mutex_trylock(&qemu_global_mutex)) {

            qemu_cpu_kick_thread(first_cpu);

            qemu_mutex_lock(&qemu_global_mutex);

        }

        iothread_requesting_mutex = false;

        qemu_cond_broadcast(&qemu_io_proceeded_cond);

    }

}


static inline void gen_op_addl_ESP_im(int32_t val)

{

    tcg_gen_ld_tl(cpu_tmp0, cpu_env, offsetof(CPUState, regs[R_ESP]));

    tcg_gen_addi_tl(cpu_tmp0, cpu_tmp0, val);

#ifdef TARGET_X86_64

    tcg_gen_andi_tl(cpu_tmp0, cpu_tmp0, 0xffffffff);

#endif

    tcg_gen_st_tl(cpu_tmp0, cpu_env, offsetof(CPUState, regs[R_ESP]));

}


static unsigned int dec_movu_r(DisasContext *dc)

{

	TCGv t0;

	int size = memsize_z(dc);

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

		    memsize_char(size),

		    dc->op1, dc->op2));

	cris_cc_mask(dc, CC_MASK_NZ);

	t0 = tcg_temp_new(TCG_TYPE_TL);

	dec_prep_move_r(dc, dc->op1, dc->op2, size, 0, t0);

	cris_alu(dc, CC_OP_MOVE, cpu_R[dc->op2], cpu_R[dc->op2], t0, 4);

	tcg_temp_free(t0);

	return 2;

}


AVInputFormat *av_find_input_format(const char *short_name)

{

    AVInputFormat *fmt = NULL;

    while ((fmt = av_iformat_next(fmt)))

        if (match_format(short_name, fmt->name))

            return fmt;

    return NULL;

}


static av_cold void dsputil_init_sse2(DSPContext *c, AVCodecContext *avctx,

                                      int mm_flags)

{

#if HAVE_SSE2_INLINE

    const int high_bit_depth = avctx->bits_per_raw_sample > 8;

    if (!high_bit_depth && avctx->idct_algo == FF_IDCT_XVIDMMX) {

        c->idct_put              = ff_idct_xvid_sse2_put;

        c->idct_add              = ff_idct_xvid_sse2_add;

        c->idct                  = ff_idct_xvid_sse2;

        c->idct_permutation_type = FF_SSE2_IDCT_PERM;

    }

#endif /* HAVE_SSE2_INLINE */

#if HAVE_SSE2_EXTERNAL

    c->scalarproduct_int16          = ff_scalarproduct_int16_sse2;

    c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_sse2;

    if (mm_flags & AV_CPU_FLAG_ATOM) {

        c->vector_clip_int32 = ff_vector_clip_int32_int_sse2;

    } else {

        c->vector_clip_int32 = ff_vector_clip_int32_sse2;

    }

    if (avctx->flags & CODEC_FLAG_BITEXACT) {

        c->apply_window_int16 = ff_apply_window_int16_sse2;

    } else if (!(mm_flags & AV_CPU_FLAG_SSE2SLOW)) {

        c->apply_window_int16 = ff_apply_window_int16_round_sse2;

    }

    c->bswap_buf = ff_bswap32_buf_sse2;

#endif /* HAVE_SSE2_EXTERNAL */

}


static int au_probe(AVProbeData *p)

{

    /* check file header */

    if (p->buf_size <= 24)

        return 0;

    if (p->buf[0] == '.' && p->buf[1] == 's' &&

        p->buf[2] == 'n' && p->buf[3] == 'd')

        return AVPROBE_SCORE_MAX;

    else

        return 0;

}


static void pc_fw_add_pflash_drv(void)

{

    QemuOpts *opts;

    QEMUMachine *machine;

    char *filename;

    if (bios_name == NULL) {

        bios_name = BIOS_FILENAME;

    }

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    opts = drive_add(IF_PFLASH, -1, filename, "readonly=on");

    g_free(filename);

    if (opts == NULL) {

      return;

    }

    machine = find_default_machine();

    if (machine == NULL) {

      return;

    }

    drive_init(opts, machine->use_scsi);

}


void ff_af_queue_remove(AudioFrameQueue *afq, int nb_samples, int64_t *pts,

                        int *duration)

{

    int64_t out_pts = AV_NOPTS_VALUE;

    int removed_samples = 0;

#ifdef DEBUG

    ff_af_queue_log_state(afq);

#endif

    /* get output pts from the next frame or generated pts */

    if (afq->frame_queue) {

        if (afq->frame_queue->pts != AV_NOPTS_VALUE)

            out_pts = afq->frame_queue->pts - afq->remaining_delay;

    } else {

        if (afq->next_pts != AV_NOPTS_VALUE)

            out_pts = afq->next_pts - afq->remaining_delay;

    }

    if (pts) {

        if (out_pts != AV_NOPTS_VALUE)

            *pts = ff_samples_to_time_base(afq->avctx, out_pts);

        else

            *pts = AV_NOPTS_VALUE;

    }

    /* if the delay is larger than the packet duration, we use up delay samples

       for the output packet and leave all frames in the queue */

    if (afq->remaining_delay >= nb_samples) {

        removed_samples      += nb_samples;

        afq->remaining_delay -= nb_samples;

    }

    /* remove frames from the queue until we have enough to cover the

       requested number of samples or until the queue is empty */

    while (removed_samples < nb_samples && afq->frame_queue) {

        removed_samples += afq->frame_queue->duration;

        delete_next_frame(afq);

    }

    afq->remaining_samples -= removed_samples;

    /* if there are no frames left and we have room for more samples, use

       any remaining delay samples */

    if (removed_samples < nb_samples && afq->remaining_samples > 0) {

        int add_samples = FFMIN(afq->remaining_samples,

                                nb_samples - removed_samples);

        removed_samples        += add_samples;

        afq->remaining_samples -= add_samples;

    }

    if (removed_samples > nb_samples)

        av_log(afq->avctx, AV_LOG_WARNING, "frame_size is too large\n");

    if (duration)

        *duration = ff_samples_to_time_base(afq->avctx, removed_samples);

}


void stream_start(BlockDriverState *bs, BlockDriverState *base,

                  const char *base_id, int64_t speed,

                  BlockDriverCompletionFunc *cb,

                  void *opaque, Error **errp)

{

    StreamBlockJob *s;

    Coroutine *co;

    s = block_job_create(&stream_job_type, bs, speed, cb, opaque, errp);

    if (!s) {

        return;

    }

    s->base = base;

    if (base_id) {

        pstrcpy(s->backing_file_id, sizeof(s->backing_file_id), base_id);

    }

    co = qemu_coroutine_create(stream_run);

    trace_stream_start(bs, base, s, co, opaque);

    qemu_coroutine_enter(co, s);

}


static double get_diff_limited_q(MpegEncContext *s, RateControlEntry *rce, double q){

    RateControlContext *rcc= &s->rc_context;

    AVCodecContext *a= s->avctx;

    const int pict_type= rce->new_pict_type;

    const double last_p_q    = rcc->last_qscale_for[P_TYPE];

    const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type];

    if     (pict_type==I_TYPE && (a->i_quant_factor>0.0 || rcc->last_non_b_pict_type==P_TYPE))

        q= last_p_q    *FFABS(a->i_quant_factor) + a->i_quant_offset;

    else if(pict_type==B_TYPE && a->b_quant_factor>0.0)

        q= last_non_b_q*    a->b_quant_factor  + a->b_quant_offset;

    /* last qscale / qdiff stuff */

    if(rcc->last_non_b_pict_type==pict_type || pict_type!=I_TYPE){

        double last_q= rcc->last_qscale_for[pict_type];

        const int maxdiff= FF_QP2LAMBDA * a->max_qdiff;

        if     (q > last_q + maxdiff) q= last_q + maxdiff;

        else if(q < last_q - maxdiff) q= last_q - maxdiff;

    }

    rcc->last_qscale_for[pict_type]= q; //Note we cannot do that after blurring

    if(pict_type!=B_TYPE)

        rcc->last_non_b_pict_type= pict_type;

    return q;

}


static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)

{

    const char *hdlr, *descr = NULL, *hdlr_type = NULL;

    int64_t pos = avio_tell(pb);

    if (!track) { /* no media --> data handler */

        hdlr      = "dhlr";

        hdlr_type = "url ";

        descr     = "DataHandler";

    } else {

        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";

        if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {

            hdlr_type = "vide";

            descr     = "VideoHandler";

        } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {

            hdlr_type = "soun";

            descr     = "SoundHandler";

        } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {

            if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";

            else                                      hdlr_type = "text";

            descr = "SubtitleHandler";

        } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {

            hdlr_type = "hint";

            descr     = "HintHandler";

        }

    }

    avio_wb32(pb, 0); /* size */

    ffio_wfourcc(pb, "hdlr");

    avio_wb32(pb, 0); /* Version & flags */

    avio_write(pb, hdlr, 4); /* handler */

    ffio_wfourcc(pb, hdlr_type); /* handler type */

    avio_wb32(pb, 0); /* reserved */

    avio_wb32(pb, 0); /* reserved */

    avio_wb32(pb, 0); /* reserved */

    if (!track || track->mode == MODE_MOV)

        avio_w8(pb, strlen(descr)); /* pascal string */

    avio_write(pb, descr, strlen(descr)); /* handler description */

    if (track && track->mode != MODE_MOV)

        avio_w8(pb, 0); /* c string */

    return update_size(pb, pos);

}


void trace_init_file(const char *file)

{

#ifdef CONFIG_TRACE_SIMPLE

    st_set_trace_file(file);

#elif defined CONFIG_TRACE_LOG

    /* If both the simple and the log backends are enabled, "-trace file"

     * only applies to the simple backend; use "-D" for the log backend.

     */

    if (file) {

        qemu_set_log_filename(file);

    }

#else

    if (file) {

        fprintf(stderr, "error: -trace file=...: "

                "option not supported by the selected tracing backends\n");

        exit(1);

    }

#endif

}


static int srt_probe(AVProbeData *p)

{

    const unsigned char *ptr = p->buf;

    int i, v, num = 0;

    if (AV_RB24(ptr) == 0xEFBBBF)

        ptr += 3;  /* skip UTF-8 BOM */

    while (*ptr == '\r' || *ptr == '\n')

        ptr++;

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

        if ((num == i || num + 1 == i)

            && sscanf(ptr, "%*d:%*2d:%*2d%*1[,.]%*3d --> %*d:%*2d:%*2d%*1[,.]%3d", &v) == 1)

            return AVPROBE_SCORE_MAX;

        num = atoi(ptr);

        ptr += strcspn(ptr, "\n") + 1;

    }

    return 0;

}


static void piix4_update_hotplug(PIIX4PMState *s)

{

    PCIDevice *dev = &s->dev;

    BusState *bus = qdev_get_parent_bus(&dev->qdev);

    DeviceState *qdev, *next;

    s->pci0_hotplug_enable = ~0;

    QTAILQ_FOREACH_SAFE(qdev, &bus->children, sibling, next) {

        PCIDevice *pdev = PCI_DEVICE(qdev);

        PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pdev);

        int slot = PCI_SLOT(pdev->devfn);

        if (pc->no_hotplug) {

            s->pci0_hotplug_enable &= ~(1 << slot);

        }

    }

}


static void stream_set_speed(BlockJob *job, int64_t speed, Error **errp)

{

    StreamBlockJob *s = container_of(job, StreamBlockJob, common);

    if (speed < 0) {

        error_setg(errp, QERR_INVALID_PARAMETER, "speed");

        return;

    }

    ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);

}


static av_cold int dnxhd_decode_close(AVCodecContext *avctx)

{

    DNXHDContext *ctx = avctx->priv_data;

    ff_free_vlc(&ctx->ac_vlc);

    ff_free_vlc(&ctx->dc_vlc);

    ff_free_vlc(&ctx->run_vlc);

    av_freep(&ctx->mb_scan_index);

    av_freep(&ctx->rows);

    return 0;

}


int unix_start_incoming_migration(const char *path)

{

    struct sockaddr_un un;

    int sock;

    dprintf("Attempting to start an incoming migration\n");

    sock = socket(PF_UNIX, SOCK_STREAM, 0);

    if (sock < 0) {

        fprintf(stderr, "Could not open unix socket: %s\n", strerror(errno));

        return -EINVAL;

    }

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

    un.sun_family = AF_UNIX;

    snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);

    unlink(un.sun_path);

    if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {

        fprintf(stderr, "bind(unix:%s): %s\n", un.sun_path, strerror(errno));

        goto err;

    }

    if (listen(sock, 1) < 0) {

        fprintf(stderr, "listen(unix:%s): %s\n", un.sun_path, strerror(errno));

        goto err;

    }

    qemu_set_fd_handler2(sock, NULL, unix_accept_incoming_migration, NULL,

			 (void *)(unsigned long)sock);

    return 0;

err:

    close(sock);

    return -EINVAL;

}


void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)

{

    BlockDriver *drv = bs->drv;

    Error *local_err = NULL;

    memset(&bs->bl, 0, sizeof(bs->bl));

    if (!drv) {

        return;

    }

    /* Default alignment based on whether driver has byte interface */

    bs->request_alignment = drv->bdrv_co_preadv ? 1 : 512;

    /* Take some limits from the children as a default */

    if (bs->file) {

        bdrv_refresh_limits(bs->file->bs, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            return;

        }

        bs->bl.opt_transfer = bs->file->bs->bl.opt_transfer;

        bs->bl.max_transfer = bs->file->bs->bl.max_transfer;

        bs->bl.min_mem_alignment = bs->file->bs->bl.min_mem_alignment;

        bs->bl.opt_mem_alignment = bs->file->bs->bl.opt_mem_alignment;

        bs->bl.max_iov = bs->file->bs->bl.max_iov;

    } else {

        bs->bl.min_mem_alignment = 512;

        bs->bl.opt_mem_alignment = getpagesize();

        /* Safe default since most protocols use readv()/writev()/etc */

        bs->bl.max_iov = IOV_MAX;

    }

    if (bs->backing) {

        bdrv_refresh_limits(bs->backing->bs, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            return;

        }

        bs->bl.opt_transfer = MAX(bs->bl.opt_transfer,

                                  bs->backing->bs->bl.opt_transfer);

        bs->bl.max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,

                                           bs->backing->bs->bl.max_transfer);

        bs->bl.opt_mem_alignment =

            MAX(bs->bl.opt_mem_alignment,

                bs->backing->bs->bl.opt_mem_alignment);

        bs->bl.min_mem_alignment =

            MAX(bs->bl.min_mem_alignment,

                bs->backing->bs->bl.min_mem_alignment);

        bs->bl.max_iov =

            MIN(bs->bl.max_iov,

                bs->backing->bs->bl.max_iov);

    }

    /* Then let the driver override it */

    if (drv->bdrv_refresh_limits) {

        drv->bdrv_refresh_limits(bs, errp);

    }

}


static int check_refblocks(BlockDriverState *bs, BdrvCheckResult *res,

                           BdrvCheckMode fix, bool *rebuild,

                           void **refcount_table, int64_t *nb_clusters)

{

    BDRVQcow2State *s = bs->opaque;

    int64_t i, size;

    int ret;

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

        uint64_t offset, cluster;

        offset = s->refcount_table[i];

        cluster = offset >> s->cluster_bits;

        /* Refcount blocks are cluster aligned */

        if (offset_into_cluster(s, offset)) {

            fprintf(stderr, "ERROR refcount block %" PRId64 " is not "

                "cluster aligned; refcount table entry corrupted\n", i);

            res->corruptions++;

            *rebuild = true;

            continue;

        }

        if (cluster >= *nb_clusters) {

            fprintf(stderr, "%s refcount block %" PRId64 " is outside image\n",

                    fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR", i);

            if (fix & BDRV_FIX_ERRORS) {

                int64_t new_nb_clusters;

                Error *local_err = NULL;

                if (offset > INT64_MAX - s->cluster_size) {

                    ret = -EINVAL;

                    goto resize_fail;

                }

                ret = bdrv_truncate(bs->file, offset + s->cluster_size,

                                    &local_err);

                if (ret < 0) {

                    error_report_err(local_err);

                    goto resize_fail;

                }

                size = bdrv_getlength(bs->file->bs);

                if (size < 0) {

                    ret = size;

                    goto resize_fail;

                }

                new_nb_clusters = size_to_clusters(s, size);

                assert(new_nb_clusters >= *nb_clusters);

                ret = realloc_refcount_array(s, refcount_table,

                                             nb_clusters, new_nb_clusters);

                if (ret < 0) {

                    res->check_errors++;

                    return ret;

                }

                if (cluster >= *nb_clusters) {

                    ret = -EINVAL;

                    goto resize_fail;

                }

                res->corruptions_fixed++;

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

                                    offset, s->cluster_size);

                if (ret < 0) {

                    return ret;

                }

                /* No need to check whether the refcount is now greater than 1:

                 * This area was just allocated and zeroed, so it can only be

                 * exactly 1 after inc_refcounts() */

                continue;

resize_fail:

                res->corruptions++;

                *rebuild = true;

                fprintf(stderr, "ERROR could not resize image: %s\n",

                        strerror(-ret));

            } else {

                res->corruptions++;

            }

            continue;

        }

        if (offset != 0) {

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

                                offset, s->cluster_size);

            if (ret < 0) {

                return ret;

            }

            if (s->get_refcount(*refcount_table, cluster) != 1) {

                fprintf(stderr, "ERROR refcount block %" PRId64

                        " refcount=%" PRIu64 "\n", i,

                        s->get_refcount(*refcount_table, cluster));

                res->corruptions++;

                *rebuild = true;

            }

        }

    }

    return 0;

}


DriveInfo *drive_init(QemuOpts *opts, BlockInterfaceType block_default_type)

{

    const char *buf;

    const char *file = NULL;

    const char *serial;

    const char *mediastr = "";

    BlockInterfaceType type;

    enum { MEDIA_DISK, MEDIA_CDROM } media;

    int bus_id, unit_id;

    int cyls, heads, secs, translation;

    BlockDriver *drv = NULL;

    int max_devs;

    int index;

    int ro = 0;

    int bdrv_flags = 0;

    int on_read_error, on_write_error;

    const char *devaddr;

    DriveInfo *dinfo;

    BlockIOLimit io_limits;

    int snapshot = 0;

    bool copy_on_read;

    int ret;

    Error *error = NULL;

    translation = BIOS_ATA_TRANSLATION_AUTO;

    media = MEDIA_DISK;

    /* extract parameters */

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

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

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

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

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

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

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

    ro = qemu_opt_get_bool(opts, "readonly", 0);

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

    file = qemu_opt_get(opts, "file");

    serial = qemu_opt_get(opts, "serial");

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

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

            ;

        if (type == IF_COUNT) {

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

            return NULL;

	}

    } else {

        type = block_default_type;

    }

    max_devs = if_max_devs[type];

    if (cyls || heads || secs) {

        if (cyls < 1) {

            error_report("invalid physical cyls number");

	    return NULL;

	}

        if (heads < 1) {

            error_report("invalid physical heads number");

	    return NULL;

	}

        if (secs < 1) {

            error_report("invalid physical secs number");

	    return NULL;

	}

    }

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

        if (!cyls) {

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

                         buf);

            return NULL;

        }

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

            translation = BIOS_ATA_TRANSLATION_NONE;

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

            translation = BIOS_ATA_TRANSLATION_LBA;

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

            translation = BIOS_ATA_TRANSLATION_AUTO;

	else {

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

	    return NULL;

	}

    }

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

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

	    media = MEDIA_DISK;

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

            if (cyls || secs || heads) {

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

	        return NULL;

            }

	    media = MEDIA_CDROM;

	} else {

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

	    return NULL;

	}

    }

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

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

            error_report("invalid discard option");

            return NULL;

        }

    }

    bdrv_flags |= BDRV_O_CACHE_WB;

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

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

            error_report("invalid cache option");

            return NULL;

        }

    }

#ifdef CONFIG_LINUX_AIO

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

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

            bdrv_flags |= BDRV_O_NATIVE_AIO;

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

            /* this is the default */

        } else {

           error_report("invalid aio option");

           return NULL;

        }

    }

#endif

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

        if (is_help_option(buf)) {

            error_printf("Supported formats:");

            bdrv_iterate_format(bdrv_format_print, NULL);

            error_printf("\n");

            return NULL;

        }

        drv = bdrv_find_whitelisted_format(buf);

        if (!drv) {

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

            return NULL;

        }

    }

    /* disk I/O throttling */

    io_limits.bps[BLOCK_IO_LIMIT_TOTAL]  =

                           qemu_opt_get_number(opts, "bps", 0);

    io_limits.bps[BLOCK_IO_LIMIT_READ]   =

                           qemu_opt_get_number(opts, "bps_rd", 0);

    io_limits.bps[BLOCK_IO_LIMIT_WRITE]  =

                           qemu_opt_get_number(opts, "bps_wr", 0);

    io_limits.iops[BLOCK_IO_LIMIT_TOTAL] =

                           qemu_opt_get_number(opts, "iops", 0);

    io_limits.iops[BLOCK_IO_LIMIT_READ]  =

                           qemu_opt_get_number(opts, "iops_rd", 0);

    io_limits.iops[BLOCK_IO_LIMIT_WRITE] =

                           qemu_opt_get_number(opts, "iops_wr", 0);

    if (!do_check_io_limits(&io_limits, &error)) {

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

        error_free(error);

        return NULL;

    }

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

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

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

                "update your scripts.\n");

    }

    on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;

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

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

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

            return NULL;

        }

        on_write_error = parse_block_error_action(buf, 0);

        if (on_write_error < 0) {

            return NULL;

        }

    }

    on_read_error = BLOCKDEV_ON_ERROR_REPORT;

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

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

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

            return NULL;

        }

        on_read_error = parse_block_error_action(buf, 1);

        if (on_read_error < 0) {

            return NULL;

        }

    }

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

        if (type != IF_VIRTIO) {

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

            return NULL;

        }

    }

    /* compute bus and unit according index */

    if (index != -1) {

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

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

            return NULL;

        }

        bus_id = drive_index_to_bus_id(type, index);

        unit_id = drive_index_to_unit_id(type, index);

    }

    /* if user doesn't specify a unit_id,

     * try to find the first free

     */

    if (unit_id == -1) {

       unit_id = 0;

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

           unit_id++;

           if (max_devs && unit_id >= max_devs) {

               unit_id -= max_devs;

               bus_id++;

           }

       }

    }

    /* check unit id */

    if (max_devs && unit_id >= max_devs) {

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

                     unit_id, max_devs - 1);

        return NULL;

    }

    /*

     * catch multiple definitions

     */

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

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

                     bus_id, unit_id, index);

        return NULL;

    }

    /* init */

    dinfo = g_malloc0(sizeof(*dinfo));

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

        dinfo->id = g_strdup(buf);

    } else {

        /* no id supplied -> create one */

        dinfo->id = g_malloc0(32);

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

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

        if (max_devs)

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

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

        else

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

                     if_name[type], mediastr, unit_id);

    }

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

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

    dinfo->bdrv->read_only = ro;

    dinfo->devaddr = devaddr;

    dinfo->type = type;

    dinfo->bus = bus_id;

    dinfo->unit = unit_id;

    dinfo->cyls = cyls;

    dinfo->heads = heads;

    dinfo->secs = secs;

    dinfo->trans = translation;

    dinfo->opts = opts;

    dinfo->refcount = 1;

    dinfo->serial = serial;

    QTAILQ_INSERT_TAIL(&drives, dinfo, next);

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

    /* disk I/O throttling */

    bdrv_set_io_limits(dinfo->bdrv, &io_limits);

    switch(type) {

    case IF_IDE:

    case IF_SCSI:

    case IF_XEN:

    case IF_NONE:

        dinfo->media_cd = media == MEDIA_CDROM;

        break;

    case IF_SD:

    case IF_FLOPPY:

    case IF_PFLASH:

    case IF_MTD:

        break;

    case IF_VIRTIO:

        /* add virtio block device */

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

        if (arch_type == QEMU_ARCH_S390X) {

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

        } else {

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

        }

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

        if (devaddr)

            qemu_opt_set(opts, "addr", devaddr);

        break;

    default:

        abort();

    }

    if (!file || !*file) {

        return dinfo;

    }

    if (snapshot) {

        /* always use cache=unsafe with snapshot */

        bdrv_flags &= ~BDRV_O_CACHE_MASK;

        bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);

    }

    if (copy_on_read) {

        bdrv_flags |= BDRV_O_COPY_ON_READ;

    }

    if (runstate_check(RUN_STATE_INMIGRATE)) {

        bdrv_flags |= BDRV_O_INCOMING;

    }

    if (media == MEDIA_CDROM) {

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

        ro = 1;

    } else if (ro == 1) {

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

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

            error_report("readonly not supported by this bus type");

            goto err;

        }

    }

    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;

    if (ro && copy_on_read) {

        error_report("warning: disabling copy_on_read on readonly drive");

    }

    ret = bdrv_open(dinfo->bdrv, file, NULL, bdrv_flags, drv);

    if (ret < 0) {

        if (ret == -EMEDIUMTYPE) {

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

                         file, drv->format_name);

        } else {

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

                         file, strerror(-ret));

        }

        goto err;

    }

    if (bdrv_key_required(dinfo->bdrv))

        autostart = 0;

    return dinfo;

err:

    bdrv_delete(dinfo->bdrv);

    g_free(dinfo->id);

    QTAILQ_REMOVE(&drives, dinfo, next);

    g_free(dinfo);

    return NULL;

}


static const char *keyval_parse_one(QDict *qdict, const char *params,

                                    const char *implied_key,

                                    Error **errp)

{

    const char *key, *key_end, *s;

    size_t len;

    char key_in_cur[128];

    QDict *cur;

    int ret;

    QObject *next;

    QString *val;

    key = params;

    len = strcspn(params, "=,");

    if (implied_key && len && key[len] != '=') {

        /* Desugar implied key */

        key = implied_key;

        len = strlen(implied_key);

    }

    key_end = key + len;

    /*

     * Loop over key fragments: @s points to current fragment, it

     * applies to @cur.  @key_in_cur[] holds the previous fragment.

     */

    cur = qdict;

    s = key;

    for (;;) {

        ret = parse_qapi_name(s, false);

        len = ret < 0 ? 0 : ret;

        assert(s + len <= key_end);

        if (!len || (s + len < key_end && s[len] != '.')) {

            assert(key != implied_key);

            error_setg(errp, "Invalid parameter '%.*s'",

                       (int)(key_end - key), key);

            return NULL;

        }

        if (len >= sizeof(key_in_cur)) {

            assert(key != implied_key);

            error_setg(errp, "Parameter%s '%.*s' is too long",

                       s != key || s + len != key_end ? " fragment" : "",

                       (int)len, s);

            return NULL;

        }

        if (s != key) {

            next = keyval_parse_put(cur, key_in_cur, NULL,

                                    key, s - 1, errp);

            if (!next) {

                return NULL;

            }

            cur = qobject_to_qdict(next);

            assert(cur);

        }

        memcpy(key_in_cur, s, len);

        key_in_cur[len] = 0;

        s += len;

        if (*s != '.') {

            break;

        }

        s++;

    }

    if (key == implied_key) {

        assert(!*s);

        s = params;

    } else {

        if (*s != '=') {

            error_setg(errp, "Expected '=' after parameter '%.*s'",

                       (int)(s - key), key);

            return NULL;

        }

        s++;

    }

    val = qstring_new();

    for (;;) {

        if (!*s) {

            break;

        } else if (*s == ',') {

            s++;

            if (*s != ',') {

                break;

            }

        }

        qstring_append_chr(val, *s++);

    }

    if (!keyval_parse_put(cur, key_in_cur, val, key, key_end, errp)) {

        return NULL;

    }

    return s;

}


static void mdct_test(AC3MDCTContext *mdct, AVLFG *lfg)

{

    int16_t input[MDCT_SAMPLES];

    int32_t output[AC3_MAX_COEFS];

    float input1[MDCT_SAMPLES];

    float output1[AC3_MAX_COEFS];

    float s, a, err, e, emax;

    int i, k, n;

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

        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;

        input1[i] = input[i];

    }

    mdct512(mdct, output, input);

    /* do it by hand */

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

        s = 0;

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

            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));

            s += input1[n] * cos(a);

        }

        output1[k] = -2 * s / MDCT_SAMPLES;

    }

    err  = 0;

    emax = 0;

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

        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);

        e = output[i] - output1[i];

        if (e > emax)

            emax = e;

        err += e * e;

    }

    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);

}


static AVRational update_sar(int old_w, int old_h, AVRational sar, int new_w, int new_h)

{

    // attempt to keep aspect during typical resolution switches

    if (!sar.num)

        sar = (AVRational){1, 1};

    sar = av_mul_q(sar, (AVRational){new_h * old_w, new_w * old_h});

    return sar;

}


static uint32_t qpci_pc_config_readl(QPCIBus *bus, int devfn, uint8_t offset)

{

    outl(0xcf8, (1 << 31) | (devfn << 8) | offset);

    return inl(0xcfc);

}


static int decode_block(BinkAudioContext *s, float **out, int use_dct)

{

    int ch, i, j, k;

    float q, quant[25];

    int width, coeff;

    GetBitContext *gb = &s->gb;

    if (use_dct)

        skip_bits(gb, 2);

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

        FFTSample *coeffs = out[ch];

        if (s->version_b) {

            if (get_bits_left(gb) < 64)

                return AVERROR_INVALIDDATA;

            coeffs[0] = av_int2float(get_bits_long(gb, 32)) * s->root;

            coeffs[1] = av_int2float(get_bits_long(gb, 32)) * s->root;

        } else {

            if (get_bits_left(gb) < 58)

                return AVERROR_INVALIDDATA;

            coeffs[0] = get_float(gb) * s->root;

            coeffs[1] = get_float(gb) * s->root;

        }

        if (get_bits_left(gb) < s->num_bands * 8)

            return AVERROR_INVALIDDATA;

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

            int value = get_bits(gb, 8);

            quant[i]  = quant_table[FFMIN(value, 95)];

        }

        k = 0;

        q = quant[0];

        // parse coefficients

        i = 2;

        while (i < s->frame_len) {

            if (s->version_b) {

                j = i + 16;

            } else {

                int v;

                GET_BITS_SAFE(v, 1);

                if (v) {

                    GET_BITS_SAFE(v, 4);

                    j = i + rle_length_tab[v] * 8;

                } else {

                    j = i + 8;

                }

            }

            j = FFMIN(j, s->frame_len);

            GET_BITS_SAFE(width, 4);

            if (width == 0) {

                memset(coeffs + i, 0, (j - i) * sizeof(*coeffs));

                i = j;

                while (s->bands[k] < i)

                    q = quant[k++];

            } else {

                while (i < j) {

                    if (s->bands[k] == i)

                        q = quant[k++];

                    GET_BITS_SAFE(coeff, width);

                    if (coeff) {

                        int v;

                        GET_BITS_SAFE(v, 1);

                        if (v)

                            coeffs[i] = -q * coeff;

                        else

                            coeffs[i] =  q * coeff;

                    } else {

                        coeffs[i] = 0.0f;

                    }

                    i++;

                }

            }

        }

        if (CONFIG_BINKAUDIO_DCT_DECODER && use_dct) {

            coeffs[0] /= 0.5;

            s->trans.dct.dct_calc(&s->trans.dct,  coeffs);

        }

        else if (CONFIG_BINKAUDIO_RDFT_DECODER)

            s->trans.rdft.rdft_calc(&s->trans.rdft, coeffs);

    }

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

        int j;

        int count = s->overlap_len * s->channels;

        if (!s->first) {

            j = ch;

            for (i = 0; i < s->overlap_len; i++, j += s->channels)

                out[ch][i] = (s->previous[ch][i] * (count - j) +

                                      out[ch][i] *          j) / count;

        }

        memcpy(s->previous[ch], &out[ch][s->frame_len - s->overlap_len],

               s->overlap_len * sizeof(*s->previous[ch]));

    }

    s->first = 0;

    return 0;

}


static int load_normal_reset(S390CPU *cpu)

{

    S390CPUClass *scc = S390_CPU_GET_CLASS(cpu);

    pause_all_vcpus();

    cpu_synchronize_all_states();

    cpu_reset_all();

    io_subsystem_reset();

    scc->initial_cpu_reset(CPU(cpu));

    scc->load_normal(CPU(cpu));

    cpu_synchronize_all_post_reset();

    resume_all_vcpus();

    return 0;

}


static void v9fs_post_lcreate(V9fsState *s, V9fsLcreateState *vs, int err)

{

    if (err == 0) {

        v9fs_string_copy(&vs->fidp->path, &vs->fullname);

        stat_to_qid(&vs->stbuf, &vs->qid);

        vs->offset += pdu_marshal(vs->pdu, vs->offset, "Qd", &vs->qid,

                &vs->iounit);

        err = vs->offset;

    } else {

        vs->fidp->fid_type = P9_FID_NONE;

        close(vs->fidp->fs.fd);

        err = -errno;

    }

    complete_pdu(s, vs->pdu, err);

    v9fs_string_free(&vs->name);

    v9fs_string_free(&vs->fullname);

    qemu_free(vs);

}


static void get_xbzrle_cache_stats(MigrationInfo *info)

{

    if (migrate_use_xbzrle()) {

        info->has_xbzrle_cache = true;

        info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));

        info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();

        info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();

        info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();

        info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();

        info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();

        info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();

    }

}


static PowerPCCPU *ppc440_init_xilinx(ram_addr_t *ram_size,

                                      int do_init,

                                      const char *cpu_model,

                                      uint32_t sysclk)

{

    PowerPCCPU *cpu;

    CPUPPCState *env;

    qemu_irq *irqs;

    cpu = POWERPC_CPU(cpu_generic_init(TYPE_POWERPC_CPU, cpu_model));

    if (cpu == NULL) {

        fprintf(stderr, "Unable to initialize CPU!\n");

        exit(1);

    }

    env = &cpu->env;

    ppc_booke_timers_init(cpu, sysclk, 0/* no flags */);

    ppc_dcr_init(env, NULL, NULL);

    /* interrupt controller */

    irqs = g_malloc0(sizeof(qemu_irq) * PPCUIC_OUTPUT_NB);

    irqs[PPCUIC_OUTPUT_INT] = ((qemu_irq *)env->irq_inputs)[PPC40x_INPUT_INT];

    irqs[PPCUIC_OUTPUT_CINT] = ((qemu_irq *)env->irq_inputs)[PPC40x_INPUT_CINT];

    ppcuic_init(env, irqs, 0x0C0, 0, 1);

    return cpu;

}


static void create_default_qtables(uint8_t *qtables, uint8_t q)

{

    int factor = q;

    int i;

    factor = av_clip(q, 1, 99);

    if (q < 50)

        q = 5000 / factor;

    else

        q = 200 - factor * 2;

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

        int val = (default_quantizers[i] * q + 50) / 100;

        /* Limit the quantizers to 1 <= q <= 255. */

        val = av_clip(val, 1, 255);

        qtables[i] = val;

    }

}


void ff_af_queue_close(AudioFrameQueue *afq)

{

    /* remove/free any remaining frames */

    while (afq->frame_queue)

        delete_next_frame(afq);

    memset(afq, 0, sizeof(*afq));

}


static void lumRangeToJpeg16_c(int16_t *_dst, int width)

{

    int i;

    int32_t *dst = (int32_t *) _dst;

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

        dst[i] = (FFMIN(dst[i],30189<<4)*19077 - (39057361<<4))>>14;

}


static void fill_coding_method_array(sb_int8_array tone_level_idx,

                                     sb_int8_array tone_level_idx_temp,

                                     sb_int8_array coding_method,

                                     int nb_channels,

                                     int c, int superblocktype_2_3,

                                     int cm_table_select)

{

    int ch, sb, j;

    int tmp, acc, esp_40, comp;

    int add1, add2, add3, add4;

    int64_t multres;

    if (!superblocktype_2_3) {

        /* This case is untested, no samples available */

        SAMPLES_NEEDED

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

            for (sb = 0; sb < 30; sb++) {

                for (j = 1; j < 63; j++) {  // The loop only iterates to 63 so the code doesn't overflow the buffer

                    add1 = tone_level_idx[ch][sb][j] - 10;

                    if (add1 < 0)

                        add1 = 0;

                    add2 = add3 = add4 = 0;

                    if (sb > 1) {

                        add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;

                        if (add2 < 0)

                            add2 = 0;

                    }

                    if (sb > 0) {

                        add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;

                        if (add3 < 0)

                            add3 = 0;

                    }

                    if (sb < 29) {

                        add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;

                        if (add4 < 0)

                            add4 = 0;

                    }

                    tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;

                    if (tmp < 0)

                        tmp = 0;

                    tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;

                }

                tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];

            }

            acc = 0;

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

                for (sb = 0; sb < 30; sb++)

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

                        acc += tone_level_idx_temp[ch][sb][j];

            multres = 0x66666667 * (acc * 10);

            esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);

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

                for (sb = 0; sb < 30; sb++)

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

                        comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;

                        if (comp < 0)

                            comp += 0xff;

                        comp /= 256; // signed shift

                        switch(sb) {

                            case 0:

                                if (comp < 30)

                                    comp = 30;

                                comp += 15;

                                break;

                            case 1:

                                if (comp < 24)

                                    comp = 24;

                                comp += 10;

                                break;

                            case 2:

                            case 3:

                            case 4:

                                if (comp < 16)

                                    comp = 16;

                        }

                        if (comp <= 5)

                            tmp = 0;

                        else if (comp <= 10)

                            tmp = 10;

                        else if (comp <= 16)

                            tmp = 16;

                        else if (comp <= 24)

                            tmp = -1;

                        else

                            tmp = 0;

                        coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;

                    }

            for (sb = 0; sb < 30; sb++)

                fix_coding_method_array(sb, nb_channels, coding_method);

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

                for (sb = 0; sb < 30; sb++)

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

                        if (sb >= 10) {

                            if (coding_method[ch][sb][j] < 10)

                                coding_method[ch][sb][j] = 10;

                        } else {

                            if (sb >= 2) {

                                if (coding_method[ch][sb][j] < 16)

                                    coding_method[ch][sb][j] = 16;

                            } else {

                                if (coding_method[ch][sb][j] < 30)

                                    coding_method[ch][sb][j] = 30;

                            }

                        }

    } else { // superblocktype_2_3 != 0

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

            for (sb = 0; sb < 30; sb++)

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

                    coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];

    }

}


static void find_motion(DeshakeContext *deshake, uint8_t *src1, uint8_t *src2,

                        int width, int height, int stride, Transform *t)

{

    int x, y;

    IntMotionVector mv = {0, 0};

    int counts[128][128];

    int count_max_value = 0;

    int contrast;

    int pos;

    double *angles = av_malloc(sizeof(*angles) * width * height / (16 * deshake->blocksize));

    int center_x = 0, center_y = 0;

    double p_x, p_y;

    // Reset counts to zero

    for (x = 0; x < deshake->rx * 2 + 1; x++) {

        for (y = 0; y < deshake->ry * 2 + 1; y++) {

            counts[x][y] = 0;

        }

    }

    pos = 0;

    // Find motion for every block and store the motion vector in the counts

    for (y = deshake->ry; y < height - deshake->ry - (deshake->blocksize * 2); y += deshake->blocksize * 2) {

        // We use a width of 16 here to match the libavcodec sad functions

        for (x = deshake->rx; x < width - deshake->rx - 16; x += 16) {

            // If the contrast is too low, just skip this block as it probably

            // won't be very useful to us.

            contrast = block_contrast(src2, x, y, stride, deshake->blocksize);

            if (contrast > deshake->contrast) {

                //av_log(NULL, AV_LOG_ERROR, "%d\n", contrast);

                find_block_motion(deshake, src1, src2, x, y, stride, &mv);

                if (mv.x != -1 && mv.y != -1) {

                    counts[mv.x + deshake->rx][mv.y + deshake->ry] += 1;

                    if (x > deshake->rx && y > deshake->ry)

                        angles[pos++] = block_angle(x, y, 0, 0, &mv);

                    center_x += mv.x;

                    center_y += mv.y;

                }

            }

        }

    }

    pos = FFMAX(1, pos);

    center_x /= pos;

    center_y /= pos;

    t->angle = clean_mean(angles, pos);

    if (t->angle < 0.001)

        t->angle = 0;

    // Find the most common motion vector in the frame and use it as the gmv

    for (y = deshake->ry * 2; y >= 0; y--) {

        for (x = 0; x < deshake->rx * 2 + 1; x++) {

            //av_log(NULL, AV_LOG_ERROR, "%5d ", counts[x][y]);

            if (counts[x][y] > count_max_value) {

                t->vector.x = x - deshake->rx;

                t->vector.y = y - deshake->ry;

                count_max_value = counts[x][y];

            }

        }

        //av_log(NULL, AV_LOG_ERROR, "\n");

    }

    p_x = (center_x - width / 2);

    p_y = (center_y - height / 2);

    t->vector.x += (cos(t->angle)-1)*p_x  - sin(t->angle)*p_y;

    t->vector.y += sin(t->angle)*p_x  + (cos(t->angle)-1)*p_y;

    // Clamp max shift & rotation?

    t->vector.x = av_clipf(t->vector.x, -deshake->rx * 2, deshake->rx * 2);

    t->vector.y = av_clipf(t->vector.y, -deshake->ry * 2, deshake->ry * 2);

    t->angle = av_clipf(t->angle, -0.1, 0.1);

    //av_log(NULL, AV_LOG_ERROR, "%d x %d\n", avg->x, avg->y);

    av_free(angles);

}


static int dirac_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt)

{

    DiracContext *s     = avctx->priv_data;

    AVFrame *picture    = data;

    uint8_t *buf        = pkt->data;

    int buf_size        = pkt->size;

    int i, data_unit_size, buf_idx = 0;

    int ret;

    /* release unused frames */

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

        if (s->all_frames[i].avframe->data[0] && !s->all_frames[i].avframe->reference) {

            av_frame_unref(s->all_frames[i].avframe);

            memset(s->all_frames[i].interpolated, 0, sizeof(s->all_frames[i].interpolated));

        }

    s->current_picture = NULL;

    *got_frame = 0;

    /* end of stream, so flush delayed pics */

    if (buf_size == 0)

        return get_delayed_pic(s, (AVFrame *)data, got_frame);

    for (;;) {

        /*[DIRAC_STD] Here starts the code from parse_info() defined in 9.6

          [DIRAC_STD] PARSE_INFO_PREFIX = "BBCD" as defined in ISO/IEC 646

          BBCD start code search */

        for (; buf_idx + DATA_UNIT_HEADER_SIZE < buf_size; buf_idx++) {

            if (buf[buf_idx  ] == 'B' && buf[buf_idx+1] == 'B' &&

                buf[buf_idx+2] == 'C' && buf[buf_idx+3] == 'D')

                break;

        }

        /* BBCD found or end of data */

        if (buf_idx + DATA_UNIT_HEADER_SIZE >= buf_size)

            break;

        data_unit_size = AV_RB32(buf+buf_idx+5);

        if (buf_idx + data_unit_size > buf_size || !data_unit_size) {

            if(buf_idx + data_unit_size > buf_size)

            av_log(s->avctx, AV_LOG_ERROR,

                   "Data unit with size %d is larger than input buffer, discarding\n",

                   data_unit_size);

            buf_idx += 4;

            continue;

        }

        /* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3 inside the function parse_sequence() */

        if (dirac_decode_data_unit(avctx, buf+buf_idx, data_unit_size))

        {

            av_log(s->avctx, AV_LOG_ERROR,"Error in dirac_decode_data_unit\n");

            return -1;

        }

        buf_idx += data_unit_size;

    }

    if (!s->current_picture)

        return buf_size;

    if (s->current_picture->avframe->display_picture_number > s->frame_number) {

        DiracFrame *delayed_frame = remove_frame(s->delay_frames, s->frame_number);

        s->current_picture->avframe->reference |= DELAYED_PIC_REF;

        if (add_frame(s->delay_frames, MAX_DELAY, s->current_picture)) {

            int min_num = s->delay_frames[0]->avframe->display_picture_number;

            /* Too many delayed frames, so we display the frame with the lowest pts */

            av_log(avctx, AV_LOG_ERROR, "Delay frame overflow\n");

            for (i = 1; s->delay_frames[i]; i++)

                if (s->delay_frames[i]->avframe->display_picture_number < min_num)

                    min_num = s->delay_frames[i]->avframe->display_picture_number;

            delayed_frame = remove_frame(s->delay_frames, min_num);

            add_frame(s->delay_frames, MAX_DELAY, s->current_picture);

        }

        if (delayed_frame) {

            delayed_frame->avframe->reference ^= DELAYED_PIC_REF;

            if((ret=av_frame_ref(data, delayed_frame->avframe)) < 0)

                return ret;

            *got_frame = 1;

        }

    } else if (s->current_picture->avframe->display_picture_number == s->frame_number) {

        /* The right frame at the right time :-) */

        if((ret=av_frame_ref(data, s->current_picture->avframe)) < 0)

            return ret;

        *got_frame = 1;

    }

    if (*got_frame)

        s->frame_number = picture->display_picture_number + 1;

    return buf_idx;

}


static TCGv gen_ea(CPUM68KState *env, DisasContext *s, uint16_t insn,

                   int opsize, TCGv val, TCGv *addrp, ea_what what)

{

    TCGv reg;

    TCGv result;

    uint32_t offset;

    switch ((insn >> 3) & 7) {

    case 0: /* Data register direct.  */

        reg = DREG(insn, 0);

        if (what == EA_STORE) {

            gen_partset_reg(opsize, reg, val);

            return store_dummy;

        } else {

            return gen_extend(reg, opsize, what == EA_LOADS);

        }

    case 1: /* Address register direct.  */

        reg = AREG(insn, 0);

        if (what == EA_STORE) {

            tcg_gen_mov_i32(reg, val);

            return store_dummy;

        } else {

            return gen_extend(reg, opsize, what == EA_LOADS);

        }

    case 2: /* Indirect register */

        reg = AREG(insn, 0);

        return gen_ldst(s, opsize, reg, val, what);

    case 3: /* Indirect postincrement.  */

        reg = AREG(insn, 0);

        result = gen_ldst(s, opsize, reg, val, what);

        /* ??? This is not exception safe.  The instruction may still

           fault after this point.  */

        if (what == EA_STORE || !addrp)

            tcg_gen_addi_i32(reg, reg, opsize_bytes(opsize));

        return result;

    case 4: /* Indirect predecrememnt.  */

        {

            TCGv tmp;

            if (addrp && what == EA_STORE) {

                tmp = *addrp;

            } else {

                tmp = gen_lea(env, s, insn, opsize);

                if (IS_NULL_QREG(tmp))

                    return tmp;

                if (addrp)

                    *addrp = tmp;

            }

            result = gen_ldst(s, opsize, tmp, val, what);

            /* ??? This is not exception safe.  The instruction may still

               fault after this point.  */

            if (what == EA_STORE || !addrp) {

                reg = AREG(insn, 0);

                tcg_gen_mov_i32(reg, tmp);

            }

        }

        return result;

    case 5: /* Indirect displacement.  */

    case 6: /* Indirect index + displacement.  */

        return gen_ea_once(env, s, insn, opsize, val, addrp, what);

    case 7: /* Other */

        switch (insn & 7) {

        case 0: /* Absolute short.  */

        case 1: /* Absolute long.  */

        case 2: /* pc displacement  */

        case 3: /* pc index+displacement.  */

            return gen_ea_once(env, s, insn, opsize, val, addrp, what);

        case 4: /* Immediate.  */

            /* Sign extend values for consistency.  */

            switch (opsize) {

            case OS_BYTE:

                if (what == EA_LOADS) {

                    offset = cpu_ldsb_code(env, s->pc + 1);

                } else {

                    offset = cpu_ldub_code(env, s->pc + 1);

                }

                s->pc += 2;

                break;

            case OS_WORD:

                if (what == EA_LOADS) {

                    offset = cpu_ldsw_code(env, s->pc);

                } else {

                    offset = cpu_lduw_code(env, s->pc);

                }

                s->pc += 2;

                break;

            case OS_LONG:

                offset = read_im32(env, s);

                break;

            default:

                qemu_assert(0, "Bad immediate operand");

            }

            return tcg_const_i32(offset);

        default:

            return NULL_QREG;

        }

    }

    /* Should never happen.  */

    return NULL_QREG;

}


static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)

{

    NvencContext *ctx = avctx->priv_data;

    if (avctx->bit_rate > 0) {

        ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;

    } else if (ctx->encode_config.rcParams.averageBitRate > 0) {

        ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;

    }

    if (avctx->rc_max_rate > 0)

        ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;

    if (ctx->rc < 0) {

        if (ctx->flags & NVENC_ONE_PASS)

            ctx->twopass = 0;

        if (ctx->flags & NVENC_TWO_PASSES)

            ctx->twopass = 1;

        if (ctx->twopass < 0)

            ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;

        if (ctx->cbr) {

            if (ctx->twopass) {

                ctx->rc = NV_ENC_PARAMS_RC_2_PASS_QUALITY;

            } else {

                ctx->rc = NV_ENC_PARAMS_RC_CBR;

            }

        } else if (avctx->global_quality > 0) {

            ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;

        } else if (ctx->twopass) {

            ctx->rc = NV_ENC_PARAMS_RC_2_PASS_VBR;

        } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {

            ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;

        }

    }

    if (ctx->flags & NVENC_LOSSLESS) {

        set_lossless(avctx);

    } else if (ctx->rc > 0) {

        nvenc_override_rate_control(avctx);

    } else {

        ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;

        set_vbr(avctx);

    }

    if (avctx->rc_buffer_size > 0) {

        ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;

    } else if (ctx->encode_config.rcParams.averageBitRate > 0) {

        ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;

    }

}


static av_cold int vp3_decode_end(AVCodecContext *avctx)

{

    Vp3DecodeContext *s = avctx->priv_data;

    int i;

    if (avctx->is_copy && !s->current_frame.data[0])

        return 0;

    av_free(s->superblock_coding);

    av_free(s->all_fragments);

    av_free(s->coded_fragment_list[0]);

    av_free(s->dct_tokens_base);

    av_free(s->superblock_fragments);

    av_free(s->macroblock_coding);

    av_free(s->motion_val[0]);

    av_free(s->motion_val[1]);

    av_free(s->edge_emu_buffer);

    if (avctx->is_copy) return 0;

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

        free_vlc(&s->dc_vlc[i]);

        free_vlc(&s->ac_vlc_1[i]);

        free_vlc(&s->ac_vlc_2[i]);

        free_vlc(&s->ac_vlc_3[i]);

        free_vlc(&s->ac_vlc_4[i]);

    }

    free_vlc(&s->superblock_run_length_vlc);

    free_vlc(&s->fragment_run_length_vlc);

    free_vlc(&s->mode_code_vlc);

    free_vlc(&s->motion_vector_vlc);

    /* release all frames */

    if (s->golden_frame.data[0])

        ff_thread_release_buffer(avctx, &s->golden_frame);

    if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)

        ff_thread_release_buffer(avctx, &s->last_frame);

    /* no need to release the current_frame since it will always be pointing

     * to the same frame as either the golden or last frame */

    return 0;

}


static void vnc_disconnect_finish(VncState *vs)
{
    vnc_qmp_event(vs, QEVENT_VNC_DISCONNECTED);
    buffer_free(&vs->input);
    buffer_free(&vs->output);
    qobject_decref(vs->info);
#ifdef CONFIG_VNC_TLS
    vnc_tls_client_cleanup(vs);
#endif /* CONFIG_VNC_TLS */
#ifdef CONFIG_VNC_SASL
    vnc_sasl_client_cleanup(vs);
#endif /* CONFIG_VNC_SASL */
    audio_del(vs);
    QTAILQ_REMOVE(&vs->vd->clients, vs, next);
    if (QTAILQ_EMPTY(&vs->vd->clients)) {
        dcl->idle = 1;
    }
    qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
    vnc_remove_timer(vs->vd);
    if (vs->vd->lock_key_sync)
        qemu_remove_led_event_handler(vs->led);
    qemu_free(vs);
}


void qemu_opts_print(QemuOpts *opts)

{

    QemuOpt *opt;

    QemuOptDesc *desc = opts->list->desc;

    if (desc[0].name == NULL) {

        QTAILQ_FOREACH(opt, &opts->head, next) {

            printf("%s=\"%s\" ", opt->name, opt->str);

        }

        return;

    }

    for (; desc && desc->name; desc++) {

        const char *value;

        QemuOpt *opt = qemu_opt_find(opts, desc->name);

        value = opt ? opt->str : desc->def_value_str;

        if (!value) {

            continue;

        }

        if (desc->type == QEMU_OPT_STRING) {

            printf("%s='%s' ", desc->name, value);

        } else if ((desc->type == QEMU_OPT_SIZE ||

                    desc->type == QEMU_OPT_NUMBER) && opt) {

            printf("%s=%" PRId64 " ", desc->name, opt->value.uint);

        } else {

            printf("%s=%s ", desc->name, value);

        }

    }

}


static uint32_t nvic_readl(nvic_state *s, uint32_t offset)

{

    ARMCPU *cpu;

    uint32_t val;

    int irq;

    switch (offset) {

    case 4: /* Interrupt Control Type.  */

        return (s->num_irq / 32) - 1;

    case 0x10: /* SysTick Control and Status.  */

        val = s->systick.control;

        s->systick.control &= ~SYSTICK_COUNTFLAG;

        return val;

    case 0x14: /* SysTick Reload Value.  */

        return s->systick.reload;

    case 0x18: /* SysTick Current Value.  */

        {

            int64_t t;

            if ((s->systick.control & SYSTICK_ENABLE) == 0)

                return 0;

            t = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

            if (t >= s->systick.tick)

                return 0;

            val = ((s->systick.tick - (t + 1)) / systick_scale(s)) + 1;

            /* The interrupt in triggered when the timer reaches zero.

               However the counter is not reloaded until the next clock

               tick.  This is a hack to return zero during the first tick.  */

            if (val > s->systick.reload)

                val = 0;

            return val;

        }

    case 0x1c: /* SysTick Calibration Value.  */

        return 10000;

    case 0xd00: /* CPUID Base.  */

        cpu = ARM_CPU(current_cpu);

        return cpu->env.cp15.c0_cpuid;

    case 0xd04: /* Interrupt Control State.  */

        /* VECTACTIVE */

        val = s->gic.running_irq[0];

        if (val == 1023) {

            val = 0;

        } else if (val >= 32) {

            val -= 16;

        }

        /* RETTOBASE */

        if (s->gic.running_irq[0] == 1023

                || s->gic.last_active[s->gic.running_irq[0]][0] == 1023) {

            val |= (1 << 11);

        }

        /* VECTPENDING */

        if (s->gic.current_pending[0] != 1023)

            val |= (s->gic.current_pending[0] << 12);

        /* ISRPENDING */

        for (irq = 32; irq < s->num_irq; irq++) {

            if (s->gic.irq_state[irq].pending) {

                val |= (1 << 22);

                break;

            }

        }

        /* PENDSTSET */

        if (s->gic.irq_state[ARMV7M_EXCP_SYSTICK].pending)

            val |= (1 << 26);

        /* PENDSVSET */

        if (s->gic.irq_state[ARMV7M_EXCP_PENDSV].pending)

            val |= (1 << 28);

        /* NMIPENDSET */

        if (s->gic.irq_state[ARMV7M_EXCP_NMI].pending)

            val |= (1 << 31);

        return val;

    case 0xd08: /* Vector Table Offset.  */

        cpu = ARM_CPU(current_cpu);

        return cpu->env.v7m.vecbase;

    case 0xd0c: /* Application Interrupt/Reset Control.  */

        return 0xfa05000;

    case 0xd10: /* System Control.  */

        /* TODO: Implement SLEEPONEXIT.  */

        return 0;

    case 0xd14: /* Configuration Control.  */

        /* TODO: Implement Configuration Control bits.  */

        return 0;

    case 0xd24: /* System Handler Status.  */

        val = 0;

        if (s->gic.irq_state[ARMV7M_EXCP_MEM].active) val |= (1 << 0);

        if (s->gic.irq_state[ARMV7M_EXCP_BUS].active) val |= (1 << 1);

        if (s->gic.irq_state[ARMV7M_EXCP_USAGE].active) val |= (1 << 3);

        if (s->gic.irq_state[ARMV7M_EXCP_SVC].active) val |= (1 << 7);

        if (s->gic.irq_state[ARMV7M_EXCP_DEBUG].active) val |= (1 << 8);

        if (s->gic.irq_state[ARMV7M_EXCP_PENDSV].active) val |= (1 << 10);

        if (s->gic.irq_state[ARMV7M_EXCP_SYSTICK].active) val |= (1 << 11);

        if (s->gic.irq_state[ARMV7M_EXCP_USAGE].pending) val |= (1 << 12);

        if (s->gic.irq_state[ARMV7M_EXCP_MEM].pending) val |= (1 << 13);

        if (s->gic.irq_state[ARMV7M_EXCP_BUS].pending) val |= (1 << 14);

        if (s->gic.irq_state[ARMV7M_EXCP_SVC].pending) val |= (1 << 15);

        if (s->gic.irq_state[ARMV7M_EXCP_MEM].enabled) val |= (1 << 16);

        if (s->gic.irq_state[ARMV7M_EXCP_BUS].enabled) val |= (1 << 17);

        if (s->gic.irq_state[ARMV7M_EXCP_USAGE].enabled) val |= (1 << 18);

        return val;

    case 0xd28: /* Configurable Fault Status.  */

        /* TODO: Implement Fault Status.  */

        qemu_log_mask(LOG_UNIMP, "Configurable Fault Status unimplemented\n");

        return 0;

    case 0xd2c: /* Hard Fault Status.  */

    case 0xd30: /* Debug Fault Status.  */

    case 0xd34: /* Mem Manage Address.  */

    case 0xd38: /* Bus Fault Address.  */

    case 0xd3c: /* Aux Fault Status.  */

        /* TODO: Implement fault status registers.  */

        qemu_log_mask(LOG_UNIMP, "Fault status registers unimplemented\n");

        return 0;

    case 0xd40: /* PFR0.  */

        return 0x00000030;

    case 0xd44: /* PRF1.  */

        return 0x00000200;

    case 0xd48: /* DFR0.  */

        return 0x00100000;

    case 0xd4c: /* AFR0.  */

        return 0x00000000;

    case 0xd50: /* MMFR0.  */

        return 0x00000030;

    case 0xd54: /* MMFR1.  */

        return 0x00000000;

    case 0xd58: /* MMFR2.  */

        return 0x00000000;

    case 0xd5c: /* MMFR3.  */

        return 0x00000000;

    case 0xd60: /* ISAR0.  */

        return 0x01141110;

    case 0xd64: /* ISAR1.  */

        return 0x02111000;

    case 0xd68: /* ISAR2.  */

        return 0x21112231;

    case 0xd6c: /* ISAR3.  */

        return 0x01111110;

    case 0xd70: /* ISAR4.  */

        return 0x01310102;

    /* TODO: Implement debug registers.  */

    default:

        qemu_log_mask(LOG_GUEST_ERROR, "NVIC: Bad read offset 0x%x\n", offset);

        return 0;

    }

}


static int gxf_write_header(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    GXFContext *gxf = s->priv_data;

    GXFStreamContext *vsc = NULL;

    uint8_t tracks[255] = {0};

    int i, media_info = 0;

    if (!pb->seekable) {

        av_log(s, AV_LOG_ERROR, "gxf muxer does not support streamed output, patch welcome");

        return -1;

    }

    gxf->flags |= 0x00080000; /* material is simple clip */

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

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

        GXFStreamContext *sc = av_mallocz(sizeof(*sc));

        if (!sc)

            return AVERROR(ENOMEM);

        st->priv_data = sc;

        sc->media_type = ff_codec_get_tag(gxf_media_types, st->codecpar->codec_id);

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

            if (st->codecpar->codec_id != AV_CODEC_ID_PCM_S16LE) {

                av_log(s, AV_LOG_ERROR, "only 16 BIT PCM LE allowed for now\n");

                return -1;

            }

            if (st->codecpar->sample_rate != 48000) {

                av_log(s, AV_LOG_ERROR, "only 48000hz sampling rate is allowed\n");

                return -1;

            }

            if (st->codecpar->channels != 1) {

                av_log(s, AV_LOG_ERROR, "only mono tracks are allowed\n");

                return -1;

            }

            sc->track_type = 2;

            sc->sample_rate = st->codecpar->sample_rate;

            avpriv_set_pts_info(st, 64, 1, sc->sample_rate);

            sc->sample_size = 16;

            sc->frame_rate_index = -2;

            sc->lines_index = -2;

            sc->fields = -2;

            gxf->audio_tracks++;

            gxf->flags |= 0x04000000; /* audio is 16 bit pcm */

            media_info = 'A';

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

            if (i != 0) {

                av_log(s, AV_LOG_ERROR, "video stream must be the first track\n");

                return -1;

            }

            /* FIXME check from time_base ? */

            if (st->codecpar->height == 480 || st->codecpar->height == 512) { /* NTSC or NTSC+VBI */

                sc->frame_rate_index = 5;

                sc->sample_rate = 60;

                gxf->flags |= 0x00000080;

                gxf->time_base = (AVRational){ 1001, 60000 };

            } else if (st->codecpar->height == 576 || st->codecpar->height == 608) { /* PAL or PAL+VBI */

                sc->frame_rate_index = 6;

                sc->media_type++;

                sc->sample_rate = 50;

                gxf->flags |= 0x00000040;

                gxf->time_base = (AVRational){ 1, 50 };

            } else {

                av_log(s, AV_LOG_ERROR, "unsupported video resolution, "

                       "gxf muxer only accepts PAL or NTSC resolutions currently\n");

                return -1;

            }

            avpriv_set_pts_info(st, 64, gxf->time_base.num, gxf->time_base.den);

            if (gxf_find_lines_index(st) < 0)

                sc->lines_index = -1;

            sc->sample_size = st->codecpar->bit_rate;

            sc->fields = 2; /* interlaced */

            vsc = sc;

            switch (st->codecpar->codec_id) {

            case AV_CODEC_ID_MJPEG:

                sc->track_type = 1;

                gxf->flags |= 0x00004000;

                media_info = 'J';

                break;

            case AV_CODEC_ID_MPEG1VIDEO:

                sc->track_type = 9;

                gxf->mpeg_tracks++;

                media_info = 'L';

                break;

            case AV_CODEC_ID_MPEG2VIDEO:

                sc->first_gop_closed = -1;

                sc->track_type = 4;

                gxf->mpeg_tracks++;

                gxf->flags |= 0x00008000;

                media_info = 'M';

                break;

            case AV_CODEC_ID_DVVIDEO:

                if (st->codecpar->format == AV_PIX_FMT_YUV422P) {

                    sc->media_type += 2;

                    sc->track_type = 6;

                    gxf->flags |= 0x00002000;

                    media_info = 'E';

                } else {

                    sc->track_type = 5;

                    gxf->flags |= 0x00001000;

                    media_info = 'D';

                }

                break;

            default:

                av_log(s, AV_LOG_ERROR, "video codec not supported\n");

                return -1;

            }

        }

        /* FIXME first 10 audio tracks are 0 to 9 next 22 are A to V */

        sc->media_info = media_info<<8 | ('0'+tracks[media_info]++);

        sc->order = s->nb_streams - st->index;

    }

    if (ff_audio_interleave_init(s, GXF_samples_per_frame, (AVRational){ 1, 48000 }) < 0)

        return -1;

    gxf_init_timecode_track(&gxf->timecode_track, vsc);

    gxf->flags |= 0x200000; // time code track is non-drop frame

    gxf_write_map_packet(s, 0);

    gxf_write_flt_packet(s);

    gxf_write_umf_packet(s);

    gxf->packet_count = 3;

    avio_flush(pb);

    return 0;

}


static void qxl_render_update_area_unlocked(PCIQXLDevice *qxl)

{

    VGACommonState *vga = &qxl->vga;

    int i;

    if (qxl->guest_primary.resized) {

        qxl->guest_primary.resized = 0;

        qxl->guest_primary.data = memory_region_get_ram_ptr(&qxl->vga.vram);

        qxl_set_rect_to_surface(qxl, &qxl->dirty[0]);

        qxl->num_dirty_rects = 1;

        trace_qxl_render_guest_primary_resized(

               qxl->guest_primary.surface.width,

               qxl->guest_primary.surface.height,

               qxl->guest_primary.qxl_stride,

               qxl->guest_primary.bytes_pp,

               qxl->guest_primary.bits_pp);

        if (qxl->guest_primary.qxl_stride > 0) {

            qemu_free_displaysurface(vga->ds);

            qemu_create_displaysurface_from(qxl->guest_primary.surface.width,

                                            qxl->guest_primary.surface.height,

                                            qxl->guest_primary.bits_pp,

                                            qxl->guest_primary.abs_stride,

                                            qxl->guest_primary.data);

        } else {

            qemu_resize_displaysurface(vga->ds,

                    qxl->guest_primary.surface.width,

                    qxl->guest_primary.surface.height);

        }

        dpy_gfx_resize(vga->ds);

    }

    for (i = 0; i < qxl->num_dirty_rects; i++) {

        if (qemu_spice_rect_is_empty(qxl->dirty+i)) {

            break;

        }

        qxl_blit(qxl, qxl->dirty+i);

        dpy_gfx_update(vga->ds,

                       qxl->dirty[i].left, qxl->dirty[i].top,

                       qxl->dirty[i].right - qxl->dirty[i].left,

                       qxl->dirty[i].bottom - qxl->dirty[i].top);

    }

    qxl->num_dirty_rects = 0;

}


static void page_init(void)

{

    /* NOTE: we can always suppose that qemu_host_page_size >=

       TARGET_PAGE_SIZE */

#ifdef _WIN32

    {

        SYSTEM_INFO system_info;

        GetSystemInfo(&system_info);

        qemu_real_host_page_size = system_info.dwPageSize;

    }

#else

    qemu_real_host_page_size = getpagesize();

#endif

    if (qemu_host_page_size == 0) {

        qemu_host_page_size = qemu_real_host_page_size;

    }

    if (qemu_host_page_size < TARGET_PAGE_SIZE) {

        qemu_host_page_size = TARGET_PAGE_SIZE;

    }

    qemu_host_page_mask = ~(qemu_host_page_size - 1);

#if defined(CONFIG_BSD) && defined(CONFIG_USER_ONLY)

    {

#ifdef HAVE_KINFO_GETVMMAP

        struct kinfo_vmentry *freep;

        int i, cnt;

        freep = kinfo_getvmmap(getpid(), &cnt);

        if (freep) {

            mmap_lock();

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

                unsigned long startaddr, endaddr;

                startaddr = freep[i].kve_start;

                endaddr = freep[i].kve_end;

                if (h2g_valid(startaddr)) {

                    startaddr = h2g(startaddr) & TARGET_PAGE_MASK;

                    if (h2g_valid(endaddr)) {

                        endaddr = h2g(endaddr);

                        page_set_flags(startaddr, endaddr, PAGE_RESERVED);

                    } else {

#if TARGET_ABI_BITS <= L1_MAP_ADDR_SPACE_BITS

                        endaddr = ~0ul;

                        page_set_flags(startaddr, endaddr, PAGE_RESERVED);

#endif

                    }

                }

            }

            free(freep);

            mmap_unlock();

        }

#else

        FILE *f;

        last_brk = (unsigned long)sbrk(0);

        f = fopen("/compat/linux/proc/self/maps", "r");

        if (f) {

            mmap_lock();

            do {

                unsigned long startaddr, endaddr;

                int n;

                n = fscanf(f, "%lx-%lx %*[^\n]\n", &startaddr, &endaddr);

                if (n == 2 && h2g_valid(startaddr)) {

                    startaddr = h2g(startaddr) & TARGET_PAGE_MASK;

                    if (h2g_valid(endaddr)) {

                        endaddr = h2g(endaddr);

                    } else {

                        endaddr = ~0ul;

                    }

                    page_set_flags(startaddr, endaddr, PAGE_RESERVED);

                }

            } while (!feof(f));

            fclose(f);

            mmap_unlock();

        }

#endif

    }

#endif

}


static SocketAddress *tcp_build_address(const char *host_port, Error **errp)

{

    InetSocketAddress *iaddr = g_new(InetSocketAddress, 1);

    SocketAddress *saddr;

    if (inet_parse(iaddr, host_port, errp)) {

        qapi_free_InetSocketAddress(iaddr);

        return NULL;

    }

    saddr = g_new0(SocketAddress, 1);

    saddr->type = SOCKET_ADDRESS_KIND_INET;

    saddr->u.inet.data = iaddr;

    return saddr;

}