static inline int _find_pte(CPUState *env, mmu_ctx_t *ctx, int is_64b, int h,

                            int rw, int type, int target_page_bits)

{

    target_phys_addr_t pteg_off;

    target_ulong pte0, pte1;

    int i, good = -1;

    int ret, r;

    ret = -1; /* No entry found */

    pteg_off = get_pteg_offset(env, ctx->hash[h],

                               is_64b ? HASH_PTE_SIZE_64 : HASH_PTE_SIZE_32);

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

#if defined(TARGET_PPC64)

        if (is_64b) {

            if (env->external_htab) {

                pte0 = ldq_p(env->external_htab + pteg_off + (i * 16));

                pte1 = ldq_p(env->external_htab + pteg_off + (i * 16) + 8);

            } else {

                pte0 = ldq_phys(env->htab_base + pteg_off + (i * 16));

                pte1 = ldq_phys(env->htab_base + pteg_off + (i * 16) + 8);

            }

            /* We have a TLB that saves 4K pages, so let's

             * split a huge page to 4k chunks */

            if (target_page_bits != TARGET_PAGE_BITS)

                pte1 |= (ctx->eaddr & (( 1 << target_page_bits ) - 1))

                        & TARGET_PAGE_MASK;

            r = pte64_check(ctx, pte0, pte1, h, rw, type);

            LOG_MMU("Load pte from " TARGET_FMT_lx " => " TARGET_FMT_lx " "

                    TARGET_FMT_lx " %d %d %d " TARGET_FMT_lx "\n",

                    pteg_base + (i * 16), pte0, pte1, (int)(pte0 & 1), h,

                    (int)((pte0 >> 1) & 1), ctx->ptem);

        } else

#endif

        {

            if (env->external_htab) {

                pte0 = ldl_p(env->external_htab + pteg_off + (i * 8));

                pte1 = ldl_p(env->external_htab + pteg_off + (i * 8) + 4);

            } else {

                pte0 = ldl_phys(env->htab_base + pteg_off + (i * 8));

                pte1 = ldl_phys(env->htab_base + pteg_off + (i * 8) + 4);

            }

            r = pte32_check(ctx, pte0, pte1, h, rw, type);

            LOG_MMU("Load pte from " TARGET_FMT_lx " => " TARGET_FMT_lx " "

                    TARGET_FMT_lx " %d %d %d " TARGET_FMT_lx "\n",

                    pteg_base + (i * 8), pte0, pte1, (int)(pte0 >> 31), h,

                    (int)((pte0 >> 6) & 1), ctx->ptem);

        }

        switch (r) {

        case -3:

            /* PTE inconsistency */

            return -1;

        case -2:

            /* Access violation */

            ret = -2;

            good = i;

            break;

        case -1:

        default:

            /* No PTE match */

            break;

        case 0:

            /* access granted */

            /* XXX: we should go on looping to check all PTEs consistency

             *      but if we can speed-up the whole thing as the

             *      result would be undefined if PTEs are not consistent.

             */

            ret = 0;

            good = i;

            goto done;

        }

    }

    if (good != -1) {

    done:

        LOG_MMU("found PTE at addr " TARGET_FMT_lx " prot=%01x ret=%d\n",

                ctx->raddr, ctx->prot, ret);

        /* Update page flags */

        pte1 = ctx->raddr;

        if (pte_update_flags(ctx, &pte1, ret, rw) == 1) {

#if defined(TARGET_PPC64)

            if (is_64b) {

                if (env->external_htab) {

                    stq_p(env->external_htab + pteg_off + (good * 16) + 8,

                          pte1);

                } else {

                    stq_phys_notdirty(env->htab_base + pteg_off +

                                      (good * 16) + 8, pte1);

                }

            } else

#endif

            {

                if (env->external_htab) {

                    stl_p(env->external_htab + pteg_off + (good * 8) + 4,

                          pte1);

                } else {

                    stl_phys_notdirty(env->htab_base + pteg_off +

                                      (good * 8) + 4, pte1);

                }

            }

        }

    }

    return ret;

}


static int decode_sequence_header(AVCodecContext *avctx, GetBitContext *gb)

{

    VC9Context *v = avctx->priv_data;

    v->profile = get_bits(gb, 2);

    av_log(avctx, AV_LOG_DEBUG, "Profile: %i\n", v->profile);

#if HAS_ADVANCED_PROFILE

    if (v->profile > PROFILE_MAIN)

    {

        v->level = get_bits(gb, 3);

        v->chromaformat = get_bits(gb, 2);

        if (v->chromaformat != 1)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "Only 4:2:0 chroma format supported\n");

            return -1;

        }

    }

    else

#endif

    {

        v->res_sm = get_bits(gb, 2); //reserved

        if (v->res_sm)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "Reserved RES_SM=%i is forbidden\n", v->res_sm);

            //return -1;

        }

    }

    // (fps-2)/4 (->30)

    v->frmrtq_postproc = get_bits(gb, 3); //common

    // (bitrate-32kbps)/64kbps

    v->bitrtq_postproc = get_bits(gb, 5); //common

    v->loopfilter = get_bits(gb, 1); //common

#if HAS_ADVANCED_PROFILE

    if (v->profile <= PROFILE_MAIN)

#endif

    {

        v->res_x8 = get_bits(gb, 1); //reserved

        if (v->res_x8)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "1 for reserved RES_X8 is forbidden\n");

            return -1;

        }

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

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

        if (!v->res_fasttx)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "0 for reserved RES_FASTTX is forbidden\n");

            //return -1;

        }

    }

    v->fastuvmc =  get_bits(gb, 1); //common

    if (!v->profile && !v->fastuvmc)

    {

        av_log(avctx, AV_LOG_ERROR,

               "FASTUVMC unavailable in Simple Profile\n");

        return -1;

    }

    v->extended_mv =  get_bits(gb, 1); //common

    if (!v->profile && v->extended_mv)

    {

        av_log(avctx, AV_LOG_ERROR,

               "Extended MVs unavailable in Simple Profile\n");

        return -1;

    }

    v->dquant =  get_bits(gb, 2); //common

    v->vstransform =  get_bits(gb, 1); //common

#if HAS_ADVANCED_PROFILE

    if (v->profile <= PROFILE_MAIN)

#endif

    {

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

        if (v->res_transtab)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "1 for reserved RES_TRANSTAB is forbidden\n");

            return -1;

        }

    }

    v->overlap = get_bits(gb, 1); //common

#if HAS_ADVANCED_PROFILE

    if (v->profile <= PROFILE_MAIN)

#endif

    {

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

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

    }

    avctx->max_b_frames = get_bits(gb, 3); //common

    v->quantizer_mode = get_bits(gb, 2); //common

#if HAS_ADVANCED_PROFILE

    if (v->profile <= PROFILE_MAIN)

#endif

    {

        v->finterpflag = get_bits(gb, 1); //common

        v->res_rtm_flag = get_bits(gb, 1); //reserved

        if (!v->res_rtm_flag)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "0 for reserved RES_RTM_FLAG is forbidden\n");

            //return -1;

        }

#if TRACE

        av_log(avctx, AV_LOG_INFO,

               "Profile %i:\nfrmrtq_postproc=%i, bitrtq_postproc=%i\n"

               "LoopFilter=%i, MultiRes=%i, FastUVMV=%i, Extended MV=%i\n"

               "Rangered=%i, VSTransform=%i, Overlap=%i, SyncMarker=%i\n"

               "DQuant=%i, Quantizer mode=%i, Max B frames=%i\n",

               v->profile, v->frmrtq_postproc, v->bitrtq_postproc,

               v->loopfilter, v->multires, v->fastuvmc, v->extended_mv,

               v->rangered, v->vstransform, v->overlap, v->syncmarker,

               v->dquant, v->quantizer_mode, avctx->max_b_frames

               );

#endif

    }

#if HAS_ADVANCED_PROFILE

    else decode_advanced_sequence_header(avctx, gb);

#endif

}


static int mov_probe(AVProbeData *p)

{

    int64_t offset;

    uint32_t tag;

    int score = 0;

    /* check file header */

    offset = 0;

    for (;;) {

        /* ignore invalid offset */

        if ((offset + 8) > (unsigned int)p->buf_size)

            return score;

        tag = AV_RL32(p->buf + offset + 4);

        switch(tag) {

        /* check for obvious tags */

        case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */

        case MKTAG('m','o','o','v'):

        case MKTAG('m','d','a','t'):

        case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */

        case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */

        case MKTAG('f','t','y','p'):

            return AVPROBE_SCORE_MAX;

        /* those are more common words, so rate then a bit less */

        case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */

        case MKTAG('w','i','d','e'):

        case MKTAG('f','r','e','e'):

        case MKTAG('j','u','n','k'):

        case MKTAG('p','i','c','t'):

            return AVPROBE_SCORE_MAX - 5;

        case MKTAG(0x82,0x82,0x7f,0x7d):

        case MKTAG('s','k','i','p'):

        case MKTAG('u','u','i','d'):

        case MKTAG('p','r','f','l'):

            offset = AV_RB32(p->buf+offset) + offset;

            /* if we only find those cause probedata is too small at least rate them */

            score = AVPROBE_SCORE_MAX - 50;

            break;

        default:

            /* unrecognized tag */

            return score;

        }

    }

}


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

{

	const uint8_t *s = src;

	const uint8_t *end;

#ifdef HAVE_MMX

	const uint8_t *mm_end;

#endif

	uint16_t *d = (uint16_t *)dst;

	end = s + src_size;

#ifdef HAVE_MMX

	mm_end = end - 15;

#if 1 //is faster only if multiplies are reasonable fast (FIXME figure out on which cpus this is faster, on Athlon its slightly faster)

	asm volatile(

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

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

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

		ASMALIGN16

		"1:				\n\t"

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

		"movd	(%1), %%mm0		\n\t"

		"movd	4(%1), %%mm3		\n\t"

		"punpckldq 8(%1), %%mm0		\n\t"

		"punpckldq 12(%1), %%mm3	\n\t"

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

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

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

		"pand %%mm6, %%mm3		\n\t"

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

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

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

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

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

		"por %%mm4, %%mm3		\n\t"

		"psrld $6, %%mm0		\n\t"

		"pslld $10, %%mm3		\n\t"

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

		MOVNTQ"	%%mm0, (%0)		\n\t"

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

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

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

		" jb 1b				\n\t"

		: "+r" (d), "+r"(s)

		: "r" (mm_end), "m" (mask3215g), "m" (mask3216br), "m" (mul3215)

	);

#else

	__asm __volatile(PREFETCH"	%0"::"m"(*src):"memory");

	__asm __volatile(

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

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

	    ::"m"(red_15mask),"m"(green_15mask));

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

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

		"movd	4%1, %%mm3\n\t"

		"punpckldq 8%1, %%mm0\n\t"

		"punpckldq 12%1, %%mm3\n\t"

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

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

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

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

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

		"psrlq	$3, %%mm3\n\t"

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

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

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

		"psrlq	$6, %%mm4\n\t"

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

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

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

		"psrlq	$9, %%mm5\n\t"

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

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

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

		"por	%%mm4, %%mm3\n\t"

		"por	%%mm2, %%mm0\n\t"

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

		"psllq	$16, %%mm3\n\t"

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

		MOVNTQ"	%%mm0, %0\n\t"

		:"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");

		d += 4;

		s += 16;

	}

#endif

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

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

#endif

	while(s < end)

	{

		register int rgb = *(uint32_t*)s; s += 4;

		*d++ = ((rgb&0xFF)>>3) + ((rgb&0xF800)>>6) + ((rgb&0xF80000)>>9);

	}

}


static int source_request_frame(AVFilterLink *outlink)

{

    Frei0rContext *frei0r = outlink->src->priv;

    AVFilterBufferRef *picref = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);

    int ret;

    picref->video->pixel_aspect = (AVRational) {1, 1};

    picref->pts = frei0r->pts++;

    picref->pos = -1;

    ret = ff_start_frame(outlink, avfilter_ref_buffer(picref, ~0));

    if (ret < 0)

        goto fail;

    frei0r->update(frei0r->instance, av_rescale_q(picref->pts, frei0r->time_base, (AVRational){1,1000}),

                   NULL, (uint32_t *)picref->data[0]);

    ret = ff_draw_slice(outlink, 0, outlink->h, 1);

    if (ret < 0)

        goto fail;

    ret = ff_end_frame(outlink);

fail:

    avfilter_unref_buffer(picref);

    return ret;

}


static int vmdk_is_allocated(BlockDriverState *bs, int64_t sector_num,

                             int nb_sectors, int *pnum)

{

    BDRVVmdkState *s = bs->opaque;

    int index_in_cluster, n;

    uint64_t cluster_offset;

    cluster_offset = get_cluster_offset(bs, sector_num << 9, 0);

    index_in_cluster = sector_num % s->cluster_sectors;

    n = s->cluster_sectors - index_in_cluster;

    if (n > nb_sectors)

        n = nb_sectors;

    *pnum = n;

    return (cluster_offset != 0);

}


void put_vp8_epel_h_altivec_core(uint8_t *dst, int dst_stride,

                                 uint8_t *src, int src_stride,

                                 int h, int mx, int w, int is6tap)

{

    LOAD_H_SUBPEL_FILTER(mx-1);

    vec_u8 align_vec0, align_vec8, permh0, permh8, filt;

    vec_u8 perm_6tap0, perm_6tap8, perml0, perml8;

    vec_u8 a, b, pixh, pixl, outer;

    vec_s16 f16h, f16l;

    vec_s32 filth, filtl;

    vec_u8 perm_inner = { 1,2,3,4, 2,3,4,5, 3,4,5,6, 4,5,6,7 };

    vec_u8 perm_outer = { 4,9, 0,5, 5,10, 1,6, 6,11, 2,7, 7,12, 3,8 };

    vec_s32 c64 = vec_sl(vec_splat_s32(1), vec_splat_u32(6));

    vec_u16 c7  = vec_splat_u16(7);

    align_vec0 = vec_lvsl( -2, src);

    align_vec8 = vec_lvsl(8-2, src);

    permh0     = vec_perm(align_vec0, align_vec0, perm_inner);

    permh8     = vec_perm(align_vec8, align_vec8, perm_inner);

    perm_inner = vec_add(perm_inner, vec_splat_u8(4));

    perml0     = vec_perm(align_vec0, align_vec0, perm_inner);

    perml8     = vec_perm(align_vec8, align_vec8, perm_inner);

    perm_6tap0 = vec_perm(align_vec0, align_vec0, perm_outer);

    perm_6tap8 = vec_perm(align_vec8, align_vec8, perm_outer);

    while (h --> 0) {

        FILTER_H(f16h, 0);

        if (w == 16) {

            FILTER_H(f16l, 8);

            filt = vec_packsu(f16h, f16l);

            vec_st(filt, 0, dst);

        } else {

            filt = vec_packsu(f16h, f16h);

            vec_ste((vec_u32)filt, 0, (uint32_t*)dst);

            if (w == 8)

                vec_ste((vec_u32)filt, 4, (uint32_t*)dst);

        }

        src += src_stride;

        dst += dst_stride;

    }

}


static int mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri,

                      uint64_t *value)

{

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

    uint32_t mpidr = cs->cpu_index;

    /* We don't support setting cluster ID ([8..11])

     * so these bits always RAZ.

     */

    if (arm_feature(env, ARM_FEATURE_V7MP)) {

        mpidr |= (1 << 31);

        /* Cores which are uniprocessor (non-coherent)

         * but still implement the MP extensions set

         * bit 30. (For instance, A9UP.) However we do

         * not currently model any of those cores.

         */

    }

    *value = mpidr;

    return 0;

}


void cpu_loop (CPUSPARCState *env)

{

    int trapnr, ret;

    target_siginfo_t info;

    while (1) {

        trapnr = cpu_sparc_exec (env);

        switch (trapnr) {

#ifndef TARGET_SPARC64

        case 0x88:

        case 0x90:

#else

        case 0x110:

        case 0x16d:

#endif

            ret = do_syscall (env, env->gregs[1],

                              env->regwptr[0], env->regwptr[1],

                              env->regwptr[2], env->regwptr[3],

                              env->regwptr[4], env->regwptr[5]);

            if ((unsigned int)ret >= (unsigned int)(-515)) {

#if defined(TARGET_SPARC64) && !defined(TARGET_ABI32)

                env->xcc |= PSR_CARRY;

#else

                env->psr |= PSR_CARRY;

#endif

                ret = -ret;

            } else {

#if defined(TARGET_SPARC64) && !defined(TARGET_ABI32)

                env->xcc &= ~PSR_CARRY;

#else

                env->psr &= ~PSR_CARRY;

#endif

            }

            env->regwptr[0] = ret;

            /* next instruction */

            env->pc = env->npc;

            env->npc = env->npc + 4;

            break;

        case 0x83: /* flush windows */

#ifdef TARGET_ABI32

        case 0x103:

#endif

            flush_windows(env);

            /* next instruction */

            env->pc = env->npc;

            env->npc = env->npc + 4;

            break;

#ifndef TARGET_SPARC64

        case TT_WIN_OVF: /* window overflow */

            save_window(env);

            break;

        case TT_WIN_UNF: /* window underflow */

            restore_window(env);

            break;

        case TT_TFAULT:

        case TT_DFAULT:

            {

                info.si_signo = SIGSEGV;

                info.si_errno = 0;

                /* XXX: check env->error_code */

                info.si_code = TARGET_SEGV_MAPERR;

                info._sifields._sigfault._addr = env->mmuregs[4];

                queue_signal(env, info.si_signo, &info);

            }

            break;

#else

        case TT_SPILL: /* window overflow */

            save_window(env);

            break;

        case TT_FILL: /* window underflow */

            restore_window(env);

            break;

        case TT_TFAULT:

        case TT_DFAULT:

            {

                info.si_signo = SIGSEGV;

                info.si_errno = 0;

                /* XXX: check env->error_code */

                info.si_code = TARGET_SEGV_MAPERR;

                if (trapnr == TT_DFAULT)

                    info._sifields._sigfault._addr = env->dmmuregs[4];

                else

                    info._sifields._sigfault._addr = env->tsptr->tpc;

                queue_signal(env, info.si_signo, &info);

            }

            break;

#ifndef TARGET_ABI32

        case 0x16e:

            flush_windows(env);

            sparc64_get_context(env);

            break;

        case 0x16f:

            flush_windows(env);

            sparc64_set_context(env);

            break;

#endif

#endif

        case EXCP_INTERRUPT:

            /* just indicate that signals should be handled asap */

            break;

        case EXCP_DEBUG:

            {

                int sig;

                sig = gdb_handlesig (env, TARGET_SIGTRAP);

                if (sig)

                  {

                    info.si_signo = sig;

                    info.si_errno = 0;

                    info.si_code = TARGET_TRAP_BRKPT;

                    queue_signal(env, info.si_signo, &info);

                  }

            }

            break;

        default:

            printf ("Unhandled trap: 0x%x\n", trapnr);

            cpu_dump_state(env, stderr, fprintf, 0);

            exit (1);

        }

        process_pending_signals (env);

    }

}


static av_cold int init(AVFilterContext *ctx, const char *args0)

{

    PanContext *const pan = ctx->priv;

    char *arg, *arg0, *tokenizer, *args = av_strdup(args0);

    int out_ch_id, in_ch_id, len, named, ret;

    int nb_in_channels[2] = { 0, 0 }; // number of unnamed and named input channels

    double gain;

    if (!args0) {

        av_log(ctx, AV_LOG_ERROR,

               "pan filter needs a channel layout and a set "

               "of channels definitions as parameter\n");

        return AVERROR(EINVAL);

    }

    if (!args)

        return AVERROR(ENOMEM);

    arg = av_strtok(args, ":", &tokenizer);

    ret = ff_parse_channel_layout(&pan->out_channel_layout, arg, ctx);

    if (ret < 0)

        return ret;

    pan->nb_output_channels = av_get_channel_layout_nb_channels(pan->out_channel_layout);

    /* parse channel specifications */

    while ((arg = arg0 = av_strtok(NULL, ":", &tokenizer))) {

        /* channel name */

        if (parse_channel_name(&arg, &out_ch_id, &named)) {

            av_log(ctx, AV_LOG_ERROR,

                   "Expected out channel name, got \"%.8s\"\n", arg);

            return AVERROR(EINVAL);

        }

        if (named) {

            if (!((pan->out_channel_layout >> out_ch_id) & 1)) {

                av_log(ctx, AV_LOG_ERROR,

                       "Channel \"%.8s\" does not exist in the chosen layout\n", arg0);

                return AVERROR(EINVAL);

            }

            /* get the channel number in the output channel layout:

             * out_channel_layout & ((1 << out_ch_id) - 1) are all the

             * channels that come before out_ch_id,

             * so their count is the index of out_ch_id */

            out_ch_id = av_get_channel_layout_nb_channels(pan->out_channel_layout & (((int64_t)1 << out_ch_id) - 1));

        }

        if (out_ch_id < 0 || out_ch_id >= pan->nb_output_channels) {

            av_log(ctx, AV_LOG_ERROR,

                   "Invalid out channel name \"%.8s\"\n", arg0);

            return AVERROR(EINVAL);

        }

        if (*arg == '=') {

            arg++;

        } else if (*arg == '<') {

            pan->need_renorm |= (int64_t)1 << out_ch_id;

            arg++;

        } else {

            av_log(ctx, AV_LOG_ERROR,

                   "Syntax error after channel name in \"%.8s\"\n", arg0);

            return AVERROR(EINVAL);

        }

        /* gains */

        while (1) {

            gain = 1;

            if (sscanf(arg, " %lf %n* %n", &gain, &len, &len))

                arg += len;

            if (parse_channel_name(&arg, &in_ch_id, &named)){

                av_log(ctx, AV_LOG_ERROR,

                       "Expected in channel name, got \"%.8s\"\n", arg);

                return AVERROR(EINVAL);

            }

            nb_in_channels[named]++;

            if (nb_in_channels[!named]) {

                av_log(ctx, AV_LOG_ERROR,

                       "Can not mix named and numbered channels\n");

                return AVERROR(EINVAL);

            }

            pan->gain[out_ch_id][in_ch_id] = gain;

            if (!*arg)

                break;

            if (*arg != '+') {

                av_log(ctx, AV_LOG_ERROR, "Syntax error near \"%.8s\"\n", arg);

                return AVERROR(EINVAL);

            }

            arg++;

            skip_spaces(&arg);

        }

    }

    pan->need_renumber = !!nb_in_channels[1];

    av_free(args);

    return 0;

}


static void pvpanic_isa_realizefn(DeviceState *dev, Error **errp)

{

    ISADevice *d = ISA_DEVICE(dev);

    PVPanicState *s = ISA_PVPANIC_DEVICE(dev);

    static bool port_configured;

    FWCfgState *fw_cfg;

    isa_register_ioport(d, &s->io, s->ioport);

    if (!port_configured) {

        fw_cfg = fw_cfg_find();

        if (fw_cfg) {

            fw_cfg_add_file(fw_cfg, "etc/pvpanic-port",

                            g_memdup(&s->ioport, sizeof(s->ioport)),

                            sizeof(s->ioport));

            port_configured = true;

        }

    }

}


static TRBCCode xhci_address_slot(XHCIState *xhci, unsigned int slotid,
                                  uint64_t pictx, bool bsr)
{
    XHCISlot *slot;
    USBPort *uport;
    USBDevice *dev;
    dma_addr_t ictx, octx, dcbaap;
    uint64_t poctx;
    uint32_t ictl_ctx[2];
    uint32_t slot_ctx[4];
    uint32_t ep0_ctx[5];
    int i;
    TRBCCode res;
    trace_usb_xhci_slot_address(slotid);
    assert(slotid >= 1 && slotid <= xhci->numslots);
    dcbaap = xhci_addr64(xhci->dcbaap_low, xhci->dcbaap_high);
    poctx = ldq_le_pci_dma(&xhci->pci_dev, dcbaap + 8*slotid);
    ictx = xhci_mask64(pictx);
    octx = xhci_mask64(poctx);
    DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
    DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
    xhci_dma_read_u32s(xhci, ictx, ictl_ctx, sizeof(ictl_ctx));
    if (ictl_ctx[0] != 0x0 || ictl_ctx[1] != 0x3) {
        fprintf(stderr, "xhci: invalid input context control %08x %08x\n",
                ictl_ctx[0], ictl_ctx[1]);
        return CC_TRB_ERROR;
    }
    xhci_dma_read_u32s(xhci, ictx+32, slot_ctx, sizeof(slot_ctx));
    xhci_dma_read_u32s(xhci, ictx+64, ep0_ctx, sizeof(ep0_ctx));
    DPRINTF("xhci: input slot context: %08x %08x %08x %08x\n",
            slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
    DPRINTF("xhci: input ep0 context: %08x %08x %08x %08x %08x\n",
            ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);
    uport = xhci_lookup_uport(xhci, slot_ctx);
    if (uport == NULL) {
        fprintf(stderr, "xhci: port not found\n");
        return CC_TRB_ERROR;
    }
    dev = uport->dev;
    if (!dev) {
        fprintf(stderr, "xhci: port %s not connected\n", uport->path);
        return CC_USB_TRANSACTION_ERROR;
    }
    for (i = 0; i < xhci->numslots; i++) {
        if (i == slotid-1) {
            continue;
        }
        if (xhci->slots[i].uport == uport) {
            fprintf(stderr, "xhci: port %s already assigned to slot %d\n",
                    uport->path, i+1);
            return CC_TRB_ERROR;
        }
    }
    slot = &xhci->slots[slotid-1];
    slot->uport = uport;
    slot->ctx = octx;
    if (bsr) {
        slot_ctx[3] = SLOT_DEFAULT << SLOT_STATE_SHIFT;
    } else {
        USBPacket p;
        slot_ctx[3] = (SLOT_ADDRESSED << SLOT_STATE_SHIFT) | slotid;
        usb_device_reset(dev);
        usb_packet_setup(&p, USB_TOKEN_OUT,
                         usb_ep_get(dev, USB_TOKEN_OUT, 0), 0,
                         0, false, false);
        usb_device_handle_control(dev, &p,
                                  DeviceOutRequest | USB_REQ_SET_ADDRESS,
                                  slotid, 0, 0, NULL);
        assert(p.status != USB_RET_ASYNC);
    }
    res = xhci_enable_ep(xhci, slotid, 1, octx+32, ep0_ctx);
    DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
            slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
    DPRINTF("xhci: output ep0 context: %08x %08x %08x %08x %08x\n",
            ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);
    xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
    xhci_dma_write_u32s(xhci, octx+32, ep0_ctx, sizeof(ep0_ctx));
    return res;
}


static int compare_ocl_device_desc(const void *a, const void *b)

{

    return ((const OpenCLDeviceBenchmark*)a)->runtime - ((const OpenCLDeviceBenchmark*)b)->runtime;

}


void ff_vc1dsp_init_mmx(VC1DSPContext *dsp)

{

    int mm_flags = av_get_cpu_flags();

#if HAVE_INLINE_ASM

    if (mm_flags & AV_CPU_FLAG_MMX) {

        dsp->put_vc1_mspel_pixels_tab[ 0] = ff_put_vc1_mspel_mc00_mmx;

        dsp->put_vc1_mspel_pixels_tab[ 4] = put_vc1_mspel_mc01_mmx;

        dsp->put_vc1_mspel_pixels_tab[ 8] = put_vc1_mspel_mc02_mmx;

        dsp->put_vc1_mspel_pixels_tab[12] = put_vc1_mspel_mc03_mmx;

        dsp->put_vc1_mspel_pixels_tab[ 1] = put_vc1_mspel_mc10_mmx;

        dsp->put_vc1_mspel_pixels_tab[ 5] = put_vc1_mspel_mc11_mmx;

        dsp->put_vc1_mspel_pixels_tab[ 9] = put_vc1_mspel_mc12_mmx;

        dsp->put_vc1_mspel_pixels_tab[13] = put_vc1_mspel_mc13_mmx;

        dsp->put_vc1_mspel_pixels_tab[ 2] = put_vc1_mspel_mc20_mmx;

        dsp->put_vc1_mspel_pixels_tab[ 6] = put_vc1_mspel_mc21_mmx;

        dsp->put_vc1_mspel_pixels_tab[10] = put_vc1_mspel_mc22_mmx;

        dsp->put_vc1_mspel_pixels_tab[14] = put_vc1_mspel_mc23_mmx;

        dsp->put_vc1_mspel_pixels_tab[ 3] = put_vc1_mspel_mc30_mmx;

        dsp->put_vc1_mspel_pixels_tab[ 7] = put_vc1_mspel_mc31_mmx;

        dsp->put_vc1_mspel_pixels_tab[11] = put_vc1_mspel_mc32_mmx;

        dsp->put_vc1_mspel_pixels_tab[15] = put_vc1_mspel_mc33_mmx;

    }

    if (mm_flags & AV_CPU_FLAG_MMX2){

        dsp->avg_vc1_mspel_pixels_tab[ 0] = ff_avg_vc1_mspel_mc00_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[ 4] = avg_vc1_mspel_mc01_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[ 8] = avg_vc1_mspel_mc02_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[12] = avg_vc1_mspel_mc03_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[ 1] = avg_vc1_mspel_mc10_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[ 5] = avg_vc1_mspel_mc11_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[ 9] = avg_vc1_mspel_mc12_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[13] = avg_vc1_mspel_mc13_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[ 2] = avg_vc1_mspel_mc20_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[ 6] = avg_vc1_mspel_mc21_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[10] = avg_vc1_mspel_mc22_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[14] = avg_vc1_mspel_mc23_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[ 3] = avg_vc1_mspel_mc30_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[ 7] = avg_vc1_mspel_mc31_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[11] = avg_vc1_mspel_mc32_mmx2;

        dsp->avg_vc1_mspel_pixels_tab[15] = avg_vc1_mspel_mc33_mmx2;

        dsp->vc1_inv_trans_8x8_dc = vc1_inv_trans_8x8_dc_mmx2;

        dsp->vc1_inv_trans_4x8_dc = vc1_inv_trans_4x8_dc_mmx2;

        dsp->vc1_inv_trans_8x4_dc = vc1_inv_trans_8x4_dc_mmx2;

        dsp->vc1_inv_trans_4x4_dc = vc1_inv_trans_4x4_dc_mmx2;

    }

#endif /* HAVE_INLINE_ASM */

#define ASSIGN_LF(EXT) \

        dsp->vc1_v_loop_filter4  = ff_vc1_v_loop_filter4_ ## EXT; \

        dsp->vc1_h_loop_filter4  = ff_vc1_h_loop_filter4_ ## EXT; \

        dsp->vc1_v_loop_filter8  = ff_vc1_v_loop_filter8_ ## EXT; \

        dsp->vc1_h_loop_filter8  = ff_vc1_h_loop_filter8_ ## EXT; \

        dsp->vc1_v_loop_filter16 = vc1_v_loop_filter16_ ## EXT; \

        dsp->vc1_h_loop_filter16 = vc1_h_loop_filter16_ ## EXT

#if HAVE_YASM

    if (mm_flags & AV_CPU_FLAG_MMX) {

        dsp->put_no_rnd_vc1_chroma_pixels_tab[0]= ff_put_vc1_chroma_mc8_mmx_nornd;

    }

    return;

    if (mm_flags & AV_CPU_FLAG_MMX2) {

        ASSIGN_LF(mmx2);

        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0]= ff_avg_vc1_chroma_mc8_mmx2_nornd;

    } else if (mm_flags & AV_CPU_FLAG_3DNOW) {

        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0]= ff_avg_vc1_chroma_mc8_3dnow_nornd;

    }

    if (mm_flags & AV_CPU_FLAG_SSE2) {

        dsp->vc1_v_loop_filter8  = ff_vc1_v_loop_filter8_sse2;

        dsp->vc1_h_loop_filter8  = ff_vc1_h_loop_filter8_sse2;

        dsp->vc1_v_loop_filter16 = vc1_v_loop_filter16_sse2;

        dsp->vc1_h_loop_filter16 = vc1_h_loop_filter16_sse2;

    }

    if (mm_flags & AV_CPU_FLAG_SSSE3) {

        ASSIGN_LF(ssse3);

        dsp->put_no_rnd_vc1_chroma_pixels_tab[0]= ff_put_vc1_chroma_mc8_ssse3_nornd;

        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0]= ff_avg_vc1_chroma_mc8_ssse3_nornd;

    }

    if (mm_flags & AV_CPU_FLAG_SSE4) {

        dsp->vc1_h_loop_filter8  = ff_vc1_h_loop_filter8_sse4;

        dsp->vc1_h_loop_filter16 = vc1_h_loop_filter16_sse4;

    }

#endif

}


static av_cold int ffv1_encode_close(AVCodecContext *avctx)

{

    av_frame_free(&avctx->coded_frame);

    ffv1_close(avctx);

    return 0;

}


static inline void conv_to_float(float *arr, int32_t *cof, int num)

{

    int i;

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

        arr[i] = (float)cof[i]/INT32_MAX;

}


static int process_input(int file_index)

{

    InputFile *ifile = input_files[file_index];

    AVFormatContext *is;

    InputStream *ist;

    AVPacket pkt;

    int ret, i, j;

    int64_t duration;

    int64_t pkt_dts;

    is  = ifile->ctx;

    ret = get_input_packet(ifile, &pkt);

    if (ret == AVERROR(EAGAIN)) {

        ifile->eagain = 1;

        return ret;

    }

    if (ret < 0 && ifile->loop) {

        if ((ret = seek_to_start(ifile, is)) < 0)

            return ret;

        ret = get_input_packet(ifile, &pkt);

    }

    if (ret < 0) {

        if (ret != AVERROR_EOF) {

            print_error(is->filename, ret);

            if (exit_on_error)

                exit_program(1);

        }

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

            ist = input_streams[ifile->ist_index + i];

            if (ist->decoding_needed) {

                ret = process_input_packet(ist, NULL, 0);

                if (ret>0)

                    return 0;

            }

            /* mark all outputs that don't go through lavfi as finished */

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

                OutputStream *ost = output_streams[j];

                if (ost->source_index == ifile->ist_index + i &&

                    (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))

                    finish_output_stream(ost);

            }

        }

        ifile->eof_reached = 1;

        return AVERROR(EAGAIN);

    }

    reset_eagain();

    if (do_pkt_dump) {

        av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,

                         is->streams[pkt.stream_index]);

    }

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

       dynamically in stream : we ignore them */

    if (pkt.stream_index >= ifile->nb_streams) {

        report_new_stream(file_index, &pkt);

        goto discard_packet;

    }

    ist = input_streams[ifile->ist_index + pkt.stream_index];

    ist->data_size += pkt.size;

    ist->nb_packets++;

    if (ist->discard)

        goto discard_packet;

    if (exit_on_error && (pkt.flags & AV_PKT_FLAG_CORRUPT)) {

        av_log(NULL, AV_LOG_FATAL, "%s: corrupt input packet in stream %d\n", is->filename, pkt.stream_index);

        exit_program(1);

    }

    if (debug_ts) {

        av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "

               "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",

               ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),

               av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),

               av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),

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

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

               av_ts2str(input_files[ist->file_index]->ts_offset),

               av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));

    }

    if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){

        int64_t stime, stime2;

        // Correcting starttime based on the enabled streams

        // FIXME this ideally should be done before the first use of starttime but we do not know which are the enabled streams at that point.

        //       so we instead do it here as part of discontinuity handling

        if (   ist->next_dts == AV_NOPTS_VALUE

            && ifile->ts_offset == -is->start_time

            && (is->iformat->flags & AVFMT_TS_DISCONT)) {

            int64_t new_start_time = INT64_MAX;

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

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

                if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)

                    continue;

                new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));

            }

            if (new_start_time > is->start_time) {

                av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);

                ifile->ts_offset = -new_start_time;

            }

        }

        stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);

        stime2= stime + (1ULL<<ist->st->pts_wrap_bits);

        ist->wrap_correction_done = 1;

        if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {

            pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;

            ist->wrap_correction_done = 0;

        }

        if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {

            pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;

            ist->wrap_correction_done = 0;

        }

    }

    /* add the stream-global side data to the first packet */

    if (ist->nb_packets == 1) {

        if (ist->st->nb_side_data)

            av_packet_split_side_data(&pkt);

        for (i = 0; i < ist->st->nb_side_data; i++) {

            AVPacketSideData *src_sd = &ist->st->side_data[i];

            uint8_t *dst_data;

            if (av_packet_get_side_data(&pkt, src_sd->type, NULL))

                continue;

            if (ist->autorotate && src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)

                continue;

            dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);

            if (!dst_data)

                exit_program(1);

            memcpy(dst_data, src_sd->data, src_sd->size);

        }

    }

    if (pkt.dts != AV_NOPTS_VALUE)

        pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);

    if (pkt.pts != AV_NOPTS_VALUE)

        pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);

    if (pkt.pts != AV_NOPTS_VALUE)

        pkt.pts *= ist->ts_scale;

    if (pkt.dts != AV_NOPTS_VALUE)

        pkt.dts *= ist->ts_scale;

    pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);

    if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||

         ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&

        pkt_dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts

        && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {

        int64_t delta   = pkt_dts - ifile->last_ts;

        if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||

            delta >  1LL*dts_delta_threshold*AV_TIME_BASE){

            ifile->ts_offset -= delta;

            av_log(NULL, AV_LOG_DEBUG,

                   "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",

                   delta, ifile->ts_offset);

            pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);

            if (pkt.pts != AV_NOPTS_VALUE)

                pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);

        }

    }

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

    if (pkt.pts != AV_NOPTS_VALUE) {

        pkt.pts += duration;

        ist->max_pts = FFMAX(pkt.pts, ist->max_pts);

        ist->min_pts = FFMIN(pkt.pts, ist->min_pts);

    }

    if (pkt.dts != AV_NOPTS_VALUE)

        pkt.dts += duration;

    pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);

    if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||

         ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&

         pkt_dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&

        !copy_ts) {

        int64_t delta   = pkt_dts - ist->next_dts;

        if (is->iformat->flags & AVFMT_TS_DISCONT) {

            if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||

                delta >  1LL*dts_delta_threshold*AV_TIME_BASE ||

                pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {

                ifile->ts_offset -= delta;

                av_log(NULL, AV_LOG_DEBUG,

                       "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",

                       delta, ifile->ts_offset);

                pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);

                if (pkt.pts != AV_NOPTS_VALUE)

                    pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);

            }

        } else {

            if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||

                 delta >  1LL*dts_error_threshold*AV_TIME_BASE) {

                av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);

                pkt.dts = AV_NOPTS_VALUE;

            }

            if (pkt.pts != AV_NOPTS_VALUE){

                int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);

                delta   = pkt_pts - ist->next_dts;

                if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||

                     delta >  1LL*dts_error_threshold*AV_TIME_BASE) {

                    av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);

                    pkt.pts = AV_NOPTS_VALUE;

                }

            }

        }

    }

    if (pkt.dts != AV_NOPTS_VALUE)

        ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);

    if (debug_ts) {

        av_log(NULL, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",

               ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),

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

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

               av_ts2str(input_files[ist->file_index]->ts_offset),

               av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));

    }

    sub2video_heartbeat(ist, pkt.pts);

    process_input_packet(ist, &pkt, 0);

discard_packet:

    av_packet_unref(&pkt);

    return 0;

}


void ff_put_h264_qpel4_mc23_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_midv_qrt_4w_msa(src - (2 * stride) - 2, stride, dst, stride, 4, 1);

}


static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)

{

    AVFilterLink *outlink = inlink->dst->outputs[0];

    AVFilterBufferRef *outpicref = NULL;

    int ret = 0;

    if (inpicref->perms & AV_PERM_PRESERVE) {

        outpicref = ff_get_video_buffer(outlink, AV_PERM_WRITE,

                                        outlink->w, outlink->h);

        if (!outpicref)

            return AVERROR(ENOMEM);

        avfilter_copy_buffer_ref_props(outpicref, inpicref);

        outpicref->video->w = outlink->w;

        outpicref->video->h = outlink->h;

    } else {

        outpicref = avfilter_ref_buffer(inpicref, ~0);

        if (!outpicref)

            return AVERROR(ENOMEM);

    }

    ret = ff_start_frame(outlink, avfilter_ref_buffer(outpicref, ~0));

    if (ret < 0) {

        avfilter_unref_bufferp(&outpicref);

        return ret;

    }

    outlink->out_buf = outpicref;

    return 0;

}


host_memory_backend_memory_complete(UserCreatable *uc, Error **errp)

{

    HostMemoryBackend *backend = MEMORY_BACKEND(uc);

    HostMemoryBackendClass *bc = MEMORY_BACKEND_GET_CLASS(uc);

    Error *local_err = NULL;

    void *ptr;

    uint64_t sz;

    if (bc->alloc) {

        bc->alloc(backend, &local_err);

        if (local_err) {

            goto out;

        }

        ptr = memory_region_get_ram_ptr(&backend->mr);

        sz = memory_region_size(&backend->mr);

        if (backend->merge) {

            qemu_madvise(ptr, sz, QEMU_MADV_MERGEABLE);

        }

        if (!backend->dump) {

            qemu_madvise(ptr, sz, QEMU_MADV_DONTDUMP);

        }

#ifdef CONFIG_NUMA

        unsigned long lastbit = find_last_bit(backend->host_nodes, MAX_NODES);

        /* lastbit == MAX_NODES means maxnode = 0 */

        unsigned long maxnode = (lastbit + 1) % (MAX_NODES + 1);

        /* ensure policy won't be ignored in case memory is preallocated

         * before mbind(). note: MPOL_MF_STRICT is ignored on hugepages so

         * this doesn't catch hugepage case. */

        unsigned flags = MPOL_MF_STRICT | MPOL_MF_MOVE;

        /* check for invalid host-nodes and policies and give more verbose

         * error messages than mbind(). */

        if (maxnode && backend->policy == MPOL_DEFAULT) {

            error_setg(errp, "host-nodes must be empty for policy default,"

                       " or you should explicitly specify a policy other"

                       " than default");

            return;

        } else if (maxnode == 0 && backend->policy != MPOL_DEFAULT) {

            error_setg(errp, "host-nodes must be set for policy %s",

                       HostMemPolicy_lookup[backend->policy]);

            return;

        }

        /* We can have up to MAX_NODES nodes, but we need to pass maxnode+1

         * as argument to mbind() due to an old Linux bug (feature?) which

         * cuts off the last specified node. This means backend->host_nodes

         * must have MAX_NODES+1 bits available.

         */

        assert(sizeof(backend->host_nodes) >=

               BITS_TO_LONGS(MAX_NODES + 1) * sizeof(unsigned long));

        assert(maxnode <= MAX_NODES);

        if (mbind(ptr, sz, backend->policy,

                  maxnode ? backend->host_nodes : NULL, maxnode + 1, flags)) {

            if (backend->policy != MPOL_DEFAULT || errno != ENOSYS) {

                error_setg_errno(errp, errno,

                                 "cannot bind memory to host NUMA nodes");

                return;

            }

        }

#endif

        /* Preallocate memory after the NUMA policy has been instantiated.

         * This is necessary to guarantee memory is allocated with

         * specified NUMA policy in place.

         */

        if (backend->prealloc) {

            os_mem_prealloc(memory_region_get_fd(&backend->mr), ptr, sz,

                            &local_err);

            if (local_err) {

                goto out;

            }

        }

    }

out:

    error_propagate(errp, local_err);

}


static void fill_gv_table(int table[256 + 2*YUVRGB_TABLE_HEADROOM], const int elemsize, const int inc)

{

    int i;

    int off    = -(inc >> 9);

    for (i = 0; i < 256 + 2*YUVRGB_TABLE_HEADROOM; i++) {

        int64_t cb = av_clip(i-YUVRGB_TABLE_HEADROOM, 0, 255)*inc;

        table[i] = elemsize * (off + (cb >> 16));

    }

}


static ssize_t write_console_data(SCLPEvent *event, const uint8_t *buf,

                                  size_t len)

{

    SCLPConsole *scon = SCLP_CONSOLE(event);

    if (!scon->chr) {

        /* If there's no backend, we can just say we consumed all data. */

        return len;

    }

    return qemu_chr_fe_write_all(scon->chr, buf, len);

}


static int rewrite_footer(BlockDriverState* bs)

{

    int ret;

    BDRVVPCState *s = bs->opaque;

    int64_t offset = s->free_data_block_offset;

    ret = bdrv_pwrite(bs->file, offset, s->footer_buf, HEADER_SIZE);

    if (ret < 0)

        return ret;

    return 0;

}


static uint32_t sdhci_read_dataport(SDHCIState *s, unsigned size)

{

    uint32_t value = 0;

    int i;

    /* first check that a valid data exists in host controller input buffer */

    if ((s->prnsts & SDHC_DATA_AVAILABLE) == 0) {

        ERRPRINT("Trying to read from empty buffer\n");

        return 0;

    }

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

        value |= s->fifo_buffer[s->data_count] << i * 8;

        s->data_count++;

        /* check if we've read all valid data (blksize bytes) from buffer */

        if ((s->data_count) >= (s->blksize & 0x0fff)) {

            DPRINT_L2("All %u bytes of data have been read from input buffer\n",

                    s->data_count);

            s->prnsts &= ~SDHC_DATA_AVAILABLE; /* no more data in a buffer */

            s->data_count = 0;  /* next buff read must start at position [0] */

            if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {

                s->blkcnt--;

            }

            /* if that was the last block of data */

            if ((s->trnmod & SDHC_TRNS_MULTI) == 0 ||

                ((s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0)) ||

                 /* stop at gap request */

                (s->stopped_state == sdhc_gap_read &&

                 !(s->prnsts & SDHC_DAT_LINE_ACTIVE))) {

                sdhci_end_transfer(s);

            } else { /* if there are more data, read next block from card */

                sdhci_read_block_from_card(s);

            }

            break;

        }

    }

    return value;

}


static int archipelago_aio_segmented_rw(BDRVArchipelagoState *s,

                                        size_t count,

                                        off_t offset,

                                        ArchipelagoAIOCB *aio_cb,

                                        int op)

{

    int i, ret, segments_nr, last_segment_size;

    ArchipelagoSegmentedRequest *segreq;

    segreq = g_malloc(sizeof(ArchipelagoSegmentedRequest));

    if (op == ARCHIP_OP_FLUSH) {

        segments_nr = 1;

        segreq->ref = segments_nr;

        segreq->total = count;

        segreq->count = 0;

        segreq->failed = 0;

        ret = archipelago_submit_request(s, 0, count, offset, aio_cb,

                                           segreq, ARCHIP_OP_FLUSH);

        if (ret < 0) {

            goto err_exit;

        }

        return 0;

    }

    segments_nr = (int)(count / MAX_REQUEST_SIZE) + \

                  ((count % MAX_REQUEST_SIZE) ? 1 : 0);

    last_segment_size = (int)(count % MAX_REQUEST_SIZE);

    segreq->ref = segments_nr;

    segreq->total = count;

    segreq->count = 0;

    segreq->failed = 0;

    for (i = 0; i < segments_nr - 1; i++) {

        ret = archipelago_submit_request(s, i * MAX_REQUEST_SIZE,

                                           MAX_REQUEST_SIZE,

                                           offset + i * MAX_REQUEST_SIZE,

                                           aio_cb, segreq, op);

        if (ret < 0) {

            goto err_exit;

        }

    }

    if ((segments_nr > 1) && last_segment_size) {

        ret = archipelago_submit_request(s, i * MAX_REQUEST_SIZE,

                                           last_segment_size,

                                           offset + i * MAX_REQUEST_SIZE,

                                           aio_cb, segreq, op);

    } else if ((segments_nr > 1) && !last_segment_size) {

        ret = archipelago_submit_request(s, i * MAX_REQUEST_SIZE,

                                           MAX_REQUEST_SIZE,

                                           offset + i * MAX_REQUEST_SIZE,

                                           aio_cb, segreq, op);

    } else if (segments_nr == 1) {

            ret = archipelago_submit_request(s, 0, count, offset, aio_cb,

                                               segreq, op);

    }

    if (ret < 0) {

        goto err_exit;

    }

    return 0;

err_exit:

    __sync_add_and_fetch(&segreq->failed, 1);

    if (segments_nr == 1) {

        if (__sync_add_and_fetch(&segreq->ref, -1) == 0) {

            g_free(segreq);

        }

    } else {

        if ((__sync_add_and_fetch(&segreq->ref, -segments_nr + i)) == 0) {

            g_free(segreq);

        }

    }

    return ret;

}


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

{

    RamDecompressState s1, *s = &s1;

    uint8_t buf[10];

    ram_addr_t i;

    if (ram_decompress_open(s, f) < 0)

        return -EINVAL;

    for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {

        if (ram_decompress_buf(s, buf, 1) < 0) {

            fprintf(stderr, "Error while reading ram block header\n");

            goto error;

        }

        if (buf[0] == 0) {

            if (ram_decompress_buf(s, qemu_get_ram_ptr(i),

                                   BDRV_HASH_BLOCK_SIZE) < 0) {

                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);

                goto error;

            }

        } else {

        error:

            printf("Error block header\n");

            return -EINVAL;

        }

    }

    ram_decompress_close(s);

    return 0;

}


static void v9fs_attach(void *opaque)

{

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    int32_t fid, afid, n_uname;

    V9fsString uname, aname;

    V9fsFidState *fidp;

    size_t offset = 7;

    V9fsQID qid;

    ssize_t err;

    pdu_unmarshal(pdu, offset, "ddssd", &fid, &afid, &uname, &aname, &n_uname);

    trace_v9fs_attach(pdu->tag, pdu->id, fid, afid, uname.data, aname.data);

    fidp = alloc_fid(s, fid);

    if (fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    fidp->uid = n_uname;

    err = v9fs_co_name_to_path(pdu, NULL, "/", &fidp->path);

    if (err < 0) {

        err = -EINVAL;

        clunk_fid(s, fid);

        goto out;

    }

    err = fid_to_qid(pdu, fidp, &qid);

    if (err < 0) {

        err = -EINVAL;

        clunk_fid(s, fid);

        goto out;

    }

    offset += pdu_marshal(pdu, offset, "Q", &qid);

    err = offset;

out:

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, err);

    v9fs_string_free(&uname);

    v9fs_string_free(&aname);

}


static void virtio_blk_free_request(VirtIOBlockReq *req)

{

    if (req) {

        g_slice_free(VirtQueueElement, req->elem);

        g_slice_free(VirtIOBlockReq, req);

    }

}


static int vmd_decode(VmdVideoContext *s, AVFrame *frame)

{

    int i;

    unsigned int *palette32;

    unsigned char r, g, b;

    GetByteContext gb;

    unsigned char meth;

    unsigned char *dp;   /* pointer to current frame */

    unsigned char *pp;   /* pointer to previous frame */

    unsigned char len;

    int ofs;

    int frame_x, frame_y;

    int frame_width, frame_height;

    frame_x = AV_RL16(&s->buf[6]);

    frame_y = AV_RL16(&s->buf[8]);

    frame_width = AV_RL16(&s->buf[10]) - frame_x + 1;

    frame_height = AV_RL16(&s->buf[12]) - frame_y + 1;

    if ((frame_width == s->avctx->width && frame_height == s->avctx->height) &&

        (frame_x || frame_y)) {

        s->x_off = frame_x;

        s->y_off = frame_y;

    }

    frame_x -= s->x_off;

    frame_y -= s->y_off;

    if (frame_x < 0 || frame_width < 0 ||

        frame_x >= s->avctx->width ||

        frame_width > s->avctx->width ||

        frame_x + frame_width > s->avctx->width) {

        av_log(s->avctx, AV_LOG_ERROR,

               "Invalid horizontal range %d-%d\n",

               frame_x, frame_width);

        return AVERROR_INVALIDDATA;

    }

    if (frame_y < 0 || frame_height < 0 ||

        frame_y >= s->avctx->height ||

        frame_height > s->avctx->height ||

        frame_y + frame_height > s->avctx->height) {

        av_log(s->avctx, AV_LOG_ERROR,

               "Invalid vertical range %d-%d\n",

               frame_x, frame_width);

        return AVERROR_INVALIDDATA;

    }

    /* if only a certain region will be updated, copy the entire previous

     * frame before the decode */

    if (s->prev_frame->data[0] &&

        (frame_x || frame_y || (frame_width != s->avctx->width) ||

        (frame_height != s->avctx->height))) {

        memcpy(frame->data[0], s->prev_frame->data[0],

            s->avctx->height * frame->linesize[0]);

    }

    /* check if there is a new palette */

    bytestream2_init(&gb, s->buf + 16, s->size - 16);

    if (s->buf[15] & 0x02) {

        bytestream2_skip(&gb, 2);

        palette32 = (unsigned int *)s->palette;

        if (bytestream2_get_bytes_left(&gb) >= PALETTE_COUNT * 3) {

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

                r = bytestream2_get_byteu(&gb) * 4;

                g = bytestream2_get_byteu(&gb) * 4;

                b = bytestream2_get_byteu(&gb) * 4;

                palette32[i] = 0xFFU << 24 | (r << 16) | (g << 8) | (b);

                palette32[i] |= palette32[i] >> 6 & 0x30303;

            }

        } else {

            av_log(s->avctx, AV_LOG_ERROR, "Incomplete palette\n");

            return AVERROR_INVALIDDATA;

        }

    }

    if (!s->size)

        return 0;

    /* originally UnpackFrame in VAG's code */

    if (bytestream2_get_bytes_left(&gb) < 1)

        return AVERROR_INVALIDDATA;

    meth = bytestream2_get_byteu(&gb);

    if (meth & 0x80) {

        if (!s->unpack_buffer_size) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Trying to unpack LZ-compressed frame with no LZ buffer\n");

            return AVERROR_INVALIDDATA;

        }

        lz_unpack(gb.buffer, bytestream2_get_bytes_left(&gb),

                  s->unpack_buffer, s->unpack_buffer_size);

        meth &= 0x7F;

        bytestream2_init(&gb, s->unpack_buffer, s->unpack_buffer_size);

    }

    dp = &frame->data[0][frame_y * frame->linesize[0] + frame_x];

    pp = &s->prev_frame->data[0][frame_y * s->prev_frame->linesize[0] + frame_x];

    switch (meth) {

    case 1:

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

            ofs = 0;

            do {

                len = bytestream2_get_byte(&gb);

                if (len & 0x80) {

                    len = (len & 0x7F) + 1;

                    if (ofs + len > frame_width ||

                        bytestream2_get_bytes_left(&gb) < len)

                        return AVERROR_INVALIDDATA;

                    bytestream2_get_bufferu(&gb, &dp[ofs], len);

                    ofs += len;

                } else {

                    /* interframe pixel copy */

                    if (ofs + len + 1 > frame_width || !s->prev_frame->data[0])

                        return AVERROR_INVALIDDATA;

                    memcpy(&dp[ofs], &pp[ofs], len + 1);

                    ofs += len + 1;

                }

            } while (ofs < frame_width);

            if (ofs > frame_width) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "offset > width (%d > %d)\n",

                       ofs, frame_width);

                return AVERROR_INVALIDDATA;

            }

            dp += frame->linesize[0];

            pp += s->prev_frame->linesize[0];

        }

        break;

    case 2:

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

            bytestream2_get_buffer(&gb, dp, frame_width);

            dp += frame->linesize[0];

            pp += s->prev_frame->linesize[0];

        }

        break;

    case 3:

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

            ofs = 0;

            do {

                len = bytestream2_get_byte(&gb);

                if (len & 0x80) {

                    len = (len & 0x7F) + 1;

                    if (bytestream2_peek_byte(&gb) == 0xFF) {

                        int slen = len;

                        bytestream2_get_byte(&gb);

                        len = rle_unpack(gb.buffer, &dp[ofs],

                                         len, bytestream2_get_bytes_left(&gb),

                                         frame_width - ofs);

                        ofs += slen;

                        bytestream2_skip(&gb, len);

                    } else {

                        bytestream2_get_buffer(&gb, &dp[ofs], len);

                        ofs += len;

                    }

                } else {

                    /* interframe pixel copy */

                    if (ofs + len + 1 > frame_width || !s->prev_frame->data[0])

                        return AVERROR_INVALIDDATA;

                    memcpy(&dp[ofs], &pp[ofs], len + 1);

                    ofs += len + 1;

                }

            } while (ofs < frame_width);

            if (ofs > frame_width) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "offset > width (%d > %d)\n",

                       ofs, frame_width);

                return AVERROR_INVALIDDATA;

            }

            dp += frame->linesize[0];

            pp += s->prev_frame->linesize[0];

        }

        break;

    }

    return 0;

}


static void show_program(WriterContext *w, AVFormatContext *fmt_ctx, AVProgram *program)

{

    int i;

    writer_print_section_header(w, SECTION_ID_PROGRAM);

    print_int("program_id", program->id);

    print_int("program_num", program->program_num);

    print_int("nb_streams", program->nb_stream_indexes);

    print_int("pmt_pid", program->pmt_pid);

    print_int("pcr_pid", program->pcr_pid);

    print_ts("start_pts", program->start_time);

    print_time("start_time", program->start_time, &AV_TIME_BASE_Q);

    print_ts("end_pts", program->end_time);

    print_time("end_time", program->end_time, &AV_TIME_BASE_Q);

    show_tags(w, program->metadata, SECTION_ID_PROGRAM_TAGS);

    writer_print_section_header(w, SECTION_ID_PROGRAM_STREAMS);

    for (i = 0; i < program->nb_stream_indexes; i++) {

        if (selected_streams[program->stream_index[i]])

            show_stream(w, fmt_ctx, program->stream_index[i], 1);

    }

    writer_print_section_footer(w);

    writer_print_section_footer(w);

}


static int vaapi_encode_h264_write_extra_header(AVCodecContext *avctx,

                                                VAAPIEncodePicture *pic,

                                                int index, int *type,

                                                char *data, size_t *data_len)

{

    VAAPIEncodeContext      *ctx = avctx->priv_data;

    VAAPIEncodeH264Context *priv = ctx->priv_data;

    VAAPIEncodeH264Options  *opt = ctx->codec_options;

    CodedBitstreamFragment   *au = &priv->current_access_unit;

    int err, i;

    if (priv->sei_needed) {

        if (priv->aud_needed) {

            vaapi_encode_h264_add_nal(avctx, au, &priv->aud);

            priv->aud_needed = 0;

        }

        memset(&priv->sei, 0, sizeof(priv->sei));

        priv->sei.nal_unit_header.nal_unit_type = H264_NAL_SEI;

        i = 0;

        if (pic->encode_order == 0 && opt->sei & SEI_IDENTIFIER) {

            priv->sei.payload[i].payload_type = H264_SEI_TYPE_USER_DATA_UNREGISTERED;

            priv->sei.payload[i].payload.user_data_unregistered = priv->identifier;

            ++i;

        }

        if (opt->sei & SEI_TIMING) {

            if (pic->type == PICTURE_TYPE_IDR) {

                priv->sei.payload[i].payload_type = H264_SEI_TYPE_BUFFERING_PERIOD;

                priv->sei.payload[i].payload.buffering_period = priv->buffering_period;

                ++i;

            }

            priv->sei.payload[i].payload_type = H264_SEI_TYPE_PIC_TIMING;

            priv->sei.payload[i].payload.pic_timing = priv->pic_timing;

            ++i;

        }

        if (opt->sei & SEI_RECOVERY_POINT && pic->type == PICTURE_TYPE_I) {

            priv->sei.payload[i].payload_type = H264_SEI_TYPE_RECOVERY_POINT;

            priv->sei.payload[i].payload.recovery_point = priv->recovery_point;

            ++i;

        }

        priv->sei.payload_count = i;

        av_assert0(priv->sei.payload_count > 0);

        err = vaapi_encode_h264_add_nal(avctx, au, &priv->sei);

        if (err < 0)

            goto fail;

        priv->sei_needed = 0;

        err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);

        if (err < 0)

            goto fail;

        ff_cbs_fragment_uninit(&priv->cbc, au);

        *type = VAEncPackedHeaderRawData;

        return 0;

#if !HAVE_VAAPI_1

    } else if (priv->sei_cbr_workaround_needed) {

        // Insert a zero-length header using the old SEI type.  This is

        // required to avoid triggering broken behaviour on Intel platforms

        // in CBR mode where an invalid SEI message is generated by the

        // driver and inserted into the stream.

        *data_len = 0;

        *type = VAEncPackedHeaderH264_SEI;

        priv->sei_cbr_workaround_needed = 0;

        return 0;

#endif

    } else {

        return AVERROR_EOF;

    }

fail:

    ff_cbs_fragment_uninit(&priv->cbc, au);

    return err;

}


unsigned int DoubleCPDO(const unsigned int opcode)

{

   FPA11 *fpa11 = GET_FPA11();

   float64 rFm, rFn = 0;

   unsigned int Fd, Fm, Fn, nRc = 1;

   //printk("DoubleCPDO(0x%08x)\n",opcode);

   Fm = getFm(opcode);

   if (CONSTANT_FM(opcode))

   {

     rFm = getDoubleConstant(Fm);

   }

   else

   {

     switch (fpa11->fType[Fm])

     {

        case typeSingle:

          rFm = float32_to_float64(fpa11->fpreg[Fm].fSingle, &fpa11->fp_status);

        break;

        case typeDouble:

          rFm = fpa11->fpreg[Fm].fDouble;

          break;

        case typeExtended:

            // !! patb

	    //printk("not implemented! why not?\n");

            //!! ScottB

            // should never get here, if extended involved

            // then other operand should be promoted then

            // ExtendedCPDO called.

            break;

        default: return 0;

     }

   }

   if (!MONADIC_INSTRUCTION(opcode))

   {

      Fn = getFn(opcode);

      switch (fpa11->fType[Fn])

      {

        case typeSingle:

          rFn = float32_to_float64(fpa11->fpreg[Fn].fSingle, &fpa11->fp_status);

        break;

        case typeDouble:

          rFn = fpa11->fpreg[Fn].fDouble;

        break;

        default: return 0;

      }

   }

   Fd = getFd(opcode);

   /* !! this switch isn't optimized; better (opcode & MASK_ARITHMETIC_OPCODE)>>24, sort of */

   switch (opcode & MASK_ARITHMETIC_OPCODE)

   {

      /* dyadic opcodes */

      case ADF_CODE:

         fpa11->fpreg[Fd].fDouble = float64_add(rFn,rFm, &fpa11->fp_status);

      break;

      case MUF_CODE:

      case FML_CODE:

         fpa11->fpreg[Fd].fDouble = float64_mul(rFn,rFm, &fpa11->fp_status);

      break;

      case SUF_CODE:

         fpa11->fpreg[Fd].fDouble = float64_sub(rFn,rFm, &fpa11->fp_status);

      break;

      case RSF_CODE:

         fpa11->fpreg[Fd].fDouble = float64_sub(rFm,rFn, &fpa11->fp_status);

      break;

      case DVF_CODE:

      case FDV_CODE:

         fpa11->fpreg[Fd].fDouble = float64_div(rFn,rFm, &fpa11->fp_status);

      break;

      case RDF_CODE:

      case FRD_CODE:

         fpa11->fpreg[Fd].fDouble = float64_div(rFm,rFn, &fpa11->fp_status);

      break;

#if 0

      case POW_CODE:

         fpa11->fpreg[Fd].fDouble = float64_pow(rFn,rFm);

      break;

      case RPW_CODE:

         fpa11->fpreg[Fd].fDouble = float64_pow(rFm,rFn);

      break;

#endif

      case RMF_CODE:

         fpa11->fpreg[Fd].fDouble = float64_rem(rFn,rFm, &fpa11->fp_status);

      break;

#if 0

      case POL_CODE:

         fpa11->fpreg[Fd].fDouble = float64_pol(rFn,rFm);

      break;

#endif

      /* monadic opcodes */

      case MVF_CODE:

         fpa11->fpreg[Fd].fDouble = rFm;

      break;

      case MNF_CODE:

      {

         unsigned int *p = (unsigned int*)&rFm;

#ifdef WORDS_BIGENDIAN

         p[0] ^= 0x80000000;

#else

         p[1] ^= 0x80000000;

#endif

         fpa11->fpreg[Fd].fDouble = rFm;

      }

      break;

      case ABS_CODE:

      {

         unsigned int *p = (unsigned int*)&rFm;

#ifdef WORDS_BIGENDIAN

         p[0] &= 0x7fffffff;

#else

         p[1] &= 0x7fffffff;

#endif

         fpa11->fpreg[Fd].fDouble = rFm;

      }

      break;

      case RND_CODE:

      case URD_CODE:

         fpa11->fpreg[Fd].fDouble = float64_round_to_int(rFm, &fpa11->fp_status);

      break;

      case SQT_CODE:

         fpa11->fpreg[Fd].fDouble = float64_sqrt(rFm, &fpa11->fp_status);

      break;

#if 0

      case LOG_CODE:

         fpa11->fpreg[Fd].fDouble = float64_log(rFm);

      break;

      case LGN_CODE:

         fpa11->fpreg[Fd].fDouble = float64_ln(rFm);

      break;

      case EXP_CODE:

         fpa11->fpreg[Fd].fDouble = float64_exp(rFm);

      break;

      case SIN_CODE:

         fpa11->fpreg[Fd].fDouble = float64_sin(rFm);

      break;

      case COS_CODE:

         fpa11->fpreg[Fd].fDouble = float64_cos(rFm);

      break;

      case TAN_CODE:

         fpa11->fpreg[Fd].fDouble = float64_tan(rFm);

      break;

      case ASN_CODE:

         fpa11->fpreg[Fd].fDouble = float64_arcsin(rFm);

      break;

      case ACS_CODE:

         fpa11->fpreg[Fd].fDouble = float64_arccos(rFm);

      break;

      case ATN_CODE:

         fpa11->fpreg[Fd].fDouble = float64_arctan(rFm);

      break;

#endif

      case NRM_CODE:

      break;

      default:

      {

        nRc = 0;

      }

   }

   if (0 != nRc) fpa11->fType[Fd] = typeDouble;

   return nRc;

}


static void pci_nop(void)

{

    qvirtio_scsi_start(NULL);

    qvirtio_scsi_stop();

}


long do_sigreturn(CPUS390XState *env)

{

    sigframe *frame;

    abi_ulong frame_addr = env->regs[15];

    qemu_log("%s: frame_addr 0x%llx\n", __FUNCTION__,

             (unsigned long long)frame_addr);

    target_sigset_t target_set;

    sigset_t set;

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) {

        goto badframe;

    }

    if (__get_user(target_set.sig[0], &frame->sc.oldmask[0])) {

        goto badframe;

    }

    target_to_host_sigset_internal(&set, &target_set);

    sigprocmask(SIG_SETMASK, &set, NULL); /* ~_BLOCKABLE? */

    if (restore_sigregs(env, &frame->sregs)) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return env->regs[2];

badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


void helper_check_iow(CPUX86State *env, uint32_t t0)

{

    check_io(env, t0, 2);

}


AVStream *av_new_stream(AVFormatContext *s, int id)

{

    AVStream *st;

    int i;

#if LIBAVFORMAT_VERSION_MAJOR >= 53

    AVStream **streams;

    if (s->nb_streams >= INT_MAX/sizeof(*streams))

        return NULL;

    streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));

    if (!streams)

        return NULL;

    s->streams = streams;

#else

    if (s->nb_streams >= MAX_STREAMS){

        av_log(s, AV_LOG_ERROR, "Too many streams\n");

        return NULL;

    }

#endif

    st = av_mallocz(sizeof(AVStream));

    if (!st)

        return NULL;

    st->codec= avcodec_alloc_context();

    if (s->iformat) {

        /* no default bitrate if decoding */

        st->codec->bit_rate = 0;

    }

    st->index = s->nb_streams;

    st->id = id;

    st->start_time = AV_NOPTS_VALUE;

    st->duration = AV_NOPTS_VALUE;

        /* we set the current DTS to 0 so that formats without any timestamps

           but durations get some timestamps, formats with some unknown

           timestamps have their first few packets buffered and the

           timestamps corrected before they are returned to the user */

    st->cur_dts = 0;

    st->first_dts = AV_NOPTS_VALUE;

    st->probe_packets = MAX_PROBE_PACKETS;

    /* default pts setting is MPEG-like */

    av_set_pts_info(st, 33, 1, 90000);

    st->last_IP_pts = AV_NOPTS_VALUE;

    for(i=0; i<MAX_REORDER_DELAY+1; i++)

        st->pts_buffer[i]= AV_NOPTS_VALUE;

    st->reference_dts = AV_NOPTS_VALUE;

    st->sample_aspect_ratio = (AVRational){0,1};

    s->streams[s->nb_streams++] = st;

    return st;

}


void tcg_prologue_init(TCGContext *s)

{

    size_t prologue_size, total_size;

    void *buf0, *buf1;

    /* Put the prologue at the beginning of code_gen_buffer.  */

    buf0 = s->code_gen_buffer;

    s->code_ptr = buf0;

    s->code_buf = buf0;

    s->code_gen_prologue = buf0;

    /* Generate the prologue.  */

    tcg_target_qemu_prologue(s);

    buf1 = s->code_ptr;

    flush_icache_range((uintptr_t)buf0, (uintptr_t)buf1);

    /* Deduct the prologue from the buffer.  */

    prologue_size = tcg_current_code_size(s);

    s->code_gen_ptr = buf1;

    s->code_gen_buffer = buf1;

    s->code_buf = buf1;

    total_size = s->code_gen_buffer_size - prologue_size;

    s->code_gen_buffer_size = total_size;

    /* Compute a high-water mark, at which we voluntarily flush the buffer

       and start over.  The size here is arbitrary, significantly larger

       than we expect the code generation for any one opcode to require.  */

    /* ??? We currently have no good estimate for, or checks in,

       tcg_out_tb_finalize.  If there are quite a lot of guest memory ops,

       the number of out-of-line fragments could be quite high.  In the

       short-term, increase the highwater buffer.  */

    s->code_gen_highwater = s->code_gen_buffer + (total_size - 64*1024);

    tcg_register_jit(s->code_gen_buffer, total_size);

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_OUT_ASM)) {

        qemu_log("PROLOGUE: [size=%zu]\n", prologue_size);

        log_disas(buf0, prologue_size);

        qemu_log("\n");

        qemu_log_flush();

    }

#endif

}


void qemu_clock_warp(QEMUClockType type)

{

    int64_t clock;

    int64_t deadline;

    /*

     * There are too many global variables to make the "warp" behavior

     * applicable to other clocks.  But a clock argument removes the

     * need for if statements all over the place.

     */

    if (type != QEMU_CLOCK_VIRTUAL || !use_icount) {

        return;

    }

    if (icount_sleep) {

        /*

         * If the CPUs have been sleeping, advance QEMU_CLOCK_VIRTUAL timer now.

         * This ensures that the deadline for the timer is computed correctly

         * below.

         * This also makes sure that the insn counter is synchronized before

         * the CPU starts running, in case the CPU is woken by an event other

         * than the earliest QEMU_CLOCK_VIRTUAL timer.

         */

        icount_warp_rt(NULL);

        timer_del(icount_warp_timer);

    }

    if (!all_cpu_threads_idle()) {

        return;

    }

    if (qtest_enabled()) {

        /* When testing, qtest commands advance icount.  */

	return;

    }

    /* We want to use the earliest deadline from ALL vm_clocks */

    clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT);

    deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);

    if (deadline < 0) {

        static bool notified;

        if (!icount_sleep && !notified) {

            error_report("WARNING: icount sleep disabled and no active timers");

            notified = true;

        }

        return;

    }

    if (deadline > 0) {

        /*

         * Ensure QEMU_CLOCK_VIRTUAL proceeds even when the virtual CPU goes to

         * sleep.  Otherwise, the CPU might be waiting for a future timer

         * interrupt to wake it up, but the interrupt never comes because

         * the vCPU isn't running any insns and thus doesn't advance the

         * QEMU_CLOCK_VIRTUAL.

         */

        if (!icount_sleep) {

            /*

             * We never let VCPUs sleep in no sleep icount mode.

             * If there is a pending QEMU_CLOCK_VIRTUAL timer we just advance

             * to the next QEMU_CLOCK_VIRTUAL event and notify it.

             * It is useful when we want a deterministic execution time,

             * isolated from host latencies.

             */

            seqlock_write_lock(&timers_state.vm_clock_seqlock);

            timers_state.qemu_icount_bias += deadline;

            seqlock_write_unlock(&timers_state.vm_clock_seqlock);

            qemu_clock_notify(QEMU_CLOCK_VIRTUAL);

        } else {

            /*

             * We do stop VCPUs and only advance QEMU_CLOCK_VIRTUAL after some

             * "real" time, (related to the time left until the next event) has

             * passed. The QEMU_CLOCK_VIRTUAL_RT clock will do this.

             * This avoids that the warps are visible externally; for example,

             * you will not be sending network packets continuously instead of

             * every 100ms.

             */

            seqlock_write_lock(&timers_state.vm_clock_seqlock);

            if (vm_clock_warp_start == -1 || vm_clock_warp_start > clock) {

                vm_clock_warp_start = clock;

            }

            seqlock_write_unlock(&timers_state.vm_clock_seqlock);

            timer_mod_anticipate(icount_warp_timer, clock + deadline);

        }

    } else if (deadline == 0) {

        qemu_clock_notify(QEMU_CLOCK_VIRTUAL);

    }

}


static void report_unavailable_features(FeatureWord w, uint32_t mask)

{

    FeatureWordInfo *f = &feature_word_info[w];

    int i;

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

        if ((1UL << i) & mask) {

            const char *reg = get_register_name_32(f->cpuid_reg);

            assert(reg);

            fprintf(stderr, "warning: %s doesn't support requested feature: "

                "CPUID.%02XH:%s%s%s [bit %d]\n",

                kvm_enabled() ? "host" : "TCG",

                f->cpuid_eax, reg,

                f->feat_names[i] ? "." : "",

                f->feat_names[i] ? f->feat_names[i] : "", i);

        }

    }

}


static int nbd_receive_option_reply(QIOChannel *ioc, uint32_t opt,

                                    nbd_opt_reply *reply, Error **errp)

{

    QEMU_BUILD_BUG_ON(sizeof(*reply) != 20);

    if (nbd_read(ioc, reply, sizeof(*reply), errp) < 0) {

        error_prepend(errp, "failed to read option reply");

        nbd_send_opt_abort(ioc);

        return -1;

    }

    be64_to_cpus(&reply->magic);

    be32_to_cpus(&reply->option);

    be32_to_cpus(&reply->type);

    be32_to_cpus(&reply->length);

    trace_nbd_receive_option_reply(reply->option, reply->type, reply->length);

    if (reply->magic != NBD_REP_MAGIC) {

        error_setg(errp, "Unexpected option reply magic");

        nbd_send_opt_abort(ioc);

        return -1;

    }

    if (reply->option != opt) {

        error_setg(errp, "Unexpected option type %x expected %x",

                   reply->option, opt);

        nbd_send_opt_abort(ioc);

        return -1;

    }

    return 0;

}


void omap_badwidth_write8(void *opaque, target_phys_addr_t addr,

                uint32_t value)

{

    uint8_t val8 = value;

    OMAP_8B_REG(addr);

    cpu_physical_memory_write(addr, (void *) &val8, 1);

}


static PCIDevice *qemu_pci_hot_add_storage(Monitor *mon,

                                           const char *devaddr,

                                           const char *opts)

{

    PCIDevice *dev;

    DriveInfo *dinfo = NULL;

    int type = -1;

    char buf[128];

    if (get_param_value(buf, sizeof(buf), "if", opts)) {

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

            type = IF_SCSI;

        else if (!strcmp(buf, "virtio")) {

            type = IF_VIRTIO;

        } else {

            monitor_printf(mon, "type %s not a hotpluggable PCI device.\n", buf);

            return NULL;

        }

    } else {

        monitor_printf(mon, "no if= specified\n");

        return NULL;

    }

    if (get_param_value(buf, sizeof(buf), "file", opts)) {

        dinfo = add_init_drive(opts);

        if (!dinfo)

            return NULL;

        if (dinfo->devaddr) {

            monitor_printf(mon, "Parameter addr not supported\n");

            return NULL;

        }

    } else {

        dinfo = NULL;

    }

    switch (type) {

    case IF_SCSI:

        dev = pci_create("lsi53c895a", devaddr);

        break;

    case IF_VIRTIO:

        if (!dinfo) {

            monitor_printf(mon, "virtio requires a backing file/device.\n");

            return NULL;

        }

        dev = pci_create("virtio-blk-pci", devaddr);

        qdev_prop_set_drive(&dev->qdev, "drive", dinfo);

        break;

    default:

        dev = NULL;

    }

    if (dev)

        qdev_init(&dev->qdev);

    return dev;

}


static inline void clear_float_exceptions(CPUSPARCState *env)

{

    set_float_exception_flags(0, &env->fp_status);

}


void helper_ldxfsr(CPUSPARCState *env, uint64_t new_fsr)

{

    env->fsr = (new_fsr & FSR_LDXFSR_MASK) | (env->fsr & FSR_LDXFSR_OLDMASK);

    set_fsr(env);

}


static void apply_motion_4x4(RoqContext *ri, int x, int y, unsigned char mv,

    signed char mean_x, signed char mean_y)

{

    int i, hw, mx, my;

    unsigned char *pa, *pb;

    mx = x + 8 - (mv >> 4) - mean_x;

    my = y + 8 - (mv & 0xf) - mean_y;

    pa = ri->current_frame.data[0] + (y * ri->y_stride) + x;

    pb = ri->last_frame.data[0] + (my * ri->y_stride) + mx;

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

        pa[0] = pb[0];

        pa[1] = pb[1];

        pa[2] = pb[2];

        pa[3] = pb[3];

        pa += ri->y_stride;

        pb += ri->y_stride;

    }

#if 0

    pa = ri->current_frame.data[1] + (y/2) * (ri->c_stride) + x/2;

    pb = ri->last_frame.data[1] + (my/2) * (ri->c_stride) + (mx + 1)/2;

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

        pa[0] = pb[0];

        pa[1] = pb[1];

        pa += ri->c_stride;

        pb += ri->c_stride;

    }

    pa = ri->current_frame.data[2] + (y/2) * (ri->c_stride) + x/2;

    pb = ri->last_frame.data[2] + (my/2) * (ri->c_stride) + (mx + 1)/2;

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

        pa[0] = pb[0];

        pa[1] = pb[1];

        pa += ri->c_stride;

        pb += ri->c_stride;

    }

#else

    hw = ri->y_stride/2;

    pa = ri->current_frame.data[1] + (y * ri->y_stride)/4 + x/2;

    pb = ri->last_frame.data[1] + (my/2) * (ri->y_stride/2) + (mx + 1)/2;

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

        switch(((my & 0x01) << 1) | (mx & 0x01)) {

        case 0:

            pa[0] = pb[0];

            pa[1] = pb[1];

            pa[hw] = pb[hw];

            pa[hw+1] = pb[hw+1];

            break;

        case 1:

            pa[0] = avg2(pb[0], pb[1]);

            pa[1] = avg2(pb[1], pb[2]);

            pa[hw] = avg2(pb[hw], pb[hw+1]);

            pa[hw+1] = avg2(pb[hw+1], pb[hw+2]);

            break;

        case 2:

            pa[0] = avg2(pb[0], pb[hw]);

            pa[1] = avg2(pb[1], pb[hw+1]);

            pa[hw] = avg2(pb[hw], pb[hw*2]);

            pa[hw+1] = avg2(pb[hw+1], pb[(hw*2)+1]);

            break;

        case 3:

            pa[0] = avg4(pb[0], pb[1], pb[hw], pb[hw+1]);

            pa[1] = avg4(pb[1], pb[2], pb[hw+1], pb[hw+2]);

            pa[hw] = avg4(pb[hw], pb[hw+1], pb[hw*2], pb[(hw*2)+1]);

            pa[hw+1] = avg4(pb[hw+1], pb[hw+2], pb[(hw*2)+1], pb[(hw*2)+1]);

            break;

        }

        pa = ri->current_frame.data[2] + (y * ri->y_stride)/4 + x/2;

        pb = ri->last_frame.data[2] + (my/2) * (ri->y_stride/2) + (mx + 1)/2;

    }

#endif

}


static void pty_chr_update_read_handler(CharDriverState *chr)

{

    PtyCharDriver *s = chr->opaque;

    GPollFD pfd;

    pfd.fd = g_io_channel_unix_get_fd(s->fd);

    pfd.events = G_IO_OUT;

    pfd.revents = 0;

    g_poll(&pfd, 1, 0);

    if (pfd.revents & G_IO_HUP) {

        pty_chr_state(chr, 0);

    } else {

        pty_chr_state(chr, 1);

    }

}


static int protocol_client_vencrypt_auth(VncState *vs, uint8_t *data, size_t len)

{

    int auth = read_u32(data, 0);

    if (auth != vs->vd->subauth) {

	VNC_DEBUG("Rejecting auth %d\n", auth);

	vnc_write_u8(vs, 0); /* Reject auth */

	vnc_flush(vs);

	vnc_client_error(vs);

    } else {

	VNC_DEBUG("Accepting auth %d, starting handshake\n", auth);

	vnc_write_u8(vs, 1); /* Accept auth */

	vnc_flush(vs);

	if (vnc_start_tls(vs) < 0) {

	    VNC_DEBUG("Failed to complete TLS\n");

	    return 0;

	}

	if (vs->wiremode == VNC_WIREMODE_TLS) {

	    VNC_DEBUG("Starting VeNCrypt subauth\n");

	    return start_auth_vencrypt_subauth(vs);

	} else {

	    VNC_DEBUG("TLS handshake blocked\n");

	    return 0;

	}

    }

    return 0;

}


static int ata_passthrough_16_xfer_size(SCSIDevice *dev, uint8_t *buf)

{

    int extend = buf[1] & 0x1;

    int length = buf[2] & 0x3;

    int xfer;

    int unit = ata_passthrough_xfer_unit(dev, buf);

    switch (length) {

    case 0:

    case 3: /* USB-specific.  */

        xfer = 0;

        break;

    case 1:

        xfer = buf[4];

        xfer |= (extend ? buf[3] << 8 : 0);

        break;

    case 2:

        xfer = buf[6];

        xfer |= (extend ? buf[5] << 8 : 0);

        break;

    }

    return xfer * unit;

}