int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)

{

    int ret;

    size= ffio_limit(s, size);

    ret= av_new_packet(pkt, size);

    if(ret<0)

        return ret;

    pkt->pos= avio_tell(s);

    ret= avio_read(s, pkt->data, size);

    if(ret<=0)

        av_free_packet(pkt);

    else

        av_shrink_packet(pkt, ret);

    if (pkt->size < orig_size)

        pkt->flags |= AV_PKT_FLAG_CORRUPT;

    return ret;

}


void xtensa_translate_init(void)

{

    static const char * const regnames[] = {

        "ar0", "ar1", "ar2", "ar3",

        "ar4", "ar5", "ar6", "ar7",

        "ar8", "ar9", "ar10", "ar11",

        "ar12", "ar13", "ar14", "ar15",

    };

    static const char * const fregnames[] = {

        "f0", "f1", "f2", "f3",

        "f4", "f5", "f6", "f7",

        "f8", "f9", "f10", "f11",

        "f12", "f13", "f14", "f15",

    };

    int i;

    cpu_env = tcg_global_reg_new_ptr(TCG_AREG0, "env");

    cpu_pc = tcg_global_mem_new_i32(TCG_AREG0,

            offsetof(CPUXtensaState, pc), "pc");

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

        cpu_R[i] = tcg_global_mem_new_i32(TCG_AREG0,

                offsetof(CPUXtensaState, regs[i]),

                regnames[i]);

    }

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

        cpu_FR[i] = tcg_global_mem_new_i32(TCG_AREG0,

                offsetof(CPUXtensaState, fregs[i]),

                fregnames[i]);

    }

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

        if (sregnames[i]) {

            cpu_SR[i] = tcg_global_mem_new_i32(TCG_AREG0,

                    offsetof(CPUXtensaState, sregs[i]),

                    sregnames[i]);

        }

    }

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

        if (uregnames[i]) {

            cpu_UR[i] = tcg_global_mem_new_i32(TCG_AREG0,

                    offsetof(CPUXtensaState, uregs[i]),

                    uregnames[i]);

        }

    }

#define GEN_HELPER 2

#include "helper.h"

}


float64 HELPER(recpe_f64)(float64 input, void *fpstp)

{

    float_status *fpst = fpstp;

    float64 f64 = float64_squash_input_denormal(input, fpst);

    uint64_t f64_val = float64_val(f64);

    uint64_t f64_sbit = 0x8000000000000000ULL & f64_val;

    int64_t f64_exp = extract64(f64_val, 52, 11);

    float64 r64;

    uint64_t r64_val;

    int64_t r64_exp;

    uint64_t r64_frac;

    /* Deal with any special cases */

    if (float64_is_any_nan(f64)) {

        float64 nan = f64;

        if (float64_is_signaling_nan(f64)) {

            float_raise(float_flag_invalid, fpst);

            nan = float64_maybe_silence_nan(f64);

        }

        if (fpst->default_nan_mode) {

            nan =  float64_default_nan;

        }

        return nan;

    } else if (float64_is_infinity(f64)) {

        return float64_set_sign(float64_zero, float64_is_neg(f64));

    } else if (float64_is_zero(f64)) {

        float_raise(float_flag_divbyzero, fpst);

        return float64_set_sign(float64_infinity, float64_is_neg(f64));

    } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {

        /* Abs(value) < 2.0^-1024 */

        float_raise(float_flag_overflow | float_flag_inexact, fpst);

        if (round_to_inf(fpst, f64_sbit)) {

            return float64_set_sign(float64_infinity, float64_is_neg(f64));

        } else {

            return float64_set_sign(float64_maxnorm, float64_is_neg(f64));

        }

    } else if (f64_exp >= 1023 && fpst->flush_to_zero) {

        float_raise(float_flag_underflow, fpst);

        return float64_set_sign(float64_zero, float64_is_neg(f64));

    }

    r64 = call_recip_estimate(f64, 2045, fpst);

    r64_val = float64_val(r64);

    r64_exp = extract64(r64_val, 52, 11);

    r64_frac = extract64(r64_val, 0, 52);

    /* result = sign : result_exp<10:0> : fraction<51:0> */

    return make_float64(f64_sbit |

                        ((r64_exp & 0x7ff) << 52) |

                        r64_frac);

}


static void stm32f2xx_usart_write(void *opaque, hwaddr addr,

                                  uint64_t val64, unsigned int size)

{

    STM32F2XXUsartState *s = opaque;

    uint32_t value = val64;

    unsigned char ch;

    DB_PRINT("Write 0x%" PRIx32 ", 0x%"HWADDR_PRIx"\n", value, addr);

    switch (addr) {

    case USART_SR:

        if (value <= 0x3FF) {

            s->usart_sr = value;

        } else {

            s->usart_sr &= value;

        }

        if (!(s->usart_sr & USART_SR_RXNE)) {

            qemu_set_irq(s->irq, 0);

        }

        return;

    case USART_DR:

        if (value < 0xF000) {

            ch = value;

            if (s->chr) {

                qemu_chr_fe_write_all(s->chr, &ch, 1);

            }

            s->usart_sr |= USART_SR_TC;

            s->usart_sr &= ~USART_SR_TXE;

        }

        return;

    case USART_BRR:

        s->usart_brr = value;

        return;

    case USART_CR1:

        s->usart_cr1 = value;

            if (s->usart_cr1 & USART_CR1_RXNEIE &&

                s->usart_sr & USART_SR_RXNE) {

                qemu_set_irq(s->irq, 1);

            }

        return;

    case USART_CR2:

        s->usart_cr2 = value;

        return;

    case USART_CR3:

        s->usart_cr3 = value;

        return;

    case USART_GTPR:

        s->usart_gtpr = value;

        return;

    default:

        qemu_log_mask(LOG_GUEST_ERROR,

                      "%s: Bad offset 0x%"HWADDR_PRIx"\n", __func__, addr);

    }

}


static void simpleCopy(SwsContext *c, uint8_t* srcParam[], int srcStrideParam[], int srcSliceY,

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

	int srcStride[3];

	uint8_t *src[3];

	uint8_t *dst[3];

	if(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) || isGray(c->srcFormat)){

		src[0]= srcParam[0];

		src[1]=

		src[2]= NULL;

		srcStride[0]= srcStrideParam[0];

		srcStride[1]=

		srcStride[2]= 0;

	}

	if(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(isPacked(c->srcFormat))

	{

		if(dstStride[0]==srcStride[0])

			memcpy(dst[0] + dstStride[0]*srcSliceY, src[0], srcSliceH*dstStride[0]);

		else

		{

			int i;

			uint8_t *srcPtr= src[0];

			uint8_t *dstPtr= dst[0] + dstStride[0]*srcSliceY;

			int length=0;

			/* universal length finder */

			while(length+c->srcW <= dstStride[0]

			   && length+c->srcW <= srcStride[0]) length+= c->srcW;

			ASSERT(length!=0);

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

			{

				memcpy(dstPtr, srcPtr, length);

				srcPtr+= srcStride[0];

				dstPtr+= dstStride[0];

			}

		}

	}

	else

	{ /* Planar YUV */

		int plane;

		for(plane=0; plane<3; plane++)

		{

			int length= plane==0 ? c->srcW  : ((c->srcW+1)>>1);

			int y=      plane==0 ? srcSliceY: ((srcSliceY+1)>>1);

			int height= plane==0 ? srcSliceH: ((srcSliceH+1)>>1);

			if(dstStride[plane]==srcStride[plane])

				memcpy(dst[plane] + dstStride[plane]*y, src[plane], height*dstStride[plane]);

			else

			{

				int i;

				uint8_t *srcPtr= src[plane];

				uint8_t *dstPtr= dst[plane] + dstStride[plane]*y;

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

				{

					memcpy(dstPtr, srcPtr, length);

					srcPtr+= srcStride[plane];

					dstPtr+= dstStride[plane];

				}

			}

		}

	}

}


static void free_ahci_device(QPCIDevice *dev)

{

    QPCIBus *pcibus = dev ? dev->bus : NULL;

    /* libqos doesn't have a function for this, so free it manually */

    g_free(dev);

    qpci_free_pc(pcibus);

}


int av_reduce(int *dst_nom, int *dst_den, int64_t nom, int64_t den, int64_t max){

    AVRational a0={0,1}, a1={1,0};

    int sign= (nom<0) ^ (den<0);

    int64_t gcd= ff_gcd(FFABS(nom), FFABS(den));

    nom = FFABS(nom)/gcd;

    den = FFABS(den)/gcd;

    if(nom<=max && den<=max){

        a1= (AVRational){nom, den};

        den=0;

    }

    while(den){

        int64_t x       = nom / den;

        int64_t next_den= nom - den*x;

        int64_t a2n= x*a1.num + a0.num;

        int64_t a2d= x*a1.den + a0.den;

        if(a2n > max || a2d > max){

            if(a1.num) x= (max - a0.num) / a1.num;

            if(a1.den) x= FFMIN(x, (max - a0.den) / a1.den);

            // Won't overflow, sum == original denominator

            if (den*(2*x*a1.den + a0.den) > nom*a1.den)

                a1 = (AVRational){x*a1.num + a0.num, x*a1.den + a0.den};

            break;

        }

        a0= a1;

        a1= (AVRational){a2n, a2d};

        nom= den;

        den= next_den;

    }

    assert(ff_gcd(a1.num, a1.den) == 1);

    *dst_nom = sign ? -a1.num : a1.num;

    *dst_den = a1.den;

    return den==0;

}


PPC_OP(cmpi)

{

    if (Ts0 < SPARAM(1)) {

        T0 = 0x08;

    } else if (Ts0 > SPARAM(1)) {

        T0 = 0x04;

    } else {

        T0 = 0x02;

    }

    RETURN();

}


static int bdrv_rd_badreq_bytes(BlockDriverState *bs,

                                int64_t offset, int count)

{

    int64_t size = bs->total_sectors << SECTOR_BITS;

    return

        count < 0 ||

        size < 0 ||

        count > size ||

        offset > size - count;

}


static AVStream * parse_media_type(AVFormatContext *s, AVStream *st, int sid,

                                   ff_asf_guid mediatype, ff_asf_guid subtype,

                                   ff_asf_guid formattype, int size)

{

    WtvContext *wtv = s->priv_data;

    AVIOContext *pb = wtv->pb;

    if (!ff_guidcmp(subtype, mediasubtype_cpfilters_processed) &&

        !ff_guidcmp(formattype, format_cpfilters_processed)) {

        ff_asf_guid actual_subtype;

        ff_asf_guid actual_formattype;

        if (size < 32) {

            av_log(s, AV_LOG_WARNING, "format buffer size underflow\n");

            avio_skip(pb, size);

            return NULL;

        }

        avio_skip(pb, size - 32);

        ff_get_guid(pb, &actual_subtype);

        ff_get_guid(pb, &actual_formattype);

        avio_seek(pb, -size, SEEK_CUR);

        st = parse_media_type(s, st, sid, mediatype, actual_subtype, actual_formattype, size - 32);

        avio_skip(pb, 32);

        return st;

    } else if (!ff_guidcmp(mediatype, mediatype_audio)) {

        st = new_stream(s, st, sid, AVMEDIA_TYPE_AUDIO);

        if (!st)

            return NULL;

        if (!ff_guidcmp(formattype, format_waveformatex)) {

            ff_get_wav_header(pb, st->codec, size);

        } else {

            if (ff_guidcmp(formattype, format_none))

                av_log(s, AV_LOG_WARNING, "unknown formattype:"PRI_GUID"\n", ARG_GUID(formattype));

            avio_skip(pb, size);

        }

        if (!memcmp(subtype + 4, (const uint8_t[]){MEDIASUBTYPE_BASE_GUID}, 12)) {

            st->codec->codec_id = ff_wav_codec_get_id(AV_RL32(subtype), st->codec->bits_per_coded_sample);

        } else if (!ff_guidcmp(subtype, mediasubtype_mpeg1payload)) {

            if (st->codec->extradata && st->codec->extradata_size >= 22)

                parse_mpeg1waveformatex(st);

            else

                av_log(s, AV_LOG_WARNING, "MPEG1WAVEFORMATEX underflow\n");

        } else {

            st->codec->codec_id = ff_codec_guid_get_id(audio_guids, subtype);

            if (st->codec->codec_id == CODEC_ID_NONE)

                av_log(s, AV_LOG_WARNING, "unknown subtype:"PRI_GUID"\n", ARG_GUID(subtype));

        }

        return st;

    } else if (!ff_guidcmp(mediatype, mediatype_video)) {

        st = new_stream(s, st, sid, AVMEDIA_TYPE_VIDEO);

        if (!st)

            return NULL;

        if (!ff_guidcmp(formattype, format_videoinfo2)) {

            int consumed = parse_videoinfoheader2(s, st);

            avio_skip(pb, FFMAX(size - consumed, 0));

        } else if (!ff_guidcmp(formattype, format_mpeg2_video)) {

            int consumed = parse_videoinfoheader2(s, st);

            avio_skip(pb, FFMAX(size - consumed, 0));

        } else {

            if (ff_guidcmp(formattype, format_none))

                av_log(s, AV_LOG_WARNING, "unknown formattype:"PRI_GUID"\n", ARG_GUID(formattype));

            avio_skip(pb, size);

        }

        if (!memcmp(subtype + 4, (const uint8_t[]){MEDIASUBTYPE_BASE_GUID}, 12)) {

            st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, AV_RL32(subtype));

        } else {

            st->codec->codec_id = ff_codec_guid_get_id(video_guids, subtype);

        }

        if (st->codec->codec_id == CODEC_ID_NONE)

            av_log(s, AV_LOG_WARNING, "unknown subtype:"PRI_GUID"\n", ARG_GUID(subtype));

        return st;

    } else if (!ff_guidcmp(mediatype, mediatype_mpeg2_pes) &&

               !ff_guidcmp(subtype, mediasubtype_dvb_subtitle)) {

        st = new_stream(s, st, sid, AVMEDIA_TYPE_SUBTITLE);

        if (!st)

            return NULL;

        if (ff_guidcmp(formattype, format_none))

            av_log(s, AV_LOG_WARNING, "unknown formattype:"PRI_GUID"\n", ARG_GUID(formattype));

        avio_skip(pb, size);

        st->codec->codec_id = CODEC_ID_DVB_SUBTITLE;

        return st;

    } else if (!ff_guidcmp(mediatype, mediatype_mstvcaption) &&

               (!ff_guidcmp(subtype, mediasubtype_teletext) || !ff_guidcmp(subtype, mediasubtype_dtvccdata))) {

        st = new_stream(s, st, sid, AVMEDIA_TYPE_SUBTITLE);

        if (!st)

            return NULL;

        if (ff_guidcmp(formattype, format_none))

            av_log(s, AV_LOG_WARNING, "unknown formattype:"PRI_GUID"\n", ARG_GUID(formattype));

        avio_skip(pb, size);

        st->codec->codec_id   = CODEC_ID_DVB_TELETEXT;

        return st;

    } else if (!ff_guidcmp(mediatype, mediatype_mpeg2_sections) &&

               !ff_guidcmp(subtype, mediasubtype_mpeg2_sections)) {

        if (ff_guidcmp(formattype, format_none))

            av_log(s, AV_LOG_WARNING, "unknown formattype:"PRI_GUID"\n", ARG_GUID(formattype));

        avio_skip(pb, size);

        return NULL;

    }

    av_log(s, AV_LOG_WARNING, "unknown media type, mediatype:"PRI_GUID

                              ", subtype:"PRI_GUID", formattype:"PRI_GUID"\n",

                              ARG_GUID(mediatype), ARG_GUID(subtype), ARG_GUID(formattype));

    avio_skip(pb, size);

    return NULL;

}


static inline void RENAME(hyscale)(uint16_t *dst, long dstWidth, uint8_t *src, int srcW, int xInc,

				   int flags, int canMMX2BeUsed, int16_t *hLumFilter,

				   int16_t *hLumFilterPos, int hLumFilterSize, void *funnyYCode,

				   int srcFormat, uint8_t *formatConvBuffer, int16_t *mmx2Filter,

				   int32_t *mmx2FilterPos)

{

    if(srcFormat==IMGFMT_YUY2)

    {

	RENAME(yuy2ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_UYVY)

    {

	RENAME(uyvyToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_BGR32)

    {

	RENAME(bgr32ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_BGR24)

    {

	RENAME(bgr24ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_BGR16)

    {

	RENAME(bgr16ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_BGR15)

    {

	RENAME(bgr15ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_RGB32)

    {

	RENAME(rgb32ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_RGB24)

    {

	RENAME(rgb24ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

#ifdef HAVE_MMX

	// use the new MMX scaler if the mmx2 can't be used (its faster than the x86asm one)

    if(!(flags&SWS_FAST_BILINEAR) || (!canMMX2BeUsed))

#else

    if(!(flags&SWS_FAST_BILINEAR))

#endif

    {

    	RENAME(hScale)(dst, dstWidth, src, srcW, xInc, hLumFilter, hLumFilterPos, hLumFilterSize);

    }

    else // Fast Bilinear upscale / crap downscale

    {

#if defined(ARCH_X86) || defined(ARCH_X86_64)

#ifdef HAVE_MMX2

	int i;

	if(canMMX2BeUsed)

	{

		asm volatile(

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

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

			"mov %1, %%"REG_D"		\n\t"

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

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

			"xor %%"REG_a", %%"REG_a"	\n\t" // i

			PREFETCH" (%%"REG_c")		\n\t"

			PREFETCH" 32(%%"REG_c")		\n\t"

			PREFETCH" 64(%%"REG_c")		\n\t"

#ifdef ARCH_X86_64

#define FUNNY_Y_CODE \

			"movl (%%"REG_b"), %%esi	\n\t"\

			"call *%4			\n\t"\

			"movl (%%"REG_b", %%"REG_a"), %%esi\n\t"\

			"add %%"REG_S", %%"REG_c"	\n\t"\

			"add %%"REG_a", %%"REG_D"	\n\t"\

			"xor %%"REG_a", %%"REG_a"	\n\t"\

#else

#define FUNNY_Y_CODE \

			"movl (%%"REG_b"), %%esi	\n\t"\

			"call *%4			\n\t"\

			"addl (%%"REG_b", %%"REG_a"), %%"REG_c"\n\t"\

			"add %%"REG_a", %%"REG_D"	\n\t"\

			"xor %%"REG_a", %%"REG_a"	\n\t"\

#endif

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

			:: "m" (src), "m" (dst), "m" (mmx2Filter), "m" (mmx2FilterPos),

			"m" (funnyYCode)

			: "%"REG_a, "%"REG_b, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D

		);

		for(i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) dst[i] = src[srcW-1]*128;

	}

	else

	{

#endif

	long xInc_shr16 = xInc >> 16;

	uint16_t xInc_mask = xInc & 0xffff;

	//NO MMX just normal asm ...

	asm volatile(

		"xor %%"REG_a", %%"REG_a"	\n\t" // i

		"xor %%"REG_b", %%"REG_b"	\n\t" // xx

		"xorl %%ecx, %%ecx		\n\t" // 2*xalpha

		ASMALIGN16

		"1:				\n\t"

		"movzbl  (%0, %%"REG_b"), %%edi	\n\t" //src[xx]

		"movzbl 1(%0, %%"REG_b"), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

		"mov %1, %%"REG_D"		\n\t"

		"shrl $9, %%esi			\n\t"

		"movw %%si, (%%"REG_D", %%"REG_a", 2)\n\t"

		"addw %4, %%cx			\n\t" //2*xalpha += xInc&0xFF

		"adc %3, %%"REG_b"		\n\t" //xx+= xInc>>8 + carry

		"movzbl (%0, %%"REG_b"), %%edi	\n\t" //src[xx]

		"movzbl 1(%0, %%"REG_b"), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

		"mov %1, %%"REG_D"		\n\t"

		"shrl $9, %%esi			\n\t"

		"movw %%si, 2(%%"REG_D", %%"REG_a", 2)\n\t"

		"addw %4, %%cx			\n\t" //2*xalpha += xInc&0xFF

		"adc %3, %%"REG_b"		\n\t" //xx+= xInc>>8 + carry

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

		"cmp %2, %%"REG_a"		\n\t"

		" jb 1b				\n\t"

		:: "r" (src), "m" (dst), "m" (dstWidth), "m" (xInc_shr16), "m" (xInc_mask)

		: "%"REG_a, "%"REG_b, "%ecx", "%"REG_D, "%esi"

		);

#ifdef HAVE_MMX2

	} //if MMX2 can't be used

#endif

#else

	int i;

	unsigned int xpos=0;

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

	{

		register unsigned int xx=xpos>>16;

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

		dst[i]= (src[xx]<<7) + (src[xx+1] - src[xx])*xalpha;

		xpos+=xInc;

	}

#endif

    }

}


static void filter(AVFilterContext *ctx, AVFilterBufferRef *dstpic,

                   int parity, int tff)

{

    YADIFContext *yadif = ctx->priv;

    int y, i;

    for (i = 0; i < yadif->csp->nb_components; i++) {

        int w = dstpic->video->w;

        int h = dstpic->video->h;

        int refs = yadif->cur->linesize[i];

        int df = (yadif->csp->comp[i].depth_minus1 + 8) / 8;

        if (i == 1 || i == 2) {

        /* Why is this not part of the per-plane description thing? */

            w >>= yadif->csp->log2_chroma_w;

            h >>= yadif->csp->log2_chroma_h;

        }

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

            if ((y ^ parity) & 1) {

                uint8_t *prev = &yadif->prev->data[i][y*refs];

                uint8_t *cur  = &yadif->cur ->data[i][y*refs];

                uint8_t *next = &yadif->next->data[i][y*refs];

                uint8_t *dst  = &dstpic->data[i][y*dstpic->linesize[i]];

                int     mode  = y==1 || y+2==h ? 2 : yadif->mode;

                yadif->filter_line(dst, prev, cur, next, w, y+1<h ? refs : -refs, y ? -refs : refs, parity ^ tff, mode);

            } else {

                memcpy(&dstpic->data[i][y*dstpic->linesize[i]],

                       &yadif->cur->data[i][y*refs], w*df);

            }

        }

    }

    emms_c();

}


static void vorbis_free_extradata(PayloadContext * data)

{

    av_free(data);

}


static int dxva2_alloc(AVCodecContext *s)

{

    InputStream  *ist = s->opaque;

    int loglevel = (ist->hwaccel_id == HWACCEL_AUTO) ? AV_LOG_VERBOSE : AV_LOG_ERROR;

    DXVA2Context *ctx;

    HANDLE device_handle;

    HRESULT hr;

    AVHWDeviceContext    *device_ctx;

    AVDXVA2DeviceContext *device_hwctx;

    int ret;

    ctx = av_mallocz(sizeof(*ctx));

    if (!ctx)

        return AVERROR(ENOMEM);

    ist->hwaccel_ctx           = ctx;

    ist->hwaccel_uninit        = dxva2_uninit;

    ist->hwaccel_get_buffer    = dxva2_get_buffer;

    ist->hwaccel_retrieve_data = dxva2_retrieve_data;

    ret = av_hwdevice_ctx_create(&ctx->hw_device_ctx, AV_HWDEVICE_TYPE_DXVA2,

                                 ist->hwaccel_device, NULL, 0);

    if (ret < 0)

        goto fail;

    device_ctx   = (AVHWDeviceContext*)ctx->hw_device_ctx->data;

    device_hwctx = device_ctx->hwctx;

    hr = IDirect3DDeviceManager9_OpenDeviceHandle(device_hwctx->devmgr,

                                                  &device_handle);

    if (FAILED(hr)) {

        av_log(NULL, loglevel, "Failed to open a device handle\n");

        goto fail;

    }

    hr = IDirect3DDeviceManager9_GetVideoService(device_hwctx->devmgr, device_handle,

                                                 &IID_IDirectXVideoDecoderService,

                                                 (void **)&ctx->decoder_service);

    IDirect3DDeviceManager9_CloseDeviceHandle(device_hwctx->devmgr, device_handle);

    if (FAILED(hr)) {

        av_log(NULL, loglevel, "Failed to create IDirectXVideoDecoderService\n");

        goto fail;

    }

    ctx->tmp_frame = av_frame_alloc();

    if (!ctx->tmp_frame)

        goto fail;

    s->hwaccel_context = av_mallocz(sizeof(struct dxva_context));

    if (!s->hwaccel_context)

        goto fail;

    return 0;

fail:

    dxva2_uninit(s);

    return AVERROR(EINVAL);

}


static av_cold int amr_nb_encode_init(AVCodecContext *avctx)

{

    AMRContext *s = avctx->priv_data;

    if (avctx->sample_rate != 8000) {

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

        return AVERROR(ENOSYS);

    }

    if (avctx->channels != 1) {

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

        return AVERROR(ENOSYS);

    }

    avctx->frame_size  = 160;

    avctx->initial_padding = 50;

    ff_af_queue_init(avctx, &s->afq);

    s->enc_state = Encoder_Interface_init(s->enc_dtx);

    if (!s->enc_state) {

        av_log(avctx, AV_LOG_ERROR, "Encoder_Interface_init error\n");

        av_freep(&avctx->coded_frame);

        return -1;

    }

    s->enc_mode    = get_bitrate_mode(avctx->bit_rate, avctx);

    s->enc_bitrate = avctx->bit_rate;

    return 0;

}


static void avc_luma_mid_4w_msa(const uint8_t *src, int32_t src_stride,

                                uint8_t *dst, int32_t dst_stride,

                                int32_t height)

{

    uint32_t loop_cnt;

    v16i8 src0, src1, src2, src3, src4;

    v16i8 mask0, mask1, mask2;

    v8i16 hz_out0, hz_out1, hz_out2, hz_out3;

    v8i16 hz_out4, hz_out5, hz_out6, hz_out7, hz_out8;

    v8i16 dst0, dst1, dst2, dst3;

    LD_SB3(&luma_mask_arr[48], 16, mask0, mask1, mask2);

    LD_SB5(src, src_stride, src0, src1, src2, src3, src4);

    src += (5 * src_stride);

    XORI_B5_128_SB(src0, src1, src2, src3, src4);

    hz_out0 = AVC_XOR_VSHF_B_AND_APPLY_6TAP_HORIZ_FILT_SH(src0, src1,

                                                          mask0, mask1, mask2);

    hz_out2 = AVC_XOR_VSHF_B_AND_APPLY_6TAP_HORIZ_FILT_SH(src2, src3,

                                                          mask0, mask1, mask2);

    PCKOD_D2_SH(hz_out0, hz_out0, hz_out2, hz_out2, hz_out1, hz_out3);

    hz_out4 = AVC_HORZ_FILTER_SH(src4, src4, mask0, mask1, mask2);

    for (loop_cnt = (height >> 2); loop_cnt--;) {

        LD_SB4(src, src_stride, src0, src1, src2, src3);

        src += (4 * src_stride);

        XORI_B4_128_SB(src0, src1, src2, src3);

        hz_out5 = AVC_XOR_VSHF_B_AND_APPLY_6TAP_HORIZ_FILT_SH(src0, src1,

                                                              mask0, mask1,

                                                              mask2);

        hz_out7 = AVC_XOR_VSHF_B_AND_APPLY_6TAP_HORIZ_FILT_SH(src2, src3,

                                                              mask0, mask1,

                                                              mask2);

        PCKOD_D2_SH(hz_out5, hz_out5, hz_out7, hz_out7, hz_out6, hz_out8);

        dst0 = AVC_CALC_DPADD_H_6PIX_2COEFF_R_SH(hz_out0, hz_out1, hz_out2,

                                                 hz_out3, hz_out4, hz_out5);

        dst1 = AVC_CALC_DPADD_H_6PIX_2COEFF_R_SH(hz_out1, hz_out2, hz_out3,

                                                 hz_out4, hz_out5, hz_out6);

        dst2 = AVC_CALC_DPADD_H_6PIX_2COEFF_R_SH(hz_out2, hz_out3, hz_out4,

                                                 hz_out5, hz_out6, hz_out7);

        dst3 = AVC_CALC_DPADD_H_6PIX_2COEFF_R_SH(hz_out3, hz_out4, hz_out5,

                                                 hz_out6, hz_out7, hz_out8);

        PCKEV_B2_SB(dst1, dst0, dst3, dst2, src0, src1);

        XORI_B2_128_SB(src0, src1);

        ST4x4_UB(src0, src1, 0, 2, 0, 2, dst, dst_stride);

        dst += (4 * dst_stride);

        hz_out0 = hz_out4;

        hz_out1 = hz_out5;

        hz_out2 = hz_out6;

        hz_out3 = hz_out7;

        hz_out4 = hz_out8;

    }

}


static int svq1_motion_inter_4v_block(MpegEncContext *s, GetBitContext *bitbuf,

                                      uint8_t *current, uint8_t *previous,

                                      int pitch, svq1_pmv *motion, int x, int y)

{

    uint8_t *src;

    uint8_t *dst;

    svq1_pmv mv;

    svq1_pmv *pmv[4];

    int i, result;

    /* predict and decode motion vector (0) */

    pmv[0] = &motion[0];

    if (y == 0) {

        pmv[1] =

        pmv[2] = pmv[0];

    } else {

        pmv[1] = &motion[(x / 8) + 2];

        pmv[2] = &motion[(x / 8) + 4];

    }

    result = svq1_decode_motion_vector(bitbuf, &mv, pmv);

    if (result != 0)

        return result;

    /* predict and decode motion vector (1) */

    pmv[0] = &mv;

    if (y == 0) {

        pmv[1] =

        pmv[2] = pmv[0];

    } else {

        pmv[1] = &motion[(x / 8) + 3];

    }

    result = svq1_decode_motion_vector(bitbuf, &motion[0], pmv);

    if (result != 0)

        return result;

    /* predict and decode motion vector (2) */

    pmv[1] = &motion[0];

    pmv[2] = &motion[(x / 8) + 1];

    result = svq1_decode_motion_vector(bitbuf, &motion[(x / 8) + 2], pmv);

    if (result != 0)

        return result;

    /* predict and decode motion vector (3) */

    pmv[2] = &motion[(x / 8) + 2];

    pmv[3] = &motion[(x / 8) + 3];

    result = svq1_decode_motion_vector(bitbuf, pmv[3], pmv);

    if (result != 0)

        return result;

    /* form predictions */

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

        int mvx = pmv[i]->x + (i  & 1) * 16;

        int mvy = pmv[i]->y + (i >> 1) * 16;

        // FIXME: clipping or padding?

        if (y + (mvy >> 1) < 0)

            mvy = 0;

        if (x + (mvx >> 1) < 0)

            mvx = 0;

        src = &previous[(x + (mvx >> 1)) + (y + (mvy >> 1)) * pitch];

        dst = current;

        s->dsp.put_pixels_tab[1][((mvy & 1) << 1) | (mvx & 1)](dst, src, pitch, 8);

        /* select next block */

        if (i & 1)

            current += 8 * (pitch - 1);

        else

            current += 8;

    }

    return 0;

}


int ff_avc_parse_nal_units(AVIOContext *pb, const uint8_t *buf_in, int size)

{

    const uint8_t *p = buf_in;

    const uint8_t *end = p + size;

    const uint8_t *nal_start, *nal_end;

    size = 0;

    nal_start = ff_avc_find_startcode(p, end);

    while (nal_start < end) {

        while(!*(nal_start++));

        nal_end = ff_avc_find_startcode(nal_start, end);

        avio_wb32(pb, nal_end - nal_start);

        avio_write(pb, nal_start, nal_end - nal_start);

        size += 4 + nal_end - nal_start;

        nal_start = nal_end;

    }

    return size;

}


static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx,

                      const uint8_t **poutbuf, int *poutbuf_size,

                      const uint8_t *buf, int buf_size)

{

    FLACParseContext *fpc = s->priv_data;

    FLACHeaderMarker *curr;

    int nb_headers;

    int read_size = 0;

    if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {

        FLACFrameInfo fi;

        if (frame_header_is_valid(avctx, buf, &fi))

            avctx->frame_size = fi.blocksize;

        *poutbuf      = buf;

        *poutbuf_size = buf_size;

        return buf_size;

    }

    fpc->avctx = avctx;

    if (fpc->best_header_valid)

        return get_best_header(fpc, poutbuf, poutbuf_size);

    /* If a best_header was found last call remove it with the buffer data. */

    if (fpc->best_header && fpc->best_header->best_child) {

        FLACHeaderMarker *temp;

        FLACHeaderMarker *best_child = fpc->best_header->best_child;

        /* Remove headers in list until the end of the best_header. */

        for (curr = fpc->headers; curr != best_child; curr = temp) {

            if (curr != fpc->best_header) {

                av_log(avctx, AV_LOG_DEBUG,

                       "dropping low score %i frame header from offset %i to %i\n",

                       curr->max_score, curr->offset, curr->next->offset);

            }

            temp = curr->next;

            av_freep(&curr->link_penalty);

            av_free(curr);

            fpc->nb_headers_buffered--;

        }

        /* Release returned data from ring buffer. */

        av_fifo_drain(fpc->fifo_buf, best_child->offset);

        /* Fix the offset for the headers remaining to match the new buffer. */

        for (curr = best_child->next; curr; curr = curr->next)

            curr->offset -= best_child->offset;

        fpc->nb_headers_buffered--;

        best_child->offset = 0;

        fpc->headers       = best_child;

        if (fpc->nb_headers_buffered >= FLAC_MIN_HEADERS) {

            fpc->best_header = best_child;

            return get_best_header(fpc, poutbuf, poutbuf_size);

        }

        fpc->best_header   = NULL;

    } else if (fpc->best_header) {

        /* No end frame no need to delete the buffer; probably eof */

        FLACHeaderMarker *temp;

        for (curr = fpc->headers; curr != fpc->best_header; curr = temp) {

            temp = curr->next;

            av_freep(&curr->link_penalty);

            av_free(curr);

        }

        fpc->headers = fpc->best_header->next;

        av_freep(&fpc->best_header->link_penalty);

        av_freep(&fpc->best_header);

    }

    /* Find and score new headers. */

    if (buf_size || !fpc->end_padded) {

        int start_offset;

        /* Pad the end once if EOF, to check the final region for headers. */

        if (!buf_size) {

            fpc->end_padded      = 1;

            buf_size = read_size = MAX_FRAME_HEADER_SIZE;

        } else {

            /* The maximum read size is the upper-bound of what the parser

               needs to have the required number of frames buffered */

            int nb_desired = FLAC_MIN_HEADERS - fpc->nb_headers_buffered + 1;

            read_size = FFMIN(buf_size, nb_desired * FLAC_AVG_FRAME_SIZE);

        }

        /* Fill the buffer. */

        if (av_fifo_realloc2(fpc->fifo_buf,

                             read_size + av_fifo_size(fpc->fifo_buf)) < 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "couldn't reallocate buffer of size %d\n",

                   read_size + av_fifo_size(fpc->fifo_buf));

            goto handle_error;

        }

        if (buf) {

            av_fifo_generic_write(fpc->fifo_buf, (void*) buf, read_size, NULL);

        } else {

            int8_t pad[MAX_FRAME_HEADER_SIZE];

            memset(pad, 0, sizeof(pad));

            av_fifo_generic_write(fpc->fifo_buf, (void*) pad, sizeof(pad), NULL);

        }

        /* Tag headers and update sequences. */

        start_offset = av_fifo_size(fpc->fifo_buf) -

                       (read_size + (MAX_FRAME_HEADER_SIZE - 1));

        start_offset = FFMAX(0, start_offset);

        nb_headers   = find_new_headers(fpc, start_offset);

        if (nb_headers < 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "find_new_headers couldn't allocate FLAC header\n");

            goto handle_error;

        }

        fpc->nb_headers_buffered = nb_headers;

        /* Wait till FLAC_MIN_HEADERS to output a valid frame. */

        if (!fpc->end_padded && fpc->nb_headers_buffered < FLAC_MIN_HEADERS)

            goto handle_error;

        /* If headers found, update the scores since we have longer chains. */

        if (fpc->end_padded || fpc->nb_headers_found)

            score_sequences(fpc);

        /* restore the state pre-padding */

        if (fpc->end_padded) {

            /* HACK: drain the tail of the fifo */

            fpc->fifo_buf->wptr -= MAX_FRAME_HEADER_SIZE;

            fpc->fifo_buf->wndx -= MAX_FRAME_HEADER_SIZE;

            if (fpc->fifo_buf->wptr < 0) {

                fpc->fifo_buf->wptr += fpc->fifo_buf->end -

                    fpc->fifo_buf->buffer;

            }

            buf_size = read_size = 0;

        }

    }

    curr = fpc->headers;

    for (curr = fpc->headers; curr; curr = curr->next)

        if (!fpc->best_header || curr->max_score > fpc->best_header->max_score)

            fpc->best_header = curr;

    if (fpc->best_header) {

        fpc->best_header_valid = 1;

        if (fpc->best_header->offset > 0) {

            /* Output a junk frame. */

            av_log(avctx, AV_LOG_DEBUG, "Junk frame till offset %i\n",

                   fpc->best_header->offset);

            /* Set frame_size to 0. It is unknown or invalid in a junk frame. */

            avctx->frame_size = 0;

            *poutbuf_size     = fpc->best_header->offset;

            *poutbuf          = flac_fifo_read_wrap(fpc, 0, *poutbuf_size,

                                                    &fpc->wrap_buf,

                                                    &fpc->wrap_buf_allocated_size);

            return buf_size ? read_size : (fpc->best_header->offset -

                                           av_fifo_size(fpc->fifo_buf));

        }

        if (!buf_size)

            return get_best_header(fpc, poutbuf, poutbuf_size);

    }

handle_error:

    *poutbuf      = NULL;

    *poutbuf_size = 0;

    return read_size;

}


void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)

{

    if (s->chr_read) {

        s->chr_read(s->handler_opaque, buf, len);

    }

}


tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcpiphdr *ti)

{

	uint16_t mss;

	int opt, optlen;

	DEBUG_CALL("tcp_dooptions");

	DEBUG_ARGS((dfd," tp = %lx  cnt=%i \n", (long )tp, cnt));

	for (; cnt > 0; cnt -= optlen, cp += optlen) {

		opt = cp[0];

		if (opt == TCPOPT_EOL)

			break;

		if (opt == TCPOPT_NOP)

			optlen = 1;

		else {

			optlen = cp[1];

			if (optlen <= 0)

				break;

		}

		switch (opt) {

		default:

			continue;

		case TCPOPT_MAXSEG:

			if (optlen != TCPOLEN_MAXSEG)

				continue;

			if (!(ti->ti_flags & TH_SYN))

				continue;

			memcpy((char *) &mss, (char *) cp + 2, sizeof(mss));

			NTOHS(mss);

			(void) tcp_mss(tp, mss);	/* sets t_maxseg */

			break;

		}

	}

}


static void test_qemu_strtoull_hex(void)

{

    const char *str = "0123";

    char f = 'X';

    const char *endptr = &f;

    uint64_t res = 999;

    int err;

    err = qemu_strtoull(str, &endptr, 16, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 0x123);

    g_assert(endptr == str + strlen(str));

    str = "0x123";

    endptr = &f;

    res = 999;

    err = qemu_strtoull(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 0x123);

    g_assert(endptr == str + strlen(str));

}


static inline void RENAME(yuy2ToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, int width)

{

#ifdef HAVE_MMXFIXME

#else

	int i;

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

	{

		dstU[i]= (src1[4*i + 1] + src2[4*i + 1])>>1;

		dstV[i]= (src1[4*i + 3] + src2[4*i + 3])>>1;

	}

#endif

}


static inline void RENAME(rgb15to32)(const uint8_t *src, uint8_t *dst, long src_size)

{

    const uint16_t *end;

#if COMPILE_TEMPLATE_MMX

    const uint16_t *mm_end;

#endif

    uint8_t *d = dst;

    const uint16_t *s = (const uint16_t *)src;

    end = s + src_size/2;

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");

    __asm__ volatile("pxor    %%mm7,%%mm7    \n\t":::"memory");

    __asm__ volatile("pcmpeqd %%mm6,%%mm6    \n\t":::"memory");

    mm_end = end - 3;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

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

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

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

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

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

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

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

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

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

            PACK_RGB32

            :"=m"(*d)

            :"m"(*s),"m"(mask15b),"m"(mask15g),"m"(mask15r)

            :"memory");

        d += 16;

        s += 4;

    }

    __asm__ volatile(SFENCE:::"memory");

    __asm__ volatile(EMMS:::"memory");

#endif

    while (s < end) {

        register uint16_t bgr;

        bgr = *s++;

#if HAVE_BIGENDIAN

        *d++ = 255;

        *d++ = (bgr&0x7C00)>>7;

        *d++ = (bgr&0x3E0)>>2;

        *d++ = (bgr&0x1F)<<3;

#else

        *d++ = (bgr&0x1F)<<3;

        *d++ = (bgr&0x3E0)>>2;

        *d++ = (bgr&0x7C00)>>7;

        *d++ = 255;

#endif

    }

}


static int qcow_create(const char *filename, QEMUOptionParameter *options)

{

    const char *backing_file = NULL;

    const char *backing_fmt = NULL;

    uint64_t sectors = 0;

    int flags = 0;

    size_t cluster_size = 65536;

    int prealloc = 0;

    /* Read out options */

    while (options && options->name) {

        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {

            sectors = options->value.n / 512;

        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {

            backing_file = options->value.s;

        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {

            backing_fmt = options->value.s;

        } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {

            flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;

        } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {

            if (options->value.n) {

                cluster_size = options->value.n;

            }

        } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {

            if (!options->value.s || !strcmp(options->value.s, "off")) {

                prealloc = 0;

            } else if (!strcmp(options->value.s, "metadata")) {

                prealloc = 1;

            } else {

                fprintf(stderr, "Invalid preallocation mode: '%s'\n",

                    options->value.s);

                return -EINVAL;

            }

        }

        options++;

    }

    if (backing_file && prealloc) {

        fprintf(stderr, "Backing file and preallocation cannot be used at "

            "the same time\n");

        return -EINVAL;

    }

    return qcow_create2(filename, sectors, backing_file, backing_fmt, flags,

        cluster_size, prealloc);

}


void do_interrupt(CPUState *env)

{

	int ex_vec = -1;

	D(fprintf (stderr, "exception index=%d interrupt_req=%d\n",

		   env->exception_index,

		   env->interrupt_request));

	switch (env->exception_index)

	{

		case EXCP_BREAK:

			/* These exceptions are genereated by the core itself.

			   ERP should point to the insn following the brk.  */

			ex_vec = env->trap_vector;

			env->pregs[PR_ERP] = env->pc + 2;

			break;

		case EXCP_MMU_FAULT:

			ex_vec = env->fault_vector;

			env->pregs[PR_ERP] = env->pc;

			break;

		default:

			/* Is the core accepting interrupts?  */

			if (!(env->pregs[PR_CCS] & I_FLAG))

				return;

			/* The interrupt controller gives us the

			   vector.  */

			ex_vec = env->interrupt_vector;

			/* Normal interrupts are taken between

			   TB's.  env->pc is valid here.  */

			env->pregs[PR_ERP] = env->pc;

			break;

	}

	if ((env->pregs[PR_CCS] & U_FLAG)) {

		D(fprintf(logfile, "excp isr=%x PC=%x ERP=%x pid=%x ccs=%x cc=%d %x\n",

			  ex_vec, env->pc,

			  env->pregs[PR_ERP], env->pregs[PR_PID],

			  env->pregs[PR_CCS],

			  env->cc_op, env->cc_mask));

	}

	env->pc = ldl_code(env->pregs[PR_EBP] + ex_vec * 4);

	if (env->pregs[PR_CCS] & U_FLAG) {

		/* Swap stack pointers.  */

		env->pregs[PR_USP] = env->regs[R_SP];

		env->regs[R_SP] = env->ksp;

	}

	/* Apply the CRIS CCS shift. Clears U if set.  */

	cris_shift_ccs(env);

	D(fprintf (logfile, "%s isr=%x vec=%x ccs=%x pid=%d erp=%x\n",

		   __func__, env->pc, ex_vec,

		   env->pregs[PR_CCS],

		   env->pregs[PR_PID],

		   env->pregs[PR_ERP]));

}


void *qemu_blockalign0(BlockDriverState *bs, size_t size)

{

    return memset(qemu_blockalign(bs, size), 0, size);

}


static void t_gen_asr(TCGv d, TCGv a, TCGv b)

{

	TCGv t0, t_31;

	t0 = tcg_temp_new(TCG_TYPE_TL);

	t_31 = tcg_temp_new(TCG_TYPE_TL);

	tcg_gen_sar_tl(d, a, b);

	tcg_gen_movi_tl(t_31, 31);

	tcg_gen_sub_tl(t0, t_31, b);

	tcg_gen_sar_tl(t0, t0, t_31);

	tcg_gen_or_tl(d, d, t0);

	tcg_temp_free(t0);

	tcg_temp_free(t_31);

}


static inline uint64_t do_fri(uint64_t arg, int rounding_mode)

{

    CPU_DoubleU farg;

    farg.ll = arg;

    if (unlikely(float64_is_signaling_nan(farg.d))) {

        /* sNaN round */

        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN | POWERPC_EXCP_FP_VXCVI);

    } else if (unlikely(float64_is_nan(farg.d) || float64_is_infinity(farg.d))) {

        /* qNan / infinity round */

        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);

    } else {

        set_float_rounding_mode(rounding_mode, &env->fp_status);

        farg.ll = float64_round_to_int(farg.d, &env->fp_status);

        /* Restore rounding mode from FPSCR */

        fpscr_set_rounding_mode();

    }

    return farg.ll;

}


static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)

{

    PCIDevice *pci_dev = (PCIDevice *)qdev;

    PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);

    PCIBus *bus;

    int devfn, rc;

    /* initialize cap_present for pci_is_express() and pci_config_size() */

    if (info->is_express) {

        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;

    }

    bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));

    devfn = pci_dev->devfn;

    pci_dev = do_pci_register_device(pci_dev, bus, base->name, devfn,

                                     info->config_read, info->config_write);

    assert(pci_dev);

    rc = info->init(pci_dev);

    if (rc != 0)

        return rc;

    if (qdev->hotplugged)

        bus->hotplug(pci_dev, 1);

    return 0;

}


static inline void bit_copy(PutBitContext *pb, GetBitContext *gb)

{

    int bits_left = get_bits_left(gb);

    while (bits_left >= 16) {

        put_bits(pb, 16, get_bits(gb, 16));

        bits_left -= 16;

    }

    if (bits_left > 0) {

        put_bits(pb, bits_left, get_bits(gb, bits_left));

    }

}


static int coroutine_fn v9fs_mark_fids_unreclaim(V9fsPDU *pdu, V9fsPath *path)

{

    int err;

    V9fsState *s = pdu->s;

    V9fsFidState *fidp, head_fid;

    head_fid.next = s->fid_list;

    for (fidp = s->fid_list; fidp; fidp = fidp->next) {

        if (fidp->path.size != path->size) {

            continue;

        }

        if (!memcmp(fidp->path.data, path->data, path->size)) {

            /* Mark the fid non reclaimable. */

            fidp->flags |= FID_NON_RECLAIMABLE;

            /* reopen the file/dir if already closed */

            err = v9fs_reopen_fid(pdu, fidp);

            if (err < 0) {

                return -1;

            }

            /*

             * Go back to head of fid list because

             * the list could have got updated when

             * switched to the worker thread

             */

            if (err == 0) {

                fidp = &head_fid;

            }

        }

    }

    return 0;

}


float64 helper_fabs_DT(float64 t0)

{

    return float64_abs(t0);

}


static long gethugepagesize(const char *path, Error **errp)

{

    struct statfs fs;

    int ret;

    do {

        ret = statfs(path, &fs);

    } while (ret != 0 && errno == EINTR);

    if (ret != 0) {

        error_setg_errno(errp, errno, "failed to get page size of file %s",

                         path);

        return 0;

    }

    if (!qtest_driver() &&

        fs.f_type != HUGETLBFS_MAGIC) {

        fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);

    }

    return fs.f_bsize;

}


static void gen_sllq(DisasContext *ctx)

{

    int l1 = gen_new_label();

    int l2 = gen_new_label();

    TCGv t0 = tcg_temp_local_new();

    TCGv t1 = tcg_temp_local_new();

    TCGv t2 = tcg_temp_local_new();

    tcg_gen_andi_tl(t2, cpu_gpr[rB(ctx->opcode)], 0x1F);

    tcg_gen_movi_tl(t1, 0xFFFFFFFF);

    tcg_gen_shl_tl(t1, t1, t2);

    tcg_gen_andi_tl(t0, cpu_gpr[rB(ctx->opcode)], 0x20);

    tcg_gen_brcondi_tl(TCG_COND_EQ, t0, 0, l1);

    gen_load_spr(t0, SPR_MQ);

    tcg_gen_and_tl(cpu_gpr[rA(ctx->opcode)], t0, t1);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_shl_tl(t0, cpu_gpr[rS(ctx->opcode)], t2);

    gen_load_spr(t2, SPR_MQ);

    tcg_gen_andc_tl(t1, t2, t1);

    tcg_gen_or_tl(cpu_gpr[rA(ctx->opcode)], t0, t1);

    gen_set_label(l2);

    tcg_temp_free(t0);

    tcg_temp_free(t1);

    tcg_temp_free(t2);

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, cpu_gpr[rA(ctx->opcode)]);

}


static void raw_eject(BlockDriverState *bs, bool eject_flag)

{

    bdrv_eject(bs->file->bs, eject_flag);

}


int acpi_add_cpu_info(Object *o, void *opaque)

{

    AcpiCpuInfo *cpu = opaque;

    uint64_t apic_id;

    if (object_dynamic_cast(o, TYPE_CPU)) {

        apic_id = object_property_get_int(o, "apic-id", NULL);

        assert(apic_id <= MAX_CPUMASK_BITS);

        set_bit(apic_id, cpu->found_cpus);

    }

    object_child_foreach(o, acpi_add_cpu_info, opaque);

    return 0;

}


int ff_listen_bind(int fd, const struct sockaddr *addr,

                   socklen_t addrlen, int timeout, URLContext *h)

{

    int ret;

    int reuse = 1;

    struct pollfd lp = { fd, POLLIN, 0 };

    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))) {

        av_log(NULL, AV_LOG_WARNING, "setsockopt(SO_REUSEADDR) failed\n");

    }

    ret = bind(fd, addr, addrlen);

    if (ret)

        return ff_neterrno();

    ret = listen(fd, 1);

    if (ret)

        return ff_neterrno();

    ret = ff_poll_interrupt(&lp, 1, timeout, &h->interrupt_callback);

    if (ret < 0)

        return ret;

    ret = accept(fd, NULL, NULL);

    if (ret < 0)

        return ff_neterrno();

    closesocket(fd);

    ff_socket_nonblock(ret, 1);

    return ret;

}


static uint64_t vtd_get_iotlb_key(uint64_t gfn, uint8_t source_id,

                                  uint32_t level)

{

    return gfn | ((uint64_t)(source_id) << VTD_IOTLB_SID_SHIFT) |

           ((uint64_t)(level) << VTD_IOTLB_LVL_SHIFT);

}


static int chr_can_read(void *opaque)

{

    SCLPConsole *scon = opaque;

    return SIZE_BUFFER_VT220 - scon->iov_data_len;

}


static void virtio_scsi_do_tmf(VirtIOSCSI *s, VirtIOSCSIReq *req)

{

    SCSIDevice *d = virtio_scsi_device_find(s, req->req.tmf->lun);

    SCSIRequest *r, *next;

    BusChild *kid;

    int target;

    /* Here VIRTIO_SCSI_S_OK means "FUNCTION COMPLETE".  */

    req->resp.tmf->response = VIRTIO_SCSI_S_OK;

    tswap32s(&req->req.tmf->subtype);

    switch (req->req.tmf->subtype) {

    case VIRTIO_SCSI_T_TMF_ABORT_TASK:

    case VIRTIO_SCSI_T_TMF_QUERY_TASK:

        if (!d) {

            goto fail;

        }

        if (d->lun != virtio_scsi_get_lun(req->req.tmf->lun)) {

            goto incorrect_lun;

        }

        QTAILQ_FOREACH_SAFE(r, &d->requests, next, next) {

            VirtIOSCSIReq *cmd_req = r->hba_private;

            if (cmd_req && cmd_req->req.cmd->tag == req->req.tmf->tag) {

                break;

            }

        }

        if (r) {

            /*

             * Assert that the request has not been completed yet, we

             * check for it in the loop above.

             */

            assert(r->hba_private);

            if (req->req.tmf->subtype == VIRTIO_SCSI_T_TMF_QUERY_TASK) {

                /* "If the specified command is present in the task set, then

                 * return a service response set to FUNCTION SUCCEEDED".

                 */

                req->resp.tmf->response = VIRTIO_SCSI_S_FUNCTION_SUCCEEDED;

            } else {

                scsi_req_cancel(r);

            }

        }

        break;

    case VIRTIO_SCSI_T_TMF_LOGICAL_UNIT_RESET:

        if (!d) {

            goto fail;

        }

        if (d->lun != virtio_scsi_get_lun(req->req.tmf->lun)) {

            goto incorrect_lun;

        }

        s->resetting++;

        qdev_reset_all(&d->qdev);

        s->resetting--;

        break;

    case VIRTIO_SCSI_T_TMF_ABORT_TASK_SET:

    case VIRTIO_SCSI_T_TMF_CLEAR_TASK_SET:

    case VIRTIO_SCSI_T_TMF_QUERY_TASK_SET:

        if (!d) {

            goto fail;

        }

        if (d->lun != virtio_scsi_get_lun(req->req.tmf->lun)) {

            goto incorrect_lun;

        }

        QTAILQ_FOREACH_SAFE(r, &d->requests, next, next) {

            if (r->hba_private) {

                if (req->req.tmf->subtype == VIRTIO_SCSI_T_TMF_QUERY_TASK_SET) {

                    /* "If there is any command present in the task set, then

                     * return a service response set to FUNCTION SUCCEEDED".

                     */

                    req->resp.tmf->response = VIRTIO_SCSI_S_FUNCTION_SUCCEEDED;

                    break;

                } else {

                    scsi_req_cancel(r);

                }

            }

        }

        break;

    case VIRTIO_SCSI_T_TMF_I_T_NEXUS_RESET:

        target = req->req.tmf->lun[1];

        s->resetting++;

        QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {

             d = DO_UPCAST(SCSIDevice, qdev, kid->child);

             if (d->channel == 0 && d->id == target) {

                qdev_reset_all(&d->qdev);

             }

        }

        s->resetting--;

        break;

    case VIRTIO_SCSI_T_TMF_CLEAR_ACA:

    default:

        req->resp.tmf->response = VIRTIO_SCSI_S_FUNCTION_REJECTED;

        break;

    }

    return;

incorrect_lun:

    req->resp.tmf->response = VIRTIO_SCSI_S_INCORRECT_LUN;

    return;

fail:

    req->resp.tmf->response = VIRTIO_SCSI_S_BAD_TARGET;

}


int iommu_dma_memory_set(DMAContext *dma, dma_addr_t addr, uint8_t c,

                         dma_addr_t len)

{

    target_phys_addr_t paddr, plen;

    int err;

#ifdef DEBUG_IOMMU

    fprintf(stderr, "dma_memory_set context=%p addr=0x" DMA_ADDR_FMT

            " len=0x" DMA_ADDR_FMT "\n", dma, addr, len);

#endif

    while (len) {

        err = dma->translate(dma, addr, &paddr, &plen,

                             DMA_DIRECTION_FROM_DEVICE);

        if (err) {

            return err;

        }

        /* The translation might be valid for larger regions. */

        if (plen > len) {

            plen = len;

        }

        do_dma_memory_set(dma->as, paddr, c, plen);

        len -= plen;

        addr += plen;

    }

    return 0;

}


static void ppc6xx_set_irq (void *opaque, int pin, int level)

{

    CPUState *env = opaque;

    int cur_level;

#if defined(PPC_DEBUG_IRQ)

    if (loglevel & CPU_LOG_INT) {

        fprintf(logfile, "%s: env %p pin %d level %d\n", __func__,

                env, pin, level);

    }

#endif

    cur_level = (env->irq_input_state >> pin) & 1;

    /* Don't generate spurious events */

    if ((cur_level == 1 && level == 0) || (cur_level == 0 && level != 0)) {

        switch (pin) {

        case PPC6xx_INPUT_INT:

            /* Level sensitive - active high */

#if defined(PPC_DEBUG_IRQ)

            if (loglevel & CPU_LOG_INT) {

                fprintf(logfile, "%s: set the external IRQ state to %d\n",

                        __func__, level);

            }

#endif

            ppc_set_irq(env, PPC_INTERRUPT_EXT, level);

            break;

        case PPC6xx_INPUT_SMI:

            /* Level sensitive - active high */

#if defined(PPC_DEBUG_IRQ)

            if (loglevel & CPU_LOG_INT) {

                fprintf(logfile, "%s: set the SMI IRQ state to %d\n",

                        __func__, level);

            }

#endif

            ppc_set_irq(env, PPC_INTERRUPT_SMI, level);

            break;

        case PPC6xx_INPUT_MCP:

            /* Negative edge sensitive */

            /* XXX: TODO: actual reaction may depends on HID0 status

             *            603/604/740/750: check HID0[EMCP]

             */

            if (cur_level == 1 && level == 0) {

#if defined(PPC_DEBUG_IRQ)

                if (loglevel & CPU_LOG_INT) {

                    fprintf(logfile, "%s: raise machine check state\n",

                            __func__);

                }

#endif

                ppc_set_irq(env, PPC_INTERRUPT_MCK, 1);

            }

            break;

        case PPC6xx_INPUT_CKSTP_IN:

            /* Level sensitive - active low */

            /* XXX: TODO: relay the signal to CKSTP_OUT pin */

            if (level) {

#if defined(PPC_DEBUG_IRQ)

                if (loglevel & CPU_LOG_INT) {

                    fprintf(logfile, "%s: stop the CPU\n", __func__);

                }

#endif

                env->halted = 1;

            } else {

#if defined(PPC_DEBUG_IRQ)

                if (loglevel & CPU_LOG_INT) {

                    fprintf(logfile, "%s: restart the CPU\n", __func__);

                }

#endif

                env->halted = 0;

            }

            break;

        case PPC6xx_INPUT_HRESET:

            /* Level sensitive - active low */

            if (level) {

#if 0 // XXX: TOFIX

#if defined(PPC_DEBUG_IRQ)

                if (loglevel & CPU_LOG_INT) {

                    fprintf(logfile, "%s: reset the CPU\n", __func__);

                }

#endif

                cpu_reset(env);

#endif

            }

            break;

        case PPC6xx_INPUT_SRESET:

#if defined(PPC_DEBUG_IRQ)

            if (loglevel & CPU_LOG_INT) {

                fprintf(logfile, "%s: set the RESET IRQ state to %d\n",

                        __func__, level);

            }

#endif

            ppc_set_irq(env, PPC_INTERRUPT_RESET, level);

            break;

        default:

            /* Unknown pin - do nothing */

#if defined(PPC_DEBUG_IRQ)

            if (loglevel & CPU_LOG_INT) {

                fprintf(logfile, "%s: unknown IRQ pin %d\n", __func__, pin);

            }

#endif

            return;

        }

        if (level)

            env->irq_input_state |= 1 << pin;

        else

            env->irq_input_state &= ~(1 << pin);

    }

}


static void sdp_service_record_build(struct sdp_service_record_s *record,

                struct sdp_def_service_s *def, int handle)

{

    int len = 0;

    uint8_t *data;

    int *uuid;

    record->uuids = 0;

    while (def->attributes[record->attributes].data.type) {

        len += 3;

        len += sdp_attr_max_size(&def->attributes[record->attributes ++].data,

                        &record->uuids);

    }

    record->uuids = pow2ceil(record->uuids);

    record->attribute_list =

            g_malloc0(record->attributes * sizeof(*record->attribute_list));

    record->uuid =

            g_malloc0(record->uuids * sizeof(*record->uuid));

    data = g_malloc(len);

    record->attributes = 0;

    uuid = record->uuid;

    while (def->attributes[record->attributes].data.type) {

        record->attribute_list[record->attributes].pair = data;

        len = 0;

        data[len ++] = SDP_DTYPE_UINT | SDP_DSIZE_2;

        data[len ++] = def->attributes[record->attributes].id >> 8;

        data[len ++] = def->attributes[record->attributes].id & 0xff;

        len += sdp_attr_write(data + len,

                        &def->attributes[record->attributes].data, &uuid);

        /* Special case: assign a ServiceRecordHandle in sequence */

        if (def->attributes[record->attributes].id == SDP_ATTR_RECORD_HANDLE)

            def->attributes[record->attributes].data.value.uint = handle;

        /* Note: we could also assign a ServiceDescription based on

         * sdp->device.device->lmp_name.  */

        record->attribute_list[record->attributes ++].len = len;

        data += len;

    }

    /* Sort the attribute list by the AttributeID */

    qsort(record->attribute_list, record->attributes,

                    sizeof(*record->attribute_list),

                    (void *) sdp_attributeid_compare);

    /* Sort the searchable UUIDs list for bisection */

    qsort(record->uuid, record->uuids,

                    sizeof(*record->uuid),

                    (void *) sdp_uuid_compare);

}


static int skip_check(MpegEncContext *s, Picture *p, Picture *ref)

{

    int x, y, plane;

    int score = 0;

    int64_t score64 = 0;

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

        const int stride = p->f.linesize[plane];

        const int bw = plane ? 1 : 2;

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

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

                int off = p->shared ? 0 : 16;

                uint8_t *dptr = p->f.data[plane] + 8 * (x + y * stride) + off;

                uint8_t *rptr = ref->f.data[plane] + 8 * (x + y * stride);

                int v   = s->dsp.frame_skip_cmp[1](s, dptr, rptr, stride, 8);

                switch (s->avctx->frame_skip_exp) {

                case 0: score    =  FFMAX(score, v);          break;

                case 1: score   += FFABS(v);                  break;

                case 2: score   += v * v;                     break;

                case 3: score64 += FFABS(v * v * (int64_t)v); break;

                case 4: score64 += v * v * (int64_t)(v * v);  break;

                }

            }

        }

    }

    if (score)

        score64 = score;

    if (score64 < s->avctx->frame_skip_threshold)

        return 1;

    if (score64 < ((s->avctx->frame_skip_factor * (int64_t)s->lambda) >> 8))

        return 1;

    return 0;

}


int ff_slice_thread_init(AVCodecContext *avctx)

{

    int i;

    SliceThreadContext *c;

    int thread_count = avctx->thread_count;

#if HAVE_W32THREADS

    w32thread_init();

#endif

    // We cannot do this in the encoder init as the threads are created before

    if (av_codec_is_encoder(avctx->codec) &&

        avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO &&

        avctx->height > 2800)

        thread_count = avctx->thread_count = 1;

    if (!thread_count) {

        int nb_cpus = av_cpu_count();

        if  (avctx->height)

            nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);

        // use number of cores + 1 as thread count if there is more than one

        if (nb_cpus > 1)

            thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);

        else

            thread_count = avctx->thread_count = 1;

    }

    if (thread_count <= 1) {

        avctx->active_thread_type = 0;

        return 0;

    }

    c = av_mallocz(sizeof(SliceThreadContext));

    if (!c)

        return -1;

    c->workers = av_mallocz_array(thread_count, sizeof(pthread_t));

    if (!c->workers) {

        av_free(c);

        return -1;

    }

    avctx->internal->thread_ctx = c;

    c->current_job = 0;

    c->job_count = 0;

    c->job_size = 0;

    c->done = 0;

    pthread_cond_init(&c->current_job_cond, NULL);

    pthread_cond_init(&c->last_job_cond, NULL);

    pthread_mutex_init(&c->current_job_lock, NULL);

    pthread_mutex_lock(&c->current_job_lock);

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

        if(pthread_create(&c->workers[i], NULL, worker, avctx)) {

           avctx->thread_count = i;

           pthread_mutex_unlock(&c->current_job_lock);

           ff_thread_free(avctx);

           return -1;

        }

    }

    thread_park_workers(c, thread_count);

    avctx->execute = thread_execute;

    avctx->execute2 = thread_execute2;

    return 0;

}


int ff_mpa_decode_header(AVCodecContext *avctx, uint32_t head, int *sample_rate)

{

    MPADecodeContext s1, *s = &s1;

    s1.avctx = avctx;

    if (ff_mpa_check_header(head) != 0)

        return -1;

    if (ff_mpegaudio_decode_header(s, head) != 0) {

        return -1;

    }

    switch(s->layer) {

    case 1:

        avctx->frame_size = 384;

        break;

    case 2:

        avctx->frame_size = 1152;

        break;

    default:

    case 3:

        if (s->lsf)

            avctx->frame_size = 576;

        else

            avctx->frame_size = 1152;

        break;

    }

    *sample_rate = s->sample_rate;

    avctx->channels = s->nb_channels;

    avctx->bit_rate = s->bit_rate;

    avctx->sub_id = s->layer;

    return s->frame_size;

}


int ff_vaapi_decode_init(AVCodecContext *avctx)

{

    VAAPIDecodeContext *ctx = avctx->internal->hwaccel_priv_data;

    VAStatus vas;

    int err;

    ctx->va_config  = VA_INVALID_ID;

    ctx->va_context = VA_INVALID_ID;

#if FF_API_VAAPI_CONTEXT

    if (avctx->hwaccel_context) {

        av_log(avctx, AV_LOG_WARNING, "Using deprecated struct "

               "vaapi_context in decode.\n");

        ctx->have_old_context = 1;

        ctx->old_context = avctx->hwaccel_context;

        // Really we only want the VAAPI device context, but this

        // allocates a whole generic device context because we don't

        // have any other way to determine how big it should be.

        ctx->device_ref =

            av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_VAAPI);

        if (!ctx->device_ref) {

            err = AVERROR(ENOMEM);

            goto fail;

        }

        ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;

        ctx->hwctx  = ctx->device->hwctx;

        ctx->hwctx->display = ctx->old_context->display;

        // The old VAAPI decode setup assumed this quirk was always

        // present, so set it here to avoid the behaviour changing.

        ctx->hwctx->driver_quirks =

            AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS;

    } else

#endif

    if (avctx->hw_frames_ctx) {

        // This structure has a shorter lifetime than the enclosing

        // AVCodecContext, so we inherit the references from there

        // and do not need to make separate ones.

        ctx->frames = (AVHWFramesContext*)avctx->hw_frames_ctx->data;

        ctx->hwfc   = ctx->frames->hwctx;

        ctx->device = ctx->frames->device_ctx;

        ctx->hwctx  = ctx->device->hwctx;

    } else if (avctx->hw_device_ctx) {

        ctx->device = (AVHWDeviceContext*)avctx->hw_device_ctx->data;

        ctx->hwctx  = ctx->device->hwctx;

        if (ctx->device->type != AV_HWDEVICE_TYPE_VAAPI) {

            av_log(avctx, AV_LOG_ERROR, "Device supplied for VAAPI "

                   "decoding must be a VAAPI device (not %d).\n",

                   ctx->device->type);

            err = AVERROR(EINVAL);

            goto fail;

        }

    } else {

        av_log(avctx, AV_LOG_ERROR, "A hardware device or frames context "

               "is required for VAAPI decoding.\n");

        err = AVERROR(EINVAL);

        goto fail;

    }

#if FF_API_VAAPI_CONTEXT

    if (ctx->have_old_context) {

        ctx->va_config  = ctx->old_context->config_id;

        ctx->va_context = ctx->old_context->context_id;

        av_log(avctx, AV_LOG_DEBUG, "Using user-supplied decoder "

               "context: %#x/%#x.\n", ctx->va_config, ctx->va_context);

    } else {

#endif

    err = vaapi_decode_make_config(avctx);

    if (err)

        goto fail;

    if (!avctx->hw_frames_ctx) {

        avctx->hw_frames_ctx = av_hwframe_ctx_alloc(avctx->hw_device_ctx);

        if (!avctx->hw_frames_ctx) {

            err = AVERROR(ENOMEM);

            goto fail;

        }

        ctx->frames = (AVHWFramesContext*)avctx->hw_frames_ctx->data;

        ctx->frames->format = AV_PIX_FMT_VAAPI;

        ctx->frames->width  = avctx->coded_width;

        ctx->frames->height = avctx->coded_height;

        ctx->frames->sw_format         = ctx->surface_format;

        ctx->frames->initial_pool_size = ctx->surface_count;

        err = av_hwframe_ctx_init(avctx->hw_frames_ctx);

        if (err < 0) {

            av_log(avctx, AV_LOG_ERROR, "Failed to initialise internal "

                   "frames context: %d.\n", err);

            goto fail;

        }

        ctx->hwfc = ctx->frames->hwctx;

    }

    vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,

                          avctx->coded_width, avctx->coded_height,

                          VA_PROGRESSIVE,

                          ctx->hwfc->surface_ids,

                          ctx->hwfc->nb_surfaces,

                          &ctx->va_context);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR, "Failed to create decode "

               "context: %d (%s).\n", vas, vaErrorStr(vas));

        err = AVERROR(EIO);

        goto fail;

    }

    av_log(avctx, AV_LOG_DEBUG, "Decode context initialised: "

           "%#x/%#x.\n", ctx->va_config, ctx->va_context);

#if FF_API_VAAPI_CONTEXT

    }

#endif

    return 0;

fail:

    ff_vaapi_decode_uninit(avctx);

    return err;

}


void helper_set_alarm(CPUAlphaState *env, uint64_t expire)

{

    if (expire) {

        env->alarm_expire = expire;

        qemu_mod_timer(env->alarm_timer, expire);

    } else {

        qemu_del_timer(env->alarm_timer);

    }

}


static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)

{

    FrameBuffer  *buf = av_mallocz(sizeof(*buf));

    int i, ret;

    const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;

    int h_chroma_shift, v_chroma_shift;

    int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1

    int w = s->width, h = s->height;

    if (!buf)

        return AVERROR(ENOMEM);

    if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {

        w += 2*edge;

        h += 2*edge;

    }

    avcodec_align_dimensions(s, &w, &h);

    if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,

                              s->pix_fmt, 32)) < 0) {

        av_freep(&buf);

        return ret;

    }

    /* XXX this shouldn't be needed, but some tests break without this line

     * those decoders are buggy and need to be fixed.

     * the following tests fail:

     * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit

     */

    memset(buf->base[0], 128, ret);

    avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);

    for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {

        const int h_shift = i==0 ? 0 : h_chroma_shift;

        const int v_shift = i==0 ? 0 : v_chroma_shift;

        if (s->flags & CODEC_FLAG_EMU_EDGE)

            buf->data[i] = buf->base[i];

        else

            buf->data[i] = buf->base[i] +

                           FFALIGN((buf->linesize[i]*edge >> v_shift) +

                                   (pixel_size*edge >> h_shift), 32);

    }

    buf->w       = s->width;

    buf->h       = s->height;

    buf->pix_fmt = s->pix_fmt;

    buf->pool    = pool;

    *pbuf = buf;

    return 0;

}


static int mxf_set_audio_pts(MXFContext *mxf, AVCodecContext *codec, AVPacket *pkt)

{

    MXFTrack *track = mxf->fc->streams[pkt->stream_index]->priv_data;

    pkt->pts = track->sample_count;

    if (codec->channels <= 0 || av_get_bits_per_sample(codec->codec_id) <= 0)

        return AVERROR(EINVAL);

    track->sample_count += pkt->size / (codec->channels * av_get_bits_per_sample(codec->codec_id) / 8);

    return 0;

}


uint32_t HELPER(sar_cc)(CPUM68KState *env, uint32_t val, uint32_t shift)

{

    uint64_t temp;

    uint32_t result;

    shift &= 63;

    temp = (int64_t)val << 32 >> shift;

    result = temp >> 32;

    env->cc_c = (temp >> 31) & 1;

    env->cc_n = result;

    env->cc_z = result;

    env->cc_v = result ^ val;

    env->cc_x = shift ? env->cc_c : env->cc_x;

    return result;

}


static void build_basic_mjpeg_vlc(MJpegDecodeContext *s)

{

    build_vlc(&s->vlcs[0][0], avpriv_mjpeg_bits_dc_luminance,

              avpriv_mjpeg_val_dc, 12, 0, 0);

    build_vlc(&s->vlcs[0][1], avpriv_mjpeg_bits_dc_chrominance,

              avpriv_mjpeg_val_dc, 12, 0, 0);

    build_vlc(&s->vlcs[1][0], avpriv_mjpeg_bits_ac_luminance,

              avpriv_mjpeg_val_ac_luminance, 251, 0, 1);

    build_vlc(&s->vlcs[1][1], avpriv_mjpeg_bits_ac_chrominance,

              avpriv_mjpeg_val_ac_chrominance, 251, 0, 1);

    build_vlc(&s->vlcs[2][0], avpriv_mjpeg_bits_ac_luminance,

              avpriv_mjpeg_val_ac_luminance, 251, 0, 0);

    build_vlc(&s->vlcs[2][1], avpriv_mjpeg_bits_ac_chrominance,

              avpriv_mjpeg_val_ac_chrominance, 251, 0, 0);

}


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

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    dc->realize = fsl_imx31_realize;

    dc->desc = "i.MX31 SOC";

}


static int dirac_decode_data_unit(AVCodecContext *avctx, const uint8_t *buf, int size)

{

    DiracContext *s   = avctx->priv_data;

    DiracFrame *pic   = NULL;

    AVDiracSeqHeader *dsh;

    int ret, i;

    uint8_t parse_code;

    unsigned tmp;

    if (size < DATA_UNIT_HEADER_SIZE)

        return AVERROR_INVALIDDATA;

    parse_code = buf[4];

    init_get_bits(&s->gb, &buf[13], 8*(size - DATA_UNIT_HEADER_SIZE));

    if (parse_code == DIRAC_PCODE_SEQ_HEADER) {

        if (s->seen_sequence_header)

            return 0;

        /* [DIRAC_STD] 10. Sequence header */

        ret = av_dirac_parse_sequence_header(&dsh, buf + DATA_UNIT_HEADER_SIZE, size - DATA_UNIT_HEADER_SIZE, avctx);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "error parsing sequence header");

            return ret;

        }

        ret = ff_set_dimensions(avctx, dsh->width, dsh->height);

        if (ret < 0) {

            av_freep(&dsh);

            return ret;

        }

        ff_set_sar(avctx, dsh->sample_aspect_ratio);

        avctx->pix_fmt         = dsh->pix_fmt;

        avctx->color_range     = dsh->color_range;

        avctx->color_trc       = dsh->color_trc;

        avctx->color_primaries = dsh->color_primaries;

        avctx->colorspace      = dsh->colorspace;

        avctx->profile         = dsh->profile;

        avctx->level           = dsh->level;

        avctx->framerate       = dsh->framerate;

        s->bit_depth           = dsh->bit_depth;

        s->version.major       = dsh->version.major;

        s->version.minor       = dsh->version.minor;

        s->seq                 = *dsh;

        av_freep(&dsh);

        s->pshift = s->bit_depth > 8;

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

        ret = alloc_sequence_buffers(s);

        if (ret < 0)

            return ret;

        s->seen_sequence_header = 1;

    } else if (parse_code == DIRAC_PCODE_END_SEQ) { /* [DIRAC_STD] End of Sequence */

        free_sequence_buffers(s);

        s->seen_sequence_header = 0;

    } else if (parse_code == DIRAC_PCODE_AUX) {

        if (buf[13] == 1) {     /* encoder implementation/version */

            int ver[3];

            /* versions older than 1.0.8 don't store quant delta for

               subbands with only one codeblock */

            if (sscanf(buf+14, "Schroedinger %d.%d.%d", ver, ver+1, ver+2) == 3)

                if (ver[0] == 1 && ver[1] == 0 && ver[2] <= 7)

                    s->old_delta_quant = 1;

        }

    } else if (parse_code & 0x8) {  /* picture data unit */

        if (!s->seen_sequence_header) {

            av_log(avctx, AV_LOG_DEBUG, "Dropping frame without sequence header\n");

            return AVERROR_INVALIDDATA;

        }

        /* find an unused frame */

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

            if (s->all_frames[i].avframe->data[0] == NULL)

                pic = &s->all_frames[i];

        if (!pic) {

            av_log(avctx, AV_LOG_ERROR, "framelist full\n");

            return AVERROR_INVALIDDATA;

        }

        av_frame_unref(pic->avframe);

        /* [DIRAC_STD] Defined in 9.6.1 ... */

        tmp            =  parse_code & 0x03;                   /* [DIRAC_STD] num_refs()      */

        if (tmp > 2) {

            av_log(avctx, AV_LOG_ERROR, "num_refs of 3\n");

            return AVERROR_INVALIDDATA;

        }

        s->num_refs      = tmp;

        s->is_arith      = (parse_code & 0x48) == 0x08;          /* [DIRAC_STD] using_ac()            */

        s->low_delay     = (parse_code & 0x88) == 0x88;          /* [DIRAC_STD] is_low_delay()        */

        s->core_syntax   = (parse_code & 0x88) == 0x08;          /* [DIRAC_STD] is_core_syntax()      */

        s->ld_picture    = (parse_code & 0xF8) == 0xC8;          /* [DIRAC_STD] is_ld_picture()       */

        s->hq_picture    = (parse_code & 0xF8) == 0xE8;          /* [DIRAC_STD] is_hq_picture()       */

        s->dc_prediction = (parse_code & 0x28) == 0x08;          /* [DIRAC_STD] using_dc_prediction() */

        pic->reference   = (parse_code & 0x0C) == 0x0C;          /* [DIRAC_STD] is_reference()        */

        pic->avframe->key_frame = s->num_refs == 0;              /* [DIRAC_STD] is_intra()            */

        pic->avframe->pict_type = s->num_refs + 1;               /* Definition of AVPictureType in avutil.h */

        /* VC-2 Low Delay has a different parse code than the Dirac Low Delay */

        if (s->version.minor == 2 && parse_code == 0x88)

            s->ld_picture = 1;

        if (s->low_delay && !(s->ld_picture || s->hq_picture) ) {

            av_log(avctx, AV_LOG_ERROR, "Invalid low delay flag\n");

            return AVERROR_INVALIDDATA;

        }

        if ((ret = get_buffer_with_edge(avctx, pic->avframe, (parse_code & 0x0C) == 0x0C ? AV_GET_BUFFER_FLAG_REF : 0)) < 0)

            return ret;

        s->current_picture = pic;

        s->plane[0].stride = pic->avframe->linesize[0];

        s->plane[1].stride = pic->avframe->linesize[1];

        s->plane[2].stride = pic->avframe->linesize[2];

        if (alloc_buffers(s, FFMAX3(FFABS(s->plane[0].stride), FFABS(s->plane[1].stride), FFABS(s->plane[2].stride))) < 0)

            return AVERROR(ENOMEM);

        /* [DIRAC_STD] 11.1 Picture parse. picture_parse() */

        ret = dirac_decode_picture_header(s);

        if (ret < 0)

            return ret;

        /* [DIRAC_STD] 13.0 Transform data syntax. transform_data() */

        ret = dirac_decode_frame_internal(s);

        if (ret < 0)

            return ret;

    }

    return 0;

}


static void filter0(int32_t *dst, const int32_t *src, int32_t coeff, ptrdiff_t len)

{

    int i;

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

        dst[i] -= mul22(src[i], coeff);

}


static int encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                        const AVFrame *frame, int *got_packet_ptr)

{

    int i, k, channel;

    DCAContext *c = avctx->priv_data;

    const int16_t *samples;

    int ret, real_channel = 0;

    if ((ret = ff_alloc_packet2(avctx, avpkt, DCA_MAX_FRAME_SIZE + DCA_HEADER_SIZE)))

        return ret;

    samples = (const int16_t *)frame->data[0];

    for (i = 0; i < PCM_SAMPLES; i ++) { /* i is the decimated sample number */

        for (channel = 0; channel < c->prim_channels + 1; channel++) {

            real_channel = c->channel_order_tab[channel];

            if (real_channel >= 0) {

                /* Get 32 PCM samples */

                for (k = 0; k < 32; k++) { /* k is the sample number in a 32-sample block */

                    c->pcm[k] = samples[avctx->channels * (32 * i + k) + channel] << 16;

                }

                /* Put subband samples into the proper place */

                qmf_decompose(c, c->pcm, &c->subband[i][real_channel][0], real_channel);

            }

        }

    }

    if (c->lfe_channel) {

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

            for (k = 0; k < LFE_INTERPOLATION; k++) /* k is the sample number in a 32-sample block */

                c->pcm[k] = samples[avctx->channels * (LFE_INTERPOLATION*i+k) + c->lfe_offset] << 16;

            c->lfe_data[i] = lfe_downsample(c, c->pcm);

        }

    }

    put_frame(c, c->subband, avpkt->data);

    avpkt->size     = c->frame_size;

    *got_packet_ptr = 1;

    return 0;

}


static inline void RENAME(yuv2nv12X)(SwsContext *c, int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,

				     int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,

				     uint8_t *dest, uint8_t *uDest, int dstW, int chrDstW, int dstFormat)

{

yuv2nv12XinC(lumFilter, lumSrc, lumFilterSize,

	     chrFilter, chrSrc, chrFilterSize,

	     dest, uDest, dstW, chrDstW, dstFormat);

}


static void thread_pool_completion_bh(void *opaque)
{
    ThreadPool *pool = opaque;
    ThreadPoolElement *elem, *next;
    aio_context_acquire(pool->ctx);
restart:
    QLIST_FOREACH_SAFE(elem, &pool->head, all, next) {
        if (elem->state != THREAD_DONE) {
            continue;
        }
        trace_thread_pool_complete(pool, elem, elem->common.opaque,
                                   elem->ret);
        QLIST_REMOVE(elem, all);
        if (elem->common.cb) {
            /* Read state before ret.  */
            smp_rmb();
            /* Schedule ourselves in case elem->common.cb() calls aio_poll() to
             * wait for another request that completed at the same time.
            qemu_bh_schedule(pool->completion_bh);
            aio_context_release(pool->ctx);
            elem->common.cb(elem->common.opaque, elem->ret);
            aio_context_acquire(pool->ctx);
            qemu_aio_unref(elem);
            goto restart;
        } else {
            qemu_aio_unref(elem);
        }
    }
    aio_context_release(pool->ctx);
}


static int yop_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    YopDecContext *yop = s->priv_data;

    AVIOContext *pb  = s->pb;

    int ret;

    int actual_video_data_size = yop->frame_size -

                                 yop->audio_block_length - yop->palette_size;

    yop->video_packet.stream_index = 1;

    if (yop->video_packet.data) {

        *pkt                   =  yop->video_packet;

        yop->video_packet.data =  NULL;

        yop->video_packet.size =  0;

        pkt->data[0]           =  yop->odd_frame;

        pkt->flags             |= AV_PKT_FLAG_KEY;

        yop->odd_frame         ^= 1;

        return pkt->size;

    }

    ret = av_new_packet(&yop->video_packet,

                        yop->frame_size - yop->audio_block_length);

    if (ret < 0)

        return ret;

    yop->video_packet.pos = avio_tell(pb);

    ret = avio_read(pb, yop->video_packet.data, yop->palette_size);

    if (ret < 0) {

        goto err_out;

    }else if (ret < yop->palette_size) {

        ret = AVERROR_EOF;

        goto err_out;

    }

    ret = av_get_packet(pb, pkt, 920);

    if (ret < 0)

        goto err_out;

    // Set position to the start of the frame

    pkt->pos = yop->video_packet.pos;

    avio_skip(pb, yop->audio_block_length - ret);

    ret = avio_read(pb, yop->video_packet.data + yop->palette_size,

                     actual_video_data_size);

    if (ret < 0)

        goto err_out;

    else if (ret < actual_video_data_size)

        av_shrink_packet(&yop->video_packet, yop->palette_size + ret);

    // Arbitrarily return the audio data first

    return yop->audio_block_length;

err_out:

    av_free_packet(&yop->video_packet);

    return ret;

}


static int upload_texture(SDL_Texture *tex, AVFrame *frame, struct SwsContext **img_convert_ctx) {

    int ret = 0;

    switch (frame->format) {

        case AV_PIX_FMT_YUV420P:

            ret = SDL_UpdateYUVTexture(tex, NULL, frame->data[0], frame->linesize[0],

                                                  frame->data[1], frame->linesize[1],

                                                  frame->data[2], frame->linesize[2]);

            break;

        case AV_PIX_FMT_BGRA:

            ret = SDL_UpdateTexture(tex, NULL, frame->data[0], frame->linesize[0]);

            break;

        default:

            /* This should only happen if we are not using avfilter... */

            *img_convert_ctx = sws_getCachedContext(*img_convert_ctx,

                frame->width, frame->height, frame->format, frame->width, frame->height,

                AV_PIX_FMT_BGRA, sws_flags, NULL, NULL, NULL);

            if (*img_convert_ctx != NULL) {

                uint8_t *pixels;

                int pitch;

                if (!SDL_LockTexture(tex, NULL, (void **)&pixels, &pitch)) {

                    sws_scale(*img_convert_ctx, (const uint8_t * const *)frame->data, frame->linesize,

                              0, frame->height, &pixels, &pitch);

                    SDL_UnlockTexture(tex);

                }

            } else {

                av_log(NULL, AV_LOG_FATAL, "Cannot initialize the conversion context\n");

                ret = -1;

            }

            break;

    }

    return ret;

}


static int vorbis_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                               const AVFrame *frame, int *got_packet_ptr)

{

    vorbis_enc_context *venc = avctx->priv_data;

    int i, ret, need_more;

    int frame_size = 1 << (venc->log2_blocksize[1] - 1);

    vorbis_enc_mode *mode;

    vorbis_enc_mapping *mapping;

    PutBitContext pb;

    if (frame) {

        if ((ret = ff_af_queue_add(&venc->afq, frame)) < 0)

            return ret;

        ff_bufqueue_add(avctx, &venc->bufqueue, av_frame_clone(frame));

    } else

        if (!venc->afq.remaining_samples)

            return 0;

    need_more = venc->bufqueue.available * avctx->frame_size < frame_size;

    need_more = frame && need_more;

    if (need_more)

        return 0;

    /* Pad the bufqueue with empty frames for encoding the last packet. */

    if (!frame) {

        if (venc->bufqueue.available * avctx->frame_size < frame_size) {

            int frames_needed = (frame_size/avctx->frame_size) - venc->bufqueue.available;

            int i;

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

               AVFrame *empty = spawn_empty_frame(avctx, venc->channels);

               if (!empty)

                   return AVERROR(ENOMEM);

               ff_bufqueue_add(avctx, &venc->bufqueue, empty);

            }

        }

    }

    move_audio(venc, avctx->frame_size);

    if (!apply_window_and_mdct(venc))

        return 0;

    if ((ret = ff_alloc_packet2(avctx, avpkt, 8192, 0)) < 0)

        return ret;

    init_put_bits(&pb, avpkt->data, avpkt->size);

    if (pb.size_in_bits - put_bits_count(&pb) < 1 + ilog(venc->nmodes - 1)) {

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

        return AVERROR(EINVAL);

    }

    put_bits(&pb, 1, 0); // magic bit

    put_bits(&pb, ilog(venc->nmodes - 1), 1); // Mode for current frame

    mode    = &venc->modes[1];

    mapping = &venc->mappings[mode->mapping];

    if (mode->blockflag) {

        put_bits(&pb, 1, 1); // Previous windowflag

        put_bits(&pb, 1, 1); // Next windowflag

    }

    for (i = 0; i < venc->channels; i++) {

        vorbis_enc_floor *fc = &venc->floors[mapping->floor[mapping->mux[i]]];

        uint16_t posts[MAX_FLOOR_VALUES];

        floor_fit(venc, fc, &venc->coeffs[i * frame_size], posts, frame_size);

        if (floor_encode(venc, fc, &pb, posts, &venc->floor[i * frame_size], frame_size)) {

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

            return AVERROR(EINVAL);

        }

    }

    for (i = 0; i < venc->channels * frame_size; i++)

        venc->coeffs[i] /= venc->floor[i];

    for (i = 0; i < mapping->coupling_steps; i++) {

        float *mag = venc->coeffs + mapping->magnitude[i] * frame_size;

        float *ang = venc->coeffs + mapping->angle[i]     * frame_size;

        int j;

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

            float a = ang[j];

            ang[j] -= mag[j];

            if (mag[j] > 0)

                ang[j] = -ang[j];

            if (ang[j] < 0)

                mag[j] = a;

        }

    }

    if (residue_encode(venc, &venc->residues[mapping->residue[mapping->mux[0]]],

                       &pb, venc->coeffs, frame_size, venc->channels)) {

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

        return AVERROR(EINVAL);

    }

    flush_put_bits(&pb);

    avpkt->size = put_bits_count(&pb) >> 3;

    ff_af_queue_remove(&venc->afq, frame_size, &avpkt->pts, &avpkt->duration);

    if (frame_size > avpkt->duration) {

        uint8_t *side = av_packet_new_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, 10);

        if (!side)

            return AVERROR(ENOMEM);

        AV_WL32(&side[4], frame_size - avpkt->duration);

    }

    *got_packet_ptr = 1;

    return 0;

}


void avfilter_start_frame(AVFilterLink *link, AVFilterBufferRef *picref)

{

    void (*start_frame)(AVFilterLink *, AVFilterBufferRef *);

    AVFilterPad *dst = &link_dpad(link);

    FF_DPRINTF_START(NULL, start_frame); ff_dprintf_link(NULL, link, 0); dprintf(NULL, " "); ff_dprintf_ref(NULL, picref, 1);

    if (!(start_frame = dst->start_frame))

        start_frame = avfilter_default_start_frame;

    /* prepare to copy the picture if it has insufficient permissions */

    if ((dst->min_perms & picref->perms) != dst->min_perms ||

         dst->rej_perms & picref->perms) {

        av_log(link->dst, AV_LOG_DEBUG,

                "frame copy needed (have perms %x, need %x, reject %x)\n",

                picref->perms,

                link_dpad(link).min_perms, link_dpad(link).rej_perms);

        link->cur_buf = avfilter_default_get_video_buffer(link, dst->min_perms, link->w, link->h);

        link->src_buf = picref;

        avfilter_copy_buffer_ref_props(link->cur_buf, link->src_buf);

    }

    else

        link->cur_buf = picref;

    start_frame(link, link->cur_buf);

}


static void ivshmem_check_memdev_is_busy(Object *obj, const char *name,

                                         Object *val, Error **errp)

{

    if (host_memory_backend_is_mapped(MEMORY_BACKEND(val))) {

        char *path = object_get_canonical_path_component(val);

        error_setg(errp, "can't use already busy memdev: %s", path);

        g_free(path);

    } else {

        qdev_prop_allow_set_link_before_realize(obj, name, val, errp);

    }

}


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

                               int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    vorbis_context *vc = avctx->priv_data;

    AVFrame *frame     = data;

    GetBitContext *gb = &vc->gb;

    float *channel_ptrs[255];

    int i, len, ret;

    av_dlog(NULL, "packet length %d \n", buf_size);

    /* get output buffer */

    frame->nb_samples = vc->blocksize[1] / 2;

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

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

        return ret;

    }

    if (vc->audio_channels > 8) {

        for (i = 0; i < vc->audio_channels; i++)

            channel_ptrs[i] = (float *)frame->extended_data[i];

    } else {

        for (i = 0; i < vc->audio_channels; i++) {

            int ch = ff_vorbis_channel_layout_offsets[vc->audio_channels - 1][i];

            channel_ptrs[ch] = (float *)frame->extended_data[i];

        }

    }

    init_get_bits(gb, buf, buf_size*8);

    if ((len = vorbis_parse_audio_packet(vc, channel_ptrs)) <= 0)

        return len;

    if (!vc->first_frame) {

        vc->first_frame = 1;

        *got_frame_ptr = 0;

        return buf_size;

    }

    av_dlog(NULL, "parsed %d bytes %d bits, returned %d samples (*ch*bits) \n",

            get_bits_count(gb) / 8, get_bits_count(gb) % 8, len);

    frame->nb_samples = len;

    *got_frame_ptr    = 1;

    return buf_size;

}


static int qemu_balloon_status(MonitorCompletion cb, void *opaque)

{

    if (!balloon_event_fn) {

        return 0;

    }

    balloon_event_fn(balloon_opaque, 0, cb, opaque);

    return 1;

}


static void put_pixels_clamped4_c(const DCTELEM *block, uint8_t *restrict pixels,

                                 int line_size)

{

    int i;

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    /* read the pixels */

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

        pixels[0] = cm[block[0]];

        pixels[1] = cm[block[1]];

        pixels[2] = cm[block[2]];

        pixels[3] = cm[block[3]];

        pixels += line_size;

        block += 8;

    }

}


static void check_pred4x4(H264PredContext *h, uint8_t *buf0, uint8_t *buf1,

                          int codec, int chroma_format, int bit_depth)

{

    if (chroma_format == 1) {

        uint8_t *topright = buf0 + 2*16;

        int pred_mode;

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

            if (check_pred_func(h->pred4x4[pred_mode], "4x4", pred4x4_modes[codec][pred_mode])) {

                randomize_buffers();

                call_ref(src0, topright, (ptrdiff_t)12*SIZEOF_PIXEL);

                call_new(src1, topright, (ptrdiff_t)12*SIZEOF_PIXEL);

                if (memcmp(buf0, buf1, BUF_SIZE))

                    fail();

                bench_new(src1, topright, (ptrdiff_t)12*SIZEOF_PIXEL);

            }

        }

    }

}


int ff_mov_iso639_to_lang(const char *lang, int mp4)

{

    int i, code = 0;

    /* old way, only for QT? */

    for (i = 0; !mp4 && i < FF_ARRAY_ELEMS(mov_mdhd_language_map); i++) {

        if (mov_mdhd_language_map[i] && !strcmp(lang, mov_mdhd_language_map[i]))

            return i;

    }

    /* XXX:can we do that in mov too? */

    if (!mp4)

        return 0;

    /* handle undefined as such */

    if (lang[0] == '\0')

        lang = "und";

    /* 5bit ascii */

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

        unsigned char c = (unsigned char)lang[i];

        if (c < 0x60)

            return 0;

        if (c > 0x60 + 0x1f)

            return 0;

        code <<= 5;

        code |= (c - 0x60);

    }

    return code;

}


static int dxva2_vp9_start_frame(AVCodecContext *avctx,

                                 av_unused const uint8_t *buffer,

                                 av_unused uint32_t size)

{

    const VP9SharedContext *h = avctx->priv_data;

    AVDXVAContext *ctx = avctx->hwaccel_context;

    struct vp9_dxva2_picture_context *ctx_pic = h->frames[CUR_FRAME].hwaccel_picture_private;

    if (DXVA_CONTEXT_DECODER(avctx, ctx) == NULL ||

        DXVA_CONTEXT_CFG(avctx, ctx) == NULL ||

        DXVA_CONTEXT_COUNT(avctx, ctx) <= 0)

        return -1;

    av_assert0(ctx_pic);

    /* Fill up DXVA_PicParams_VP9 */

    if (fill_picture_parameters(avctx, ctx, h, &ctx_pic->pp) < 0)

        return -1;

    ctx_pic->bitstream_size = 0;

    ctx_pic->bitstream      = NULL;

    return 0;

}


static void test_nop(gconstpointer data)

{

    QTestState *s;

    const char *machine = data;

    char *args;

    args = g_strdup_printf("-display none -machine %s", machine);

    s = qtest_start(args);

    if (s) {

        qtest_quit(s);

    }

    g_free(args);

}


static int ass_get_duration(const uint8_t *p)

{

    int sh, sm, ss, sc, eh, em, es, ec;

    uint64_t start, end;

    if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",

               &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)

        return 0;

    start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;

    end   = 3600000*eh + 60000*em + 1000*es + 10*ec;

    return end - start;

}


static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,
                         GetBitContext *gb, SBRData *ch_data)
{
    int i;
    ch_data->bs_freq_res[0] = ch_data->bs_freq_res[ch_data->bs_num_env[1]];
    ch_data->bs_num_env[0] = ch_data->bs_num_env[1];
    ch_data->bs_amp_res = sbr->bs_amp_res_header;
    switch (ch_data->bs_frame_class = get_bits(gb, 2)) {
    case FIXFIX:
        ch_data->bs_num_env[1] = 1 << get_bits(gb, 2);
        if (ch_data->bs_num_env[1] == 1)
            ch_data->bs_amp_res = 0;
        ch_data->bs_freq_res[1] = get_bits1(gb);
        for (i = 1; i < ch_data->bs_num_env[1]; i++)
            ch_data->bs_freq_res[i + 1] = ch_data->bs_freq_res[1];
        break;
    case FIXVAR:
        ch_data->bs_var_bord[1] = get_bits(gb, 2);
        ch_data->bs_num_rel[1]  = get_bits(gb, 2);
        ch_data->bs_num_env[1]  = ch_data->bs_num_rel[1] + 1;
        for (i = 0; i < ch_data->bs_num_rel[1]; i++)
            ch_data->bs_rel_bord[1][i] = 2 * get_bits(gb, 2) + 2;
        ch_data->bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env[1]]);
        for (i = 0; i < ch_data->bs_num_env[1]; i++)
            ch_data->bs_freq_res[ch_data->bs_num_env[1] - i] = get_bits1(gb);
        break;
    case VARFIX:
        ch_data->bs_var_bord[0] = get_bits(gb, 2);
        ch_data->bs_num_rel[0]  = get_bits(gb, 2);
        ch_data->bs_num_env[1]  = ch_data->bs_num_rel[0] + 1;
        for (i = 0; i < ch_data->bs_num_rel[0]; i++)
            ch_data->bs_rel_bord[0][i] = 2 * get_bits(gb, 2) + 2;
        ch_data->bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env[1]]);
        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env[1]);
        break;
    case VARVAR:
        ch_data->bs_var_bord[0] = get_bits(gb, 2);
        ch_data->bs_var_bord[1] = get_bits(gb, 2);
        ch_data->bs_num_rel[0]  = get_bits(gb, 2);
        ch_data->bs_num_rel[1]  = get_bits(gb, 2);
        ch_data->bs_num_env[1]  = ch_data->bs_num_rel[0] + ch_data->bs_num_rel[1] + 1;
        for (i = 0; i < ch_data->bs_num_rel[0]; i++)
            ch_data->bs_rel_bord[0][i] = 2 * get_bits(gb, 2) + 2;
        for (i = 0; i < ch_data->bs_num_rel[1]; i++)
            ch_data->bs_rel_bord[1][i] = 2 * get_bits(gb, 2) + 2;
        ch_data->bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env[1]]);
        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env[1]);
        break;
    }
    if (ch_data->bs_pointer > ch_data->bs_num_env[1] + 1) {
        av_log(ac->avccontext, AV_LOG_ERROR,
               "Invalid bitstream, bs_pointer points to a middle noise border outside the time borders table: %d\n",
               ch_data->bs_pointer);
        return -1;
    }
    if (ch_data->bs_frame_class == FIXFIX && ch_data->bs_num_env[1] > 4) {
        av_log(ac->avccontext, AV_LOG_ERROR,
               "Invalid bitstream, too many SBR envelopes in FIXFIX type SBR frame: %d\n",
               ch_data->bs_num_env[1]);
        return -1;
    }
    if (ch_data->bs_frame_class == VARVAR && ch_data->bs_num_env[1] > 5) {
        av_log(ac->avccontext, AV_LOG_ERROR,
               "Invalid bitstream, too many SBR envelopes in VARVAR type SBR frame: %d\n",
               ch_data->bs_num_env[1]);
        return -1;
    }
    ch_data->bs_num_noise = (ch_data->bs_num_env[1] > 1) + 1;
    return 0;
}


static int modified_clear_reset(S390CPU *cpu)

{

    S390CPUClass *scc = S390_CPU_GET_CLASS(cpu);

    pause_all_vcpus();

    cpu_synchronize_all_states();

    cpu_full_reset_all();

    io_subsystem_reset();

    scc->load_normal(CPU(cpu));

    cpu_synchronize_all_post_reset();

    resume_all_vcpus();

    return 0;

}


static av_cold int png_enc_init(AVCodecContext *avctx)

{

    PNGEncContext *s = avctx->priv_data;

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

    avctx->coded_frame->key_frame = 1;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    ff_huffyuvencdsp_init(&s->hdsp);

    s->filter_type = av_clip(avctx->prediction_method,

                             PNG_FILTER_VALUE_NONE,

                             PNG_FILTER_VALUE_MIXED);

    if (avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)

        s->filter_type = PNG_FILTER_VALUE_NONE;

    return 0;

}


static void test_smbios_ep_table(test_data *data)

{

    struct smbios_entry_point *ep_table = &data->smbios_ep_table;

    uint32_t addr = data->smbios_ep_addr;

    ACPI_READ_ARRAY(ep_table->anchor_string, addr);

    g_assert(!memcmp(ep_table->anchor_string, "_SM_", 4));

    ACPI_READ_FIELD(ep_table->checksum, addr);

    ACPI_READ_FIELD(ep_table->length, addr);

    ACPI_READ_FIELD(ep_table->smbios_major_version, addr);

    ACPI_READ_FIELD(ep_table->smbios_minor_version, addr);

    ACPI_READ_FIELD(ep_table->max_structure_size, addr);

    ACPI_READ_FIELD(ep_table->entry_point_revision, addr);

    ACPI_READ_ARRAY(ep_table->formatted_area, addr);

    ACPI_READ_ARRAY(ep_table->intermediate_anchor_string, addr);

    g_assert(!memcmp(ep_table->intermediate_anchor_string, "_DMI_", 5));

    ACPI_READ_FIELD(ep_table->intermediate_checksum, addr);

    ACPI_READ_FIELD(ep_table->structure_table_length, addr);

    g_assert_cmpuint(ep_table->structure_table_length, >, 0);

    ACPI_READ_FIELD(ep_table->structure_table_address, addr);

    ACPI_READ_FIELD(ep_table->number_of_structures, addr);

    g_assert_cmpuint(ep_table->number_of_structures, >, 0);

    ACPI_READ_FIELD(ep_table->smbios_bcd_revision, addr);

    g_assert(!acpi_checksum((uint8_t *)ep_table, sizeof *ep_table));

    g_assert(!acpi_checksum((uint8_t *)ep_table + 0x10,

                            sizeof *ep_table - 0x10));

}