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

                                     uint8_t *dst, int32_t dst_stride,

                                     int32_t height, uint8_t ver_offset)

{

    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, dst4, dst5, dst6, dst7;

    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, 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_SH(hz_out0, hz_out1, hz_out2,

                                               hz_out3, hz_out4, hz_out5);

        dst2 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out1, hz_out2, hz_out3,

                                               hz_out4, hz_out5, hz_out6);

        dst4 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out2, hz_out3, hz_out4,

                                               hz_out5, hz_out6, hz_out7);

        dst6 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out3, hz_out4, hz_out5,

                                               hz_out6, hz_out7, hz_out8);

        if (ver_offset) {

            dst1 = __msa_srari_h(hz_out3, 5);

            dst3 = __msa_srari_h(hz_out4, 5);

            dst5 = __msa_srari_h(hz_out5, 5);

            dst7 = __msa_srari_h(hz_out6, 5);

        } else {

            dst1 = __msa_srari_h(hz_out2, 5);

            dst3 = __msa_srari_h(hz_out3, 5);

            dst5 = __msa_srari_h(hz_out4, 5);

            dst7 = __msa_srari_h(hz_out5, 5);

        }

        SAT_SH4_SH(dst1, dst3, dst5, dst7, 7);

        dst0 = __msa_aver_s_h(dst0, dst1);

        dst1 = __msa_aver_s_h(dst2, dst3);

        dst2 = __msa_aver_s_h(dst4, dst5);

        dst3 = __msa_aver_s_h(dst6, dst7);

        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 void aml_free(gpointer data, gpointer user_data)

{

    Aml *var = data;

    build_free_array(var->buf);

}


static void virtio_scsi_handle_cmd(VirtIODevice *vdev, VirtQueue *vq)

{

    /* use non-QOM casts in the data path */

    VirtIOSCSI *s = (VirtIOSCSI *)vdev;

    VirtIOSCSICommon *vs = &s->parent_obj;

    VirtIOSCSIReq *req;

    int n;

    while ((req = virtio_scsi_pop_req(s, vq))) {

        SCSIDevice *d;

        int out_size, in_size;

        if (req->elem.out_num < 1 || req->elem.in_num < 1) {

            virtio_scsi_bad_req();

        }

        out_size = req->elem.out_sg[0].iov_len;

        in_size = req->elem.in_sg[0].iov_len;

        if (out_size < sizeof(VirtIOSCSICmdReq) + vs->cdb_size ||

            in_size < sizeof(VirtIOSCSICmdResp) + vs->sense_size) {

            virtio_scsi_bad_req();

        }

        if (req->elem.out_num > 1 && req->elem.in_num > 1) {

            virtio_scsi_fail_cmd_req(req);

            continue;

        }

        d = virtio_scsi_device_find(s, req->req.cmd->lun);

        if (!d) {

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

            virtio_scsi_complete_req(req);

            continue;

        }

        req->sreq = scsi_req_new(d, req->req.cmd->tag,

                                 virtio_scsi_get_lun(req->req.cmd->lun),

                                 req->req.cmd->cdb, req);

        if (req->sreq->cmd.mode != SCSI_XFER_NONE) {

            int req_mode =

                (req->elem.in_num > 1 ? SCSI_XFER_FROM_DEV : SCSI_XFER_TO_DEV);

            if (req->sreq->cmd.mode != req_mode ||

                req->sreq->cmd.xfer > req->qsgl.size) {

                req->resp.cmd->response = VIRTIO_SCSI_S_OVERRUN;

                virtio_scsi_complete_req(req);

                continue;

            }

        }

        n = scsi_req_enqueue(req->sreq);

        if (n) {

            scsi_req_continue(req->sreq);

        }

    }

}


CharDriverState *text_console_init(QemuOpts *opts)

{

    CharDriverState *chr;

    QemuConsole *s;

    unsigned width;

    unsigned height;

    chr = g_malloc0(sizeof(CharDriverState));

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

    if (width == 0)

        width = qemu_opt_get_number(opts, "cols", 0) * FONT_WIDTH;

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

    if (height == 0)

        height = qemu_opt_get_number(opts, "rows", 0) * FONT_HEIGHT;

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

        s = new_console(NULL, TEXT_CONSOLE);

    } else {

        s = new_console(NULL, TEXT_CONSOLE_FIXED_SIZE);

    }

    if (!s) {

        g_free(chr);

        return NULL;

    }

    s->chr = chr;

    s->g_width = width;

    s->g_height = height;

    chr->opaque = s;

    chr->chr_set_echo = text_console_set_echo;

    return chr;

}


static uint64_t eepro100_read(void *opaque, target_phys_addr_t addr,

                              unsigned size)

{

    EEPRO100State *s = opaque;

    switch (size) {

    case 1: return eepro100_read1(s, addr);

    case 2: return eepro100_read2(s, addr);

    case 4: return eepro100_read4(s, addr);

    default: abort();

    }

}


bool vring_should_notify(VirtIODevice *vdev, Vring *vring)

{

    uint16_t old, new;

    bool v;

    /* Flush out used index updates. This is paired

     * with the barrier that the Guest executes when enabling

     * interrupts. */

    smp_mb();

    if ((vdev->guest_features & (1 << VIRTIO_F_NOTIFY_ON_EMPTY)) &&

        unlikely(!vring_more_avail(vdev, vring))) {

        return true;

    }

    if (!(vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX))) {

        return !(vring_get_avail_flags(vdev, vring) &

                 VRING_AVAIL_F_NO_INTERRUPT);

    }

    old = vring->signalled_used;

    v = vring->signalled_used_valid;

    new = vring->signalled_used = vring->last_used_idx;

    vring->signalled_used_valid = true;

    if (unlikely(!v)) {

        return true;

    }

    return vring_need_event(vring_used_event(&vring->vr), new, old);

}


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

                               const AVFrame *frame, int *got_packet_ptr)

{

    AMRContext *s = avctx->priv_data;

    int written, ret;

    int16_t *flush_buf = NULL;

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

    if (s->enc_bitrate != avctx->bit_rate) {

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

        s->enc_bitrate = avctx->bit_rate;

    }

    if ((ret = ff_alloc_packet(avpkt, 32))) {

        av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");

        return ret;

    }

    if (frame) {

        if (frame->nb_samples < avctx->frame_size) {

            flush_buf = av_mallocz(avctx->frame_size * sizeof(*flush_buf));

            if (!flush_buf)

                return AVERROR(ENOMEM);

            memcpy(flush_buf, samples, frame->nb_samples * sizeof(*flush_buf));

            samples = flush_buf;

            if (frame->nb_samples < avctx->frame_size - avctx->delay)

                s->enc_last_frame = -1;

        }

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

            av_freep(&flush_buf);

            return ret;

        }

    } else {

        if (s->enc_last_frame < 0)

            return 0;

        flush_buf = av_mallocz(avctx->frame_size * sizeof(*flush_buf));

        if (!flush_buf)

            return AVERROR(ENOMEM);

        samples = flush_buf;

        s->enc_last_frame = -1;

    }

    written = Encoder_Interface_Encode(s->enc_state, s->enc_mode, samples,

                                       avpkt->data, 0);

    av_dlog(avctx, "amr_nb_encode_frame encoded %u bytes, bitrate %u, first byte was %#02x\n",

            written, s->enc_mode, frame[0]);

    /* Get the next frame pts/duration */

    ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,

                       &avpkt->duration);

    avpkt->size = written;

    *got_packet_ptr = 1;

    av_freep(&flush_buf);

    return 0;

}


void do_unassigned_access(target_phys_addr_t addr, int is_write, int is_exec,

                          int is_asi, int size)

{

    CPUState *saved_env;

    /* XXX: hack to restore env in all cases, even if not called from

       generated code */

    saved_env = env;

    env = cpu_single_env;

    qemu_log("Unassigned " TARGET_FMT_plx " wr=%d exe=%d\n",

             addr, is_write, is_exec);

    if (!(env->sregs[SR_MSR] & MSR_EE)) {

        return;

    }

    if (is_exec) {

        if (!(env->pvr.regs[2] & PVR2_IOPB_BUS_EXC_MASK)) {

            env->sregs[SR_ESR] = ESR_EC_INSN_BUS;

            helper_raise_exception(EXCP_HW_EXCP);

        }

    } else {

        if (!(env->pvr.regs[2] & PVR2_DOPB_BUS_EXC_MASK)) {

            env->sregs[SR_ESR] = ESR_EC_DATA_BUS;

            helper_raise_exception(EXCP_HW_EXCP);

        }

    }

}


static int RENAME(swScale)(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,

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

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

	const int srcW= c->srcW;

	const int dstW= c->dstW;

	const int dstH= c->dstH;

	const int chrDstW= c->chrDstW;

	const int chrSrcW= c->chrSrcW;

	const int lumXInc= c->lumXInc;

	const int chrXInc= c->chrXInc;

	const int dstFormat= c->dstFormat;

	const int srcFormat= c->srcFormat;

	const int flags= c->flags;

	const int canMMX2BeUsed= c->canMMX2BeUsed;

	int16_t *vLumFilterPos= c->vLumFilterPos;

	int16_t *vChrFilterPos= c->vChrFilterPos;

	int16_t *hLumFilterPos= c->hLumFilterPos;

	int16_t *hChrFilterPos= c->hChrFilterPos;

	int16_t *vLumFilter= c->vLumFilter;

	int16_t *vChrFilter= c->vChrFilter;

	int16_t *hLumFilter= c->hLumFilter;

	int16_t *hChrFilter= c->hChrFilter;

	int32_t *lumMmxFilter= c->lumMmxFilter;

	int32_t *chrMmxFilter= c->chrMmxFilter;

	const int vLumFilterSize= c->vLumFilterSize;

	const int vChrFilterSize= c->vChrFilterSize;

	const int hLumFilterSize= c->hLumFilterSize;

	const int hChrFilterSize= c->hChrFilterSize;

	int16_t **lumPixBuf= c->lumPixBuf;

	int16_t **chrPixBuf= c->chrPixBuf;

	const int vLumBufSize= c->vLumBufSize;

	const int vChrBufSize= c->vChrBufSize;

	uint8_t *funnyYCode= c->funnyYCode;

	uint8_t *funnyUVCode= c->funnyUVCode;

	uint8_t *formatConvBuffer= c->formatConvBuffer;

	const int chrSrcSliceY= srcSliceY >> c->chrSrcVSubSample;

	const int chrSrcSliceH= -((-srcSliceH) >> c->chrSrcVSubSample);

	int lastDstY;

        uint8_t *pal=NULL;

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

	int dstY= c->dstY;

	int lumBufIndex= c->lumBufIndex;

	int chrBufIndex= c->chrBufIndex;

	int lastInLumBuf= c->lastInLumBuf;

	int lastInChrBuf= c->lastInChrBuf;

	if(isPacked(c->srcFormat)){

                pal= src[1];

		src[0]=

		src[1]=

		src[2]= src[0];

		srcStride[0]=

		srcStride[1]=

		srcStride[2]= srcStride[0];

	}

	srcStride[1]<<= c->vChrDrop;

	srcStride[2]<<= c->vChrDrop;

//	printf("swscale %X %X %X -> %X %X %X\n", (int)src[0], (int)src[1], (int)src[2],

//		(int)dst[0], (int)dst[1], (int)dst[2]);

#if 0 //self test FIXME move to a vfilter or something

{

static volatile int i=0;

i++;

if(srcFormat==PIX_FMT_YUV420P && i==1 && srcSliceH>= c->srcH)

	selfTest(src, srcStride, c->srcW, c->srcH);

i--;

}

#endif

//printf("sws Strides:%d %d %d -> %d %d %d\n", srcStride[0],srcStride[1],srcStride[2],

//dstStride[0],dstStride[1],dstStride[2]);

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

	{

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

		if(flags & SWS_PRINT_INFO && firstTime)

		{

			av_log(c, AV_LOG_WARNING, "SwScaler: Warning: dstStride is not aligned!\n"

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

			firstTime=0;

		}

	}

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

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

	if(srcSliceY ==0){

		lumBufIndex=0;

		chrBufIndex=0;

		dstY=0;

		lastInLumBuf= -1;

		lastInChrBuf= -1;

	}

	lastDstY= dstY;

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

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

		const int chrDstY= dstY>>c->chrDstVSubSample;

		unsigned char *uDest=dst[1]+dstStride[1]*chrDstY;

		unsigned char *vDest=dst[2]+dstStride[2]*chrDstY;

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

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

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

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

//printf("dstY:%d dstH:%d firstLumSrcY:%d lastInLumBuf:%d vLumBufSize: %d vChrBufSize: %d slice: %d %d vLumFilterSize: %d firstChrSrcY: %d vChrFilterSize: %d c->chrSrcVSubSample: %d\n",

// dstY, dstH, firstLumSrcY, lastInLumBuf, vLumBufSize, vChrBufSize, srcSliceY, srcSliceH, vLumFilterSize, firstChrSrcY, vChrFilterSize,  c->chrSrcVSubSample);

		//handle holes (FAST_BILINEAR & weird filters)

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

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

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

		ASSERT(firstLumSrcY >= lastInLumBuf - vLumBufSize + 1)

		ASSERT(firstChrSrcY >= lastInChrBuf - vChrBufSize + 1)

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

		if(lastLumSrcY < srcSliceY + srcSliceH && lastChrSrcY < -((-srcSliceY - srcSliceH)>>c->chrSrcVSubSample))

		{

			//Do horizontal scaling

			while(lastInLumBuf < lastLumSrcY)

			{

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

				lumBufIndex++;

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

				ASSERT(lumBufIndex < 2*vLumBufSize)

				ASSERT(lastInLumBuf + 1 - srcSliceY < srcSliceH)

				ASSERT(lastInLumBuf + 1 - srcSliceY >= 0)

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

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

						flags, canMMX2BeUsed, hLumFilter, hLumFilterPos, hLumFilterSize,

						funnyYCode, c->srcFormat, formatConvBuffer,

						c->lumMmx2Filter, c->lumMmx2FilterPos, pal);

				lastInLumBuf++;

			}

			while(lastInChrBuf < lastChrSrcY)

			{

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

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

				chrBufIndex++;

				ASSERT(chrBufIndex < 2*vChrBufSize)

				ASSERT(lastInChrBuf + 1 - chrSrcSliceY < (chrSrcSliceH))

				ASSERT(lastInChrBuf + 1 - chrSrcSliceY >= 0)

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

				if(!(isGray(srcFormat) || isGray(dstFormat)))

					RENAME(hcscale)(chrPixBuf[ chrBufIndex ], chrDstW, src1, src2, chrSrcW, chrXInc,

						flags, canMMX2BeUsed, hChrFilter, hChrFilterPos, hChrFilterSize,

						funnyUVCode, c->srcFormat, formatConvBuffer,

						c->chrMmx2Filter, c->chrMmx2FilterPos, pal);

				lastInChrBuf++;

			}

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

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

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

		}

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

		{

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

			firstChrSrcY,firstLumSrcY,lastChrSrcY,lastLumSrcY,

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

			vChrBufSize, vLumBufSize);*/

			//Do horizontal scaling

			while(lastInLumBuf+1 < srcSliceY + srcSliceH)

			{

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

				lumBufIndex++;

				ASSERT(lumBufIndex < 2*vLumBufSize)

				ASSERT(lastInLumBuf + 1 - srcSliceY < srcSliceH)

				ASSERT(lastInLumBuf + 1 - srcSliceY >= 0)

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

						flags, canMMX2BeUsed, hLumFilter, hLumFilterPos, hLumFilterSize,

						funnyYCode, c->srcFormat, formatConvBuffer,

						c->lumMmx2Filter, c->lumMmx2FilterPos, pal);

				lastInLumBuf++;

			}

			while(lastInChrBuf+1 < (chrSrcSliceY + chrSrcSliceH))

			{

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

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

				chrBufIndex++;

				ASSERT(chrBufIndex < 2*vChrBufSize)

				ASSERT(lastInChrBuf + 1 - chrSrcSliceY < chrSrcSliceH)

				ASSERT(lastInChrBuf + 1 - chrSrcSliceY >= 0)

				if(!(isGray(srcFormat) || isGray(dstFormat)))

					RENAME(hcscale)(chrPixBuf[ chrBufIndex ], chrDstW, src1, src2, chrSrcW, chrXInc,

						flags, canMMX2BeUsed, hChrFilter, hChrFilterPos, hChrFilterSize,

						funnyUVCode, c->srcFormat, formatConvBuffer,

						c->chrMmx2Filter, c->chrMmx2FilterPos, pal);

				lastInChrBuf++;

			}

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

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

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

			break; //we can't output a dstY line so let's try with the next slice

		}

#ifdef HAVE_MMX

		b5Dither= dither8[dstY&1];

		g6Dither= dither4[dstY&1];

		g5Dither= dither8[dstY&1];

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

#endif

	    if(dstY < dstH-2)

	    {

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

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

#ifdef HAVE_MMX

		int i;

            if(flags & SWS_ACCURATE_RND){

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

                                lumMmxFilter[2*i+0]= (int32_t)lumSrcPtr[i  ];

                                lumMmxFilter[2*i+1]= (int32_t)lumSrcPtr[i+(vLumFilterSize>1)];

                                lumMmxFilter[2*i+2]=

                                lumMmxFilter[2*i+3]= vLumFilter[dstY*vLumFilterSize + i    ]

                                                + (vLumFilterSize>1 ? vLumFilter[dstY*vLumFilterSize + i + 1]<<16 : 0);

                        }

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

                                chrMmxFilter[2*i+0]= (int32_t)chrSrcPtr[i  ];

                                chrMmxFilter[2*i+1]= (int32_t)chrSrcPtr[i+(vChrFilterSize>1)];

                                chrMmxFilter[2*i+2]=

                                chrMmxFilter[2*i+3]= vChrFilter[chrDstY*vChrFilterSize + i    ]

                                                + (vChrFilterSize>1 ? vChrFilter[chrDstY*vChrFilterSize + i + 1]<<16 : 0);

                        }

            }else{

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

		{

			lumMmxFilter[4*i+0]= (int32_t)lumSrcPtr[i];

			lumMmxFilter[4*i+1]= (uint64_t)lumSrcPtr[i] >> 32;

			lumMmxFilter[4*i+2]=

			lumMmxFilter[4*i+3]=

				((uint16_t)vLumFilter[dstY*vLumFilterSize + i])*0x10001;

		}

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

		{

			chrMmxFilter[4*i+0]= (int32_t)chrSrcPtr[i];

			chrMmxFilter[4*i+2]=

			chrMmxFilter[4*i+3]=

				((uint16_t)vChrFilter[chrDstY*vChrFilterSize + i])*0x10001;

		}

            }

#endif

		if(dstFormat == PIX_FMT_NV12 || dstFormat == PIX_FMT_NV21){

			const int chrSkipMask= (1<<c->chrDstVSubSample)-1;

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

			RENAME(yuv2nv12X)(c,

				vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,

				vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,

				dest, uDest, dstW, chrDstW, dstFormat);

		}

		else if(isPlanarYUV(dstFormat) || isGray(dstFormat)) //YV12 like

		{

			const int chrSkipMask= (1<<c->chrDstVSubSample)-1;

			if((dstY&chrSkipMask) || isGray(dstFormat)) uDest=vDest= NULL; //FIXME split functions in lumi / chromi

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

			{

				int16_t *lumBuf = lumPixBuf[0];

				int16_t *chrBuf= chrPixBuf[0];

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

			}

			else //General YV12

			{

				RENAME(yuv2yuvX)(c,

					vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,

					vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,

					dest, uDest, vDest, dstW, chrDstW);

			}

		}

		else

		{

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

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

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

			{

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

				RENAME(yuv2packed1)(c, *lumSrcPtr, *chrSrcPtr, *(chrSrcPtr+1),

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

			}

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

			{

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

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

                                lumMmxFilter[2]=

                                lumMmxFilter[3]= vLumFilter[2*dstY   ]*0x10001;

                                chrMmxFilter[2]=

                                chrMmxFilter[3]= vChrFilter[2*chrDstY]*0x10001;

				RENAME(yuv2packed2)(c, *lumSrcPtr, *(lumSrcPtr+1), *chrSrcPtr, *(chrSrcPtr+1),

						 dest, dstW, lumAlpha, chrAlpha, dstY);

			}

			else //General RGB

			{

				RENAME(yuv2packedX)(c,

					vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,

					vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,

					dest, dstW, dstY);

			}

		}

            }

	    else // hmm looks like we can't use MMX here without overwriting this array's tail

	    {

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

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

		if(dstFormat == PIX_FMT_NV12 || dstFormat == PIX_FMT_NV21){

			const int chrSkipMask= (1<<c->chrDstVSubSample)-1;

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

			yuv2nv12XinC(

				vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,

				vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,

				dest, uDest, dstW, chrDstW, dstFormat);

		}

		else if(isPlanarYUV(dstFormat) || isGray(dstFormat)) //YV12

		{

			const int chrSkipMask= (1<<c->chrDstVSubSample)-1;

			if((dstY&chrSkipMask) || isGray(dstFormat)) uDest=vDest= NULL; //FIXME split functions in lumi / chromi

			yuv2yuvXinC(

				vLumFilter+dstY*vLumFilterSize   , lumSrcPtr, vLumFilterSize,

				vChrFilter+chrDstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,

				dest, uDest, vDest, dstW, chrDstW);

		}

		else

		{

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

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

			yuv2packedXinC(c,

				vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,

				vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,

				dest, dstW, dstY);

		}

	    }

	}

#ifdef HAVE_MMX

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

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

#endif

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

	c->dstY= dstY;

	c->lumBufIndex= lumBufIndex;

	c->chrBufIndex= chrBufIndex;

	c->lastInLumBuf= lastInLumBuf;

	c->lastInChrBuf= lastInChrBuf;

	return dstY - lastDstY;

}


static inline void RENAME(bgr24ToY)(uint8_t *dst, const uint8_t *src, int width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    RENAME(bgr24ToY_mmx)(dst, src, width, PIX_FMT_BGR24);

#else

    int i;

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

        int b= src[i*3+0];

        int g= src[i*3+1];

        int r= src[i*3+2];

        dst[i]= ((RY*r + GY*g + BY*b + (33<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT);

    }

#endif /* COMPILE_TEMPLATE_MMX */

}


void FUNC(ff_simple_idct)(DCTELEM *block)

{

    int i;

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

        FUNC(idctRowCondDC)(block + i*8);

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

        FUNC(idctSparseCol)(block + i);

}


static void ohci_async_cancel_device(OHCIState *ohci, USBDevice *dev)

{

    if (ohci->async_td &&

        ohci->usb_packet.owner != NULL &&

        ohci->usb_packet.owner->dev == dev) {

        usb_cancel_packet(&ohci->usb_packet);

        ohci->async_td = 0;

    }

}


static int av_encode(AVFormatContext **output_files,

                     int nb_output_files,

                     AVFormatContext **input_files,

                     int nb_input_files,

                     AVStreamMap *stream_maps, int nb_stream_maps)

{

    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;

    AVFormatContext *is, *os;

    AVCodecContext *codec, *icodec;

    AVOutputStream *ost, **ost_table = NULL;

    AVInputStream *ist, **ist_table = NULL;

    AVInputFile *file_table;

    AVFormatContext *stream_no_data;

    int key;

    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));

    if (!file_table)

        goto fail;

    /* input stream init */

    j = 0;

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

        is = input_files[i];

        file_table[i].ist_index = j;

        file_table[i].nb_streams = is->nb_streams;

        j += is->nb_streams;

    }

    nb_istreams = j;

    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));

    if (!ist_table)

        goto fail;

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

        ist = av_mallocz(sizeof(AVInputStream));

        if (!ist)

            goto fail;

        ist_table[i] = ist;

    }

    j = 0;

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

        is = input_files[i];

        for(k=0;k<is->nb_streams;k++) {

            ist = ist_table[j++];

            ist->st = is->streams[k];

            ist->file_index = i;

            ist->index = k;

            ist->discard = 1; /* the stream is discarded by default

                                 (changed later) */

            if (ist->st->codec.rate_emu) {

                ist->start = av_gettime();

                ist->frame = 0;

            }

        }

    }

    /* output stream init */

    nb_ostreams = 0;

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

        os = output_files[i];

        nb_ostreams += os->nb_streams;

    }

    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {

        fprintf(stderr, "Number of stream maps must match number of output streams\n");

        exit(1);

    }

    /* Sanity check the mapping args -- do the input files & streams exist? */

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

        int fi = stream_maps[i].file_index;

        int si = stream_maps[i].stream_index;

        if (fi < 0 || fi > nb_input_files - 1 ||

            si < 0 || si > file_table[fi].nb_streams - 1) {

            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);

            exit(1);

        }

    }

    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);

    if (!ost_table)

        goto fail;

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

        ost = av_mallocz(sizeof(AVOutputStream));

        if (!ost)

            goto fail;

        ost_table[i] = ost;

    }

    n = 0;

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

        os = output_files[k];

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

            int found;

            ost = ost_table[n++];

            ost->file_index = k;

            ost->index = i;

            ost->st = os->streams[i];

            if (nb_stream_maps > 0) {

                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +

                    stream_maps[n-1].stream_index;

                /* Sanity check that the stream types match */

                if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {

                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",

                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,

                        ost->file_index, ost->index);

                    exit(1);

                }

            } else {

                /* get corresponding input stream index : we select the first one with the right type */

                found = 0;

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

                    ist = ist_table[j];

                    if (ist->discard &&

                        ist->st->codec.codec_type == ost->st->codec.codec_type) {

                        ost->source_index = j;

                        found = 1;

                    }

                }

                if (!found) {

                    /* try again and reuse existing stream */

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

                        ist = ist_table[j];

                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {

                            ost->source_index = j;

                            found = 1;

                        }

                    }

                    if (!found) {

                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",

                                ost->file_index, ost->index);

                        exit(1);

                    }

                }

            }

            ist = ist_table[ost->source_index];

            ist->discard = 0;

        }

    }

    /* for each output stream, we compute the right encoding parameters */

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

        ost = ost_table[i];

        ist = ist_table[ost->source_index];

        codec = &ost->st->codec;

        icodec = &ist->st->codec;

        if (ost->st->stream_copy) {

            /* if stream_copy is selected, no need to decode or encode */

            codec->codec_id = icodec->codec_id;

            codec->codec_type = icodec->codec_type;

            codec->codec_tag = icodec->codec_tag;

            codec->bit_rate = icodec->bit_rate;

            switch(codec->codec_type) {

            case CODEC_TYPE_AUDIO:

                codec->sample_rate = icodec->sample_rate;

                codec->channels = icodec->channels;

                break;

            case CODEC_TYPE_VIDEO:

                codec->frame_rate = icodec->frame_rate;

                codec->frame_rate_base = icodec->frame_rate_base;

                codec->width = icodec->width;

                codec->height = icodec->height;

                break;

            default:

                av_abort();

            }

        } else {

            switch(codec->codec_type) {

            case CODEC_TYPE_AUDIO:

                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))

                    goto fail;

                if (codec->channels == icodec->channels &&

                    codec->sample_rate == icodec->sample_rate) {

                    ost->audio_resample = 0;

                } else {

                    if (codec->channels != icodec->channels &&

                        icodec->codec_id == CODEC_ID_AC3) {

                        /* Special case for 5:1 AC3 input */

                        /* and mono or stereo output      */

                        /* Request specific number of channels */

                        icodec->channels = codec->channels;

                        if (codec->sample_rate == icodec->sample_rate)

                            ost->audio_resample = 0;

                        else {

                            ost->audio_resample = 1;

                            ost->resample = audio_resample_init(codec->channels, icodec->channels,

                                                        codec->sample_rate,

                                                        icodec->sample_rate);

			    if(!ost->resample)

			      {

				printf("Can't resample.  Aborting.\n");

				av_abort();

			      }

                        }

                        /* Request specific number of channels */

                        icodec->channels = codec->channels;

                    } else {

                        ost->audio_resample = 1;

                        ost->resample = audio_resample_init(codec->channels, icodec->channels,

                                                        codec->sample_rate,

                                                        icodec->sample_rate);

			if(!ost->resample)

			  {

			    printf("Can't resample.  Aborting.\n");

			    av_abort();

			  }

                    }

                }

                ist->decoding_needed = 1;

                ost->encoding_needed = 1;

                break;

            case CODEC_TYPE_VIDEO:

                if (codec->width == icodec->width &&

                    codec->height == icodec->height &&

                    frame_topBand == 0 &&

                    frame_bottomBand == 0 &&

                    frame_leftBand == 0 &&

                    frame_rightBand == 0)

                {

                    ost->video_resample = 0;

                    ost->video_crop = 0;

                } else if ((codec->width == icodec->width -

                                (frame_leftBand + frame_rightBand)) &&

                        (codec->height == icodec->height -

                                (frame_topBand  + frame_bottomBand)))

                {

                    ost->video_resample = 0;

                    ost->video_crop = 1;

                    ost->topBand = frame_topBand;

                    ost->leftBand = frame_leftBand;

                } else {

                    uint8_t *buf;

                    ost->video_resample = 1;

                    ost->video_crop = 0; // cropping is handled as part of resample

                    buf = av_malloc((codec->width * codec->height * 3) / 2);

                    if (!buf)

                        goto fail;

                    ost->pict_tmp.data[0] = buf;

                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);

                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;

                    ost->pict_tmp.linesize[0] = codec->width;

                    ost->pict_tmp.linesize[1] = codec->width / 2;

                    ost->pict_tmp.linesize[2] = codec->width / 2;

                    ost->img_resample_ctx = img_resample_full_init(

                                      ost->st->codec.width, ost->st->codec.height,

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

                                      frame_topBand, frame_bottomBand,

                                      frame_leftBand, frame_rightBand);

                }

                ost->encoding_needed = 1;

                ist->decoding_needed = 1;

                break;

            default:

                av_abort();

            }

            /* two pass mode */

            if (ost->encoding_needed &&

                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {

                char logfilename[1024];

                FILE *f;

                int size;

                char *logbuffer;

                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",

                         pass_logfilename ?

                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);

                if (codec->flags & CODEC_FLAG_PASS1) {

                    f = fopen(logfilename, "w");

                    if (!f) {

                        perror(logfilename);

                        exit(1);

                    }

                    ost->logfile = f;

                } else {

                    /* read the log file */

                    f = fopen(logfilename, "r");

                    if (!f) {

                        perror(logfilename);

                        exit(1);

                    }

                    fseek(f, 0, SEEK_END);

                    size = ftell(f);

                    fseek(f, 0, SEEK_SET);

                    logbuffer = av_malloc(size + 1);

                    if (!logbuffer) {

                        fprintf(stderr, "Could not allocate log buffer\n");

                        exit(1);

                    }

                    fread(logbuffer, 1, size, f);

                    fclose(f);

                    logbuffer[size] = '\0';

                    codec->stats_in = logbuffer;

                }

            }

        }

    }

    /* dump the file output parameters - cannot be done before in case

       of stream copy */

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

        dump_format(output_files[i], i, output_files[i]->filename, 1);

    }

    /* dump the stream mapping */

    fprintf(stderr, "Stream mapping:\n");

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

        ost = ost_table[i];

        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",

                ist_table[ost->source_index]->file_index,

                ist_table[ost->source_index]->index,

                ost->file_index,

                ost->index);

    }

    /* open each encoder */

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

        ost = ost_table[i];

        if (ost->encoding_needed) {

            AVCodec *codec;

            codec = avcodec_find_encoder(ost->st->codec.codec_id);

            if (!codec) {

                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",

                        ost->file_index, ost->index);

                exit(1);

            }

            if (avcodec_open(&ost->st->codec, codec) < 0) {

                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",

                        ost->file_index, ost->index);

                exit(1);

            }

        }

    }

    /* open each decoder */

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

        ist = ist_table[i];

        if (ist->decoding_needed) {

            AVCodec *codec;

            codec = avcodec_find_decoder(ist->st->codec.codec_id);

            if (!codec) {

                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",

                        ist->st->codec.codec_id, ist->file_index, ist->index);

                exit(1);

            }

            if (avcodec_open(&ist->st->codec, codec) < 0) {

                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",

                        ist->file_index, ist->index);

                exit(1);

            }

            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)

            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;

            ist->frame_decoded = 1;

        }

    }

    /* init pts */

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

        ist = ist_table[i];

	is = input_files[ist->file_index];

        ist->pts = 0;

        if (ist->decoding_needed) {

            switch (ist->st->codec.codec_type) {

            case CODEC_TYPE_AUDIO:

                av_frac_init(&ist->next_pts,

                             0, 0, is->pts_num * ist->st->codec.sample_rate);

                break;

            case CODEC_TYPE_VIDEO:

                av_frac_init(&ist->next_pts,

                             0, 0, is->pts_num * ist->st->codec.frame_rate);

                break;

            default:

                break;

            }

        }

    }

    /* compute buffer size max (should use a complete heuristic) */

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

        file_table[i].buffer_size_max = 2048;

    }

    /* open files and write file headers */

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

        os = output_files[i];

        if (av_write_header(os) < 0) {

            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);

            ret = -EINVAL;

            goto fail;

        }

    }

#ifndef CONFIG_WIN32

    if ( !using_stdin )

        fprintf(stderr, "Press [q] to stop encoding\n");

#endif

    term_init();

    stream_no_data = 0;

    key = -1;

    for(; received_sigterm == 0;) {

        int file_index, ist_index;

        AVPacket pkt;

        uint8_t *ptr;

        int len;

        uint8_t *data_buf;

        int data_size, got_picture;

        AVPicture picture;

        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];

        void *buffer_to_free;

        double pts_min;

    redo:

        /* if 'q' pressed, exits */

        if (!using_stdin) {

            /* read_key() returns 0 on EOF */

            key = read_key();

            if (key == 'q')

                break;

        }

        /* select the stream that we must read now by looking at the

           smallest output pts */

        file_index = -1;

        pts_min = 1e10;

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

            double pts;

            ost = ost_table[i];

            os = output_files[ost->file_index];

            ist = ist_table[ost->source_index];

            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;

            if (!file_table[ist->file_index].eof_reached &&

                pts < pts_min) {

                pts_min = pts;

                file_index = ist->file_index;

            }

        }

        /* if none, if is finished */

        if (file_index < 0) {

            break;

        }

        /* finish if recording time exhausted */

        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))

            break;

        /* read a packet from it and output it in the fifo */

        is = input_files[file_index];

        if (av_read_packet(is, &pkt) < 0) {

            file_table[file_index].eof_reached = 1;

            continue;

        }

        if (!pkt.size) {

            stream_no_data = is;

        } else {

            stream_no_data = 0;

        }

        if (do_hex_dump) {

            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);

            av_hex_dump(pkt.data, pkt.size);

        }

        /* the following test is needed in case new streams appear

           dynamically in stream : we ignore them */

        if (pkt.stream_index >= file_table[file_index].nb_streams)

            goto discard_packet;

        ist_index = file_table[file_index].ist_index + pkt.stream_index;

        ist = ist_table[ist_index];

        if (ist->discard)

            goto discard_packet;

        // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);

        len = pkt.size;

        ptr = pkt.data;

        while (len > 0) {

            /* decode the packet if needed */

            data_buf = NULL; /* fail safe */

            data_size = 0;

            if (ist->decoding_needed) {

                /* NOTE1: we only take into account the PTS if a new

                   frame has begun (MPEG semantics) */

                /* NOTE2: even if the fraction is not initialized,

                   av_frac_set can be used to set the integer part */

                if (ist->frame_decoded) {

                    /* If pts is unavailable -- we have to use synthetic one */

                    if( pkt.pts != AV_NOPTS_VALUE )

                    {

                        ist->pts = ist->next_pts.val = pkt.pts;

                    }

                    else

                    {

                        ist->pts = ist->next_pts.val;

                    }

                    ist->frame_decoded = 0;

                }

                switch(ist->st->codec.codec_type) {

                case CODEC_TYPE_AUDIO:

                    /* XXX: could avoid copy if PCM 16 bits with same

                       endianness as CPU */

                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,

                                               ptr, len);

                    if (ret < 0)

                        goto fail_decode;

                    /* Some bug in mpeg audio decoder gives */

                    /* data_size < 0, it seems they are overflows */

                    if (data_size <= 0) {

                        /* no audio frame */

                        ptr += ret;

                        len -= ret;

                        continue;

                    }

                    data_buf = (uint8_t *)samples;

		    av_frac_add(&ist->next_pts,

			        is->pts_den * data_size / (2 * ist->st->codec.channels));

                    break;

                case CODEC_TYPE_VIDEO:

                    {

                        AVFrame big_picture;

                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;

                        ret = avcodec_decode_video(&ist->st->codec,

                                                   &big_picture, &got_picture, ptr, len);

                        picture= *(AVPicture*)&big_picture;

                        ist->st->quality= big_picture.quality;

                        if (ret < 0) {

                        fail_decode:

                            fprintf(stderr, "Error while decoding stream #%d.%d\n",

                                    ist->file_index, ist->index);

                            av_free_packet(&pkt);

                            goto redo;

                        }

                        if (!got_picture) {

                            /* no picture yet */

                            ptr += ret;

                            len -= ret;

                            continue;

                        }

                        av_frac_add(&ist->next_pts,

			            is->pts_den * ist->st->codec.frame_rate_base);

                    }

                    break;

                default:

                    goto fail_decode;

                }

            } else {

                data_buf = ptr;

                data_size = len;

                ret = len;

            }

            ptr += ret;

            len -= ret;

            buffer_to_free = 0;

            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {

                pre_process_video_frame(ist, &picture, &buffer_to_free);

            }

            ist->frame_decoded = 1;

            /* frame rate emulation */

            if (ist->st->codec.rate_emu) {

                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);

                int64_t now = av_gettime() - ist->start;

                if (pts > now)

                    usleep(pts - now);

                ist->frame++;

            }

#if 0

            /* mpeg PTS deordering : if it is a P or I frame, the PTS

               is the one of the next displayed one */

            /* XXX: add mpeg4 too ? */

            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {

                if (ist->st->codec.pict_type != B_TYPE) {

                    int64_t tmp;

                    tmp = ist->last_ip_pts;

                    ist->last_ip_pts  = ist->frac_pts.val;

                    ist->frac_pts.val = tmp;

                }

            }

#endif

            /* transcode raw format, encode packets and output them */

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

                int frame_size;

                ost = ost_table[i];

                if (ost->source_index == ist_index) {

                    os = output_files[ost->file_index];

#if 0

                    printf("%d: got pts=%f %f\n", i, pkt.pts / 90000.0,

                           (ist->pts - ost->st->pts.val) / 90000.0);

#endif

                    /* set the input output pts pairs */

                    ost->sync_ipts = (double)ist->pts * is->pts_num /

                        is->pts_den;

                    /* XXX: take into account the various fifos,

                       in particular for audio */

                    ost->sync_opts = ost->st->pts.val;

                    //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt.pts=%lld\n", ist->pts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt.pts);

                    if (ost->encoding_needed) {

                        switch(ost->st->codec.codec_type) {

                        case CODEC_TYPE_AUDIO:

                            do_audio_out(os, ost, ist, data_buf, data_size);

                            break;

                        case CODEC_TYPE_VIDEO:

                            /* find an audio stream for synchro */

                            {

                                int i;

                                AVOutputStream *audio_sync, *ost1;

                                audio_sync = NULL;

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

                                    ost1 = ost_table[i];

                                    if (ost1->file_index == ost->file_index &&

                                        ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {

                                        audio_sync = ost1;

                                        break;

                                    }

                                }

                                do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);

                                if (do_vstats && frame_size)

                                    do_video_stats(os, ost, frame_size);

                            }

                            break;

                        default:

                            av_abort();

                        }

                    } else {

                        AVFrame avframe;

                        /* no reencoding needed : output the packet directly */

                        /* force the input stream PTS */

                        memset(&avframe, 0, sizeof(AVFrame));

                        ost->st->codec.coded_frame= &avframe;

			avframe.key_frame = pkt.flags & PKT_FLAG_KEY;

                        av_write_frame(os, ost->index, data_buf, data_size);

			ost->st->codec.frame_number++;

			ost->frame_number++;

                    }

                }

            }

            av_free(buffer_to_free);

        }

    discard_packet:

        av_free_packet(&pkt);

        /* dump report by using the output first video and audio streams */

        print_report(output_files, ost_table, nb_ostreams, 0);

    }

    term_exit();

    /* dump report by using the first video and audio streams */

    print_report(output_files, ost_table, nb_ostreams, 1);

    /* close each encoder */

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

        ost = ost_table[i];

        if (ost->encoding_needed) {

            av_freep(&ost->st->codec.stats_in);

            avcodec_close(&ost->st->codec);

        }

    }

    /* close each decoder */

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

        ist = ist_table[i];

        if (ist->decoding_needed) {

            avcodec_close(&ist->st->codec);

        }

    }

    /* write the trailer if needed and close file */

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

        os = output_files[i];

        av_write_trailer(os);

    }

    /* finished ! */

    ret = 0;

 fail1:

    av_free(file_table);

    if (ist_table) {

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

            ist = ist_table[i];

            av_free(ist);

        }

        av_free(ist_table);

    }

    if (ost_table) {

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

            ost = ost_table[i];

            if (ost) {

                if (ost->logfile) {

                    fclose(ost->logfile);

                    ost->logfile = NULL;

                }

                fifo_free(&ost->fifo); /* works even if fifo is not

                                          initialized but set to zero */

                av_free(ost->pict_tmp.data[0]);

                if (ost->video_resample)

                    img_resample_close(ost->img_resample_ctx);

                if (ost->audio_resample)

                    audio_resample_close(ost->resample);

                av_free(ost);

            }

        }

        av_free(ost_table);

    }

    return ret;

 fail:

    ret = -ENOMEM;

    goto fail1;

}


int avpriv_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf,
                                 int bit_size, int sync_extension)
{
    GetBitContext gb;
    int specific_config_bitindex;
    init_get_bits(&gb, buf, bit_size);
    c->object_type = get_object_type(&gb);
    c->sample_rate = get_sample_rate(&gb, &c->sampling_index);
    c->chan_config = get_bits(&gb, 4);
    if (c->chan_config < FF_ARRAY_ELEMS(ff_mpeg4audio_channels))
        c->channels = ff_mpeg4audio_channels[c->chan_config];
    c->sbr = -1;
    c->ps  = -1;
    if (c->object_type == AOT_SBR || (c->object_type == AOT_PS &&
        // check for W6132 Annex YYYY draft MP3onMP4
        !(show_bits(&gb, 3) & 0x03 && !(show_bits(&gb, 9) & 0x3F)))) {
        if (c->object_type == AOT_PS)
            c->ps = 1;
        c->ext_object_type = AOT_SBR;
        c->sbr = 1;
        c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);
        c->object_type = get_object_type(&gb);
        if (c->object_type == AOT_ER_BSAC)
            c->ext_chan_config = get_bits(&gb, 4);
    } else {
        c->ext_object_type = AOT_NULL;
        c->ext_sample_rate = 0;
    }
    specific_config_bitindex = get_bits_count(&gb);
    if (c->object_type == AOT_ALS) {
        skip_bits(&gb, 5);
        if (show_bits_long(&gb, 24) != MKBETAG('\0','A','L','S'))
            skip_bits_long(&gb, 24);
        specific_config_bitindex = get_bits_count(&gb);
        if (parse_config_ALS(&gb, c))
            return -1;
    }
    if (c->ext_object_type != AOT_SBR && sync_extension) {
        while (get_bits_left(&gb) > 15) {
            if (show_bits(&gb, 11) == 0x2b7) { // sync extension
                get_bits(&gb, 11);
                c->ext_object_type = get_object_type(&gb);
                if (c->ext_object_type == AOT_SBR && (c->sbr = get_bits1(&gb)) == 1)
                    c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);
                if (get_bits_left(&gb) > 11 && get_bits(&gb, 11) == 0x548)
                    c->ps = get_bits1(&gb);
                break;
            } else
                get_bits1(&gb); // skip 1 bit
        }
    }
    //PS requires SBR
    if (!c->sbr)
        c->ps = 0;
    //Limit implicit PS to the HE-AACv2 Profile
    if ((c->ps == -1 && c->object_type != AOT_AAC_LC) || c->channels & ~0x01)
        c->ps = 0;
    return specific_config_bitindex;
}


static av_always_inline void vc1_apply_p_h_loop_filter(VC1Context *v, int block_num)

{

    MpegEncContext *s  = &v->s;

    int mb_cbp         = v->cbp[s->mb_x - 1 - s->mb_stride],

        block_cbp      = mb_cbp      >> (block_num * 4), right_cbp,

        mb_is_intra    = v->is_intra[s->mb_x - 1 - s->mb_stride],

        block_is_intra = mb_is_intra >> (block_num * 4), right_is_intra;

    int idx, linesize  = block_num > 3 ? s->uvlinesize : s->linesize, ttblk;

    uint8_t *dst;

    if (block_num > 3) {

        dst = s->dest[block_num - 3] - 8 * linesize;

    } else {

        dst = s->dest[0] + (block_num & 1) * 8 + ((block_num & 2) * 4 - 16) * linesize - 8;

    }

    if (s->mb_x != s->mb_width || !(block_num & 5)) {

        int16_t (*mv)[2];

        if (block_num > 3) {

            right_cbp      = v->cbp[s->mb_x - s->mb_stride] >> (block_num * 4);

            right_is_intra = v->is_intra[s->mb_x - s->mb_stride] >> (block_num * 4);

            mv             = &v->luma_mv[s->mb_x - s->mb_stride - 1];

        } else {

            right_cbp      = (block_num & 1) ? (v->cbp[s->mb_x - s->mb_stride]      >> ((block_num - 1) * 4))

                                             : (mb_cbp                              >> ((block_num + 1) * 4));

            right_is_intra = (block_num & 1) ? (v->is_intra[s->mb_x - s->mb_stride] >> ((block_num - 1) * 4))

                                             : (mb_is_intra                         >> ((block_num + 1) * 4));

            mv             = &s->current_picture.motion_val[0][s->block_index[block_num] - s->b8_stride * 2 - 2];

        }

        if (block_is_intra & 1 || right_is_intra & 1 || mv[0][0] != mv[1][0] || mv[0][1] != mv[1][1]) {

            v->vc1dsp.vc1_h_loop_filter8(dst, linesize, v->pq);

        } else {

            idx = ((right_cbp >> 1) | block_cbp) & 5; // FIXME check

            if (idx == 5) {

                v->vc1dsp.vc1_h_loop_filter8(dst, linesize, v->pq);

            } else if (idx) {

                if (idx == 1)

                    v->vc1dsp.vc1_h_loop_filter4(dst + 4 * linesize, linesize, v->pq);

                else

                    v->vc1dsp.vc1_h_loop_filter4(dst,                linesize, v->pq);

            }

        }

    }

    dst -= 4;

    ttblk = (v->ttblk[s->mb_x - s->mb_stride - 1] >> (block_num * 4)) & 0xf;

    if (ttblk == TT_4X4 || ttblk == TT_4X8) {

        idx = (block_cbp | (block_cbp >> 1)) & 5;

        if (idx == 5) {

            v->vc1dsp.vc1_h_loop_filter8(dst, linesize, v->pq);

        } else if (idx) {

            if (idx == 1)

                v->vc1dsp.vc1_h_loop_filter4(dst + linesize * 4, linesize, v->pq);

            else

                v->vc1dsp.vc1_h_loop_filter4(dst,                linesize, v->pq);

        }

    }

}


static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size, uint8_t **data)

{

    AVIOContext *pb = s->pb;

    int len;

    for(;;) {

        len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);

        if (len != TS_PACKET_SIZE)

            return len < 0 ? len : AVERROR_EOF;

        /* check packet sync byte */

        if ((*data)[0] != 0x47) {

            /* find a new packet start */

            avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);

            if (mpegts_resync(s) < 0)

                return AVERROR(EAGAIN);

            else

                continue;

        } else {

            break;

        }

    }

    return 0;

}


int ff_parse_sample_rate(unsigned *ret, const char *arg, void *log_ctx)

{

    char *tail;

    double srate = av_strtod(arg, &tail);

    if (*tail || srate < 1 || (int)srate != srate) {

        av_log(log_ctx, AV_LOG_ERROR, "Invalid sample rate '%s'\n", arg);

        return AVERROR(EINVAL);

    }

    *ret = srate;

    return 0;

}


static void decode_abs_store(CPUTriCoreState *env, DisasContext *ctx)

{

    int32_t op2;

    int32_t r1;

    uint32_t address;

    TCGv temp;

    r1 = MASK_OP_ABS_S1D(ctx->opcode);

    address = MASK_OP_ABS_OFF18(ctx->opcode);

    op2 = MASK_OP_ABS_OP2(ctx->opcode);

    temp = tcg_const_i32(EA_ABS_FORMAT(address));

    switch (op2) {

    case OPC2_32_ABS_ST_A:

        tcg_gen_qemu_st_tl(cpu_gpr_a[r1], temp, ctx->mem_idx, MO_LESL);

        break;

    case OPC2_32_ABS_ST_D:

        gen_st_2regs_64(cpu_gpr_d[r1+1], cpu_gpr_d[r1], temp, ctx);

        break;

    case OPC2_32_ABS_ST_DA:

        gen_st_2regs_64(cpu_gpr_a[r1+1], cpu_gpr_a[r1], temp, ctx);

        break;

    case OPC2_32_ABS_ST_W:

        tcg_gen_qemu_st_tl(cpu_gpr_d[r1], temp, ctx->mem_idx, MO_LESL);

        break;

    }

    tcg_temp_free(temp);

}


static void v9fs_readdir(void *opaque)

{

    int32_t fid;

    V9fsFidState *fidp;

    ssize_t retval = 0;

    size_t offset = 7;

    uint64_t initial_offset;

    int32_t count;

    uint32_t max_count;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "dqd", &fid, &initial_offset, &max_count);

    trace_v9fs_readdir(pdu->tag, pdu->id, fid, initial_offset, max_count);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        retval = -EINVAL;

        goto out_nofid;

    }

    if (!fidp->fs.dir) {

        retval = -EINVAL;

        goto out;

    }

    if (initial_offset == 0) {

        v9fs_co_rewinddir(pdu, fidp);

    } else {

        v9fs_co_seekdir(pdu, fidp, initial_offset);

    }

    count = v9fs_do_readdir(pdu, fidp, max_count);

    if (count < 0) {

        retval = count;

        goto out;

    }

    retval = offset;

    retval += pdu_marshal(pdu, offset, "d", count);

    retval += count;

    trace_v9fs_readdir_return(pdu->tag, pdu->id, count, retval);

out:

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, retval);

}


uint64_t HELPER(lra)(CPUS390XState *env, uint64_t addr)

{

    CPUState *cs = CPU(s390_env_get_cpu(env));

    uint32_t cc = 0;

    int old_exc = cs->exception_index;

    uint64_t asc = env->psw.mask & PSW_MASK_ASC;

    uint64_t ret;

    int flags;

    /* XXX incomplete - has more corner cases */

    if (!(env->psw.mask & PSW_MASK_64) && (addr >> 32)) {

        program_interrupt(env, PGM_SPECIAL_OP, 2);

    }

    cs->exception_index = old_exc;

    if (mmu_translate(env, addr, 0, asc, &ret, &flags)) {

        cc = 3;

    }

    if (cs->exception_index == EXCP_PGM) {

        ret = env->int_pgm_code | 0x80000000;

    } else {

        ret |= addr & ~TARGET_PAGE_MASK;

    }

    cs->exception_index = old_exc;

    env->cc_op = cc;

    return ret;

}


static int bdrv_check_update_perm(BlockDriverState *bs, uint64_t new_used_perm,

                                  uint64_t new_shared_perm,

                                  BdrvChild *ignore_child, Error **errp)

{

    BdrvChild *c;

    uint64_t cumulative_perms = new_used_perm;

    uint64_t cumulative_shared_perms = new_shared_perm;

    /* There is no reason why anyone couldn't tolerate write_unchanged */

    assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);

    QLIST_FOREACH(c, &bs->parents, next_parent) {

        if (c == ignore_child) {

            continue;

        }

        if ((new_used_perm & c->shared_perm) != new_used_perm) {

            char *user = bdrv_child_user_desc(c);

            char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);

            error_setg(errp, "Conflicts with use by %s as '%s', which does not "

                             "allow '%s' on %s",

                       user, c->name, perm_names, bdrv_get_node_name(c->bs));

            g_free(user);

            g_free(perm_names);

            return -EPERM;

        }

        if ((c->perm & new_shared_perm) != c->perm) {

            char *user = bdrv_child_user_desc(c);

            char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);

            error_setg(errp, "Conflicts with use by %s as '%s', which uses "

                             "'%s' on %s",

                       user, c->name, perm_names, bdrv_get_node_name(c->bs));

            g_free(user);

            g_free(perm_names);

            return -EPERM;

        }

        cumulative_perms |= c->perm;

        cumulative_shared_perms &= c->shared_perm;

    }

    return bdrv_check_perm(bs, cumulative_perms, cumulative_shared_perms, errp);

}


static void monitor_protocol_emitter(Monitor *mon, QObject *data)

{

    QDict *qmp;

    qmp = qdict_new();

    if (!monitor_has_error(mon)) {

        /* success response */

        if (data) {

            assert(qobject_type(data) == QTYPE_QDICT);

            qobject_incref(data);

            qdict_put_obj(qmp, "return", data);

        } else {

            /* return an empty QDict by default */

            qdict_put(qmp, "return", qdict_new());

        }

    } else {

        /* error response */

        qdict_put(mon->error->error, "desc", qerror_human(mon->error));

        qdict_put(qmp, "error", mon->error->error);

        QINCREF(mon->error->error);

        QDECREF(mon->error);

        mon->error = NULL;

    }

    if (mon->mc->id) {

        qdict_put_obj(qmp, "id", mon->mc->id);

        mon->mc->id = NULL;

    }

    monitor_json_emitter(mon, QOBJECT(qmp));

    QDECREF(qmp);

}


static inline int decode_vui_parameters(H264Context *h, SPS *sps)

{

    int aspect_ratio_info_present_flag;

    unsigned int aspect_ratio_idc;

    aspect_ratio_info_present_flag = get_bits1(&h->gb);

    if (aspect_ratio_info_present_flag) {

        aspect_ratio_idc = get_bits(&h->gb, 8);

        if (aspect_ratio_idc == EXTENDED_SAR) {

            sps->sar.num = get_bits(&h->gb, 16);

            sps->sar.den = get_bits(&h->gb, 16);

        } else if (aspect_ratio_idc < FF_ARRAY_ELEMS(pixel_aspect)) {

            sps->sar = pixel_aspect[aspect_ratio_idc];

        } else {

            av_log(h->avctx, AV_LOG_ERROR, "illegal aspect ratio\n");

            return AVERROR_INVALIDDATA;

        }

    } else {

        sps->sar.num =

        sps->sar.den = 0;

    }

    if (get_bits1(&h->gb))      /* overscan_info_present_flag */

        get_bits1(&h->gb);      /* overscan_appropriate_flag */

    sps->video_signal_type_present_flag = get_bits1(&h->gb);

    if (sps->video_signal_type_present_flag) {

        get_bits(&h->gb, 3);                 /* video_format */

        sps->full_range = get_bits1(&h->gb); /* video_full_range_flag */

        sps->colour_description_present_flag = get_bits1(&h->gb);

        if (sps->colour_description_present_flag) {

            sps->color_primaries = get_bits(&h->gb, 8); /* colour_primaries */

            sps->color_trc       = get_bits(&h->gb, 8); /* transfer_characteristics */

            sps->colorspace      = get_bits(&h->gb, 8); /* matrix_coefficients */

            if (sps->color_primaries >= AVCOL_PRI_NB)

                sps->color_primaries = AVCOL_PRI_UNSPECIFIED;

            if (sps->color_trc >= AVCOL_TRC_NB)

                sps->color_trc = AVCOL_TRC_UNSPECIFIED;

            if (sps->colorspace >= AVCOL_SPC_NB)

                sps->colorspace = AVCOL_SPC_UNSPECIFIED;

        }

    }

    /* chroma_location_info_present_flag */

    if (get_bits1(&h->gb)) {

        /* chroma_sample_location_type_top_field */

        h->avctx->chroma_sample_location = get_ue_golomb(&h->gb) + 1;

        get_ue_golomb(&h->gb);  /* chroma_sample_location_type_bottom_field */

    }

    sps->timing_info_present_flag = get_bits1(&h->gb);

    if (sps->timing_info_present_flag) {

        sps->num_units_in_tick = get_bits_long(&h->gb, 32);

        sps->time_scale        = get_bits_long(&h->gb, 32);

        if (!sps->num_units_in_tick || !sps->time_scale) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "time_scale/num_units_in_tick invalid or unsupported (%"PRIu32"/%"PRIu32")\n",

                   sps->time_scale, sps->num_units_in_tick);

            return AVERROR_INVALIDDATA;

        }

        sps->fixed_frame_rate_flag = get_bits1(&h->gb);

    }

    sps->nal_hrd_parameters_present_flag = get_bits1(&h->gb);

    if (sps->nal_hrd_parameters_present_flag)

        if (decode_hrd_parameters(h, sps) < 0)

            return AVERROR_INVALIDDATA;

    sps->vcl_hrd_parameters_present_flag = get_bits1(&h->gb);

    if (sps->vcl_hrd_parameters_present_flag)

        if (decode_hrd_parameters(h, sps) < 0)

            return AVERROR_INVALIDDATA;

    if (sps->nal_hrd_parameters_present_flag ||

        sps->vcl_hrd_parameters_present_flag)

        get_bits1(&h->gb);     /* low_delay_hrd_flag */

    sps->pic_struct_present_flag = get_bits1(&h->gb);

    sps->bitstream_restriction_flag = get_bits1(&h->gb);

    if (sps->bitstream_restriction_flag) {

        get_bits1(&h->gb);     /* motion_vectors_over_pic_boundaries_flag */

        get_ue_golomb(&h->gb); /* max_bytes_per_pic_denom */

        get_ue_golomb(&h->gb); /* max_bits_per_mb_denom */

        get_ue_golomb(&h->gb); /* log2_max_mv_length_horizontal */

        get_ue_golomb(&h->gb); /* log2_max_mv_length_vertical */

        sps->num_reorder_frames = get_ue_golomb(&h->gb);

        get_ue_golomb(&h->gb); /*max_dec_frame_buffering*/

        if (get_bits_left(&h->gb) < 0) {

            sps->num_reorder_frames         = 0;

            sps->bitstream_restriction_flag = 0;

        }

        if (sps->num_reorder_frames > 16U

            /* max_dec_frame_buffering || max_dec_frame_buffering > 16 */) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "Clipping illegal num_reorder_frames %d\n",

                   sps->num_reorder_frames);

            sps->num_reorder_frames = 16;

            return AVERROR_INVALIDDATA;

        }

    }

    if (get_bits_left(&h->gb) < 0) {

        av_log(h->avctx, AV_LOG_ERROR,

               "Overread VUI by %d bits\n", -get_bits_left(&h->gb));

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,

                          const uint8_t *buf, int nb_sectors)

{

    BlockDriver *drv = bs->drv;

    int ret;

    if (!drv) {

        return -ENOMEDIUM;

    }

    if (!drv->bdrv_write_compressed) {

        return -ENOTSUP;

    }

    ret = bdrv_check_request(bs, sector_num, nb_sectors);

    if (ret < 0) {

        return ret;

    }

    assert(QLIST_EMPTY(&bs->dirty_bitmaps));

    return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);

}


static int usb_host_handle_control(USBDevice *dev, USBPacket *p,

               int request, int value, int index, int length, uint8_t *data)

{

    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);

    struct usbdevfs_urb *urb;

    AsyncURB *aurb;

    int ret;

    /*

     * Process certain standard device requests.

     * These are infrequent and are processed synchronously.

     */

    /* Note request is (bRequestType << 8) | bRequest */

    trace_usb_host_req_control(s->bus_num, s->addr, request, value, index);

    switch (request) {

    case DeviceOutRequest | USB_REQ_SET_ADDRESS:

        return usb_host_set_address(s, value);

    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:

        return usb_host_set_config(s, value & 0xff);

    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:

        return usb_host_set_interface(s, index, value);

    }

    /* The rest are asynchronous */

    if (length > sizeof(dev->data_buf)) {

        fprintf(stderr, "husb: ctrl buffer too small (%d > %zu)\n",

                length, sizeof(dev->data_buf));

        return USB_RET_STALL;

    }

    aurb = async_alloc(s);

    aurb->packet = p;

    /*

     * Setup ctrl transfer.

     *

     * s->ctrl is laid out such that data buffer immediately follows

     * 'req' struct which is exactly what usbdevfs expects.

     */

    urb = &aurb->urb;

    urb->type     = USBDEVFS_URB_TYPE_CONTROL;

    urb->endpoint = p->devep;

    urb->buffer        = &dev->setup_buf;

    urb->buffer_length = length + 8;

    urb->usercontext = s;

    trace_usb_host_urb_submit(s->bus_num, s->addr, aurb,

                              urb->buffer_length, aurb->more);

    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);

    DPRINTF("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);

    if (ret < 0) {

        DPRINTF("husb: submit failed. errno %d\n", errno);

        async_free(aurb);

        switch(errno) {

        case ETIMEDOUT:

            return USB_RET_NAK;

        case EPIPE:

        default:

            return USB_RET_STALL;

        }

    }

    return USB_RET_ASYNC;

}


static int dshow_read_header(AVFormatContext *avctx)

{

    struct dshow_ctx *ctx = avctx->priv_data;

    IGraphBuilder *graph = NULL;

    ICreateDevEnum *devenum = NULL;

    IMediaControl *control = NULL;

    IMediaEvent *media_event = NULL;

    HANDLE media_event_handle;

    HANDLE proc;

    int ret = AVERROR(EIO);

    int r;

    CoInitialize(0);

    if (!ctx->list_devices && !parse_device_name(avctx)) {

        av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");

        goto error;

    }

    ctx->video_codec_id = avctx->video_codec_id ? avctx->video_codec_id

                                                : AV_CODEC_ID_RAWVIDEO;

    if (ctx->pixel_format != AV_PIX_FMT_NONE) {

        if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) {

            av_log(avctx, AV_LOG_ERROR, "Pixel format may only be set when "

                              "video codec is not set or set to rawvideo\n");

            ret = AVERROR(EINVAL);

            goto error;

        }

    }

    if (ctx->framerate) {

        r = av_parse_video_rate(&ctx->requested_framerate, ctx->framerate);

        if (r < 0) {

            av_log(avctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate);

            goto error;

        }

    }

    r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,

                         &IID_IGraphBuilder, (void **) &graph);

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");

        goto error;

    }

    ctx->graph = graph;

    r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,

                         &IID_ICreateDevEnum, (void **) &devenum);

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");

        goto error;

    }

    if (ctx->list_devices) {

        av_log(avctx, AV_LOG_INFO, "DirectShow video devices\n");

        dshow_cycle_devices(avctx, devenum, VideoDevice, NULL);

        av_log(avctx, AV_LOG_INFO, "DirectShow audio devices\n");

        dshow_cycle_devices(avctx, devenum, AudioDevice, NULL);

        ret = AVERROR_EXIT;

        goto error;

    }

    if (ctx->list_options) {

        if (ctx->device_name[VideoDevice])

            dshow_list_device_options(avctx, devenum, VideoDevice);

        if (ctx->device_name[AudioDevice])

            dshow_list_device_options(avctx, devenum, AudioDevice);

        ret = AVERROR_EXIT;

        goto error;

    }

    if (ctx->device_name[VideoDevice]) {

        if ((r = dshow_open_device(avctx, devenum, VideoDevice)) < 0 ||

            (r = dshow_add_device(avctx, VideoDevice)) < 0) {

            ret = r;

            goto error;

        }

    }

    if (ctx->device_name[AudioDevice]) {

        if ((r = dshow_open_device(avctx, devenum, AudioDevice)) < 0 ||

            (r = dshow_add_device(avctx, AudioDevice)) < 0) {

            ret = r;

            goto error;

        }

    }

    ctx->mutex = CreateMutex(NULL, 0, NULL);

    if (!ctx->mutex) {

        av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");

        goto error;

    }

    ctx->event[1] = CreateEvent(NULL, 1, 0, NULL);

    if (!ctx->event[1]) {

        av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");

        goto error;

    }

    r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");

        goto error;

    }

    ctx->control = control;

    r = IGraphBuilder_QueryInterface(graph, &IID_IMediaEvent, (void **) &media_event);

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not get media event.\n");

        goto error;

    }

    ctx->media_event = media_event;

    r = IMediaEvent_GetEventHandle(media_event, (void *) &media_event_handle);

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not get media event handle.\n");

        goto error;

    }

    proc = GetCurrentProcess();

    r = DuplicateHandle(proc, media_event_handle, proc, &ctx->event[0],

                        0, 0, DUPLICATE_SAME_ACCESS);

    if (!r) {

        av_log(avctx, AV_LOG_ERROR, "Could not duplicate media event handle.\n");

        goto error;

    }

    r = IMediaControl_Run(control);

    if (r == S_FALSE) {

        OAFilterState pfs;

        r = IMediaControl_GetState(control, 0, &pfs);

    }

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not run filter\n");

        goto error;

    }

    ret = 0;

error:

    if (devenum)

        ICreateDevEnum_Release(devenum);

    if (ret < 0)

        dshow_read_close(avctx);

    return ret;

}


static inline void s390_machine_initfn(Object *obj)

{

    object_property_add_bool(obj, "aes-key-wrap",

                             machine_get_aes_key_wrap,

                             machine_set_aes_key_wrap, NULL);

    object_property_set_description(obj, "aes-key-wrap",

            "enable/disable AES key wrapping using the CPACF wrapping key",

    object_property_set_bool(obj, true, "aes-key-wrap", NULL);

    object_property_add_bool(obj, "dea-key-wrap",

                             machine_get_dea_key_wrap,

                             machine_set_dea_key_wrap, NULL);

    object_property_set_description(obj, "dea-key-wrap",

            "enable/disable DEA key wrapping using the CPACF wrapping key",

    object_property_set_bool(obj, true, "dea-key-wrap", NULL);

    object_property_add_str(obj, "loadparm",

            machine_get_loadparm, machine_set_loadparm, NULL);

    object_property_set_description(obj, "loadparm",

            "Up to 8 chars in set of [A-Za-z0-9. ] (lower case chars converted"

            " to upper case) to pass to machine loader, boot manager,"

            " and guest kernel",

}


static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)

{

    int i, mb_x, mb_y;

    uint16_t (*buffer)[4];

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

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

    const int mask     = ((1 << s->bits) - 1) << point_transform;

    int resync_mb_y = 0;

    int resync_mb_x = 0;

    if (s->nb_components != 3 && s->nb_components != 4)

        return AVERROR_INVALIDDATA;

    if (s->v_max != 1 || s->h_max != 1 || !s->lossless)

        return AVERROR_INVALIDDATA;

    s->restart_count = s->restart_interval;

    av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,

                   (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));

    buffer = s->ljpeg_buffer;

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

        buffer[0][i] = 1 << (s->bits - 1);

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

        uint8_t *ptr = s->picture_ptr->data[0] + (linesize * mb_y);

        if (s->interlaced && s->bottom_field)

            ptr += linesize >> 1;

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

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

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

            int modified_predictor = predictor;

            if (s->restart_interval && !s->restart_count){

                s->restart_count = s->restart_interval;

                resync_mb_x = mb_x;

                resync_mb_y = mb_y;

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

                    top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);

            }

            if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)

                modified_predictor = 1;

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

                int pred, dc;

                topleft[i] = top[i];

                top[i]     = buffer[mb_x][i];

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

                dc = mjpeg_decode_dc(s, s->dc_index[i]);

                if(dc == 0xFFFFF)

                    return -1;

                left[i] = buffer[mb_x][i] =

                    mask & (pred + (dc << point_transform));

            }

            if (s->restart_interval && !--s->restart_count) {

                align_get_bits(&s->gb);

                skip_bits(&s->gb, 16); /* skip RSTn */

            }

        }

        if (s->rct && s->nb_components == 4) {

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

                ptr[4*mb_x + 2] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);

                ptr[4*mb_x + 1] = buffer[mb_x][1] + ptr[4*mb_x + 2];

                ptr[4*mb_x + 3] = buffer[mb_x][2] + ptr[4*mb_x + 2];

                ptr[4*mb_x + 0] = buffer[mb_x][3];

            }

        } else if (s->nb_components == 4) {

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

                int c= s->comp_index[i];

                if (s->bits <= 8) {

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

                        ptr[4*mb_x+3-c] = buffer[mb_x][i];

                    }

                } else if(s->bits == 9) {

                    return AVERROR_PATCHWELCOME;

                } else {

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

                        ((uint16_t*)ptr)[4*mb_x+c] = buffer[mb_x][i];

                    }

                }

            }

        } else if (s->rct) {

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

                ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);

                ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];

                ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];

            }

        } else if (s->pegasus_rct) {

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

                ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);

                ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];

                ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];

            }

        } else {

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

                int c= s->comp_index[i];

                if (s->bits <= 8) {

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

                        ptr[3*mb_x+2-c] = buffer[mb_x][i];

                    }

                } else if(s->bits == 9) {

                    return AVERROR_PATCHWELCOME;

                } else {

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

                        ((uint16_t*)ptr)[3*mb_x+2-c] = buffer[mb_x][i];

                    }

                }

            }

        }

    }

    return 0;

}


static void qemu_spice_display_init_one(QemuConsole *con)

{

    SimpleSpiceDisplay *ssd = g_new0(SimpleSpiceDisplay, 1);

    qemu_spice_display_init_common(ssd);

    ssd->qxl.base.sif = &dpy_interface.base;

    qemu_spice_add_display_interface(&ssd->qxl, con);

    assert(ssd->worker);

    qemu_spice_create_host_memslot(ssd);

    ssd->dcl.ops = &display_listener_ops;

    ssd->dcl.con = con;

    register_displaychangelistener(&ssd->dcl);

}


int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,

                              int64_t wanted_timestamp, int flags)

{

    int a, b, m;

    int64_t timestamp;

    a = -1;

    b = nb_entries;

    // Optimize appending index entries at the end.

    if (b && entries[b - 1].timestamp < wanted_timestamp)

        a = b - 1;

    while (b - a > 1) {

        m         = (a + b) >> 1;

        // Search for the next non-discarded packet.

        while ((entries[m].flags & AVINDEX_DISCARD_FRAME) && m < b) {

            m++;

            if (m == b && entries[m].timestamp >= wanted_timestamp) {

                m = b - 1;

                break;

            }

        }

        timestamp = entries[m].timestamp;

        if (timestamp >= wanted_timestamp)

            b = m;

        if (timestamp <= wanted_timestamp)

            a = m;

    }

    m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;

    if (!(flags & AVSEEK_FLAG_ANY))

        while (m >= 0 && m < nb_entries &&

               !(entries[m].flags & AVINDEX_KEYFRAME))

            m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;

    if (m == nb_entries)

        return -1;

    return m;

}


static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
{
    InputStream *ist = s->opaque;
    FrameBuffer *buf;
    int ret, i;
    if (!ist->buffer_pool && (ret = alloc_buffer(s, ist, &ist->buffer_pool)) < 0)
        return ret;
    buf              = ist->buffer_pool;
    ist->buffer_pool = buf->next;
    buf->next        = NULL;
    if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
        av_freep(&buf->base[0]);
        av_free(buf);
        ist->dr1 = 0;
        if ((ret = alloc_buffer(s, ist, &buf)) < 0)
            return ret;
    }
    buf->refcount++;
    frame->opaque        = buf;
    frame->type          = FF_BUFFER_TYPE_USER;
    frame->extended_data = frame->data;
    frame->pkt_pts       = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
    for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
        frame->base[i]     = buf->base[i];  // XXX h264.c uses base though it shouldn't
        frame->data[i]     = buf->data[i];
        frame->linesize[i] = buf->linesize[i];
    }
    return 0;
}


static int filter_frame(AVFilterLink *inlink, AVFrame *inpic)

{

    AVFilterContext   *ctx     = inlink->dst;

    HisteqContext     *histeq  = ctx->priv;

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

    int strength  = histeq->strength  * 1000;

    int intensity = histeq->intensity * 1000;

    int x, y, i, luthi, lutlo, lut, luma, oluma, m;

    AVFrame *outpic;

    unsigned int r, g, b, jran;

    uint8_t *src, *dst;

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

    if (!outpic) {

        av_frame_free(&inpic);

        return AVERROR(ENOMEM);

    }

    av_frame_copy_props(outpic, inpic);

    /* Seed random generator for antibanding. */

    jran = LCG_SEED;

    /* Calculate and store the luminance and calculate the global histogram

       based on the luminance. */

    memset(histeq->in_histogram, 0, sizeof(histeq->in_histogram));

    src = inpic->data[0];

    dst = outpic->data[0];

    for (y = 0; y < inlink->h; y++) {

        for (x = 0; x < inlink->w * histeq->bpp; x += histeq->bpp) {

            GET_RGB_VALUES(r, g, b, src, histeq->rgba_map);

            luma = (55 * r + 182 * g + 19 * b) >> 8;

            dst[x + histeq->rgba_map[A]] = luma;

            histeq->in_histogram[luma]++;

        }

        src += inpic->linesize[0];

        dst += outpic->linesize[0];

    }

#ifdef DEBUG

    for (x = 0; x < 256; x++)

        av_dlog(ctx, "in[%d]: %u\n", x, histeq->in_histogram[x]);

#endif

    /* Calculate the lookup table. */

    histeq->LUT[0] = histeq->in_histogram[0];

    /* Accumulate */

    for (x = 1; x < 256; x++)

        histeq->LUT[x] = histeq->LUT[x-1] + histeq->in_histogram[x];

    /* Normalize */

    for (x = 0; x < 256; x++)

        histeq->LUT[x] = (histeq->LUT[x] * intensity) / (inlink->h * inlink->w);

    /* Adjust the LUT based on the selected strength. This is an alpha

       mix of the calculated LUT and a linear LUT with gain 1. */

    for (x = 0; x < 256; x++)

        histeq->LUT[x] = (strength * histeq->LUT[x]) / 255 +

                         ((255 - strength) * x)      / 255;

    /* Output the equalized frame. */

    memset(histeq->out_histogram, 0, sizeof(histeq->out_histogram));

    src = inpic->data[0];

    dst = outpic->data[0];

    for (y = 0; y < inlink->h; y++) {

        for (x = 0; x < inlink->w * histeq->bpp; x += histeq->bpp) {

            luma = dst[x + histeq->rgba_map[A]];

            if (luma == 0) {

                for (i = 0; i < histeq->bpp; ++i)

                    dst[x + i] = 0;

                histeq->out_histogram[0]++;

            } else {

                lut = histeq->LUT[luma];

                if (histeq->antibanding != HISTEQ_ANTIBANDING_NONE) {

                    if (luma > 0) {

                        lutlo = histeq->antibanding == HISTEQ_ANTIBANDING_WEAK ?

                                (histeq->LUT[luma] + histeq->LUT[luma - 1]) / 2 :

                                 histeq->LUT[luma - 1];

                    } else

                        lutlo = lut;

                    if (luma < 255) {

                        luthi = (histeq->antibanding == HISTEQ_ANTIBANDING_WEAK) ?

                            (histeq->LUT[luma] + histeq->LUT[luma + 1]) / 2 :

                             histeq->LUT[luma + 1];

                    } else

                        luthi = lut;

                    if (lutlo != luthi) {

                        jran = LCG(jran);

                        lut = lutlo + ((luthi - lutlo + 1) * jran) / LCG_M;

                    }

                }

                GET_RGB_VALUES(r, g, b, src, histeq->rgba_map);

                if (((m = FFMAX3(r, g, b)) * lut) / luma > 255) {

                    r = (r * 255) / m;

                    g = (g * 255) / m;

                    b = (b * 255) / m;

                } else {

                    r = (r * lut) / luma;

                    g = (g * lut) / luma;

                    b = (b * lut) / luma;

                }

                dst[x + histeq->rgba_map[R]] = r;

                dst[x + histeq->rgba_map[G]] = g;

                dst[x + histeq->rgba_map[B]] = b;

                oluma = (55 * r + 182 * g + 19 * b) >> 8;

                histeq->out_histogram[oluma]++;

            }

        }

        src += inpic->linesize[0];

        dst += outpic->linesize[0];

    }

#ifdef DEBUG

    for (x = 0; x < 256; x++)

        av_dlog(ctx, "out[%d]: %u\n", x, histeq->out_histogram[x]);

#endif

    av_frame_free(&inpic);

    return ff_filter_frame(outlink, outpic);

}


static void test_visitor_in_native_list_int32(TestInputVisitorData *data,

                                              const void *unused)

{

    test_native_list_integer_helper(data, unused,

                                    USER_DEF_NATIVE_LIST_UNION_KIND_S32);

}


static void nbd_trip(void *opaque)

{

    NBDClient *client = opaque;

    NBDExport *exp = client->exp;

    NBDRequest *req;

    struct nbd_request request;

    struct nbd_reply reply;

    ssize_t ret;

    uint32_t command;

    TRACE("Reading request.");

    if (client->closing) {

        return;

    }

    req = nbd_request_get(client);

    ret = nbd_co_receive_request(req, &request);

    if (ret == -EAGAIN) {

        goto done;

    }

    if (ret == -EIO) {

        goto out;

    }

    reply.handle = request.handle;

    reply.error = 0;

    if (ret < 0) {

        reply.error = -ret;

        goto error_reply;

    }

    command = request.type & NBD_CMD_MASK_COMMAND;

    if (command != NBD_CMD_DISC && (request.from + request.len) > exp->size) {

            LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64

            ", Offset: %" PRIu64 "\n",

                    request.from, request.len,

                    (uint64_t)exp->size, (uint64_t)exp->dev_offset);

        LOG("requested operation past EOF--bad client?");

        goto invalid_request;

    }

    if (client->closing) {

        /*

         * The client may be closed when we are blocked in

         * nbd_co_receive_request()

         */

        goto done;

    }

    switch (command) {

    case NBD_CMD_READ:

        TRACE("Request type is READ");

        if (request.type & NBD_CMD_FLAG_FUA) {

            ret = blk_co_flush(exp->blk);

            if (ret < 0) {

                LOG("flush failed");

                reply.error = -ret;

                goto error_reply;

            }

        }

        ret = blk_pread(exp->blk, request.from + exp->dev_offset,

                        req->data, request.len);

        if (ret < 0) {

            LOG("reading from file failed");

            reply.error = -ret;

            goto error_reply;

        }

        TRACE("Read %u byte(s)", request.len);

        if (nbd_co_send_reply(req, &reply, request.len) < 0)

            goto out;

        break;

    case NBD_CMD_WRITE:

        TRACE("Request type is WRITE");

        if (exp->nbdflags & NBD_FLAG_READ_ONLY) {

            TRACE("Server is read-only, return error");

            reply.error = EROFS;

            goto error_reply;

        }

        TRACE("Writing to device");

        ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,

                         req->data, request.len, 0);

        if (ret < 0) {

            LOG("writing to file failed");

            reply.error = -ret;

            goto error_reply;

        }

        if (request.type & NBD_CMD_FLAG_FUA) {

            ret = blk_co_flush(exp->blk);

            if (ret < 0) {

                LOG("flush failed");

                reply.error = -ret;

                goto error_reply;

            }

        }

        if (nbd_co_send_reply(req, &reply, 0) < 0) {

            goto out;

        }

        break;

    case NBD_CMD_DISC:

        TRACE("Request type is DISCONNECT");

        errno = 0;

        goto out;

    case NBD_CMD_FLUSH:

        TRACE("Request type is FLUSH");

        ret = blk_co_flush(exp->blk);

        if (ret < 0) {

            LOG("flush failed");

            reply.error = -ret;

        }

        if (nbd_co_send_reply(req, &reply, 0) < 0) {

            goto out;

        }

        break;

    case NBD_CMD_TRIM:

        TRACE("Request type is TRIM");

        ret = blk_co_discard(exp->blk, (request.from + exp->dev_offset)

                                       / BDRV_SECTOR_SIZE,

                             request.len / BDRV_SECTOR_SIZE);

        if (ret < 0) {

            LOG("discard failed");

            reply.error = -ret;

        }

        if (nbd_co_send_reply(req, &reply, 0) < 0) {

            goto out;

        }

        break;

    default:

        LOG("invalid request type (%u) received", request.type);

    invalid_request:

        reply.error = EINVAL;

    error_reply:

        if (nbd_co_send_reply(req, &reply, 0) < 0) {

            goto out;

        }

        break;

    }

    TRACE("Request/Reply complete");

done:

    nbd_request_put(req);

    return;

out:

    nbd_request_put(req);

    client_close(client);

}


void qemu_register_reset(QEMUResetHandler *func, void *opaque)

{

    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));

    re->func = func;

    re->opaque = opaque;

    TAILQ_INSERT_TAIL(&reset_handlers, re, entry);

}


void stl_phys_notdirty(hwaddr addr, uint32_t val)

{

    uint8_t *ptr;

    MemoryRegionSection *section;

    section = phys_page_find(address_space_memory.dispatch, addr >> TARGET_PAGE_BITS);

    if (!memory_region_is_ram(section->mr) || section->readonly) {

        addr = memory_region_section_addr(section, addr);

        if (memory_region_is_ram(section->mr)) {

            section = &phys_sections[phys_section_rom];

        }

        io_mem_write(section->mr, addr, val, 4);

    } else {

        unsigned long addr1 = (memory_region_get_ram_addr(section->mr)

                               & TARGET_PAGE_MASK)

            + memory_region_section_addr(section, addr);

        ptr = qemu_get_ram_ptr(addr1);

        stl_p(ptr, val);

        if (unlikely(in_migration)) {

            if (!cpu_physical_memory_is_dirty(addr1)) {

                /* invalidate code */

                tb_invalidate_phys_page_range(addr1, addr1 + 4, 0);

                /* set dirty bit */

                cpu_physical_memory_set_dirty_flags(

                    addr1, (0xff & ~CODE_DIRTY_FLAG));

            }

        }

    }

}


static void compute_antialias_float(MPADecodeContext *s,

                              GranuleDef *g)

{

    float *ptr;

    int n, i;

    /* we antialias only "long" bands */

    if (g->block_type == 2) {

        if (!g->switch_point)

            return;

        /* XXX: check this for 8000Hz case */

        n = 1;

    } else {

        n = SBLIMIT - 1;

    }

    ptr = g->sb_hybrid + 18;

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

        float tmp0, tmp1;

        float *csa = &csa_table_float[0][0];

#define FLOAT_AA(j)\

        tmp0= ptr[-1-j];\

        tmp1= ptr[   j];\

        ptr[-1-j] = tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j];\

        ptr[   j] = tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j];

        FLOAT_AA(0)

        FLOAT_AA(1)

        FLOAT_AA(2)

        FLOAT_AA(3)

        FLOAT_AA(4)

        FLOAT_AA(5)

        FLOAT_AA(6)

        FLOAT_AA(7)

        ptr += 18;

    }

}


PCIBus *i440fx_init(PCII440FXState **pi440fx_state, int *piix3_devfn, qemu_irq *pic, int ram_size)

{

    DeviceState *dev;

    PCIBus *b;

    PCIDevice *d;

    I440FXState *s;

    PIIX3State *piix3;

    dev = qdev_create(NULL, "i440FX-pcihost");

    s = FROM_SYSBUS(I440FXState, sysbus_from_qdev(dev));

    b = pci_bus_new(&s->busdev.qdev, NULL, 0);

    s->bus = b;

    qdev_init_nofail(dev);

    d = pci_create_simple(b, 0, "i440FX");

    *pi440fx_state = DO_UPCAST(PCII440FXState, dev, d);

    piix3 = DO_UPCAST(PIIX3State, dev,

                                 pci_create_simple(b, -1, "PIIX3"));

    piix3->pic = pic;

    pci_bus_irqs(b, piix3_set_irq, pci_slot_get_pirq, piix3, 4);

    (*pi440fx_state)->piix3 = piix3;

    *piix3_devfn = piix3->dev.devfn;

    ram_size = ram_size / 8 / 1024 / 1024;

    if (ram_size > 255)

        ram_size = 255;

    (*pi440fx_state)->dev.config[0x57]=ram_size;

    return b;

}


uint64_t helper_cvttq_c(CPUAlphaState *env, uint64_t a)

{

    return inline_cvttq(env, a, float_round_to_zero, 0);

}


int ff_dca_core_parse(DCACoreDecoder *s, uint8_t *data, int size)

{

    int ret;

    s->ext_audio_mask = 0;

    s->xch_pos = s->xxch_pos = s->x96_pos = 0;

    if ((ret = init_get_bits8(&s->gb, data, size)) < 0)

        return ret;

    s->gb_in = s->gb;

    if ((ret = parse_frame_header(s)) < 0)

        return ret;

    if ((ret = alloc_sample_buffer(s)) < 0)

        return ret;

    if ((ret = parse_frame_data(s, HEADER_CORE, 0)) < 0)

        return ret;

    if ((ret = parse_optional_info(s)) < 0)

        return ret;

    // Workaround for DTS in WAV

    if (s->frame_size > size && s->frame_size < size + 4)

        s->frame_size = size;

    if (ff_dca_seek_bits(&s->gb, s->frame_size * 8)) {

        av_log(s->avctx, AV_LOG_ERROR, "Read past end of core frame\n");

        if (s->avctx->err_recognition & AV_EF_EXPLODE)

            return AVERROR_INVALIDDATA;

    }

    return 0;

}


static void gen_mulu(DisasContext *dc, TCGv dest, TCGv srca, TCGv srcb)

{

    TCGv sr_cy = tcg_temp_new();

    tcg_gen_muls2_tl(dest, sr_cy, srca, srcb);

    tcg_gen_setcondi_tl(TCG_COND_NE, sr_cy, sr_cy, 0);

    tcg_gen_deposit_tl(cpu_sr, cpu_sr, sr_cy, ctz32(SR_CY), 1);

    gen_ove_cy(dc, sr_cy);

    tcg_temp_free(sr_cy);

}