static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){

    MpegEncContext * const s = &h->s;

    AVCodecContext * const avctx= s->avctx;

    H264Context *hx; ///< thread context

    int buf_index;

    int context_count;

    int next_avc;

    int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);

    int nals_needed=0; ///< number of NALs that need decoding before the next frame thread starts

    int nal_index;

    h->nal_unit_type= 0;

    h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;

    if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){

        h->current_slice = 0;

        if (!s->first_field)

            s->current_picture_ptr= NULL;

        ff_h264_reset_sei(h);

    }

    for(;pass <= 1;pass++){

        buf_index = 0;

        context_count = 0;

        next_avc = h->is_avc ? 0 : buf_size;

        nal_index = 0;

    for(;;){

        int consumed;

        int dst_length;

        int bit_length;

        uint8_t *ptr;

        int i, nalsize = 0;

        int err;

        if(buf_index >= next_avc) {

            if (buf_index >= buf_size - h->nal_length_size) break;

            nalsize = 0;

            for(i = 0; i < h->nal_length_size; i++)

                nalsize = (nalsize << 8) | buf[buf_index++];

            if(nalsize <= 0 || nalsize > buf_size - buf_index){

                av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);

                break;

            }

            next_avc= buf_index + nalsize;

        } else {

            // start code prefix search

            for(; buf_index + 3 < next_avc; buf_index++){

                // This should always succeed in the first iteration.

                if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)

                    break;

            }

            if(buf_index+3 >= buf_size) break;

            buf_index+=3;

            if(buf_index >= next_avc) continue;

        }

        hx = h->thread_context[context_count];

        ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);

        if (ptr==NULL || dst_length < 0){

            return -1;

        }

        i= buf_index + consumed;

        if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&

           buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)

            s->workaround_bugs |= FF_BUG_TRUNCATED;

        if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){

        while(dst_length > 0 && ptr[dst_length - 1] == 0)

            dst_length--;

        }

        bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));

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

            av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d/%d at %d/%d length %d pass %d\n", hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);

        }

        if (h->is_avc && (nalsize != consumed) && nalsize){

            av_log(h->s.avctx, AV_LOG_DEBUG, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);

        }

        buf_index += consumed;

        nal_index++;

        if(pass == 0) {

            // packets can sometimes contain multiple PPS/SPS

            // e.g. two PAFF field pictures in one packet, or a demuxer which splits NALs strangely

            // if so, when frame threading we can't start the next thread until we've read all of them

            switch (hx->nal_unit_type) {

                case NAL_SPS:

                case NAL_PPS:

                    nals_needed = nal_index;

                    break;

                case NAL_IDR_SLICE:

                case NAL_SLICE:

                    init_get_bits(&hx->s.gb, ptr, bit_length);

                    if (!get_ue_golomb(&hx->s.gb))

                        nals_needed = nal_index;

            }

            continue;

        }

        //FIXME do not discard SEI id

        if(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc  == 0)

            continue;

      again:

        err = 0;

        switch(hx->nal_unit_type){

        case NAL_IDR_SLICE:

            if (h->nal_unit_type != NAL_IDR_SLICE) {

                av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");

                return -1;

            }

            idr(h); // FIXME ensure we don't lose some frames if there is reordering

        case NAL_SLICE:

            init_get_bits(&hx->s.gb, ptr, bit_length);

            hx->intra_gb_ptr=

            hx->inter_gb_ptr= &hx->s.gb;

            hx->s.data_partitioning = 0;

            if((err = decode_slice_header(hx, h)))

               break;

            if (   h->sei_recovery_frame_cnt >= 0

                && ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {

                h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %

                                    (1 << h->sps.log2_max_frame_num);

            }

            s->current_picture_ptr->f.key_frame |=

                    (hx->nal_unit_type == NAL_IDR_SLICE);

            if (h->recovery_frame == h->frame_num) {

                h->sync |= 1;

                h->recovery_frame = -1;

            }

            h->sync |= !!s->current_picture_ptr->f.key_frame;

            h->sync |= 3*!!(s->flags2 & CODEC_FLAG2_SHOW_ALL);

            s->current_picture_ptr->sync = h->sync;

            if (h->current_slice == 1) {

                if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {

                    decode_postinit(h, nal_index >= nals_needed);

                }

                if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)

                    return -1;

                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)

                    ff_vdpau_h264_picture_start(s);

            }

            if(hx->redundant_pic_count==0

               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)

               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=AV_PICTURE_TYPE_B)

               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==AV_PICTURE_TYPE_I)

               && avctx->skip_frame < AVDISCARD_ALL){

                if(avctx->hwaccel) {

                    if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)

                        return -1;

                }else

                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){

                    static const uint8_t start_code[] = {0x00, 0x00, 0x01};

                    ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));

                    ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );

                }else

                    context_count++;

            }

            break;

        case NAL_DPA:

            init_get_bits(&hx->s.gb, ptr, bit_length);

            hx->intra_gb_ptr=

            hx->inter_gb_ptr= NULL;

            if ((err = decode_slice_header(hx, h)) < 0)

                break;

            hx->s.data_partitioning = 1;

            break;

        case NAL_DPB:

            init_get_bits(&hx->intra_gb, ptr, bit_length);

            hx->intra_gb_ptr= &hx->intra_gb;

            break;

        case NAL_DPC:

            init_get_bits(&hx->inter_gb, ptr, bit_length);

            hx->inter_gb_ptr= &hx->inter_gb;

            if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning

               && s->context_initialized

               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)

               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=AV_PICTURE_TYPE_B)

               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==AV_PICTURE_TYPE_I)

               && avctx->skip_frame < AVDISCARD_ALL)

                context_count++;

            break;

        case NAL_SEI:

            init_get_bits(&s->gb, ptr, bit_length);

            ff_h264_decode_sei(h);

            break;

        case NAL_SPS:

            init_get_bits(&s->gb, ptr, bit_length);

            if(ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)){

                av_log(h->s.avctx, AV_LOG_DEBUG, "SPS decoding failure, trying alternative mode\n");

                if(h->is_avc) av_assert0(next_avc - buf_index + consumed == nalsize);

                init_get_bits(&s->gb, &buf[buf_index + 1 - consumed], 8*(next_avc - buf_index + consumed));

                ff_h264_decode_seq_parameter_set(h);

            }

            if (s->flags& CODEC_FLAG_LOW_DELAY ||

                (h->sps.bitstream_restriction_flag && !h->sps.num_reorder_frames))

                s->low_delay=1;

            if(avctx->has_b_frames < 2)

                avctx->has_b_frames= !s->low_delay;

            break;

        case NAL_PPS:

            init_get_bits(&s->gb, ptr, bit_length);

            ff_h264_decode_picture_parameter_set(h, bit_length);

            break;

        case NAL_AUD:

        case NAL_END_SEQUENCE:

        case NAL_END_STREAM:

        case NAL_FILLER_DATA:

        case NAL_SPS_EXT:

        case NAL_AUXILIARY_SLICE:

            break;

        default:

            av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);

        }

        if(context_count == h->max_contexts) {

            execute_decode_slices(h, context_count);

            context_count = 0;

        }

        if (err < 0)

            av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");

        else if(err == 1) {

            /* Slice could not be decoded in parallel mode, copy down

             * NAL unit stuff to context 0 and restart. Note that

             * rbsp_buffer is not transferred, but since we no longer

             * run in parallel mode this should not be an issue. */

            h->nal_unit_type = hx->nal_unit_type;

            h->nal_ref_idc   = hx->nal_ref_idc;

            hx = h;

            goto again;

        }

    }

    }

    if(context_count)

        execute_decode_slices(h, context_count);

    return buf_index;

}


static int dnxhd_find_frame_end(DNXHDParserContext *dctx,

                                const uint8_t *buf, int buf_size)

{

    ParseContext *pc = &dctx->pc;

    uint64_t state = pc->state64;

    int pic_found = pc->frame_start_found;

    int i = 0;

    if (!pic_found) {

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

            state = (state << 8) | buf[i];

            if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {

                i++;

                pic_found = 1;

                dctx->cur_byte = 0;

                dctx->remaining = 0;

                break;

            }

        }

    }

    if (pic_found && !dctx->remaining) {

        if (!buf_size) /* EOF considered as end of frame */

            return 0;

        for (; i < buf_size; i++) {

            dctx->cur_byte++;

            state = (state << 8) | buf[i];

            if (dctx->cur_byte == 24) {

                dctx->h = (state >> 32) & 0xFFFF;

            } else if (dctx->cur_byte == 26) {

                dctx->w = (state >> 32) & 0xFFFF;

            } else if (dctx->cur_byte == 42) {

                int cid = (state >> 32) & 0xFFFFFFFF;

                if (cid <= 0)

                    continue;

                dctx->remaining = avpriv_dnxhd_get_frame_size(cid);

                if (dctx->remaining <= 0) {

                    dctx->remaining = ff_dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);

                    if (dctx->remaining <= 0)

                        return dctx->remaining;

                }

                if (buf_size - i + 47 >= dctx->remaining) {

                    int remaining = dctx->remaining;

                    pc->frame_start_found = 0;

                    pc->state64 = -1;

                    dctx->cur_byte = 0;

                    dctx->remaining = 0;

                    return remaining;

                } else {

                    dctx->remaining -= buf_size;

                }

            }

        }

    } else if (pic_found) {

        if (dctx->remaining > buf_size) {

            dctx->remaining -= buf_size;

        } else {

            int remaining = dctx->remaining;

            pc->frame_start_found = 0;

            pc->state64 = -1;

            dctx->cur_byte = 0;

            dctx->remaining = 0;

            return remaining;

        }

    }

    pc->frame_start_found = pic_found;

    pc->state64 = state;

    return END_NOT_FOUND;

}


static av_cold int vaapi_encode_h264_init_constant_bitrate(AVCodecContext *avctx)

{

    VAAPIEncodeContext      *ctx = avctx->priv_data;

    VAAPIEncodeH264Context *priv = ctx->priv_data;

    int hrd_buffer_size;

    int hrd_initial_buffer_fullness;

    if (avctx->bit_rate > INT32_MAX) {

        av_log(avctx, AV_LOG_ERROR, "Target bitrate of 2^31 bps or "

               "higher is not supported.\n");

        return AVERROR(EINVAL);

    }

    if (avctx->rc_buffer_size)

        hrd_buffer_size = avctx->rc_buffer_size;

    else

        hrd_buffer_size = avctx->bit_rate;

    if (avctx->rc_initial_buffer_occupancy)

        hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;

    else

        hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;

    priv->rc_params.misc.type = VAEncMiscParameterTypeRateControl;

    priv->rc_params.rc = (VAEncMiscParameterRateControl) {

        .bits_per_second   = avctx->bit_rate,

        .target_percentage = 66,

        .window_size       = 1000,

        .initial_qp        = (avctx->qmax >= 0 ? avctx->qmax : 40),

        .min_qp            = (avctx->qmin >= 0 ? avctx->qmin : 18),

        .basic_unit_size   = 0,

    };

    ctx->global_params[ctx->nb_global_params] =

        &priv->rc_params.misc;

    ctx->global_params_size[ctx->nb_global_params++] =

        sizeof(priv->rc_params);

    priv->hrd_params.misc.type = VAEncMiscParameterTypeHRD;

    priv->hrd_params.hrd = (VAEncMiscParameterHRD) {

        .initial_buffer_fullness = hrd_initial_buffer_fullness,

        .buffer_size             = hrd_buffer_size,

    };

    ctx->global_params[ctx->nb_global_params] =

        &priv->hrd_params.misc;

    ctx->global_params_size[ctx->nb_global_params++] =

        sizeof(priv->hrd_params);

    // These still need to be  set for pic_init_qp/slice_qp_delta.

    priv->fixed_qp_idr = 26;

    priv->fixed_qp_p   = 26;

    priv->fixed_qp_b   = 26;

    av_log(avctx, AV_LOG_DEBUG, "Using constant-bitrate = %"PRId64" bps.\n",

           avctx->bit_rate);

    return 0;

}


static inline void RENAME(planar2x)(const uint8_t *src, uint8_t *dst, long srcWidth, long srcHeight, long srcStride, long dstStride)

{

	long x,y;

	dst[0]= src[0];

	// first line

	for(x=0; x<srcWidth-1; x++){

		dst[2*x+1]= (3*src[x] +   src[x+1])>>2;

		dst[2*x+2]= (  src[x] + 3*src[x+1])>>2;

	}

	dst[2*srcWidth-1]= src[srcWidth-1];

        dst+= dstStride;

	for(y=1; y<srcHeight; y++){

#if defined (HAVE_MMX2) || defined (HAVE_3DNOW)

		const long mmxSize= srcWidth&~15;

		asm volatile(

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

			"1:				\n\t"

			"movq (%0, %%"REG_a"), %%mm0	\n\t"

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

			"movq 1(%0, %%"REG_a"), %%mm2	\n\t"

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

			"movq -1(%0, %%"REG_a"), %%mm4	\n\t"

			"movq -1(%1, %%"REG_a"), %%mm5	\n\t"

			PAVGB" %%mm0, %%mm5		\n\t"

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

			PAVGB" %%mm0, %%mm5		\n\t"

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

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

			PAVGB" %%mm1, %%mm2		\n\t"

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

			PAVGB" %%mm1, %%mm2		\n\t"

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

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

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

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

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

			"punpckhbw %%mm2, %%mm6		\n\t"

#if 1

			MOVNTQ" %%mm5, (%2, %%"REG_a", 2)\n\t"

			MOVNTQ" %%mm7, 8(%2, %%"REG_a", 2)\n\t"

			MOVNTQ" %%mm4, (%3, %%"REG_a", 2)\n\t"

			MOVNTQ" %%mm6, 8(%3, %%"REG_a", 2)\n\t"

#else

			"movq %%mm5, (%2, %%"REG_a", 2)	\n\t"

			"movq %%mm7, 8(%2, %%"REG_a", 2)\n\t"

			"movq %%mm4, (%3, %%"REG_a", 2)	\n\t"

			"movq %%mm6, 8(%3, %%"REG_a", 2)\n\t"

#endif

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

			" js 1b				\n\t"

			:: "r" (src + mmxSize  ), "r" (src + srcStride + mmxSize  ),

			   "r" (dst + mmxSize*2), "r" (dst + dstStride + mmxSize*2),

			   "g" (-mmxSize)

			: "%"REG_a

		);

#else

		const long mmxSize=1;

#endif

		dst[0        ]= (3*src[0] +   src[srcStride])>>2;

		dst[dstStride]= (  src[0] + 3*src[srcStride])>>2;

		for(x=mmxSize-1; x<srcWidth-1; x++){

			dst[2*x          +1]= (3*src[x+0] +   src[x+srcStride+1])>>2;

			dst[2*x+dstStride+2]= (  src[x+0] + 3*src[x+srcStride+1])>>2;

			dst[2*x+dstStride+1]= (  src[x+1] + 3*src[x+srcStride  ])>>2;

			dst[2*x          +2]= (3*src[x+1] +   src[x+srcStride  ])>>2;

		}

		dst[srcWidth*2 -1            ]= (3*src[srcWidth-1] +   src[srcWidth-1 + srcStride])>>2;

		dst[srcWidth*2 -1 + dstStride]= (  src[srcWidth-1] + 3*src[srcWidth-1 + srcStride])>>2;

		dst+=dstStride*2;

		src+=srcStride;

	}

	// last line

#if 1

	dst[0]= src[0];

	for(x=0; x<srcWidth-1; x++){

		dst[2*x+1]= (3*src[x] +   src[x+1])>>2;

		dst[2*x+2]= (  src[x] + 3*src[x+1])>>2;

	}

	dst[2*srcWidth-1]= src[srcWidth-1];

#else

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

		dst[2*x+0]=

		dst[2*x+1]= src[x];

	}

#endif

#ifdef HAVE_MMX

asm volatile(   EMMS" \n\t"

        	SFENCE" \n\t"

        	:::"memory");

#endif

}


static void gen_mtmsr(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        return;

    }

    if (ctx->opcode & 0x00010000) {

        /* Special form that does not need any synchronisation */

        TCGv t0 = tcg_temp_new();

        tcg_gen_andi_tl(t0, cpu_gpr[rS(ctx->opcode)], (1 << MSR_RI) | (1 << MSR_EE));

        tcg_gen_andi_tl(cpu_msr, cpu_msr, ~(target_ulong)((1 << MSR_RI) | (1 << MSR_EE)));

        tcg_gen_or_tl(cpu_msr, cpu_msr, t0);

        tcg_temp_free(t0);

    } else {

        TCGv msr = tcg_temp_new();

        /* XXX: we need to update nip before the store

         *      if we enter power saving mode, we will exit the loop

         *      directly from ppc_store_msr

         */

        gen_update_nip(ctx, ctx->nip);

#if defined(TARGET_PPC64)

        tcg_gen_deposit_tl(msr, cpu_msr, cpu_gpr[rS(ctx->opcode)], 0, 32);

#else

        tcg_gen_mov_tl(msr, cpu_gpr[rS(ctx->opcode)]);

#endif

        gen_helper_store_msr(cpu_env, msr);

        tcg_temp_free(msr);

        /* Must stop the translation as machine state (may have) changed */

        /* Note that mtmsr is not always defined as context-synchronizing */

        gen_stop_exception(ctx);

    }

#endif

}


static void flatview_ref(FlatView *view)

{

    atomic_inc(&view->ref);

}


static int huff_build10(VLC *vlc, uint8_t *len)

{

    HuffEntry he[1024];

    uint32_t codes[1024];

    uint8_t bits[1024];

    uint16_t syms[1024];

    uint32_t code;

    int i;

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

        he[i].sym = 1023 - i;

        he[i].len = len[i];

    }

    AV_QSORT(he, 1024, HuffEntry, huff_cmp_len10);

    code = 1;

    for (i = 1023; i >= 0; i--) {

        codes[i] = code >> (32 - he[i].len);

        bits[i]  = he[i].len;

        syms[i]  = he[i].sym;

        code += 0x80000000u >> (he[i].len - 1);

    }

    ff_free_vlc(vlc);

    return ff_init_vlc_sparse(vlc, FFMIN(he[1023].len, 12), 1024,

                              bits,  sizeof(*bits),  sizeof(*bits),

                              codes, sizeof(*codes), sizeof(*codes),

                              syms,  sizeof(*syms),  sizeof(*syms), 0);

}


static void test_task_complete(void)

{

    QIOTask *task;

    Object *obj = object_new(TYPE_DUMMY);

    Object *src;

    struct TestTaskData data = { NULL, NULL, false };

    task = qio_task_new(obj, task_callback, &data, NULL);

    src = qio_task_get_source(task);

    qio_task_complete(task);

    g_assert(obj == src);

    object_unref(obj);

    object_unref(src);

    g_assert(data.source == obj);

    g_assert(data.err == NULL);

    g_assert(data.freed == false);

}


static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    NUTContext *nut = s->priv_data;

    ByteIOContext *bc = &s->pb;

    int64_t pos;

    int inited_stream_count;

    nut->avf= s;

    av_set_pts_info(s, 60, 1, AV_TIME_BASE);

    /* main header */

    pos=0;

    for(;;){

        if (find_startcode(bc, MAIN_STARTCODE, pos)<0){

            av_log(s, AV_LOG_ERROR, "no main startcode found\n");

            return -1;

        }

        pos= url_ftell(bc);

        if(decode_main_header(nut) >= 0)

            break;

    }

    s->bit_rate = 0;

    nut->stream = av_malloc(sizeof(StreamContext)*nut->stream_count);

    /* stream headers */

    pos=0;

    for(inited_stream_count=0; inited_stream_count < nut->stream_count;){

        if (find_startcode(bc, STREAM_STARTCODE, pos)<0){

            av_log(s, AV_LOG_ERROR, "not all stream headers found\n");

            return -1;

        }

        pos= url_ftell(bc);

        if(decode_stream_header(nut) >= 0)

            inited_stream_count++;

    }

    /* info headers */

    pos=0;

    for(;;){

        uint64_t startcode= find_any_startcode(bc, pos);

        pos= url_ftell(bc);

        if(startcode==0){

            av_log(s, AV_LOG_ERROR, "EOF before video frames\n");

            return -1;

        }else if(startcode == KEYFRAME_STARTCODE){

            url_fseek(bc, -8, SEEK_CUR); //FIXME

            break;

        }else if(startcode != INFO_STARTCODE){

            continue;

        }

        decode_info_header(nut);

    }

    return 0;

}


int ff_v4l2_m2m_codec_reinit(V4L2m2mContext* s)

{

    int ret;

    av_log(s->avctx, AV_LOG_DEBUG, "reinit context\n");

    /* 1. streamoff */

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

    if (ret)

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

    /* 2. unmap the capture buffers (v4l2 and ffmpeg):

     *    we must wait for all references to be released before being allowed

     *    to queue new buffers.

     */

    av_log(s->avctx, AV_LOG_DEBUG, "waiting for user to release AVBufferRefs\n");

    if (atomic_load(&s->refcount))

        while(sem_wait(&s->refsync) == -1 && errno == EINTR);

    ff_v4l2_context_release(&s->capture);

    /* 3. get the new capture format */

    ret = ff_v4l2_context_get_format(&s->capture);

    if (ret) {

        av_log(s->avctx, AV_LOG_ERROR, "query the new capture format\n");

        return ret;

    }

    /* 4. set the capture format */

    ret = ff_v4l2_context_set_format(&s->capture);

    if (ret) {

        av_log(s->avctx, AV_LOG_ERROR, "setting capture format\n");

        return ret;

    }

    /* 5. complete reinit */

    sem_destroy(&s->refsync);

    sem_init(&s->refsync, 0, 0);

    s->draining = 0;

    s->reinit = 0;

    return 0;

}


static int wsvqa_read_header(AVFormatContext *s,

                             AVFormatParameters *ap)

{

    WsVqaDemuxContext *wsvqa = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *st;

    unsigned char *header;

    unsigned char scratch[VQA_PREAMBLE_SIZE];

    unsigned int chunk_tag;

    unsigned int chunk_size;

    /* initialize the video decoder stream */

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR(ENOMEM);

    av_set_pts_info(st, 33, 1, VQA_FRAMERATE);

    wsvqa->video_stream_index = st->index;

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = CODEC_ID_WS_VQA;

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

    /* skip to the start of the VQA header */

    avio_seek(pb, 20, SEEK_SET);

    /* the VQA header needs to go to the decoder */

    st->codec->extradata_size = VQA_HEADER_SIZE;

    st->codec->extradata = av_mallocz(VQA_HEADER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);

    header = (unsigned char *)st->codec->extradata;

    if (avio_read(pb, st->codec->extradata, VQA_HEADER_SIZE) !=

        VQA_HEADER_SIZE) {

        av_free(st->codec->extradata);

        return AVERROR(EIO);

    }

    st->codec->width = AV_RL16(&header[6]);

    st->codec->height = AV_RL16(&header[8]);

    /* initialize the audio decoder stream for VQA v1 or nonzero samplerate */

    if (AV_RL16(&header[24]) || (AV_RL16(&header[0]) == 1 && AV_RL16(&header[2]) == 1)) {

        st = av_new_stream(s, 0);

        if (!st)

            return AVERROR(ENOMEM);

        av_set_pts_info(st, 33, 1, VQA_FRAMERATE);

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        if (AV_RL16(&header[0]) == 1)

            st->codec->codec_id = CODEC_ID_WESTWOOD_SND1;

        else

            st->codec->codec_id = CODEC_ID_ADPCM_IMA_WS;

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

        st->codec->sample_rate = AV_RL16(&header[24]);

        if (!st->codec->sample_rate)

            st->codec->sample_rate = 22050;

        st->codec->channels = header[26];

        if (!st->codec->channels)

            st->codec->channels = 1;

        st->codec->bits_per_coded_sample = 16;

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

            st->codec->bits_per_coded_sample / 4;

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

        wsvqa->audio_stream_index = st->index;

        wsvqa->audio_samplerate = st->codec->sample_rate;

        wsvqa->audio_channels = st->codec->channels;

        wsvqa->audio_frame_counter = 0;

    }

    /* there are 0 or more chunks before the FINF chunk; iterate until

     * FINF has been skipped and the file will be ready to be demuxed */

    do {

        if (avio_read(pb, scratch, VQA_PREAMBLE_SIZE) != VQA_PREAMBLE_SIZE) {

            av_free(st->codec->extradata);

            return AVERROR(EIO);

        }

        chunk_tag = AV_RB32(&scratch[0]);

        chunk_size = AV_RB32(&scratch[4]);

        /* catch any unknown header tags, for curiousity */

        switch (chunk_tag) {

        case CINF_TAG:

        case CINH_TAG:

        case CIND_TAG:

        case PINF_TAG:

        case PINH_TAG:

        case PIND_TAG:

        case FINF_TAG:

        case CMDS_TAG:

            break;

        default:

            av_log (s, AV_LOG_ERROR, " note: unknown chunk seen (%c%c%c%c)\n",

                scratch[0], scratch[1],

                scratch[2], scratch[3]);

            break;

        }

        avio_skip(pb, chunk_size);

    } while (chunk_tag != FINF_TAG);

    return 0;

}


int ff_wma_init(AVCodecContext *avctx, int flags2)

{

    WMACodecContext *s = avctx->priv_data;

    int i;

    float bps1, high_freq;

    volatile float bps;

    int sample_rate1;

    int coef_vlc_table;

    if (   avctx->sample_rate <= 0 || avctx->sample_rate > 50000

        || avctx->channels    <= 0 || avctx->channels    > 2

        || avctx->bit_rate    <= 0)

        return -1;

    ff_fmt_convert_init(&s->fmt_conv, avctx);

    avpriv_float_dsp_init(&s->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);

    if (avctx->codec->id == AV_CODEC_ID_WMAV1) {

        s->version = 1;

    } else {

        s->version = 2;

    /* compute MDCT block size */

    s->frame_len_bits = ff_wma_get_frame_len_bits(avctx->sample_rate,

                                                  s->version, 0);

    s->next_block_len_bits = s->frame_len_bits;

    s->prev_block_len_bits = s->frame_len_bits;

    s->block_len_bits      = s->frame_len_bits;

    s->frame_len = 1 << s->frame_len_bits;

    if (s->use_variable_block_len) {

        int nb_max, nb;

        nb = ((flags2 >> 3) & 3) + 1;

        if ((avctx->bit_rate / avctx->channels) >= 32000)

            nb += 2;

        nb_max = s->frame_len_bits - BLOCK_MIN_BITS;

        if (nb > nb_max)

            nb = nb_max;

        s->nb_block_sizes = nb + 1;

    } else {

        s->nb_block_sizes = 1;

    /* init rate dependent parameters */

    s->use_noise_coding = 1;

    high_freq = avctx->sample_rate * 0.5;

    /* if version 2, then the rates are normalized */

    sample_rate1 = avctx->sample_rate;

    if (s->version == 2) {

        if (sample_rate1 >= 44100) {

            sample_rate1 = 44100;

        } else if (sample_rate1 >= 22050) {

            sample_rate1 = 22050;

        } else if (sample_rate1 >= 16000) {

            sample_rate1 = 16000;

        } else if (sample_rate1 >= 11025) {

            sample_rate1 = 11025;

        } else if (sample_rate1 >= 8000) {

            sample_rate1 = 8000;

    bps = (float)avctx->bit_rate / (float)(avctx->channels * avctx->sample_rate);

    s->byte_offset_bits = av_log2((int)(bps * s->frame_len / 8.0 + 0.5)) + 2;

    /* compute high frequency value and choose if noise coding should

       be activated */

    bps1 = bps;

    if (avctx->channels == 2)

        bps1 = bps * 1.6;

    if (sample_rate1 == 44100) {

        if (bps1 >= 0.61) {

            s->use_noise_coding = 0;

        } else {

            high_freq = high_freq * 0.4;

    } else if (sample_rate1 == 22050) {

        if (bps1 >= 1.16) {

            s->use_noise_coding = 0;

        } else if (bps1 >= 0.72) {

            high_freq = high_freq * 0.7;

        } else {

            high_freq = high_freq * 0.6;

    } else if (sample_rate1 == 16000) {

        if (bps > 0.5) {

            high_freq = high_freq * 0.5;

        } else {

            high_freq = high_freq * 0.3;

    } else if (sample_rate1 == 11025) {

        high_freq = high_freq * 0.7;

    } else if (sample_rate1 == 8000) {

        if (bps <= 0.625) {

            high_freq = high_freq * 0.5;

        } else if (bps > 0.75) {

            s->use_noise_coding = 0;

        } else {

            high_freq = high_freq * 0.65;

    } else {

        if (bps >= 0.8) {

            high_freq = high_freq * 0.75;

        } else if (bps >= 0.6) {

            high_freq = high_freq * 0.6;

        } else {

            high_freq = high_freq * 0.5;

    av_dlog(s->avctx, "flags2=0x%x\n", flags2);

    av_dlog(s->avctx, "version=%d channels=%d sample_rate=%d bitrate=%d block_align=%d\n",

            s->version, avctx->channels, avctx->sample_rate, avctx->bit_rate,

            avctx->block_align);

    av_dlog(s->avctx, "bps=%f bps1=%f high_freq=%f bitoffset=%d\n",

            bps, bps1, high_freq, s->byte_offset_bits);

    av_dlog(s->avctx, "use_noise_coding=%d use_exp_vlc=%d nb_block_sizes=%d\n",

            s->use_noise_coding, s->use_exp_vlc, s->nb_block_sizes);

    /* compute the scale factor band sizes for each MDCT block size */

    {

        int a, b, pos, lpos, k, block_len, i, j, n;

        const uint8_t *table;

        if (s->version == 1) {

            s->coefs_start = 3;

        } else {

            s->coefs_start = 0;

        for (k = 0; k < s->nb_block_sizes; k++) {

            block_len = s->frame_len >> k;

            if (s->version == 1) {

                lpos = 0;

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

                    a = ff_wma_critical_freqs[i];

                    b = avctx->sample_rate;

                    pos = ((block_len * 2 * a) + (b >> 1)) / b;

                    if (pos > block_len)

                        pos = block_len;

                    s->exponent_bands[0][i] = pos - lpos;

                    if (pos >= block_len) {

                        i++;

                        break;

                    lpos = pos;

                s->exponent_sizes[0] = i;

            } else {

                /* hardcoded tables */

                table = NULL;

                a = s->frame_len_bits - BLOCK_MIN_BITS - k;

                if (a < 3) {

                    if (avctx->sample_rate >= 44100) {

                        table = exponent_band_44100[a];

                    } else if (avctx->sample_rate >= 32000) {

                        table = exponent_band_32000[a];

                    } else if (avctx->sample_rate >= 22050) {

                        table = exponent_band_22050[a];

                if (table) {

                    n = *table++;

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

                        s->exponent_bands[k][i] = table[i];

                    s->exponent_sizes[k] = n;

                } else {

                    j = 0;

                    lpos = 0;

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

                        a = ff_wma_critical_freqs[i];

                        b = avctx->sample_rate;

                        pos = ((block_len * 2 * a) + (b << 1)) / (4 * b);

                        pos <<= 2;

                        if (pos > block_len)

                            pos = block_len;

                        if (pos > lpos)

                            s->exponent_bands[k][j++] = pos - lpos;

                        if (pos >= block_len)

                            break;

                        lpos = pos;

                    s->exponent_sizes[k] = j;

            /* max number of coefs */

            s->coefs_end[k] = (s->frame_len - ((s->frame_len * 9) / 100)) >> k;

            /* high freq computation */

            s->high_band_start[k] = (int)((block_len * 2 * high_freq) /

                                          avctx->sample_rate + 0.5);

            n = s->exponent_sizes[k];

            j = 0;

            pos = 0;

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

                int start, end;

                start = pos;

                pos += s->exponent_bands[k][i];

                end = pos;

                if (start < s->high_band_start[k])

                    start = s->high_band_start[k];

                if (end > s->coefs_end[k])

                    end = s->coefs_end[k];

                if (end > start)

                    s->exponent_high_bands[k][j++] = end - start;

            s->exponent_high_sizes[k] = j;

#if 0

            tprintf(s->avctx, "%5d: coefs_end=%d high_band_start=%d nb_high_bands=%d: ",

                    s->frame_len >> k,

                    s->coefs_end[k],

                    s->high_band_start[k],

                    s->exponent_high_sizes[k]);

            for (j = 0; j < s->exponent_high_sizes[k]; j++)

                tprintf(s->avctx, " %d", s->exponent_high_bands[k][j]);

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

#endif

#ifdef TRACE

    {

        int i, j;

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

            tprintf(s->avctx, "%5d: n=%2d:",

                    s->frame_len >> i,

                    s->exponent_sizes[i]);

            for (j = 0; j < s->exponent_sizes[i]; j++)

                tprintf(s->avctx, " %d", s->exponent_bands[i][j]);

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

#endif

    /* init MDCT windows : simple sinus window */

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

        ff_init_ff_sine_windows(s->frame_len_bits - i);

        s->windows[i] = ff_sine_windows[s->frame_len_bits - i];

    s->reset_block_lengths = 1;

    if (s->use_noise_coding) {

        /* init the noise generator */

        if (s->use_exp_vlc) {

            s->noise_mult = 0.02;

        } else {

            s->noise_mult = 0.04;

#ifdef TRACE

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

            s->noise_table[i] = 1.0 * s->noise_mult;

#else

        {

            unsigned int seed;

            float norm;

            seed = 1;

            norm = (1.0 / (float)(1LL << 31)) * sqrt(3) * s->noise_mult;

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

                seed = seed * 314159 + 1;

                s->noise_table[i] = (float)((int)seed) * norm;

#endif

    /* choose the VLC tables for the coefficients */

    coef_vlc_table = 2;

    if (avctx->sample_rate >= 32000) {

        if (bps1 < 0.72) {

            coef_vlc_table = 0;

        } else if (bps1 < 1.16) {

            coef_vlc_table = 1;

    s->coef_vlcs[0]= &coef_vlcs[coef_vlc_table * 2    ];

    s->coef_vlcs[1]= &coef_vlcs[coef_vlc_table * 2 + 1];

    init_coef_vlc(&s->coef_vlc[0], &s->run_table[0], &s->level_table[0], &s->int_table[0],

                  s->coef_vlcs[0]);

    init_coef_vlc(&s->coef_vlc[1], &s->run_table[1], &s->level_table[1], &s->int_table[1],

                  s->coef_vlcs[1]);

    return 0;


av_cold int ff_ivi_decode_close(AVCodecContext *avctx)
{
    IVI45DecContext *ctx = avctx->priv_data;
    ivi_free_buffers(&ctx->planes[0]);
    if (ctx->mb_vlc.cust_tab.table)
        ff_free_vlc(&ctx->mb_vlc.cust_tab);
    av_frame_free(&ctx->p_frame);
    return 0;
}


int qemu_check_nic_model_list(NICInfo *nd, const char * const *models,

                              const char *default_model)

{

    int i, exit_status = 0;

    if (!nd->model)

        nd->model = strdup(default_model);

    if (strcmp(nd->model, "?") != 0) {

        for (i = 0 ; models[i]; i++)

            if (strcmp(nd->model, models[i]) == 0)

                return i;

        fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);

        exit_status = 1;

    }

    fprintf(stderr, "qemu: Supported NIC models: ");

    for (i = 0 ; models[i]; i++)

        fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');

    exit(exit_status);

}


static void virtio_s390_notify(void *opaque, uint16_t vector)

{

    VirtIOS390Device *dev = (VirtIOS390Device*)opaque;

    uint64_t token = s390_virtio_device_vq_token(dev, vector);

    /* XXX kvm dependency! */

    kvm_s390_virtio_irq(s390_cpu_addr2state(0), 0, token);

}


static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)

{

    if (throttle_conflicting(cfg, errp)) {

        return false;

    }

    if (!throttle_is_valid(cfg, errp)) {

        return false;

    }

    if (throttle_max_is_missing_limit(cfg, errp)) {

        return false;

    }

    return true;

}


static void decode_block(BinkAudioContext *s, short *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 = s->coeffs_ptr[ch];

        if (s->version_b) {

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

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

        } else {

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

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

        }

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

            /* constant is result of 0.066399999/log10(M_E) */

            int value = get_bits(gb, 8);

            quant[i] = expf(FFMIN(value, 95) * 0.15289164787221953823f) * s->root;

        }

        k = 0;

        q = quant[0];

        // parse coefficients

        i = 2;

        while (i < s->frame_len) {

            if (s->version_b) {

                j = i + 16;

            } else if (get_bits1(gb)) {

                j = i + rle_length_tab[get_bits(gb, 4)] * 8;

            } else {

                j = i + 8;

            }

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

            width = get_bits(gb, 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++];

                    coeff = get_bits(gb, width);

                    if (coeff) {

                        if (get_bits1(gb))

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

            s->dsp.vector_fmul_scalar(coeffs, coeffs, s->frame_len / 2, s->frame_len);

        }

        else if (CONFIG_BINKAUDIO_RDFT_DECODER)

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

    }

    s->fmt_conv.float_to_int16_interleave(out, (const float **)s->coeffs_ptr,

                                          s->frame_len, s->channels);

    if (!s->first) {

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

        int shift = av_log2(count);

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

            out[i] = (s->previous[i] * (count - i) + out[i] * i) >> shift;

        }

    }

    memcpy(s->previous, out + s->block_size,

           s->overlap_len * s->channels * sizeof(*out));

    s->first = 0;

}


static int mpeg_mux_write_packet(AVFormatContext *ctx, int stream_index,

                                 const uint8_t *buf, int size, int64_t pts)

{

    MpegMuxContext *s = ctx->priv_data;

    AVStream *st = ctx->streams[stream_index];

    StreamInfo *stream = st->priv_data;

    int64_t dts;

    int len;

    /* XXX: system clock should be computed precisely, especially for

       CBR case. The current mode gives at least something coherent */

    if (stream_index == s->scr_stream_index)

        s->last_scr = pts;

#if 0

    printf("%d: pts=%0.3f scr=%0.3f\n",

           stream_index, pts / 90000.0, s->last_scr / 90000.0);

#endif

    /* XXX: currently no way to pass dts, will change soon */

    dts = AV_NOPTS_VALUE;

    /* we assume here that pts != AV_NOPTS_VALUE */

    if (stream->start_pts == AV_NOPTS_VALUE) {

        stream->start_pts = pts;

        stream->start_dts = dts;

    }

    while (size > 0) {

        len = s->packet_data_max_size - stream->buffer_ptr;

        if (len > size)

            len = size;

        memcpy(stream->buffer + stream->buffer_ptr, buf, len);

        stream->buffer_ptr += len;

        buf += len;

        size -= len;

        while (stream->buffer_ptr >= s->packet_data_max_size) {

            /* output the packet */

            flush_packet(ctx, stream_index,

                         stream->start_pts, stream->start_dts, s->last_scr);

            /* Make sure only the FIRST pes packet for this frame has

               a timestamp */

            stream->start_pts = AV_NOPTS_VALUE;

            stream->start_dts = AV_NOPTS_VALUE;

        }

    }

    return 0;

}


static void cpu_devinit(const char *cpu_model, unsigned int id,

                        uint64_t prom_addr, qemu_irq **cpu_irqs)

{

    CPUState *cs;

    SPARCCPU *cpu;

    CPUSPARCState *env;

    cpu = SPARC_CPU(cpu_generic_init(TYPE_SPARC_CPU, cpu_model));

    if (cpu == NULL) {

        fprintf(stderr, "qemu: Unable to find Sparc CPU definition\n");

        exit(1);

    }

    env = &cpu->env;

    cpu_sparc_set_id(env, id);

    if (id == 0) {

        qemu_register_reset(main_cpu_reset, cpu);

    } else {

        qemu_register_reset(secondary_cpu_reset, cpu);

        cs = CPU(cpu);

        cs->halted = 1;

    }

    *cpu_irqs = qemu_allocate_irqs(cpu_set_irq, cpu, MAX_PILS);

    env->prom_addr = prom_addr;

}


av_cold void avcodec_register(AVCodec *codec)

{

    AVCodec **p;

    avcodec_init();

    p = &first_avcodec;

    while (*p != NULL)

        p = &(*p)->next;

    *p          = codec;

    codec->next = NULL;

    if (codec->init_static_data)

        codec->init_static_data(codec);

}


static int read_naa_id(const uint8_t *p, uint64_t *p_wwn)

{

    int i;

    if ((p[1] & 0xF) == 3) {

        /* NAA designator type */

        if (p[3] != 8) {

            return -EINVAL;

        }

        *p_wwn = ldq_be_p(p + 4);

        return 0;

    }

    if ((p[1] & 0xF) == 8) {

        /* SCSI name string designator type */

        if (p[3] < 20 || memcmp(&p[4], "naa.", 4)) {

            return -EINVAL;

        }

        if (p[3] > 20 && p[24] != ',') {

            return -EINVAL;

        }

        *p_wwn = 0;

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

            char c = toupper(p[i]);

            c -= (c >= '0' && c <= '9' ? '0' : 'A' - 10);

            *p_wwn = (*p_wwn << 4) | c;

        }

        return 0;

    }

    return -EINVAL;

}


static int decode_i_picture_header(VC9Context *v)

{

    GetBitContext *gb = &v->s.gb;

    int pqindex, status = 0;

    /* Prolog common to all frametypes should be done in caller */

    //BF = Buffer Fullness

    if (v->profile <= PROFILE_MAIN && get_bits(gb, 7))

    {

        av_log(v->s.avctx, AV_LOG_DEBUG, "I BufferFullness not 0\n");

    }

    /* Quantizer stuff */

    pqindex = get_bits(gb, 5);

    if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)

        v->pq = pquant_table[0][pqindex];

    else

    {

        v->pq = pquant_table[v->quantizer_mode-1][pqindex];

    }

    if (pqindex < 9) v->halfpq = get_bits(gb, 1);

    if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)

        v->pquantizer = get_bits(gb, 1);

    av_log(v->s.avctx, AV_LOG_DEBUG, "I frame: QP=%i (+%i/2)\n",

           v->pq, v->halfpq);

#if HAS_ADVANCED_PROFILE

    if (v->profile <= PROFILE_MAIN)

#endif

    {

        if (v->extended_mv) v->mvrange = get_prefix(gb, 0, 3);

        if (v->multires) v->respic = get_bits(gb, 2);

    }

#if HAS_ADVANCED_PROFILE

    else

    {

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

        if (v->postprocflag) v->postproc = get_bits(gb, 1);

        /* 7.1.1.34 + 8.5.2 */

        if (v->overlap && v->pq<9)

        {

            v->condover = get_bits(gb, 1);

            if (v->condover)

            {

                v->condover = 2+get_bits(gb, 1);

                if (v->condover == 3)

                {

                    status = bitplane_decoding(&v->over_flags_plane, v);

                    if (status < 0) return -1;

#if TRACE

                    av_log(v->s.avctx, AV_LOG_DEBUG, "Overflags plane encoding: "

                           "Imode: %i, Invert: %i\n", status>>1, status&1);

#endif

                }

            }

        }

    }

#endif

    /* Epilog (AC/DC syntax) should be done in caller */

    return status;

}


static void show_stream(AVFormatContext *fmt_ctx, int stream_idx)

{

    AVStream *stream = fmt_ctx->streams[stream_idx];

    AVCodecContext *dec_ctx;

    AVCodec *dec;

    char val_str[128];

    AVDictionaryEntry *tag = NULL;

    AVRational display_aspect_ratio;

    printf("[STREAM]\n");

    printf("index=%d\n", stream->index);

    if ((dec_ctx = stream->codec)) {

        if ((dec = dec_ctx->codec)) {

            printf("codec_name=%s\n", dec->name);

            printf("codec_long_name=%s\n", dec->long_name);

        } else {

            printf("codec_name=unknown\n");

        }

        printf("codec_type=%s\n", media_type_string(dec_ctx->codec_type));

        printf("codec_time_base=%d/%d\n",

               dec_ctx->time_base.num, dec_ctx->time_base.den);

        /* print AVI/FourCC tag */

        av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);

        printf("codec_tag_string=%s\n", val_str);

        printf("codec_tag=0x%04x\n", dec_ctx->codec_tag);

        switch (dec_ctx->codec_type) {

        case AVMEDIA_TYPE_VIDEO:

            printf("width=%d\n", dec_ctx->width);

            printf("height=%d\n", dec_ctx->height);

            printf("has_b_frames=%d\n", dec_ctx->has_b_frames);

            if (dec_ctx->sample_aspect_ratio.num) {

                printf("sample_aspect_ratio=%d:%d\n",

                       dec_ctx->sample_aspect_ratio.num,

                       dec_ctx->sample_aspect_ratio.den);

                av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,

                          dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,

                          dec_ctx->height * dec_ctx->sample_aspect_ratio.den,

                          1024*1024);

                printf("display_aspect_ratio=%d:%d\n",

                       display_aspect_ratio.num, display_aspect_ratio.den);

            }

            printf("pix_fmt=%s\n",

                   dec_ctx->pix_fmt != PIX_FMT_NONE ? av_pix_fmt_descriptors[dec_ctx->pix_fmt].name

                                                    : "unknown");

            printf("level=%d\n", dec_ctx->level);

            break;

        case AVMEDIA_TYPE_AUDIO:

            printf("sample_rate=%s\n", value_string(val_str, sizeof(val_str),

                                                    dec_ctx->sample_rate,

                                                    unit_hertz_str));

            printf("channels=%d\n", dec_ctx->channels);

            printf("bits_per_sample=%d\n",

                   av_get_bits_per_sample(dec_ctx->codec_id));

            break;

        }

    } else {

        printf("codec_type=unknown\n");

    }

    if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS)

        printf("id=0x%x\n", stream->id);

    printf("r_frame_rate=%d/%d\n",

           stream->r_frame_rate.num, stream->r_frame_rate.den);

    printf("avg_frame_rate=%d/%d\n",

           stream->avg_frame_rate.num, stream->avg_frame_rate.den);

    printf("time_base=%d/%d\n",

           stream->time_base.num, stream->time_base.den);

    printf("start_time=%s\n",

           time_value_string(val_str, sizeof(val_str),

                             stream->start_time, &stream->time_base));

    printf("duration=%s\n",

           time_value_string(val_str, sizeof(val_str),

                             stream->duration, &stream->time_base));

    if (stream->nb_frames)

        printf("nb_frames=%"PRId64"\n", stream->nb_frames);

    while ((tag = av_dict_get(stream->metadata, "", tag,

                              AV_DICT_IGNORE_SUFFIX)))

        printf("TAG:%s=%s\n", tag->key, tag->value);

    printf("[/STREAM]\n");

}


static void encode_block(MpegEncContext *s, int16_t *block, int n)

{

    int i, j, table_id;

    int component, dc, last_index, val, run;

    MJpegContext *m = s->mjpeg_ctx;

    /* DC coef */

    component = (n <= 3 ? 0 : (n&1) + 1);

    table_id = (n <= 3 ? 0 : 1);

    dc = block[0]; /* overflow is impossible */

    val = dc - s->last_dc[component];

    ff_mjpeg_encode_coef(m, table_id, val, 0);

    s->last_dc[component] = dc;

    /* AC coefs */

    run = 0;

    last_index = s->block_last_index[n];

    table_id |= 2;

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

        j = s->intra_scantable.permutated[i];

        val = block[j];

        if (val == 0) {

            run++;

        } else {

            while (run >= 16) {

                ff_mjpeg_encode_code(m, table_id, 0xf0);

                run -= 16;

            }

            ff_mjpeg_encode_coef(m, table_id, val, run);

            run = 0;

        }

    }

    /* output EOB only if not already 64 values */

    if (last_index < 63 || run != 0)

        ff_mjpeg_encode_code(m, table_id, 0);

}


static void RENAME(swScale)(SwsContext *c, uint8_t* srcParam[], int srcStrideParam[], int srcSliceY,

             int srcSliceH, uint8_t* dstParam[], int dstStride[]){

	/* load a few things into local vars to make the code more readable? and faster */

	const int srcW= c->srcW;

	const int dstW= c->dstW;

	const int dstH= c->dstH;

	const int chrDstW= c->chrDstW;

	const int lumXInc= c->lumXInc;

	const int chrXInc= c->chrXInc;

	const int dstFormat= c->dstFormat;

	const int flags= c->flags;

	const int canMMX2BeUsed= c->canMMX2BeUsed;

	int16_t *vLumFilterPos= c->vLumFilterPos;

	int16_t *vChrFilterPos= c->vChrFilterPos;

	int16_t *hLumFilterPos= c->hLumFilterPos;

	int16_t *hChrFilterPos= c->hChrFilterPos;

	int16_t *vLumFilter= c->vLumFilter;

	int16_t *vChrFilter= c->vChrFilter;

	int16_t *hLumFilter= c->hLumFilter;

	int16_t *hChrFilter= c->hChrFilter;

	int16_t *lumMmxFilter= c->lumMmxFilter;

	int16_t *chrMmxFilter= c->chrMmxFilter;

	const int vLumFilterSize= c->vLumFilterSize;

	const int vChrFilterSize= c->vChrFilterSize;

	const int hLumFilterSize= c->hLumFilterSize;

	const int hChrFilterSize= c->hChrFilterSize;

	int16_t **lumPixBuf= c->lumPixBuf;

	int16_t **chrPixBuf= c->chrPixBuf;

	const int vLumBufSize= c->vLumBufSize;

	const int vChrBufSize= c->vChrBufSize;

	uint8_t *funnyYCode= c->funnyYCode;

	uint8_t *funnyUVCode= c->funnyUVCode;

	uint8_t *formatConvBuffer= c->formatConvBuffer;

	/* vars whch will change and which we need to storw back in the context */

	int dstY= c->dstY;

	int lumBufIndex= c->lumBufIndex;

	int chrBufIndex= c->chrBufIndex;

	int lastInLumBuf= c->lastInLumBuf;

	int lastInChrBuf= c->lastInChrBuf;

	int srcStride[3];

	uint8_t *src[3];

	uint8_t *dst[3];

	if((c->srcFormat == IMGFMT_IYUV) || (c->srcFormat == IMGFMT_I420)){

		src[0]= srcParam[0];

		src[1]= srcParam[2];

		src[2]= srcParam[1];

		srcStride[0]= srcStrideParam[0];

		srcStride[1]= srcStrideParam[2];

		srcStride[2]= srcStrideParam[1];

	}

	else if(c->srcFormat==IMGFMT_YV12){

		src[0]= srcParam[0];

		src[1]= srcParam[1];

		src[2]= srcParam[2];

		srcStride[0]= srcStrideParam[0];

		srcStride[1]= srcStrideParam[1];

		srcStride[2]= srcStrideParam[2];

	}

	else if(isPacked(c->srcFormat)){

		src[0]=

		src[1]=

		src[2]= srcParam[0];

		srcStride[0]= srcStrideParam[0];

		srcStride[1]=

		srcStride[2]= srcStrideParam[0]<<1;

	}

	else if(c->srcFormat==IMGFMT_Y8){

		src[0]= srcParam[0];

		src[1]=

		src[2]= NULL;

		srcStride[0]= srcStrideParam[0];

		srcStride[1]=

		srcStride[2]= 0;

	}

	if((c->dstFormat == IMGFMT_IYUV) || (c->dstFormat == IMGFMT_I420)){

		dst[0]= dstParam[0];

		dst[1]= dstParam[2];

		dst[2]= dstParam[1];

	}else{

		dst[0]= dstParam[0];

		dst[1]= dstParam[1];

		dst[2]= dstParam[2];

	}

	if(dstStride[0]%8 !=0 || dstStride[1]%8 !=0 || dstStride[2]%8 !=0)

	{

		static int firstTime=1; //FIXME move this into the context perhaps

		if(flags & SWS_PRINT_INFO && firstTime)

		{

			fprintf(stderr, "SwScaler: Warning: dstStride is not aligned!\n"

					"SwScaler:          ->cannot do aligned memory acesses anymore\n");

			firstTime=0;

		}

	}

	/* Note the user might start scaling the picture in the middle so this will not get executed

	   this is not really intended but works currently, so ppl might do it */

	if(srcSliceY ==0){

		lumBufIndex=0;

		chrBufIndex=0;

		dstY=0;

		lastInLumBuf= -1;

		lastInChrBuf= -1;

	}

	for(;dstY < dstH; dstY++){

		unsigned char *dest =dst[0]+dstStride[0]*dstY;

		unsigned char *uDest=dst[1]+dstStride[1]*(dstY>>1);

		unsigned char *vDest=dst[2]+dstStride[2]*(dstY>>1);

		const int chrDstY= isHalfChrV(dstFormat) ? (dstY>>1) : dstY;

		const int firstLumSrcY= vLumFilterPos[dstY]; //First line needed as input

		const int firstChrSrcY= vChrFilterPos[chrDstY]; //First line needed as input

		const int lastLumSrcY= firstLumSrcY + vLumFilterSize -1; // Last line needed as input

		const int lastChrSrcY= firstChrSrcY + vChrFilterSize -1; // Last line needed as input

		//handle holes (FAST_BILINEAR & weird filters)

		if(firstLumSrcY > lastInLumBuf) lastInLumBuf= firstLumSrcY-1;

		if(firstChrSrcY > lastInChrBuf) lastInChrBuf= firstChrSrcY-1;

//printf("%d %d %d\n", firstChrSrcY, lastInChrBuf, vChrBufSize);

		ASSERT(firstLumSrcY >= lastInLumBuf - vLumBufSize + 1)

		ASSERT(firstChrSrcY >= lastInChrBuf - vChrBufSize + 1)

		// Do we have enough lines in this slice to output the dstY line

		if(lastLumSrcY < srcSliceY + srcSliceH && lastChrSrcY < ((srcSliceY + srcSliceH)>>1))

		{

			//Do horizontal scaling

			while(lastInLumBuf < lastLumSrcY)

			{

				uint8_t *s= src[0]+(lastInLumBuf + 1 - srcSliceY)*srcStride[0];

				lumBufIndex++;

//				printf("%d %d %d %d\n", lumBufIndex, vLumBufSize, lastInLumBuf,  lastLumSrcY);

				ASSERT(lumBufIndex < 2*vLumBufSize)

				ASSERT(lastInLumBuf + 1 - srcSliceY < srcSliceH)

				ASSERT(lastInLumBuf + 1 - srcSliceY >= 0)

//				printf("%d %d\n", lumBufIndex, vLumBufSize);

				RENAME(hyscale)(lumPixBuf[ lumBufIndex ], dstW, s, srcW, lumXInc,

						flags, canMMX2BeUsed, hLumFilter, hLumFilterPos, hLumFilterSize,

						funnyYCode, c->srcFormat, formatConvBuffer);

				lastInLumBuf++;

			}

			while(lastInChrBuf < lastChrSrcY)

			{

				uint8_t *src1= src[1]+(lastInChrBuf + 1 - (srcSliceY>>1))*srcStride[1];

				uint8_t *src2= src[2]+(lastInChrBuf + 1 - (srcSliceY>>1))*srcStride[2];

				chrBufIndex++;

				ASSERT(chrBufIndex < 2*vChrBufSize)

				ASSERT(lastInChrBuf + 1 - (srcSliceY>>1) < (srcSliceH>>1))

				ASSERT(lastInChrBuf + 1 - (srcSliceY>>1) >= 0)

				//FIXME replace parameters through context struct (some at least)

				RENAME(hcscale)(chrPixBuf[ chrBufIndex ], chrDstW, src1, src2, (srcW+1)>>1, chrXInc,

						flags, canMMX2BeUsed, hChrFilter, hChrFilterPos, hChrFilterSize,

						funnyUVCode, c->srcFormat, formatConvBuffer);

				lastInChrBuf++;

			}

			//wrap buf index around to stay inside the ring buffer

			if(lumBufIndex >= vLumBufSize ) lumBufIndex-= vLumBufSize;

			if(chrBufIndex >= vChrBufSize ) chrBufIndex-= vChrBufSize;

		}

		else // not enough lines left in this slice -> load the rest in the buffer

		{

/*		printf("%d %d Last:%d %d LastInBuf:%d %d Index:%d %d Y:%d FSize: %d %d BSize: %d %d\n",

			firstChrSrcY,firstLumSrcY,lastChrSrcY,lastLumSrcY,

			lastInChrBuf,lastInLumBuf,chrBufIndex,lumBufIndex,dstY,vChrFilterSize,vLumFilterSize,

			vChrBufSize, vLumBufSize);

*/

			//Do horizontal scaling

			while(lastInLumBuf+1 < srcSliceY + srcSliceH)

			{

				uint8_t *s= src[0]+(lastInLumBuf + 1 - srcSliceY)*srcStride[0];

				lumBufIndex++;

				ASSERT(lumBufIndex < 2*vLumBufSize)

				ASSERT(lastInLumBuf + 1 - srcSliceY < srcSliceH)

				ASSERT(lastInLumBuf + 1 - srcSliceY >= 0)

				RENAME(hyscale)(lumPixBuf[ lumBufIndex ], dstW, s, srcW, lumXInc,

						flags, canMMX2BeUsed, hLumFilter, hLumFilterPos, hLumFilterSize,

						funnyYCode, c->srcFormat, formatConvBuffer);

				lastInLumBuf++;

			}

			while(lastInChrBuf+1 < ((srcSliceY + srcSliceH)>>1))

			{

				uint8_t *src1= src[1]+(lastInChrBuf + 1 - (srcSliceY>>1))*srcStride[1];

				uint8_t *src2= src[2]+(lastInChrBuf + 1 - (srcSliceY>>1))*srcStride[2];

				chrBufIndex++;

				ASSERT(chrBufIndex < 2*vChrBufSize)

				ASSERT(lastInChrBuf + 1 - (srcSliceY>>1) < (srcSliceH>>1))

				ASSERT(lastInChrBuf + 1 - (srcSliceY>>1) >= 0)

				RENAME(hcscale)(chrPixBuf[ chrBufIndex ], chrDstW, src1, src2, (srcW+1)>>1, chrXInc,

						flags, canMMX2BeUsed, hChrFilter, hChrFilterPos, hChrFilterSize,

						funnyUVCode, c->srcFormat, formatConvBuffer);

				lastInChrBuf++;

			}

			//wrap buf index around to stay inside the ring buffer

			if(lumBufIndex >= vLumBufSize ) lumBufIndex-= vLumBufSize;

			if(chrBufIndex >= vChrBufSize ) chrBufIndex-= vChrBufSize;

			break; //we cant output a dstY line so lets try with the next slice

		}

#ifdef HAVE_MMX

		b5Dither= dither8[dstY&1];

		g6Dither= dither4[dstY&1];

		g5Dither= dither8[dstY&1];

		r5Dither= dither8[(dstY+1)&1];

#endif

	    if(dstY < dstH-2)

	    {

		if(isPlanarYUV(dstFormat)) //YV12 like

		{

			if(dstY&1) uDest=vDest= NULL; //FIXME split functions in lumi / chromi

			if(vLumFilterSize == 1 && vChrFilterSize == 1) // Unscaled YV12

			{

				int16_t *lumBuf = lumPixBuf[0];

				int16_t *chrBuf= chrPixBuf[0];

				RENAME(yuv2yuv1)(lumBuf, chrBuf, dest, uDest, vDest, dstW);

			}

			else //General YV12

			{

				int16_t **lumSrcPtr= lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;

				int16_t **chrSrcPtr= chrPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;

				RENAME(yuv2yuvX)(

					vLumFilter+dstY*vLumFilterSize     , lumSrcPtr, vLumFilterSize,

					vChrFilter+(dstY>>1)*vChrFilterSize, chrSrcPtr, vChrFilterSize,

					dest, uDest, vDest, dstW,

					lumMmxFilter+dstY*vLumFilterSize*4, chrMmxFilter+(dstY>>1)*vChrFilterSize*4);

			}

		}

		else

		{

			int16_t **lumSrcPtr= lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;

			int16_t **chrSrcPtr= chrPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;

			ASSERT(lumSrcPtr + vLumFilterSize - 1 < lumPixBuf + vLumBufSize*2);

			ASSERT(chrSrcPtr + vChrFilterSize - 1 < chrPixBuf + vChrBufSize*2);

			if(vLumFilterSize == 1 && vChrFilterSize == 2) //Unscaled RGB

			{

				int chrAlpha= vChrFilter[2*dstY+1];

				RENAME(yuv2rgb1)(*lumSrcPtr, *chrSrcPtr, *(chrSrcPtr+1),

						 dest, dstW, chrAlpha, dstFormat, flags);

			}

			else if(vLumFilterSize == 2 && vChrFilterSize == 2) //BiLinear Upscale RGB

			{

				int lumAlpha= vLumFilter[2*dstY+1];

				int chrAlpha= vChrFilter[2*dstY+1];

				RENAME(yuv2rgb2)(*lumSrcPtr, *(lumSrcPtr+1), *chrSrcPtr, *(chrSrcPtr+1),

						 dest, dstW, lumAlpha, chrAlpha, dstFormat, flags);

			}

			else //General RGB

			{

				RENAME(yuv2rgbX)(

					vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,

					vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,

					dest, dstW, dstFormat,

					lumMmxFilter+dstY*vLumFilterSize*4, chrMmxFilter+dstY*vChrFilterSize*4);

			}

		}

            }

	    else // hmm looks like we cant use MMX here without overwriting this arrays tail

	    {

		int16_t **lumSrcPtr= lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;

		int16_t **chrSrcPtr= chrPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;

		if(isPlanarYUV(dstFormat)) //YV12

		{

			if(dstY&1) uDest=vDest= NULL; //FIXME split functions in lumi / chromi

			yuv2yuvXinC(

				vLumFilter+dstY*vLumFilterSize     , lumSrcPtr, vLumFilterSize,

				vChrFilter+(dstY>>1)*vChrFilterSize, chrSrcPtr, vChrFilterSize,

				dest, uDest, vDest, dstW);

		}

		else

		{

			ASSERT(lumSrcPtr + vLumFilterSize - 1 < lumPixBuf + vLumBufSize*2);

			ASSERT(chrSrcPtr + vChrFilterSize - 1 < chrPixBuf + vChrBufSize*2);

			yuv2rgbXinC(

				vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,

				vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,

				dest, dstW, dstFormat);

		}

	    }

	}

#ifdef HAVE_MMX

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

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

#endif

	/* store changed local vars back in the context */

	c->dstY= dstY;

	c->lumBufIndex= lumBufIndex;

	c->chrBufIndex= chrBufIndex;

	c->lastInLumBuf= lastInLumBuf;

	c->lastInChrBuf= lastInChrBuf;

}


static int vscsi_queue_cmd(VSCSIState *s, vscsi_req *req)

{

    union srp_iu *srp = &req->iu.srp;

    SCSIDevice *sdev;

    int n, id, lun;

    vscsi_decode_id_lun(be64_to_cpu(srp->cmd.lun), &id, &lun);

    /* Qemu vs. linux issue with LUNs to be sorted out ... */

    sdev = (id < 8 && lun < 16) ? s->bus.devs[id] : NULL;

    if (!sdev) {

        dprintf("VSCSI: Command for id %d with no drive\n", id);

        if (srp->cmd.cdb[0] == INQUIRY) {

            vscsi_inquiry_no_target(s, req);

        } else {

            vscsi_makeup_sense(s, req, ILLEGAL_REQUEST, 0x24, 0x00);

            vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0);

        } return 1;

    }

    req->sdev = sdev;

    req->lun = lun;

    n = sdev->info->send_command(sdev, req->qtag, srp->cmd.cdb, lun);

    dprintf("VSCSI: Queued command tag 0x%x CMD 0x%x ID %d LUN %d ret: %d\n",

            req->qtag, srp->cmd.cdb[0], id, lun, n);

    if (n) {

        /* Transfer direction must be set before preprocessing the

         * descriptors

         */

        req->writing = (n < 1);

        /* Preprocess RDMA descriptors */

        vscsi_preprocess_desc(req);

    }

    /* Get transfer direction and initiate transfer */

    if (n > 0) {

        req->data_len = n;

        sdev->info->read_data(sdev, req->qtag);

    } else if (n < 0) {

        req->data_len = -n;

        sdev->info->write_data(sdev, req->qtag);

    }

    /* Don't touch req here, it may have been recycled already */

    return 0;

}


static int do_sendv_recvv(int sockfd, struct iovec *iov, int len, int offset,

                          int do_sendv)

{

    int ret, diff, iovlen;

    struct iovec *last_iov;

    /* last_iov is inclusive, so count from one.  */

    iovlen = 1;

    last_iov = iov;

    len += offset;

    while (last_iov->iov_len < len) {

        len -= last_iov->iov_len;

        last_iov++;

        iovlen++;

    }

    diff = last_iov->iov_len - len;

    last_iov->iov_len -= diff;

    while (iov->iov_len <= offset) {

        offset -= iov->iov_len;

        iov++;

        iovlen--;

    }

    iov->iov_base = (char *) iov->iov_base + offset;

    iov->iov_len -= offset;

    {

#if defined CONFIG_IOVEC && defined CONFIG_POSIX

        struct msghdr msg;

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

        msg.msg_iov = iov;

        msg.msg_iovlen = iovlen;

        do {

            if (do_sendv) {

                ret = sendmsg(sockfd, &msg, 0);

            } else {

                ret = recvmsg(sockfd, &msg, 0);

            }

        } while (ret == -1 && errno == EINTR);

#else

        struct iovec *p = iov;

        ret = 0;

        while (iovlen > 0) {

            int rc;

            if (do_sendv) {

                rc = send(sockfd, p->iov_base, p->iov_len, 0);

            } else {

                rc = qemu_recv(sockfd, p->iov_base, p->iov_len, 0);

            }

            if (rc == -1) {

                if (errno == EINTR) {

                    continue;

                }

                if (ret == 0) {

                    ret = -1;

                }

                break;

            }

            if (rc == 0) {

                break;

            }

            ret += rc;

            iovlen--, p++;

        }

#endif

    }

    /* Undo the changes above */

    iov->iov_base = (char *) iov->iov_base - offset;

    iov->iov_len += offset;

    last_iov->iov_len += diff;

    return ret;

}


static int vp9_decode_frame(AVCodecContext *ctx, void *frame,

                            int *got_frame, AVPacket *pkt)

{

    const uint8_t *data = pkt->data;

    int size = pkt->size;

    VP9Context *s = ctx->priv_data;

    int res, tile_row, tile_col, i, ref, row, col;

    int retain_segmap_ref = s->s.frames[REF_FRAME_SEGMAP].segmentation_map &&

                            (!s->s.h.segmentation.enabled || !s->s.h.segmentation.update_map);

    ptrdiff_t yoff, uvoff, ls_y, ls_uv;

    AVFrame *f;

    int bytesperpixel;

    if ((res = decode_frame_header(ctx, data, size, &ref)) < 0) {

        return res;

    } else if (res == 0) {

        if (!s->s.refs[ref].f->buf[0]) {

            av_log(ctx, AV_LOG_ERROR, "Requested reference %d not available\n", ref);

            return AVERROR_INVALIDDATA;

        }

        if ((res = av_frame_ref(frame, s->s.refs[ref].f)) < 0)

            return res;

        ((AVFrame *)frame)->pts = pkt->pts;

#if FF_API_PKT_PTS

FF_DISABLE_DEPRECATION_WARNINGS

        ((AVFrame *)frame)->pkt_pts = pkt->pts;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

        ((AVFrame *)frame)->pkt_dts = pkt->dts;

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

            if (s->next_refs[i].f->buf[0])

                ff_thread_release_buffer(ctx, &s->next_refs[i]);

            if (s->s.refs[i].f->buf[0] &&

                (res = ff_thread_ref_frame(&s->next_refs[i], &s->s.refs[i])) < 0)

                return res;

        }

        *got_frame = 1;

        return pkt->size;

    }

    data += res;

    size -= res;

    if (!retain_segmap_ref || s->s.h.keyframe || s->s.h.intraonly) {

        if (s->s.frames[REF_FRAME_SEGMAP].tf.f->buf[0])

            vp9_unref_frame(ctx, &s->s.frames[REF_FRAME_SEGMAP]);

        if (!s->s.h.keyframe && !s->s.h.intraonly && !s->s.h.errorres && s->s.frames[CUR_FRAME].tf.f->buf[0] &&

            (res = vp9_ref_frame(ctx, &s->s.frames[REF_FRAME_SEGMAP], &s->s.frames[CUR_FRAME])) < 0)

            return res;

    }

    if (s->s.frames[REF_FRAME_MVPAIR].tf.f->buf[0])

        vp9_unref_frame(ctx, &s->s.frames[REF_FRAME_MVPAIR]);

    if (!s->s.h.intraonly && !s->s.h.keyframe && !s->s.h.errorres && s->s.frames[CUR_FRAME].tf.f->buf[0] &&

        (res = vp9_ref_frame(ctx, &s->s.frames[REF_FRAME_MVPAIR], &s->s.frames[CUR_FRAME])) < 0)

        return res;

    if (s->s.frames[CUR_FRAME].tf.f->buf[0])

        vp9_unref_frame(ctx, &s->s.frames[CUR_FRAME]);

    if ((res = vp9_alloc_frame(ctx, &s->s.frames[CUR_FRAME])) < 0)

        return res;

    f = s->s.frames[CUR_FRAME].tf.f;

    f->key_frame = s->s.h.keyframe;

    f->pict_type = (s->s.h.keyframe || s->s.h.intraonly) ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;

    ls_y = f->linesize[0];

    ls_uv =f->linesize[1];

    if (s->s.frames[REF_FRAME_SEGMAP].tf.f->buf[0] &&

        (s->s.frames[REF_FRAME_MVPAIR].tf.f->width  != s->s.frames[CUR_FRAME].tf.f->width ||

         s->s.frames[REF_FRAME_MVPAIR].tf.f->height != s->s.frames[CUR_FRAME].tf.f->height)) {

        vp9_unref_frame(ctx, &s->s.frames[REF_FRAME_SEGMAP]);

    }

    // ref frame setup

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

        if (s->next_refs[i].f->buf[0])

            ff_thread_release_buffer(ctx, &s->next_refs[i]);

        if (s->s.h.refreshrefmask & (1 << i)) {

            res = ff_thread_ref_frame(&s->next_refs[i], &s->s.frames[CUR_FRAME].tf);

        } else if (s->s.refs[i].f->buf[0]) {

            res = ff_thread_ref_frame(&s->next_refs[i], &s->s.refs[i]);

        }

        if (res < 0)

            return res;

    }

    if (ctx->hwaccel) {

        res = ctx->hwaccel->start_frame(ctx, NULL, 0);

        if (res < 0)

            return res;

        res = ctx->hwaccel->decode_slice(ctx, pkt->data, pkt->size);

        if (res < 0)

            return res;

        res = ctx->hwaccel->end_frame(ctx);

        if (res < 0)

            return res;

        goto finish;

    }

    // main tile decode loop

    bytesperpixel = s->bytesperpixel;

    memset(s->above_partition_ctx, 0, s->cols);

    memset(s->above_skip_ctx, 0, s->cols);

    if (s->s.h.keyframe || s->s.h.intraonly) {

        memset(s->above_mode_ctx, DC_PRED, s->cols * 2);

    } else {

        memset(s->above_mode_ctx, NEARESTMV, s->cols);

    }

    memset(s->above_y_nnz_ctx, 0, s->sb_cols * 16);

    memset(s->above_uv_nnz_ctx[0], 0, s->sb_cols * 16 >> s->ss_h);

    memset(s->above_uv_nnz_ctx[1], 0, s->sb_cols * 16 >> s->ss_h);

    memset(s->above_segpred_ctx, 0, s->cols);

    s->pass = s->s.frames[CUR_FRAME].uses_2pass =

        ctx->active_thread_type == FF_THREAD_FRAME && s->s.h.refreshctx && !s->s.h.parallelmode;

    if ((res = update_block_buffers(ctx)) < 0) {

        av_log(ctx, AV_LOG_ERROR,

               "Failed to allocate block buffers\n");

        return res;

    }

    if (s->s.h.refreshctx && s->s.h.parallelmode) {

        int j, k, l, m;

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

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

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

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

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

                            memcpy(s->prob_ctx[s->s.h.framectxid].coef[i][j][k][l][m],

                                   s->prob.coef[i][j][k][l][m], 3);

            if (s->s.h.txfmmode == i)

                break;

        }

        s->prob_ctx[s->s.h.framectxid].p = s->prob.p;

        ff_thread_finish_setup(ctx);

    } else if (!s->s.h.refreshctx) {

        ff_thread_finish_setup(ctx);

    }

    do {

        yoff = uvoff = 0;

        s->b = s->b_base;

        s->block = s->block_base;

        s->uvblock[0] = s->uvblock_base[0];

        s->uvblock[1] = s->uvblock_base[1];

        s->eob = s->eob_base;

        s->uveob[0] = s->uveob_base[0];

        s->uveob[1] = s->uveob_base[1];

        for (tile_row = 0; tile_row < s->s.h.tiling.tile_rows; tile_row++) {

            set_tile_offset(&s->tile_row_start, &s->tile_row_end,

                            tile_row, s->s.h.tiling.log2_tile_rows, s->sb_rows);

            if (s->pass != 2) {

                for (tile_col = 0; tile_col < s->s.h.tiling.tile_cols; tile_col++) {

                    int64_t tile_size;

                    if (tile_col == s->s.h.tiling.tile_cols - 1 &&

                        tile_row == s->s.h.tiling.tile_rows - 1) {

                        tile_size = size;

                    } else {

                        tile_size = AV_RB32(data);

                        data += 4;

                        size -= 4;

                    }

                    if (tile_size > size) {

                        ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, INT_MAX, 0);

                        return AVERROR_INVALIDDATA;

                    }

                    ff_vp56_init_range_decoder(&s->c_b[tile_col], data, tile_size);

                    if (vp56_rac_get_prob_branchy(&s->c_b[tile_col], 128)) { // marker bit

                        ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, INT_MAX, 0);

                        return AVERROR_INVALIDDATA;

                    }

                    data += tile_size;

                    size -= tile_size;

                }

            }

            for (row = s->tile_row_start; row < s->tile_row_end;

                 row += 8, yoff += ls_y * 64, uvoff += ls_uv * 64 >> s->ss_v) {

                struct VP9Filter *lflvl_ptr = s->lflvl;

                ptrdiff_t yoff2 = yoff, uvoff2 = uvoff;

                for (tile_col = 0; tile_col < s->s.h.tiling.tile_cols; tile_col++) {

                    set_tile_offset(&s->tile_col_start, &s->tile_col_end,

                                    tile_col, s->s.h.tiling.log2_tile_cols, s->sb_cols);

                    if (s->pass != 2) {

                        memset(s->left_partition_ctx, 0, 8);

                        memset(s->left_skip_ctx, 0, 8);

                        if (s->s.h.keyframe || s->s.h.intraonly) {

                            memset(s->left_mode_ctx, DC_PRED, 16);

                        } else {

                            memset(s->left_mode_ctx, NEARESTMV, 8);

                        }

                        memset(s->left_y_nnz_ctx, 0, 16);

                        memset(s->left_uv_nnz_ctx, 0, 32);

                        memset(s->left_segpred_ctx, 0, 8);

                        memcpy(&s->c, &s->c_b[tile_col], sizeof(s->c));

                    }

                    for (col = s->tile_col_start;

                         col < s->tile_col_end;

                         col += 8, yoff2 += 64 * bytesperpixel,

                         uvoff2 += 64 * bytesperpixel >> s->ss_h, lflvl_ptr++) {

                        // FIXME integrate with lf code (i.e. zero after each

                        // use, similar to invtxfm coefficients, or similar)

                        if (s->pass != 1) {

                            memset(lflvl_ptr->mask, 0, sizeof(lflvl_ptr->mask));

                        }

                        if (s->pass == 2) {

                            decode_sb_mem(ctx, row, col, lflvl_ptr,

                                          yoff2, uvoff2, BL_64X64);

                        } else {

                            decode_sb(ctx, row, col, lflvl_ptr,

                                      yoff2, uvoff2, BL_64X64);

                        }

                    }

                    if (s->pass != 2) {

                        memcpy(&s->c_b[tile_col], &s->c, sizeof(s->c));

                    }

                }

                if (s->pass == 1) {

                    continue;

                }

                // backup pre-loopfilter reconstruction data for intra

                // prediction of next row of sb64s

                if (row + 8 < s->rows) {

                    memcpy(s->intra_pred_data[0],

                           f->data[0] + yoff + 63 * ls_y,

                           8 * s->cols * bytesperpixel);

                    memcpy(s->intra_pred_data[1],

                           f->data[1] + uvoff + ((64 >> s->ss_v) - 1) * ls_uv,

                           8 * s->cols * bytesperpixel >> s->ss_h);

                    memcpy(s->intra_pred_data[2],

                           f->data[2] + uvoff + ((64 >> s->ss_v) - 1) * ls_uv,

                           8 * s->cols * bytesperpixel >> s->ss_h);

                }

                // loopfilter one row

                if (s->s.h.filter.level) {

                    yoff2 = yoff;

                    uvoff2 = uvoff;

                    lflvl_ptr = s->lflvl;

                    for (col = 0; col < s->cols;

                         col += 8, yoff2 += 64 * bytesperpixel,

                         uvoff2 += 64 * bytesperpixel >> s->ss_h, lflvl_ptr++) {

                        loopfilter_sb(ctx, lflvl_ptr, row, col, yoff2, uvoff2);

                    }

                }

                // FIXME maybe we can make this more finegrained by running the

                // loopfilter per-block instead of after each sbrow

                // In fact that would also make intra pred left preparation easier?

                ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, row >> 3, 0);

            }

        }

        if (s->pass < 2 && s->s.h.refreshctx && !s->s.h.parallelmode) {

            adapt_probs(s);

            ff_thread_finish_setup(ctx);

        }

    } while (s->pass++ == 1);

    ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, INT_MAX, 0);

finish:

    // ref frame setup

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

        if (s->s.refs[i].f->buf[0])

            ff_thread_release_buffer(ctx, &s->s.refs[i]);

        if (s->next_refs[i].f->buf[0] &&

            (res = ff_thread_ref_frame(&s->s.refs[i], &s->next_refs[i])) < 0)

            return res;

    }

    if (!s->s.h.invisible) {

        if ((res = av_frame_ref(frame, s->s.frames[CUR_FRAME].tf.f)) < 0)

            return res;

        *got_frame = 1;

    }

    return pkt->size;

}


static uint64_t gt64120_readl (void *opaque,

                               target_phys_addr_t addr, unsigned size)

{

    GT64120State *s = opaque;

    PCIHostState *phb = PCI_HOST_BRIDGE(s);

    uint32_t val;

    uint32_t saddr;

    saddr = (addr & 0xfff) >> 2;

    switch (saddr) {

    /* CPU Configuration */

    case GT_MULTI:

        /* Only one GT64xxx is present on the CPU bus, return

           the initial value */

        val = s->regs[saddr];

        break;

    /* CPU Error Report */

    case GT_CPUERR_ADDRLO:

    case GT_CPUERR_ADDRHI:

    case GT_CPUERR_DATALO:

    case GT_CPUERR_DATAHI:

    case GT_CPUERR_PARITY:

        /* Emulated memory has no error, always return the initial

           values */

        val = s->regs[saddr];

        break;

    /* CPU Sync Barrier */

    case GT_PCI0SYNC:

    case GT_PCI1SYNC:

        /* Reading those register should empty all FIFO on the PCI

           bus, which are not emulated. The return value should be

           a random value that should be ignored. */

        val = 0xc000ffee;

        break;

    /* ECC */

    case GT_ECC_ERRDATALO:

    case GT_ECC_ERRDATAHI:

    case GT_ECC_MEM:

    case GT_ECC_CALC:

    case GT_ECC_ERRADDR:

        /* Emulated memory has no error, always return the initial

           values */

        val = s->regs[saddr];

        break;

    case GT_CPU:

    case GT_SCS10LD:

    case GT_SCS10HD:

    case GT_SCS32LD:

    case GT_SCS32HD:

    case GT_CS20LD:

    case GT_CS20HD:

    case GT_CS3BOOTLD:

    case GT_CS3BOOTHD:

    case GT_SCS10AR:

    case GT_SCS32AR:

    case GT_CS20R:

    case GT_CS3BOOTR:

    case GT_PCI0IOLD:

    case GT_PCI0M0LD:

    case GT_PCI0M1LD:

    case GT_PCI1IOLD:

    case GT_PCI1M0LD:

    case GT_PCI1M1LD:

    case GT_PCI0IOHD:

    case GT_PCI0M0HD:

    case GT_PCI0M1HD:

    case GT_PCI1IOHD:

    case GT_PCI1M0HD:

    case GT_PCI1M1HD:

    case GT_PCI0IOREMAP:

    case GT_PCI0M0REMAP:

    case GT_PCI0M1REMAP:

    case GT_PCI1IOREMAP:

    case GT_PCI1M0REMAP:

    case GT_PCI1M1REMAP:

    case GT_ISD:

        val = s->regs[saddr];

        break;

    case GT_PCI0_IACK:

        /* Read the IRQ number */

        val = pic_read_irq(isa_pic);

        break;

    /* SDRAM and Device Address Decode */

    case GT_SCS0LD:

    case GT_SCS0HD:

    case GT_SCS1LD:

    case GT_SCS1HD:

    case GT_SCS2LD:

    case GT_SCS2HD:

    case GT_SCS3LD:

    case GT_SCS3HD:

    case GT_CS0LD:

    case GT_CS0HD:

    case GT_CS1LD:

    case GT_CS1HD:

    case GT_CS2LD:

    case GT_CS2HD:

    case GT_CS3LD:

    case GT_CS3HD:

    case GT_BOOTLD:

    case GT_BOOTHD:

    case GT_ADERR:

        val = s->regs[saddr];

        break;

    /* SDRAM Configuration */

    case GT_SDRAM_CFG:

    case GT_SDRAM_OPMODE:

    case GT_SDRAM_BM:

    case GT_SDRAM_ADDRDECODE:

        val = s->regs[saddr];

        break;

    /* SDRAM Parameters */

    case GT_SDRAM_B0:

    case GT_SDRAM_B1:

    case GT_SDRAM_B2:

    case GT_SDRAM_B3:

        /* We don't simulate electrical parameters of the SDRAM.

           Just return the last written value. */

        val = s->regs[saddr];

        break;

    /* Device Parameters */

    case GT_DEV_B0:

    case GT_DEV_B1:

    case GT_DEV_B2:

    case GT_DEV_B3:

    case GT_DEV_BOOT:

        val = s->regs[saddr];

        break;

    /* DMA Record */

    case GT_DMA0_CNT:

    case GT_DMA1_CNT:

    case GT_DMA2_CNT:

    case GT_DMA3_CNT:

    case GT_DMA0_SA:

    case GT_DMA1_SA:

    case GT_DMA2_SA:

    case GT_DMA3_SA:

    case GT_DMA0_DA:

    case GT_DMA1_DA:

    case GT_DMA2_DA:

    case GT_DMA3_DA:

    case GT_DMA0_NEXT:

    case GT_DMA1_NEXT:

    case GT_DMA2_NEXT:

    case GT_DMA3_NEXT:

    case GT_DMA0_CUR:

    case GT_DMA1_CUR:

    case GT_DMA2_CUR:

    case GT_DMA3_CUR:

        val = s->regs[saddr];

        break;

    /* DMA Channel Control */

    case GT_DMA0_CTRL:

    case GT_DMA1_CTRL:

    case GT_DMA2_CTRL:

    case GT_DMA3_CTRL:

        val = s->regs[saddr];

        break;

    /* DMA Arbiter */

    case GT_DMA_ARB:

        val = s->regs[saddr];

        break;

    /* Timer/Counter */

    case GT_TC0:

    case GT_TC1:

    case GT_TC2:

    case GT_TC3:

    case GT_TC_CONTROL:

        val = s->regs[saddr];

        break;

    /* PCI Internal */

    case GT_PCI0_CFGADDR:

        val = phb->config_reg;

        break;

    case GT_PCI0_CFGDATA:

        if (!(phb->config_reg & (1 << 31))) {

            val = 0xffffffff;

        } else {

            val = pci_data_read(phb->bus, phb->config_reg, 4);

        }

        if (!(s->regs[GT_PCI0_CMD] & 1) && (phb->config_reg & 0x00fff800)) {

            val = bswap32(val);

        }

        break;

    case GT_PCI0_CMD:

    case GT_PCI0_TOR:

    case GT_PCI0_BS_SCS10:

    case GT_PCI0_BS_SCS32:

    case GT_PCI0_BS_CS20:

    case GT_PCI0_BS_CS3BT:

    case GT_PCI1_IACK:

    case GT_PCI0_BARE:

    case GT_PCI0_PREFMBR:

    case GT_PCI0_SCS10_BAR:

    case GT_PCI0_SCS32_BAR:

    case GT_PCI0_CS20_BAR:

    case GT_PCI0_CS3BT_BAR:

    case GT_PCI0_SSCS10_BAR:

    case GT_PCI0_SSCS32_BAR:

    case GT_PCI0_SCS3BT_BAR:

    case GT_PCI1_CMD:

    case GT_PCI1_TOR:

    case GT_PCI1_BS_SCS10:

    case GT_PCI1_BS_SCS32:

    case GT_PCI1_BS_CS20:

    case GT_PCI1_BS_CS3BT:

    case GT_PCI1_BARE:

    case GT_PCI1_PREFMBR:

    case GT_PCI1_SCS10_BAR:

    case GT_PCI1_SCS32_BAR:

    case GT_PCI1_CS20_BAR:

    case GT_PCI1_CS3BT_BAR:

    case GT_PCI1_SSCS10_BAR:

    case GT_PCI1_SSCS32_BAR:

    case GT_PCI1_SCS3BT_BAR:

    case GT_PCI1_CFGADDR:

    case GT_PCI1_CFGDATA:

        val = s->regs[saddr];

        break;

    /* Interrupts */

    case GT_INTRCAUSE:

        val = s->regs[saddr];

        DPRINTF("INTRCAUSE %x\n", val);

        break;

    case GT_INTRMASK:

        val = s->regs[saddr];

        DPRINTF("INTRMASK %x\n", val);

        break;

    case GT_PCI0_ICMASK:

        val = s->regs[saddr];

        DPRINTF("ICMASK %x\n", val);

        break;

    case GT_PCI0_SERR0MASK:

        val = s->regs[saddr];

        DPRINTF("SERR0MASK %x\n", val);

        break;

    /* Reserved when only PCI_0 is configured. */

    case GT_HINTRCAUSE:

    case GT_CPU_INTSEL:

    case GT_PCI0_INTSEL:

    case GT_HINTRMASK:

    case GT_PCI0_HICMASK:

    case GT_PCI1_SERR1MASK:

        val = s->regs[saddr];

        break;

    default:

        val = s->regs[saddr];

        DPRINTF ("Bad register offset 0x%x\n", (int)addr);

        break;

    }

    if (!(s->regs[GT_CPU] & 0x00001000))

        val = bswap32(val);

    return val;

}


int qemu_opt_set(QemuOpts *opts, const char *name, const char *value)

{

    QemuOpt *opt;

    opt = qemu_opt_find(opts, name);

    if (!opt) {

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

        int i;

        for (i = 0; desc[i].name != NULL; i++) {

            if (strcmp(desc[i].name, name) == 0) {

                break;

            }

        }

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

            if (i == 0) {

                /* empty list -> allow any */;

            } else {

                fprintf(stderr, "option \"%s\" is not valid for %s\n",

                        name, opts->list->name);

                return -1;

            }

        }

        opt = qemu_mallocz(sizeof(*opt));

        opt->name = qemu_strdup(name);

        opt->opts = opts;

        TAILQ_INSERT_TAIL(&opts->head, opt, next);

        if (desc[i].name != NULL) {

            opt->desc = desc+i;

        }

    }

    qemu_free((/* !const */ char*)opt->str);

    opt->str = NULL;

    if (value) {

        opt->str = qemu_strdup(value);

    }

    if (qemu_opt_parse(opt) < 0) {

        fprintf(stderr, "Failed to parse \"%s\" for \"%s.%s\"\n", opt->str,

                opts->list->name, opt->name);

        qemu_opt_del(opt);

        return -1;

    }

    return 0;

}


static int scsi_initfn(SCSIDevice *dev)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);

    Error *err = NULL;

    if (!s->qdev.conf.bs) {

        error_report("drive property not set");

        return -1;

    }

    if (!(s->features & (1 << SCSI_DISK_F_REMOVABLE)) &&

        !bdrv_is_inserted(s->qdev.conf.bs)) {

        error_report("Device needs media, but drive is empty");

        return -1;

    }

    blkconf_serial(&s->qdev.conf, &s->serial);

    if (dev->type == TYPE_DISK) {

        blkconf_geometry(&dev->conf, NULL, 65535, 255, 255, &err);

        if (err) {

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

            error_free(err);

            return -1;

        }

    }

    if (s->qdev.conf.discard_granularity == -1) {

        s->qdev.conf.discard_granularity =

            MAX(s->qdev.conf.logical_block_size, DEFAULT_DISCARD_GRANULARITY);

    }

    if (!s->version) {

        s->version = g_strdup(qemu_get_version());

    }

    if (!s->vendor) {

        s->vendor = g_strdup("QEMU");

    }

    if (bdrv_is_sg(s->qdev.conf.bs)) {

        error_report("unwanted /dev/sg*");

        return -1;

    }

    if ((s->features & (1 << SCSI_DISK_F_REMOVABLE)) &&

            !(s->features & (1 << SCSI_DISK_F_NO_REMOVABLE_DEVOPS))) {

        bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_removable_block_ops, s);

    } else {

        bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_block_ops, s);

    }

    bdrv_set_guest_block_size(s->qdev.conf.bs, s->qdev.blocksize);

    bdrv_iostatus_enable(s->qdev.conf.bs);

    add_boot_device_path(s->qdev.conf.bootindex, &dev->qdev, NULL);

    return 0;

}


static void ehci_update_frindex(EHCIState *ehci, int frames)

{

    int i;

    if (!ehci_enabled(ehci)) {

        return;

    }

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

        ehci->frindex += 8;

        if (ehci->frindex == 0x00002000) {

            ehci_raise_irq(ehci, USBSTS_FLR);

        }

        if (ehci->frindex == 0x00004000) {

            ehci_raise_irq(ehci, USBSTS_FLR);

            ehci->frindex = 0;

            if (ehci->usbsts_frindex >= 0x00004000) {

                ehci->usbsts_frindex -= 0x00004000;

            } else {

                ehci->usbsts_frindex = 0;

            }

        }

    }

}


static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)

{

    while (uls->id != CODEC_ID_NONE) {

        if(mxf_match_uid(uls->uid, *uid, 16))

            break;

        uls++;

    }

    return uls;

}


static void pty_chr_state(CharDriverState *chr, int connected)

{

    PtyCharDriver *s = chr->opaque;

    if (!connected) {

        if (s->fd_tag) {

            g_source_remove(s->fd_tag);

            s->fd_tag = 0;

        }

        s->connected = 0;

        s->polling = 0;

        /* (re-)connect poll interval for idle guests: once per second.

         * We check more frequently in case the guests sends data to

         * the virtual device linked to our pty. */

        pty_chr_rearm_timer(chr, 1000);

    } else {

        if (!s->connected)

            qemu_chr_be_generic_open(chr);

        s->connected = 1;

    }

}


int h263_decode_picture_header(MpegEncContext *s)

{

    int format, width, height;

    /* picture header */

    if (get_bits(&s->gb, 22) != 0x20)

        return -1;

    skip_bits(&s->gb, 8); /* picture timestamp */

    if (get_bits1(&s->gb) != 1)

        return -1;	/* marker */

    if (get_bits1(&s->gb) != 0)

        return -1;	/* h263 id */

    skip_bits1(&s->gb);	/* split screen off */

    skip_bits1(&s->gb);	/* camera  off */

    skip_bits1(&s->gb);	/* freeze picture release off */

    format = get_bits(&s->gb, 3);

    if (format != 7) {

        s->h263_plus = 0;

        /* H.263v1 */

        width = h263_format[format][0];

        height = h263_format[format][1];

        if (!width)

            return -1;

        s->pict_type = I_TYPE + get_bits1(&s->gb);

        s->unrestricted_mv = get_bits1(&s->gb);

        s->h263_long_vectors = s->unrestricted_mv;

        if (get_bits1(&s->gb) != 0)

            return -1;	/* SAC: off */

        if (get_bits1(&s->gb) != 0)

            return -1;	/* advanced prediction mode: off */

        if (get_bits1(&s->gb) != 0)

            return -1;	/* not PB frame */

        s->qscale = get_bits(&s->gb, 5);

        skip_bits1(&s->gb);	/* Continuous Presence Multipoint mode: off */

    } else {

        s->h263_plus = 1;

        /* H.263v2 */

        /* OPPTYPE */

        if (get_bits(&s->gb, 3) != 1) /* Update Full Extended PTYPE */

            return -1;

        format = get_bits(&s->gb, 3);

        skip_bits(&s->gb,1); /* Custom PCF */

        umvplus_dec = get_bits(&s->gb, 1); /* Unrestricted Motion Vector */

        skip_bits(&s->gb, 10);

        skip_bits(&s->gb, 3); /* Reserved */

        /* MPPTYPE */

        s->pict_type = get_bits(&s->gb, 3) + 1;

        if (s->pict_type != I_TYPE &&

            s->pict_type != P_TYPE)

            return -1;

        skip_bits(&s->gb, 7);

        /* Get the picture dimensions */

        if (format == 6) {

            /* Custom Picture Format (CPFMT) */

            skip_bits(&s->gb, 4); /* aspect ratio */

            width = (get_bits(&s->gb, 9) + 1) * 4;

            skip_bits1(&s->gb);

            height = get_bits(&s->gb, 9) * 4;

#ifdef DEBUG

            fprintf(stderr,"\nH.263+ Custom picture: %dx%d\n",width,height);

#endif

        }

        else {

            width = h263_format[format][0];

            height = h263_format[format][1];

        }

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

            return -1;

        if (umvplus_dec) {

            skip_bits1(&s->gb); /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */

        }

        s->qscale = get_bits(&s->gb, 5);

    }

    /* PEI */

    while (get_bits1(&s->gb) != 0) {

        skip_bits(&s->gb, 8);

    }

    s->f_code = 1;

    s->width = width;

    s->height = height;

    return 0;

}


static void stellaris_init(const char *kernel_filename, const char *cpu_model,

                           DisplayState *ds, stellaris_board_info *board)

{

    static const int uart_irq[] = {5, 6, 33, 34};

    static const int timer_irq[] = {19, 21, 23, 35};

    static const uint32_t gpio_addr[7] =

      { 0x40004000, 0x40005000, 0x40006000, 0x40007000,

        0x40024000, 0x40025000, 0x40026000};

    static const int gpio_irq[7] = {0, 1, 2, 3, 4, 30, 31};

    qemu_irq *pic;

    qemu_irq *gpio_in[5];

    qemu_irq *gpio_out[5];

    qemu_irq adc;

    int sram_size;

    int flash_size;

    i2c_bus *i2c;

    int i;

    flash_size = ((board->dc0 & 0xffff) + 1) << 1;

    sram_size = (board->dc0 >> 18) + 1;

    pic = armv7m_init(flash_size, sram_size, kernel_filename, cpu_model);

    if (board->dc1 & (1 << 16)) {

        adc = stellaris_adc_init(0x40038000, pic[14]);

    } else {

        adc = NULL;

    }

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

        if (board->dc2 & (0x10000 << i)) {

            stellaris_gptm_init(0x40030000 + i * 0x1000,

                                pic[timer_irq[i]], adc);

        }

    }

    stellaris_sys_init(0x400fe000, pic[28], board, nd_table[0].macaddr);

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

        if (board->dc4 & (1 << i)) {

            gpio_in[i] = pl061_init(gpio_addr[i], pic[gpio_irq[i]],

                                    &gpio_out[i]);

        }

    }

    if (board->dc2 & (1 << 12)) {

        i2c = i2c_init_bus();

        stellaris_i2c_init(0x40020000, pic[8], i2c);

        if (board->peripherals & BP_OLED_I2C) {

            ssd0303_init(ds, i2c, 0x3d);

        }

    }

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

        if (board->dc2 & (1 << i)) {

            pl011_init(0x4000c000 + i * 0x1000, pic[uart_irq[i]],

                       serial_hds[i], PL011_LUMINARY);

        }

    }

    if (board->dc2 & (1 << 4)) {

        if (board->peripherals & BP_OLED_SSI) {

            void * oled;

            void * sd;

            void *ssi_bus;

            int index;

            oled = ssd0323_init(ds, &gpio_out[GPIO_C][7]);

            index = drive_get_index(IF_SD, 0, 0);

            sd = ssi_sd_init(drives_table[index].bdrv);

            ssi_bus = stellaris_ssi_bus_init(&gpio_out[GPIO_D][0],

                                             ssi_sd_xfer, sd,

                                             ssd0323_xfer_ssi, oled);

            pl022_init(0x40008000, pic[7], stellaris_ssi_bus_xfer, ssi_bus);

            /* Make sure the select pin is high.  */

            qemu_irq_raise(gpio_out[GPIO_D][0]);

        } else {

            pl022_init(0x40008000, pic[7], NULL, NULL);

        }

    }

    if (board->dc4 & (1 << 28)) {

        /* FIXME: Obey network model.  */

        stellaris_enet_init(&nd_table[0], 0x40048000, pic[42]);

    }

    if (board->peripherals & BP_GAMEPAD) {

        qemu_irq gpad_irq[5];

        static const int gpad_keycode[5] = { 0xc8, 0xd0, 0xcb, 0xcd, 0x1d };

        gpad_irq[0] = qemu_irq_invert(gpio_in[GPIO_E][0]); /* up */

        gpad_irq[1] = qemu_irq_invert(gpio_in[GPIO_E][1]); /* down */

        gpad_irq[2] = qemu_irq_invert(gpio_in[GPIO_E][2]); /* left */

        gpad_irq[3] = qemu_irq_invert(gpio_in[GPIO_E][3]); /* right */

        gpad_irq[4] = qemu_irq_invert(gpio_in[GPIO_F][1]); /* select */

        stellaris_gamepad_init(5, gpad_irq, gpad_keycode);

    }

}