static void draw_curves(AVFilterContext *ctx, AVFilterLink *inlink, AVFrame *out)

{

    AudioNEqualizerContext *s = ctx->priv;

    char *colors, *color, *saveptr = NULL;

    int ch, i, n;

    colors = av_strdup(s->colors);

    if (!colors)

        return;

    memset(out->data[0], 0, s->h * out->linesize[0]);

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

        uint8_t fg[4] = { 0xff, 0xff, 0xff, 0xff };

        int prev_v = -1;

        double f;

        color = av_strtok(ch == 0 ? colors : NULL, " |", &saveptr);

        if (color)

            av_parse_color(fg, color, -1, ctx);

        for (f = 0; f < s->w; f++) {

            double complex z;

            double complex H = 1;

            double w;

            int v, y, x;

            w = M_PI * (s->fscale ? pow(s->w - 1, f / s->w) : f) / (s->w - 1);

            z = 1. / cexp(I * w);

            for (n = 0; n < s->nb_filters; n++) {

                if (s->filters[n].channel != ch ||

                    s->filters[n].ignore)

                    continue;

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

                    FoSection *S = &s->filters[n].section[i];

                    H *= (((((S->b4 * z + S->b3) * z + S->b2) * z + S->b1) * z + S->b0) /

                          ((((S->a4 * z + S->a3) * z + S->a2) * z + S->a1) * z + S->a0));

                }

            }

            v = av_clip((1. + -20 * log10(cabs(H)) / s->mag) * s->h / 2, 0, s->h - 1);

            x = lrint(f);

            if (prev_v == -1)

                prev_v = v;

            if (v <= prev_v) {

                for (y = v; y <= prev_v; y++)

                    AV_WL32(out->data[0] + y * out->linesize[0] + x * 4, AV_RL32(fg));

            } else {

                for (y = prev_v; y <= v; y++)

                    AV_WL32(out->data[0] + y * out->linesize[0] + x * 4, AV_RL32(fg));

            }

            prev_v = v;

        }

    }

    av_free(colors);

}


static void set_sar(TiffContext *s, unsigned tag, unsigned num, unsigned den)

{

    int offset = tag == TIFF_YRES ? 2 : 0;

    s->res[offset++] = num;

    s->res[offset]   = den;

    if (s->res[0] && s->res[1] && s->res[2] && s->res[3])

        av_reduce(&s->avctx->sample_aspect_ratio.num, &s->avctx->sample_aspect_ratio.den,

                  s->res[2] * (uint64_t)s->res[1], s->res[0] * (uint64_t)s->res[3], INT32_MAX);

}


CPUX86State *cpu_x86_init(const char *cpu_model)

{

    X86CPU *cpu;

    CPUX86State *env;

    static int inited;

    cpu = X86_CPU(object_new(TYPE_X86_CPU));

    env = &cpu->env;

    env->cpu_model_str = cpu_model;

    /* init various static tables used in TCG mode */

    if (tcg_enabled() && !inited) {

        inited = 1;

        optimize_flags_init();

#ifndef CONFIG_USER_ONLY

        prev_debug_excp_handler =

            cpu_set_debug_excp_handler(breakpoint_handler);

#endif

    }

    if (cpu_x86_register(cpu, cpu_model) < 0) {

        object_delete(OBJECT(cpu));

        return NULL;

    }

    qemu_init_vcpu(env);

    return env;

}


static int glyph_enu_free(void *opaque, void *elem)
{
    av_free(elem);
    return 0;
}


static void encode_scale_factors(AVCodecContext *avctx, AACEncContext *s,

                                 SingleChannelElement *sce)

{

    int off = sce->sf_idx[0], diff;

    int i, w;

    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {

        for (i = 0; i < sce->ics.max_sfb; i++) {

            if (!sce->zeroes[w*16 + i]) {

                diff = sce->sf_idx[w*16 + i] - off + SCALE_DIFF_ZERO;

                if (diff < 0 || diff > 120)

                    av_log(avctx, AV_LOG_ERROR, "Scalefactor difference is too big to be coded\n");

                off = sce->sf_idx[w*16 + i];

                put_bits(&s->pb, ff_aac_scalefactor_bits[diff], ff_aac_scalefactor_code[diff]);

            }

        }

    }

}


static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)

{

    int pid;

    pid = filter->pid;

    if (filter->type == MPEGTS_SECTION)

        av_freep(&filter->u.section_filter.section_buf);

    av_free(filter);

    ts->pids[pid] = NULL;


static void blk_mig_reset_dirty_cursor(void)

{

    BlkMigDevState *bmds;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {

        bmds->cur_dirty = 0;

    }

}


void ppc_tlb_invalidate_all (CPUPPCState *env)

{

    switch (env->mmu_model) {

    case POWERPC_MMU_SOFT_6xx:

    case POWERPC_MMU_SOFT_74xx:

        ppc6xx_tlb_invalidate_all(env);

        break;

    case POWERPC_MMU_SOFT_4xx:

    case POWERPC_MMU_SOFT_4xx_Z:

        ppc4xx_tlb_invalidate_all(env);

        break;

    case POWERPC_MMU_REAL_4xx:

        cpu_abort(env, "No TLB for PowerPC 4xx in real mode\n");

        break;

    case POWERPC_MMU_BOOKE:

        /* XXX: TODO */

        cpu_abort(env, "MMU model not implemented\n");

        break;

    case POWERPC_MMU_BOOKE_FSL:

        /* XXX: TODO */

        cpu_abort(env, "MMU model not implemented\n");

        break;

    case POWERPC_MMU_601:

        /* XXX: TODO */

        cpu_abort(env, "MMU model not implemented\n");

        break;

    case POWERPC_MMU_32B:

#if defined(TARGET_PPC64)

    case POWERPC_MMU_64B:

    case POWERPC_MMU_64BRIDGE:

#endif /* defined(TARGET_PPC64) */

        tlb_flush(env, 1);

        break;

    default:

        /* XXX: TODO */

        cpu_abort(env, "Unknown MMU model %d\n", env->mmu_model);

        break;

    }

}


static int ffm_is_avail_data(AVFormatContext *s, int size)

{

    FFMContext *ffm = s->priv_data;

    int64_t pos, avail_size;

    int len;

    len = ffm->packet_end - ffm->packet_ptr;

    if (size <= len)

        return 1;

    pos = url_ftell(s->pb);

    if (!ffm->write_index) {

        if (pos == ffm->file_size);

            return AVERROR_EOF;

        avail_size = ffm->file_size - pos;

    } else {

    if (pos == ffm->write_index) {

        /* exactly at the end of stream */

        return AVERROR(EAGAIN);

    } else if (pos < ffm->write_index) {

        avail_size = ffm->write_index - pos;

    } else {

        avail_size = (ffm->file_size - pos) + (ffm->write_index - FFM_PACKET_SIZE);

    }

    }

    avail_size = (avail_size / ffm->packet_size) * (ffm->packet_size - FFM_HEADER_SIZE) + len;

    if (size <= avail_size)

        return 1;

    else

        return AVERROR(EAGAIN);

}


static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)

{

    AVStream *st = c->fc->streams[c->fc->nb_streams-1];

    MOVStreamContext *sc = st->priv_data;

    unsigned int i, entries;

    get_byte(pb); /* version */

    get_be24(pb); /* flags */

    entries = get_be32(pb);

    dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);

    if(entries >= UINT_MAX / sizeof(*sc->stsc_data))

        return -1;

    sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));

    if (!sc->stsc_data)

        return AVERROR(ENOMEM);

    sc->stsc_count = entries;

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

        sc->stsc_data[i].first = get_be32(pb);

        sc->stsc_data[i].count = get_be32(pb);

        sc->stsc_data[i].id = get_be32(pb);

    }

    return 0;

}


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

{

    SIFFContext *c = s->priv_data;

    if (c->has_video) {

        unsigned int size;

        if (c->cur_frame >= c->frames)

            return AVERROR_EOF;

        if (c->curstrm == -1) {

            c->pktsize = avio_rl32(s->pb) - 4;

            c->flags   = avio_rl16(s->pb);

            c->gmcsize = (c->flags & VB_HAS_GMC) ? 4 : 0;

            if (c->gmcsize)

                avio_read(s->pb, c->gmc, c->gmcsize);

            c->sndsize = (c->flags & VB_HAS_AUDIO) ? avio_rl32(s->pb) : 0;

            c->curstrm = !!(c->flags & VB_HAS_AUDIO);

        }

        if (!c->curstrm) {

            size = c->pktsize - c->sndsize - c->gmcsize - 2;

            size = ffio_limit(s->pb, size);

            if (size < 0 || c->pktsize < c->sndsize)

                return AVERROR_INVALIDDATA;

            if (av_new_packet(pkt, size + c->gmcsize + 2) < 0)

                return AVERROR(ENOMEM);

            AV_WL16(pkt->data, c->flags);

            if (c->gmcsize)

                memcpy(pkt->data + 2, c->gmc, c->gmcsize);

            if (avio_read(s->pb, pkt->data + 2 + c->gmcsize, size) != size) {

                av_free_packet(pkt);

                return AVERROR_INVALIDDATA;

            }

            pkt->stream_index = 0;

            c->curstrm        = -1;

        } else {

            int pktsize = av_get_packet(s->pb, pkt, c->sndsize - 4);

            if (pktsize < 0)

                return AVERROR(EIO);

            pkt->stream_index = 1;

            pkt->duration     = pktsize;

            c->curstrm        = 0;

        }

        if (!c->cur_frame || c->curstrm)

            pkt->flags |= AV_PKT_FLAG_KEY;

        if (c->curstrm == -1)

            c->cur_frame++;

    } else {

        int pktsize = av_get_packet(s->pb, pkt, c->block_align);

        if (!pktsize)

            return AVERROR_EOF;

        if (pktsize <= 0)

            return AVERROR(EIO);

        pkt->duration = pktsize;

    }

    return pkt->size;

}


static int packed_vscale(SwsContext *c, SwsFilterDescriptor *desc, int sliceY, int sliceH)

{

    VScalerContext *inst = desc->instance;

    int dstW = desc->dst->width;

    int chrSliceY = sliceY >> desc->dst->v_chr_sub_sample;

    int lum_fsize = inst[0].filter_size;

    int chr_fsize = inst[1].filter_size;

    uint16_t *lum_filter = inst[0].filter[0];

    uint16_t *chr_filter = inst[1].filter[0];

    int firstLum = FFMAX(1-lum_fsize, inst[0].filter_pos[chrSliceY]);

    int firstChr = FFMAX(1-chr_fsize, inst[1].filter_pos[chrSliceY]);

    int sp0 = firstLum - desc->src->plane[0].sliceY;

    int sp1 = firstChr - desc->src->plane[1].sliceY;

    int sp2 = firstChr - desc->src->plane[2].sliceY;

    int sp3 = firstLum - desc->src->plane[3].sliceY;

    int dp = sliceY - desc->dst->plane[0].sliceY;

    uint8_t **src0 = desc->src->plane[0].line + sp0;

    uint8_t **src1 = desc->src->plane[1].line + sp1;

    uint8_t **src2 = desc->src->plane[2].line + sp2;

    uint8_t **src3 = desc->alpha ? desc->src->plane[3].line + sp3 : NULL;

    uint8_t **dst = desc->dst->plane[0].line + dp;

    if (c->yuv2packed1 && lum_fsize == 1 && chr_fsize <= 2) { // unscaled RGB

        int chrAlpha = chr_fsize == 1 ? 0 : chr_filter[2 * sliceY + 1];

        ((yuv2packed1_fn)inst->pfn)(c, (const int16_t*)*src0, (const int16_t**)src1, (const int16_t**)src2, (const int16_t*)(desc->alpha ? *src3 : NULL),  *dst, dstW, chrAlpha, sliceY);

    } else if (c->yuv2packed2 && lum_fsize == 2 && chr_fsize == 2) { // bilinear upscale RGB

        int lumAlpha = lum_filter[2 * sliceY + 1];

        int chrAlpha = chr_filter[2 * sliceY + 1];

        c->lumMmxFilter[2] =

        c->lumMmxFilter[3] = lum_filter[2 * sliceY]    * 0x10001;

        c->chrMmxFilter[2] =

        c->chrMmxFilter[3] = chr_filter[2 * chrSliceY] * 0x10001;

        ((yuv2packed2_fn)inst->pfn)(c, (const int16_t**)src0, (const int16_t**)src1, (const int16_t**)src2, (const int16_t**)src3,

                    *dst, dstW, lumAlpha, chrAlpha, sliceY);

    } else { // general RGB

        ((yuv2packedX_fn)inst->pfn)(c, lum_filter + sliceY * lum_fsize,

                    (const int16_t**)src0, lum_fsize, chr_filter + sliceY * chr_fsize,

                    (const int16_t**)src1, (const int16_t**)src2, chr_fsize, (const int16_t**)src3, *dst, dstW, sliceY);

    }

    return 1;

}


WINDOW_FUNC(eight_short)

{

    const float *swindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;

    const float *pwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;

    const float *in = audio + 448;

    float *out = sce->ret;

    for (int w = 0; w < 8; w++) {

        dsp->vector_fmul        (out, in, w ? pwindow : swindow, 128);

        out += 128;

        in  += 128;

        dsp->vector_fmul_reverse(out, in, swindow, 128);

        out += 128;

    }

}


static int udp_read_packet(AVFormatContext *s,

                           AVPacket *pkt)

{

    AVFormatContext *ic;

    AVStream *st;

    RTSPStream *rtsp_st;

    fd_set rfds;

    int fd1, fd2, fd_max, n, i, ret;

    char buf[RTP_MAX_PACKET_LENGTH];

    struct timeval tv;

    for(;;) {

        if (rtsp_abort_req)

            return -EIO;

        FD_ZERO(&rfds);

        fd_max = -1;

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

            st = s->streams[i];

            rtsp_st = st->priv_data;

            ic = rtsp_st->ic;

            /* currently, we cannot probe RTCP handle because of blocking restrictions */

            rtp_get_file_handles(url_fileno(&ic->pb), &fd1, &fd2);

            if (fd1 > fd_max)

                fd_max = fd1;

            FD_SET(fd1, &rfds);

        }

        /* XXX: also add proper API to abort */

        tv.tv_sec = 0;

        tv.tv_usec = 500000;

        n = select(fd_max + 1, &rfds, NULL, NULL, &tv);

        if (n > 0) {

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

                st = s->streams[i];

                rtsp_st = st->priv_data;

                ic = rtsp_st->ic;

                rtp_get_file_handles(url_fileno(&ic->pb), &fd1, &fd2);

                if (FD_ISSET(fd1, &rfds)) {

                    ret = url_read(url_fileno(&ic->pb), buf, sizeof(buf));

                    if (ret >= 0 &&

                        rtp_parse_packet(ic, pkt, buf, ret) == 0) {

                        pkt->stream_index = i;

                        return ret;

                    }

                }

            }

        }

    }

}


static void apply_unsharp(      uint8_t *dst, int dst_stride,

                          const uint8_t *src, int src_stride,

                          int width, int height, FilterParam *fp)

{

    uint32_t **sc = fp->sc;

    uint32_t sr[MAX_MATRIX_SIZE - 1], tmp1, tmp2;

    int32_t res;

    int x, y, z;

    const uint8_t *src2 = NULL;  //silence a warning

    if (!fp->amount) {

        if (dst_stride == src_stride)

            memcpy(dst, src, src_stride * height);

        else

            for (y = 0; y < height; y++, dst += dst_stride, src += src_stride)

                memcpy(dst, src, width);

        return;

    }

    for (y = 0; y < 2 * fp->steps_y; y++)

        memset(sc[y], 0, sizeof(sc[y][0]) * (width + 2 * fp->steps_x));

    for (y = -fp->steps_y; y < height + fp->steps_y; y++) {

        if (y < height)

            src2 = src;

        memset(sr, 0, sizeof(sr[0]) * (2 * fp->steps_x - 1));

        for (x = -fp->steps_x; x < width + fp->steps_x; x++) {

            tmp1 = x <= 0 ? src2[0] : x >= width ? src2[width-1] : src2[x];

            for (z = 0; z < fp->steps_x * 2; z += 2) {

                tmp2 = sr[z + 0] + tmp1; sr[z + 0] = tmp1;

                tmp1 = sr[z + 1] + tmp2; sr[z + 1] = tmp2;

            }

            for (z = 0; z < fp->steps_y * 2; z += 2) {

                tmp2 = sc[z + 0][x + fp->steps_x] + tmp1; sc[z + 0][x + fp->steps_x] = tmp1;

                tmp1 = sc[z + 1][x + fp->steps_x] + tmp2; sc[z + 1][x + fp->steps_x] = tmp2;

            }

            if (x >= fp->steps_x && y >= fp->steps_y) {

                const uint8_t *srx = src - fp->steps_y * src_stride + x - fp->steps_x;

                uint8_t *dsx       = dst - fp->steps_y * dst_stride + x - fp->steps_x;

                res = (int32_t)*srx + ((((int32_t) * srx - (int32_t)((tmp1 + fp->halfscale) >> fp->scalebits)) * fp->amount) >> 16);

                *dsx = av_clip_uint8(res);

            }

        }

        if (y >= 0) {

            dst += dst_stride;

            src += src_stride;

        }

    }

}


static off_t read_uint32(BlockDriverState *bs, int64_t offset)

{

	uint32_t buffer;

	if (bdrv_pread(bs->file, offset, &buffer, 4) < 4)

		return 0;

	return be32_to_cpu(buffer);

}


static void gen_tlbre_40x(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    switch (rB(ctx->opcode)) {

    case 0:

        gen_helper_4xx_tlbre_hi(cpu_gpr[rD(ctx->opcode)], cpu_env,

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

        break;

    case 1:

        gen_helper_4xx_tlbre_lo(cpu_gpr[rD(ctx->opcode)], cpu_env,

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

        break;

    default:

        gen_inval_exception(ctx, POWERPC_EXCP_INVAL_INVAL);

        break;

    }

#endif

}


int aio_bh_poll(AioContext *ctx)

{

    QEMUBH *bh, **bhp, *next;

    int ret;

    ctx->walking_bh++;

    ret = 0;

    for (bh = ctx->first_bh; bh; bh = next) {

        /* Make sure that fetching bh happens before accessing its members */

        smp_read_barrier_depends();

        next = bh->next;

        /* The atomic_xchg is paired with the one in qemu_bh_schedule.  The

         * implicit memory barrier ensures that the callback sees all writes

         * done by the scheduling thread.  It also ensures that the scheduling

         * thread sees the zero before bh->cb has run, and thus will call

         * aio_notify again if necessary.

         */

        if (!bh->deleted && atomic_xchg(&bh->scheduled, 0)) {

            if (!bh->idle)

                ret = 1;

            bh->idle = 0;

            bh->cb(bh->opaque);

        }

    }

    ctx->walking_bh--;

    /* remove deleted bhs */

    if (!ctx->walking_bh) {

        qemu_mutex_lock(&ctx->bh_lock);

        bhp = &ctx->first_bh;

        while (*bhp) {

            bh = *bhp;

            if (bh->deleted) {

                *bhp = bh->next;

                g_free(bh);

            } else {

                bhp = &bh->next;

            }

        }

        qemu_mutex_unlock(&ctx->bh_lock);

    }

    return ret;

}


static void libschroedinger_handle_first_access_unit(AVCodecContext *avctx)

{

    SchroDecoderParams *p_schro_params = avctx->priv_data;

    SchroDecoder *decoder = p_schro_params->decoder;

    p_schro_params->format = schro_decoder_get_video_format(decoder);

    /* Tell FFmpeg about sequence details. */

    if (av_image_check_size(p_schro_params->format->width,

                            p_schro_params->format->height, 0, avctx) < 0) {

        av_log(avctx, AV_LOG_ERROR, "invalid dimensions (%dx%d)\n",

               p_schro_params->format->width, p_schro_params->format->height);

        avctx->height = avctx->width = 0;

        return;

    }

    avctx->height  = p_schro_params->format->height;

    avctx->width   = p_schro_params->format->width;

    avctx->pix_fmt = get_chroma_format(p_schro_params->format->chroma_format);

    if (ff_get_schro_frame_format(p_schro_params->format->chroma_format,

                                  &p_schro_params->frame_format) == -1) {

        av_log(avctx, AV_LOG_ERROR,

               "This codec currently only supports planar YUV 4:2:0, 4:2:2 "

               "and 4:4:4 formats.\n");

        return;

    }

    avctx->framerate.num = p_schro_params->format->frame_rate_numerator;

    avctx->framerate.den = p_schro_params->format->frame_rate_denominator;

}


static av_cold int atrac1_decode_end(AVCodecContext * avctx) {

    AT1Ctx *q = avctx->priv_data;

    av_freep(&q->out_samples[0]);

    ff_mdct_end(&q->mdct_ctx[0]);

    ff_mdct_end(&q->mdct_ctx[1]);

    ff_mdct_end(&q->mdct_ctx[2]);

    return 0;

}


static double block_angle(int x, int y, int cx, int cy, MotionVector *shift)

{

    double a1, a2, diff;

    a1 = atan2(y - cy, x - cx);

    a2 = atan2(y - cy + shift->y, x - cx + shift->x);

    diff = a2 - a1;

    return (diff > M_PI)  ? diff - 2 * M_PI :

           (diff < -M_PI) ? diff + 2 * M_PI :

           diff;

}


static void panicked_mon_event(const char *action)

{

    QObject *data;

    data = qobject_from_jsonf("{ 'action': %s }", action);

    monitor_protocol_event(QEVENT_GUEST_PANICKED, data);

    qobject_decref(data);

}


int inet_aton (const char * str, struct in_addr * add)

{

    const char * pch = str;

    unsigned int add1 = 0, add2 = 0, add3 = 0, add4 = 0;

    add1 = atoi(pch);

    pch = strpbrk(pch,".");

    if (pch == 0 || ++pch == 0) return 0;

    add2 = atoi(pch);

    pch = strpbrk(pch,".");

    if (pch == 0 || ++pch == 0) return 0;

    add3 = atoi(pch);

    pch = strpbrk(pch,".");

    if (pch == 0 || ++pch == 0) return 0;

    add4 = atoi(pch);

    if (!add1 || (add1|add2|add3|add4) > 255) return 0;

    add->s_addr=(add4<<24)+(add3<<16)+(add2<<8)+add1;

    return 1;

}


static int cirrus_bitblt_videotovideo_patterncopy(CirrusVGAState * s)

{

    return cirrus_bitblt_common_patterncopy(s,

					    s->vram_ptr +

                                            (s->cirrus_blt_srcaddr & ~7));

}


static void cdg_load_palette(CDGraphicsContext *cc, uint8_t *data, int low)

{

    uint8_t r, g, b;

    uint16_t color;

    int i;

    int array_offset  = low ? 0 : 8;

    uint32_t *palette = (uint32_t *) cc->frame.data[1];

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

        color = (data[2 * i] << 6) + (data[2 * i + 1] & 0x3F);

        r = ((color >> 8) & 0x000F) * 17;

        g = ((color >> 4) & 0x000F) * 17;

        b = ((color     ) & 0x000F) * 17;

        palette[i + array_offset] = 0xFF << 24 | r << 16 | g << 8 | b;

    }

    cc->frame.palette_has_changed = 1;

}


static void load_elf_image(const char *image_name, int image_fd,

                           struct image_info *info, char **pinterp_name,

                           char bprm_buf[BPRM_BUF_SIZE])

{

    struct elfhdr *ehdr = (struct elfhdr *)bprm_buf;

    struct elf_phdr *phdr;

    abi_ulong load_addr, load_bias, loaddr, hiaddr, error;

    int i, retval;

    const char *errmsg;

    /* First of all, some simple consistency checks */

    errmsg = "Invalid ELF image for this architecture";

    if (!elf_check_ident(ehdr)) {

        goto exit_errmsg;

    }

    bswap_ehdr(ehdr);

    if (!elf_check_ehdr(ehdr)) {

        goto exit_errmsg;

    }

    i = ehdr->e_phnum * sizeof(struct elf_phdr);

    if (ehdr->e_phoff + i <= BPRM_BUF_SIZE) {

        phdr = (struct elf_phdr *)(bprm_buf + ehdr->e_phoff);

    } else {

        phdr = (struct elf_phdr *) alloca(i);

        retval = pread(image_fd, phdr, i, ehdr->e_phoff);

        if (retval != i) {

            goto exit_read;

        }

    }

    bswap_phdr(phdr, ehdr->e_phnum);

#ifdef CONFIG_USE_FDPIC

    info->nsegs = 0;

    info->pt_dynamic_addr = 0;

#endif

    /* Find the maximum size of the image and allocate an appropriate

       amount of memory to handle that.  */

    loaddr = -1, hiaddr = 0;

    for (i = 0; i < ehdr->e_phnum; ++i) {

        if (phdr[i].p_type == PT_LOAD) {

            abi_ulong a = phdr[i].p_vaddr;

            if (a < loaddr) {

                loaddr = a;

            }

            a += phdr[i].p_memsz;

            if (a > hiaddr) {

                hiaddr = a;

            }

#ifdef CONFIG_USE_FDPIC

            ++info->nsegs;

#endif

        }

    }

    load_addr = loaddr;

    if (ehdr->e_type == ET_DYN) {

        /* The image indicates that it can be loaded anywhere.  Find a

           location that can hold the memory space required.  If the

           image is pre-linked, LOADDR will be non-zero.  Since we do

           not supply MAP_FIXED here we'll use that address if and

           only if it remains available.  */

        load_addr = target_mmap(loaddr, hiaddr - loaddr, PROT_NONE,

                                MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,

                                -1, 0);

        if (load_addr == -1) {

            goto exit_perror;

        }

    } else if (pinterp_name != NULL) {

        /* This is the main executable.  Make sure that the low

           address does not conflict with MMAP_MIN_ADDR or the

           QEMU application itself.  */

        probe_guest_base(image_name, loaddr, hiaddr);

    }

    load_bias = load_addr - loaddr;

#ifdef CONFIG_USE_FDPIC

    {

        struct elf32_fdpic_loadseg *loadsegs = info->loadsegs =

            g_malloc(sizeof(*loadsegs) * info->nsegs);

        for (i = 0; i < ehdr->e_phnum; ++i) {

            switch (phdr[i].p_type) {

            case PT_DYNAMIC:

                info->pt_dynamic_addr = phdr[i].p_vaddr + load_bias;

                break;

            case PT_LOAD:

                loadsegs->addr = phdr[i].p_vaddr + load_bias;

                loadsegs->p_vaddr = phdr[i].p_vaddr;

                loadsegs->p_memsz = phdr[i].p_memsz;

                ++loadsegs;

                break;

            }

        }

    }

#endif

    info->load_bias = load_bias;

    info->load_addr = load_addr;

    info->entry = ehdr->e_entry + load_bias;

    info->start_code = -1;

    info->end_code = 0;

    info->start_data = -1;

    info->end_data = 0;

    info->brk = 0;

    for (i = 0; i < ehdr->e_phnum; i++) {

        struct elf_phdr *eppnt = phdr + i;

        if (eppnt->p_type == PT_LOAD) {

            abi_ulong vaddr, vaddr_po, vaddr_ps, vaddr_ef, vaddr_em;

            int elf_prot = 0;

            if (eppnt->p_flags & PF_R) elf_prot =  PROT_READ;

            if (eppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;

            if (eppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;

            vaddr = load_bias + eppnt->p_vaddr;

            vaddr_po = TARGET_ELF_PAGEOFFSET(vaddr);

            vaddr_ps = TARGET_ELF_PAGESTART(vaddr);

            error = target_mmap(vaddr_ps, eppnt->p_filesz + vaddr_po,

                                elf_prot, MAP_PRIVATE | MAP_FIXED,

                                image_fd, eppnt->p_offset - vaddr_po);

            if (error == -1) {

                goto exit_perror;

            }

            vaddr_ef = vaddr + eppnt->p_filesz;

            vaddr_em = vaddr + eppnt->p_memsz;

            /* If the load segment requests extra zeros (e.g. bss), map it.  */

            if (vaddr_ef < vaddr_em) {

                zero_bss(vaddr_ef, vaddr_em, elf_prot);

            }

            /* Find the full program boundaries.  */

            if (elf_prot & PROT_EXEC) {

                if (vaddr < info->start_code) {

                    info->start_code = vaddr;

                }

                if (vaddr_ef > info->end_code) {

                    info->end_code = vaddr_ef;

                }

            }

            if (elf_prot & PROT_WRITE) {

                if (vaddr < info->start_data) {

                    info->start_data = vaddr;

                }

                if (vaddr_ef > info->end_data) {

                    info->end_data = vaddr_ef;

                }

                if (vaddr_em > info->brk) {

                    info->brk = vaddr_em;

                }

            }

        } else if (eppnt->p_type == PT_INTERP && pinterp_name) {

            char *interp_name;

            if (*pinterp_name) {

                errmsg = "Multiple PT_INTERP entries";

                goto exit_errmsg;

            }

            interp_name = malloc(eppnt->p_filesz);

            if (!interp_name) {

                goto exit_perror;

            }

            if (eppnt->p_offset + eppnt->p_filesz <= BPRM_BUF_SIZE) {

                memcpy(interp_name, bprm_buf + eppnt->p_offset,

                       eppnt->p_filesz);

            } else {

                retval = pread(image_fd, interp_name, eppnt->p_filesz,

                               eppnt->p_offset);

                if (retval != eppnt->p_filesz) {

                    goto exit_perror;

                }

            }

            if (interp_name[eppnt->p_filesz - 1] != 0) {

                errmsg = "Invalid PT_INTERP entry";

                goto exit_errmsg;

            }

            *pinterp_name = interp_name;

        }

    }

    if (info->end_data == 0) {

        info->start_data = info->end_code;

        info->end_data = info->end_code;

        info->brk = info->end_code;

    }

    if (qemu_log_enabled()) {

        load_symbols(ehdr, image_fd, load_bias);

    }

    close(image_fd);

    return;

 exit_read:

    if (retval >= 0) {

        errmsg = "Incomplete read of file header";

        goto exit_errmsg;

    }

 exit_perror:

    errmsg = strerror(errno);

 exit_errmsg:

    fprintf(stderr, "%s: %s\n", image_name, errmsg);

    exit(-1);

}


void omap_clk_init(struct omap_mpu_state_s *mpu)

{

    struct clk **i, *j, *k;

    int count;

    int flag;

    if (cpu_is_omap310(mpu))

        flag = CLOCK_IN_OMAP310;

    else if (cpu_is_omap1510(mpu))

        flag = CLOCK_IN_OMAP1510;

    else if (cpu_is_omap2410(mpu) || cpu_is_omap2420(mpu))

        flag = CLOCK_IN_OMAP242X;

    else if (cpu_is_omap2430(mpu))

        flag = CLOCK_IN_OMAP243X;

    else if (cpu_is_omap3430(mpu))

        flag = CLOCK_IN_OMAP243X;

    else

        return;

    for (i = onchip_clks, count = 0; *i; i ++)

        if ((*i)->flags & flag)

            count ++;

    mpu->clks = (struct clk *) g_malloc0(sizeof(struct clk) * (count + 1));

    for (i = onchip_clks, j = mpu->clks; *i; i ++)

        if ((*i)->flags & flag) {

            memcpy(j, *i, sizeof(struct clk));

            for (k = mpu->clks; k < j; k ++)

                if (j->parent && !strcmp(j->parent->name, k->name)) {

                    j->parent = k;

                    j->sibling = k->child1;

                    k->child1 = j;

                } else if (k->parent && !strcmp(k->parent->name, j->name)) {

                    k->parent = j;

                    k->sibling = j->child1;

                    j->child1 = k;

                }

            j->divisor = j->divisor ?: 1;

            j->multiplier = j->multiplier ?: 1;

            j ++;

        }

    for (j = mpu->clks; count --; j ++) {

        omap_clk_update(j);

        omap_clk_rate_update(j);

    }

}


static void ohci_pci_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->init = usb_ohci_initfn_pci;

    k->vendor_id = PCI_VENDOR_ID_APPLE;

    k->device_id = PCI_DEVICE_ID_APPLE_IPID_USB;

    k->class_id = PCI_CLASS_SERIAL_USB;

    dc->desc = "Apple USB Controller";

    dc->props = ohci_pci_properties;

}


int av_opt_set(void *obj, const char *name, const char *val, int search_flags)

{

    int ret;

    void *dst, *target_obj;

    const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);

    if (!o || !target_obj)

        return AVERROR_OPTION_NOT_FOUND;

    if (!val && (o->type != AV_OPT_TYPE_STRING &&

                 o->type != AV_OPT_TYPE_PIXEL_FMT && o->type != AV_OPT_TYPE_SAMPLE_FMT &&

                 o->type != AV_OPT_TYPE_IMAGE_SIZE && o->type != AV_OPT_TYPE_VIDEO_RATE &&

                 o->type != AV_OPT_TYPE_DURATION && o->type != AV_OPT_TYPE_COLOR &&

                 o->type != AV_OPT_TYPE_CHANNEL_LAYOUT))

        return AVERROR(EINVAL);

    dst = ((uint8_t*)target_obj) + o->offset;

    switch (o->type) {

    case AV_OPT_TYPE_STRING:   return set_string(obj, o, val, dst);

    case AV_OPT_TYPE_BINARY:   return set_string_binary(obj, o, val, dst);

    case AV_OPT_TYPE_FLAGS:

    case AV_OPT_TYPE_INT:

    case AV_OPT_TYPE_INT64:

    case AV_OPT_TYPE_FLOAT:

    case AV_OPT_TYPE_DOUBLE:

    case AV_OPT_TYPE_RATIONAL: return set_string_number(obj, target_obj, o, val, dst);

    case AV_OPT_TYPE_IMAGE_SIZE:

        if (!val || !strcmp(val, "none")) {

            *(int *)dst = *((int *)dst + 1) = 0;

            return 0;

        }

        ret = av_parse_video_size(dst, ((int *)dst) + 1, val);

        if (ret < 0)

            av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as image size\n", val);

        return ret;

    case AV_OPT_TYPE_VIDEO_RATE:

        if (!val) {

            ret = AVERROR(EINVAL);

        } else {

            ret = av_parse_video_rate(dst, val);

        }

        if (ret < 0)

            av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as video rate\n", val);

        return ret;

    case AV_OPT_TYPE_PIXEL_FMT:

        if (!val || !strcmp(val, "none")) {

            ret = AV_PIX_FMT_NONE;

        } else {

            ret = av_get_pix_fmt(val);

            if (ret == AV_PIX_FMT_NONE) {

                char *tail;

                ret = strtol(val, &tail, 0);

                if (*tail || (unsigned)ret >= AV_PIX_FMT_NB) {

                    av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as pixel format\n", val);

                    return AVERROR(EINVAL);

                }

            }

        }

        *(enum AVPixelFormat *)dst = ret;

        return 0;

    case AV_OPT_TYPE_SAMPLE_FMT:

        if (!val || !strcmp(val, "none")) {

            ret = AV_SAMPLE_FMT_NONE;

        } else {

            ret = av_get_sample_fmt(val);

            if (ret == AV_SAMPLE_FMT_NONE) {

                char *tail;

                ret = strtol(val, &tail, 0);

                if (*tail || (unsigned)ret >= AV_SAMPLE_FMT_NB) {

                    av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as sample format\n", val);

                    return AVERROR(EINVAL);

                }

            }

        }

        *(enum AVSampleFormat *)dst = ret;

        return 0;

    case AV_OPT_TYPE_DURATION:

        if (!val) {

            *(int64_t *)dst = 0;

            return 0;

        } else {

            if ((ret = av_parse_time(dst, val, 1)) < 0)

                av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as duration\n", val);

            return ret;

        }

        break;

    case AV_OPT_TYPE_COLOR:

        if (!val) {

            return 0;

        } else {

            ret = av_parse_color(dst, val, -1, obj);

            if (ret < 0)

                av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as color\n", val);

            return ret;

        }

        break;

    case AV_OPT_TYPE_CHANNEL_LAYOUT:

        if (!val || !strcmp(val, "none")) {

            *(int64_t *)dst = 0;

        } else {

#if FF_API_GET_CHANNEL_LAYOUT_COMPAT

            int64_t cl = ff_get_channel_layout(val, 0);

#else

            int64_t cl = av_get_channel_layout(val);

#endif

            if (!cl) {

                av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as channel layout\n", val);

                ret = AVERROR(EINVAL);

            }

            *(int64_t *)dst = cl;

            return ret;

        }

        break;

    }

    av_log(obj, AV_LOG_ERROR, "Invalid option type.\n");

    return AVERROR(EINVAL);

}


static struct omap_lpg_s *omap_lpg_init(MemoryRegion *system_memory,

                                        hwaddr base, omap_clk clk)

{

    struct omap_lpg_s *s = (struct omap_lpg_s *)

            g_malloc0(sizeof(struct omap_lpg_s));

    s->tm = timer_new_ms(QEMU_CLOCK_VIRTUAL, omap_lpg_tick, s);

    omap_lpg_reset(s);

    memory_region_init_io(&s->iomem, NULL, &omap_lpg_ops, s, "omap-lpg", 0x800);

    memory_region_add_subregion(system_memory, base, &s->iomem);

    omap_clk_adduser(clk, qemu_allocate_irqs(omap_lpg_clk_update, s, 1)[0]);

    return s;

}


static void restart_coroutine(void *opaque)

{

    Coroutine *co = opaque;

    DPRINTF("co=%p", co);

    qemu_coroutine_enter(co, NULL);

}


PPC_OP(test_ctrz_false)

{

    T0 = (regs->ctr == 0 && (T0 & PARAM(1)) == 0);

    RETURN();

}


static int packed_16bpc_bswap(SwsContext *c, const uint8_t *src[],

                              int srcStride[], int srcSliceY, int srcSliceH,

                              uint8_t *dst[], int dstStride[])

{

    int i, j;

    int srcstr = srcStride[0] >> 1;

    int dststr = dstStride[0] >> 1;

    uint16_t       *dstPtr =       (uint16_t *) dst[0];

    const uint16_t *srcPtr = (const uint16_t *) src[0];

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

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

            dstPtr[j] = av_bswap16(srcPtr[j]);

        }

        srcPtr += srcstr;

        dstPtr += dststr;

    }

    return srcSliceH;

}


int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,

                                BlockCompletionFunc *completion_cb,

                                void *opaque)

{

    Error *local_err = NULL;

    int err;

    bdrv_add_key(bs, NULL, &local_err);

    if (!local_err) {

        if (completion_cb)

            completion_cb(opaque, 0);

        return 0;

    }

    /* Need a key for @bs */

    if (monitor_ctrl_mode(mon)) {

        qerror_report_err(local_err);

        return -1;

    }

    monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),

                   bdrv_get_encrypted_filename(bs));

    mon->password_completion_cb = completion_cb;

    mon->password_opaque = opaque;

    err = monitor_read_password(mon, bdrv_password_cb, bs);

    if (err && completion_cb)

        completion_cb(opaque, err);

    return err;

}


static void slavio_timer_get_out(SLAVIO_TIMERState *s)

{

    int out;

    int64_t diff, ticks, count;

    uint32_t limit;

    // There are three clock tick units: CPU ticks, register units

    // (nanoseconds), and counter ticks (500 ns).

    if (s->mode == 1 && s->stopped)

	ticks = s->stop_time;

    else

	ticks = qemu_get_clock(vm_clock) - s->tick_offset;

    out = (ticks > s->expire_time);

    if (out)

	s->reached = 0x80000000;

    if (!s->limit)

	limit = 0x7fffffff;

    else

	limit = s->limit;

    // Convert register units to counter ticks

    limit = limit >> 9;

    // Convert cpu ticks to counter ticks

    diff = muldiv64(ticks - s->count_load_time, CNT_FREQ, ticks_per_sec);

    // Calculate what the counter should be, convert to register

    // units

    count = diff % limit;

    s->count = count << 9;

    s->counthigh = count >> 22;

    // Expire time: CPU ticks left to next interrupt

    // Convert remaining counter ticks to CPU ticks

    s->expire_time = ticks + muldiv64(limit - count, ticks_per_sec, CNT_FREQ);

    DPRINTF("irq %d limit %d reached %d d %" PRId64 " count %d s->c %x diff %" PRId64 " stopped %d mode %d\n", s->irq, limit, s->reached?1:0, (ticks-s->count_load_time), count, s->count, s->expire_time - ticks, s->stopped, s->mode);

    if (s->mode != 1)

	pic_set_irq_cpu(s->intctl, s->irq, out, s->cpu);

}


void cpu_x86_cpuid(CPUX86State *env, uint32_t index, uint32_t count,

                   uint32_t *eax, uint32_t *ebx,

                   uint32_t *ecx, uint32_t *edx)

{

    X86CPU *cpu = x86_env_get_cpu(env);

    CPUState *cs = CPU(cpu);

    /* test if maximum index reached */

    if (index & 0x80000000) {

        if (index > env->cpuid_xlevel) {

            if (env->cpuid_xlevel2 > 0) {

                /* Handle the Centaur's CPUID instruction. */

                if (index > env->cpuid_xlevel2) {

                    index = env->cpuid_xlevel2;

                } else if (index < 0xC0000000) {

                    index = env->cpuid_xlevel;

            } else {

                /* Intel documentation states that invalid EAX input will

                 * return the same information as EAX=cpuid_level

                 * (Intel SDM Vol. 2A - Instruction Set Reference - CPUID)

                 */

                index =  env->cpuid_level;

    } else {

        if (index > env->cpuid_level)

            index = env->cpuid_level;

    switch(index) {

    case 0:

        *eax = env->cpuid_level;

        get_cpuid_vendor(env, ebx, ecx, edx);

    case 1:

        *eax = env->cpuid_version;

        *ebx = (env->cpuid_apic_id << 24) | 8 << 8; /* CLFLUSH size in quad words, Linux wants it. */

        *ecx = env->features[FEAT_1_ECX];

        *edx = env->features[FEAT_1_EDX];

        if (cs->nr_cores * cs->nr_threads > 1) {

            *ebx |= (cs->nr_cores * cs->nr_threads) << 16;

            *edx |= 1 << 28;    /* HTT bit */

    case 2:

        /* cache info: needed for Pentium Pro compatibility */

            host_cpuid(index, 0, eax, ebx, ecx, edx);

        *eax = 1; /* Number of CPUID[EAX=2] calls required */

        *ebx = 0;

        *ecx = 0;

        *edx = (L1D_DESCRIPTOR << 16) | \

               (L1I_DESCRIPTOR <<  8) | \

               (L2_DESCRIPTOR);

    case 4:

        /* cache info: needed for Core compatibility */

        if (cs->nr_cores > 1) {

            *eax = (cs->nr_cores - 1) << 26;

        } else {

            *eax = 0;

        switch (count) {

            case 0: /* L1 dcache info */

                *eax |= CPUID_4_TYPE_DCACHE | \

                        CPUID_4_LEVEL(1) | \

                        CPUID_4_SELF_INIT_LEVEL;

                *ebx = (L1D_LINE_SIZE - 1) | \

                       ((L1D_PARTITIONS - 1) << 12) | \

                       ((L1D_ASSOCIATIVITY - 1) << 22);

                *ecx = L1D_SETS - 1;

                *edx = CPUID_4_NO_INVD_SHARING;

            case 1: /* L1 icache info */

                *eax |= CPUID_4_TYPE_ICACHE | \

                        CPUID_4_LEVEL(1) | \

                        CPUID_4_SELF_INIT_LEVEL;

                *ebx = (L1I_LINE_SIZE - 1) | \

                       ((L1I_PARTITIONS - 1) << 12) | \

                       ((L1I_ASSOCIATIVITY - 1) << 22);

                *ecx = L1I_SETS - 1;

                *edx = CPUID_4_NO_INVD_SHARING;

            case 2: /* L2 cache info */

                *eax |= CPUID_4_TYPE_UNIFIED | \

                        CPUID_4_LEVEL(2) | \

                        CPUID_4_SELF_INIT_LEVEL;

                if (cs->nr_threads > 1) {

                    *eax |= (cs->nr_threads - 1) << 14;

                *ebx = (L2_LINE_SIZE - 1) | \

                       ((L2_PARTITIONS - 1) << 12) | \

                       ((L2_ASSOCIATIVITY - 1) << 22);

                *ecx = L2_SETS - 1;

                *edx = CPUID_4_NO_INVD_SHARING;

            default: /* end of info */

                *eax = 0;

                *ebx = 0;

                *ecx = 0;

                *edx = 0;

    case 5:

        /* mwait info: needed for Core compatibility */

        *eax = 0; /* Smallest monitor-line size in bytes */

        *ebx = 0; /* Largest monitor-line size in bytes */

        *ecx = CPUID_MWAIT_EMX | CPUID_MWAIT_IBE;

        *edx = 0;

    case 6:

        /* Thermal and Power Leaf */

        *eax = 0;

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

    case 7:

        /* Structured Extended Feature Flags Enumeration Leaf */

        if (count == 0) {

            *eax = 0; /* Maximum ECX value for sub-leaves */

            *ebx = env->features[FEAT_7_0_EBX]; /* Feature flags */

            *ecx = 0; /* Reserved */

            *edx = 0; /* Reserved */

        } else {

            *eax = 0;

            *ebx = 0;

            *ecx = 0;

            *edx = 0;

    case 9:

        /* Direct Cache Access Information Leaf */

        *eax = 0; /* Bits 0-31 in DCA_CAP MSR */

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

    case 0xA:

        /* Architectural Performance Monitoring Leaf */

        if (kvm_enabled() && cpu->enable_pmu) {

            KVMState *s = cs->kvm_state;

            *eax = kvm_arch_get_supported_cpuid(s, 0xA, count, R_EAX);

            *ebx = kvm_arch_get_supported_cpuid(s, 0xA, count, R_EBX);

            *ecx = kvm_arch_get_supported_cpuid(s, 0xA, count, R_ECX);

            *edx = kvm_arch_get_supported_cpuid(s, 0xA, count, R_EDX);

        } else {

            *eax = 0;

            *ebx = 0;

            *ecx = 0;

            *edx = 0;

    case 0xD:

        /* Processor Extended State */

        if (!(env->features[FEAT_1_ECX] & CPUID_EXT_XSAVE)) {

            *eax = 0;

            *ebx = 0;

            *ecx = 0;

            *edx = 0;

        if (kvm_enabled()) {

            KVMState *s = cs->kvm_state;

            *eax = kvm_arch_get_supported_cpuid(s, 0xd, count, R_EAX);

            *ebx = kvm_arch_get_supported_cpuid(s, 0xd, count, R_EBX);

            *ecx = kvm_arch_get_supported_cpuid(s, 0xd, count, R_ECX);

            *edx = kvm_arch_get_supported_cpuid(s, 0xd, count, R_EDX);

        } else {

            *eax = 0;

            *ebx = 0;

            *ecx = 0;

            *edx = 0;

    case 0x80000000:

        *eax = env->cpuid_xlevel;

        *ebx = env->cpuid_vendor1;

        *edx = env->cpuid_vendor2;

        *ecx = env->cpuid_vendor3;

    case 0x80000001:

        *eax = env->cpuid_version;

        *ebx = 0;

        *ecx = env->features[FEAT_8000_0001_ECX];

        *edx = env->features[FEAT_8000_0001_EDX];

        /* The Linux kernel checks for the CMPLegacy bit and

         * discards multiple thread information if it is set.

         * So dont set it here for Intel to make Linux guests happy.

         */

        if (cs->nr_cores * cs->nr_threads > 1) {

            uint32_t tebx, tecx, tedx;

            get_cpuid_vendor(env, &tebx, &tecx, &tedx);

            if (tebx != CPUID_VENDOR_INTEL_1 ||

                tedx != CPUID_VENDOR_INTEL_2 ||

                tecx != CPUID_VENDOR_INTEL_3) {

                *ecx |= 1 << 1;    /* CmpLegacy bit */

    case 0x80000002:

    case 0x80000003:

    case 0x80000004:

        *eax = env->cpuid_model[(index - 0x80000002) * 4 + 0];

        *ebx = env->cpuid_model[(index - 0x80000002) * 4 + 1];

        *ecx = env->cpuid_model[(index - 0x80000002) * 4 + 2];

        *edx = env->cpuid_model[(index - 0x80000002) * 4 + 3];

    case 0x80000005:

        /* cache info (L1 cache) */

            host_cpuid(index, 0, eax, ebx, ecx, edx);

        *eax = (L1_DTLB_2M_ASSOC << 24) | (L1_DTLB_2M_ENTRIES << 16) | \

               (L1_ITLB_2M_ASSOC <<  8) | (L1_ITLB_2M_ENTRIES);

        *ebx = (L1_DTLB_4K_ASSOC << 24) | (L1_DTLB_4K_ENTRIES << 16) | \

               (L1_ITLB_4K_ASSOC <<  8) | (L1_ITLB_4K_ENTRIES);

        *ecx = (L1D_SIZE_KB_AMD << 24) | (L1D_ASSOCIATIVITY_AMD << 16) | \

               (L1D_LINES_PER_TAG << 8) | (L1D_LINE_SIZE);

        *edx = (L1I_SIZE_KB_AMD << 24) | (L1I_ASSOCIATIVITY_AMD << 16) | \

               (L1I_LINES_PER_TAG << 8) | (L1I_LINE_SIZE);

    case 0x80000006:

        /* cache info (L2 cache) */

            host_cpuid(index, 0, eax, ebx, ecx, edx);

        *eax = (AMD_ENC_ASSOC(L2_DTLB_2M_ASSOC) << 28) | \

               (L2_DTLB_2M_ENTRIES << 16) | \

               (AMD_ENC_ASSOC(L2_ITLB_2M_ASSOC) << 12) | \

               (L2_ITLB_2M_ENTRIES);

        *ebx = (AMD_ENC_ASSOC(L2_DTLB_4K_ASSOC) << 28) | \

               (L2_DTLB_4K_ENTRIES << 16) | \

               (AMD_ENC_ASSOC(L2_ITLB_4K_ASSOC) << 12) | \

               (L2_ITLB_4K_ENTRIES);

        *ecx = (L2_SIZE_KB_AMD << 16) | \

               (AMD_ENC_ASSOC(L2_ASSOCIATIVITY) << 12) | \

               (L2_LINES_PER_TAG << 8) | (L2_LINE_SIZE);

        *edx = ((L3_SIZE_KB/512) << 18) | \

               (AMD_ENC_ASSOC(L3_ASSOCIATIVITY) << 12) | \

               (L3_LINES_PER_TAG << 8) | (L3_LINE_SIZE);

    case 0x80000008:

        /* virtual & phys address size in low 2 bytes. */

/* XXX: This value must match the one used in the MMU code. */

        if (env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_LM) {

            /* 64 bit processor */

/* XXX: The physical address space is limited to 42 bits in exec.c. */

            *eax = 0x00003028; /* 48 bits virtual, 40 bits physical */

        } else {

            if (env->features[FEAT_1_EDX] & CPUID_PSE36) {

                *eax = 0x00000024; /* 36 bits physical */

            } else {

                *eax = 0x00000020; /* 32 bits physical */

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        if (cs->nr_cores * cs->nr_threads > 1) {

            *ecx |= (cs->nr_cores * cs->nr_threads) - 1;

    case 0x8000000A:

        if (env->features[FEAT_8000_0001_ECX] & CPUID_EXT3_SVM) {

            *eax = 0x00000001; /* SVM Revision */

            *ebx = 0x00000010; /* nr of ASIDs */

            *ecx = 0;

            *edx = env->features[FEAT_SVM]; /* optional features */

        } else {

            *eax = 0;

            *ebx = 0;

            *ecx = 0;

            *edx = 0;

    case 0xC0000000:

        *eax = env->cpuid_xlevel2;

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

    case 0xC0000001:

        /* Support for VIA CPU's CPUID instruction */

        *eax = env->cpuid_version;

        *ebx = 0;

        *ecx = 0;

        *edx = env->features[FEAT_C000_0001_EDX];

    case 0xC0000002:

    case 0xC0000003:

    case 0xC0000004:

        /* Reserved for the future, and now filled with zero */

        *eax = 0;

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

    default:

        /* reserved values: zero */

        *eax = 0;

        *ebx = 0;

        *ecx = 0;

        *edx = 0;


static void qxl_set_mode(PCIQXLDevice *d, int modenr, int loadvm)

{

    pcibus_t start = d->pci.io_regions[QXL_RAM_RANGE_INDEX].addr;

    pcibus_t end   = d->pci.io_regions[QXL_RAM_RANGE_INDEX].size + start;

    QXLMode *mode = d->modes->modes + modenr;

    uint64_t devmem = d->pci.io_regions[QXL_RAM_RANGE_INDEX].addr;

    QXLMemSlot slot = {

        .mem_start = start,

        .mem_end = end

    };

    QXLSurfaceCreate surface = {

        .width      = mode->x_res,

        .height     = mode->y_res,

        .stride     = -mode->x_res * 4,

        .format     = SPICE_SURFACE_FMT_32_xRGB,

        .flags      = loadvm ? QXL_SURF_FLAG_KEEP_DATA : 0,

        .mouse_mode = true,

        .mem        = devmem + d->shadow_rom.draw_area_offset,

    };

    trace_qxl_set_mode(d->id, modenr, mode->x_res, mode->y_res, mode->bits,

                       devmem);

    if (!loadvm) {

        qxl_hard_reset(d, 0);

    }

    d->guest_slots[0].slot = slot;

    qxl_add_memslot(d, 0, devmem, QXL_SYNC);

    d->guest_primary.surface = surface;

    qxl_create_guest_primary(d, 0, QXL_SYNC);

    d->mode = QXL_MODE_COMPAT;

    d->cmdflags = QXL_COMMAND_FLAG_COMPAT;

#ifdef QXL_COMMAND_FLAG_COMPAT_16BPP /* new in spice 0.6.1 */

    if (mode->bits == 16) {

        d->cmdflags |= QXL_COMMAND_FLAG_COMPAT_16BPP;

    }

#endif

    d->shadow_rom.mode = cpu_to_le32(modenr);

    d->rom->mode = cpu_to_le32(modenr);

    qxl_rom_set_dirty(d);

}


static int aac_parse_packet(AVFormatContext *ctx, PayloadContext *data,

                            AVStream *st, AVPacket *pkt, uint32_t *timestamp,

                            const uint8_t *buf, int len, uint16_t seq,

                            int flags)

{

    int ret;

    if (rtp_parse_mp4_au(data, buf))

        return -1;

    buf += data->au_headers_length_bytes + 2;

    len -= data->au_headers_length_bytes + 2;

    /* XXX: Fixme we only handle the case where rtp_parse_mp4_au define

                    one au_header */

    if ((ret = av_new_packet(pkt, data->au_headers[0].size)) < 0)

        return ret;

    memcpy(pkt->data, buf, data->au_headers[0].size);

    pkt->stream_index = st->index;

    return 0;

}


static int decode_header(SnowContext *s){

    int plane_index, tmp;

    uint8_t kstate[32];

    memset(kstate, MID_STATE, sizeof(kstate));

    s->keyframe= get_rac(&s->c, kstate);

    if(s->keyframe || s->always_reset){

        ff_snow_reset_contexts(s);

        s->spatial_decomposition_type=

        s->qlog=

        s->qbias=

        s->mv_scale=

        s->block_max_depth= 0;

    }

    if(s->keyframe){

        GET_S(s->version, tmp <= 0U)

        s->always_reset= get_rac(&s->c, s->header_state);

        s->temporal_decomposition_type= get_symbol(&s->c, s->header_state, 0);

        s->temporal_decomposition_count= get_symbol(&s->c, s->header_state, 0);

        GET_S(s->spatial_decomposition_count, 0 < tmp && tmp <= MAX_DECOMPOSITIONS)

        s->colorspace_type= get_symbol(&s->c, s->header_state, 0);

        if (s->colorspace_type == 1) {

            s->avctx->pix_fmt= AV_PIX_FMT_GRAY8;

            s->nb_planes = 1;

        } else if(s->colorspace_type == 0) {

            s->chroma_h_shift= get_symbol(&s->c, s->header_state, 0);

            s->chroma_v_shift= get_symbol(&s->c, s->header_state, 0);

            if(s->chroma_h_shift == 1 && s->chroma_v_shift==1){

                s->avctx->pix_fmt= AV_PIX_FMT_YUV420P;

            }else if(s->chroma_h_shift == 0 && s->chroma_v_shift==0){

                s->avctx->pix_fmt= AV_PIX_FMT_YUV444P;

            }else if(s->chroma_h_shift == 2 && s->chroma_v_shift==2){

                s->avctx->pix_fmt= AV_PIX_FMT_YUV410P;

            } else {

                av_log(s, AV_LOG_ERROR, "unsupported color subsample mode %d %d\n", s->chroma_h_shift, s->chroma_v_shift);

                s->chroma_h_shift = s->chroma_v_shift = 1;

                s->avctx->pix_fmt= AV_PIX_FMT_YUV420P;

                return AVERROR_INVALIDDATA;

            }

            s->nb_planes = 3;

        } else {

            av_log(s, AV_LOG_ERROR, "unsupported color space\n");

            s->chroma_h_shift = s->chroma_v_shift = 1;

            s->avctx->pix_fmt= AV_PIX_FMT_YUV420P;

            return AVERROR_INVALIDDATA;

        }

        s->spatial_scalability= get_rac(&s->c, s->header_state);

//        s->rate_scalability= get_rac(&s->c, s->header_state);

        GET_S(s->max_ref_frames, tmp < (unsigned)MAX_REF_FRAMES)

        s->max_ref_frames++;

        decode_qlogs(s);

    }

    if(!s->keyframe){

        if(get_rac(&s->c, s->header_state)){

            for(plane_index=0; plane_index<FFMIN(s->nb_planes, 2); plane_index++){

                int htaps, i, sum=0;

                Plane *p= &s->plane[plane_index];

                p->diag_mc= get_rac(&s->c, s->header_state);

                htaps= get_symbol(&s->c, s->header_state, 0)*2 + 2;

                if((unsigned)htaps >= HTAPS_MAX || htaps==0)

                    return AVERROR_INVALIDDATA;

                p->htaps= htaps;

                for(i= htaps/2; i; i--){

                    p->hcoeff[i]= get_symbol(&s->c, s->header_state, 0) * (1-2*(i&1));

                    sum += p->hcoeff[i];

                }

                p->hcoeff[0]= 32-sum;

            }

            s->plane[2].diag_mc= s->plane[1].diag_mc;

            s->plane[2].htaps  = s->plane[1].htaps;

            memcpy(s->plane[2].hcoeff, s->plane[1].hcoeff, sizeof(s->plane[1].hcoeff));

        }

        if(get_rac(&s->c, s->header_state)){

            GET_S(s->spatial_decomposition_count, 0 < tmp && tmp <= MAX_DECOMPOSITIONS)

            decode_qlogs(s);

        }

    }

    s->spatial_decomposition_type+= get_symbol(&s->c, s->header_state, 1);

    if(s->spatial_decomposition_type > 1U){

        av_log(s->avctx, AV_LOG_ERROR, "spatial_decomposition_type %d not supported\n", s->spatial_decomposition_type);

        return AVERROR_INVALIDDATA;

    }

    if(FFMIN(s->avctx-> width>>s->chroma_h_shift,

             s->avctx->height>>s->chroma_v_shift) >> (s->spatial_decomposition_count-1) <= 1){

        av_log(s->avctx, AV_LOG_ERROR, "spatial_decomposition_count %d too large for size\n", s->spatial_decomposition_count);

        return AVERROR_INVALIDDATA;

    }

    if (s->avctx->width > 65536-4) {

        av_log(s->avctx, AV_LOG_ERROR, "Width %d is too large\n", s->avctx->width);

        return AVERROR_INVALIDDATA;

    }

    s->qlog           += get_symbol(&s->c, s->header_state, 1);

    s->mv_scale       += get_symbol(&s->c, s->header_state, 1);

    s->qbias          += get_symbol(&s->c, s->header_state, 1);

    s->block_max_depth+= get_symbol(&s->c, s->header_state, 1);

    if(s->block_max_depth > 1 || s->block_max_depth < 0 || s->mv_scale > 256U){

        av_log(s->avctx, AV_LOG_ERROR, "block_max_depth= %d is too large\n", s->block_max_depth);

        s->block_max_depth= 0;

        s->mv_scale = 0;

        return AVERROR_INVALIDDATA;

    }

    if (FFABS(s->qbias) > 127) {

        av_log(s->avctx, AV_LOG_ERROR, "qbias %d is too large\n", s->qbias);

        s->qbias = 0;

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


void alpha_translate_init(void)

{

#define DEF_VAR(V)  { &cpu_##V, #V, offsetof(CPUAlphaState, V) }

    typedef struct { TCGv *var; const char *name; int ofs; } GlobalVar;

    static const GlobalVar vars[] = {

        DEF_VAR(pc),

        DEF_VAR(lock_addr),

        DEF_VAR(lock_st_addr),

        DEF_VAR(lock_value),

        DEF_VAR(unique),

#ifndef CONFIG_USER_ONLY

        DEF_VAR(sysval),

        DEF_VAR(usp),

#endif

    };

#undef DEF_VAR

    /* Use the symbolic register names that match the disassembler.  */

    static const char greg_names[31][4] = {

        "v0", "t0", "t1", "t2", "t3", "t4", "t5", "t6",

        "t7", "s0", "s1", "s2", "s3", "s4", "s5", "fp",

        "a0", "a1", "a2", "a3", "a4", "a5", "t8", "t9",

        "t10", "t11", "ra", "t12", "at", "gp", "sp"

    };

    static const char freg_names[31][4] = {

        "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",

        "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",

        "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",

        "f24", "f25", "f26", "f27", "f28", "f29", "f30"

    };

    static bool done_init = 0;

    int i;

    if (done_init) {

        return;

    }

    done_init = 1;

    cpu_env = tcg_global_reg_new_ptr(TCG_AREG0, "env");

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

        cpu_ir[i] = tcg_global_mem_new_i64(TCG_AREG0,

                                           offsetof(CPUAlphaState, ir[i]),

                                           greg_names[i]);

    }

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

        cpu_fir[i] = tcg_global_mem_new_i64(TCG_AREG0,

                                            offsetof(CPUAlphaState, fir[i]),

                                            freg_names[i]);

    }

    for (i = 0; i < ARRAY_SIZE(vars); ++i) {

        const GlobalVar *v = &vars[i];

        *v->var = tcg_global_mem_new_i64(TCG_AREG0, v->ofs, v->name);

    }

}


static void RENAME(mix6to2)(SAMPLE **out, const SAMPLE **in, COEFF *coeffp, integer len){

    int i;

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

        INTER t = in[2][i]*coeffp[0*6+2] + in[3][i]*coeffp[0*6+3];

        out[0][i] = R(t + in[0][i]*(INTER)coeffp[0*6+0] + in[4][i]*(INTER)coeffp[0*6+4]);

        out[1][i] = R(t + in[1][i]*(INTER)coeffp[1*6+1] + in[5][i]*(INTER)coeffp[1*6+5]);

    }

}


static QPCIDevice *get_device(void)

{

    QPCIDevice *dev;

    QPCIBus *pcibus;

    pcibus = qpci_init_pc();

    dev = NULL;

    qpci_device_foreach(pcibus, 0x1af4, 0x1110, save_fn, &dev);

    g_assert(dev != NULL);

    return dev;

}


void do_nego (void)

{

    if (likely(T0 != INT32_MIN)) {

        xer_ov = 0;

        T0 = -Ts0;

    } else {

        xer_ov = 1;

        xer_so = 1;

    }

}


static int nbd_co_writev_1(NbdClientSession *client, int64_t sector_num,

                           int nb_sectors, QEMUIOVector *qiov,

                           int offset)

{

    struct nbd_request request;

    struct nbd_reply reply;

    ssize_t ret;

    request.type = NBD_CMD_WRITE;

    if (!bdrv_enable_write_cache(client->bs) &&

        (client->nbdflags & NBD_FLAG_SEND_FUA)) {

        request.type |= NBD_CMD_FLAG_FUA;

    }

    request.from = sector_num * 512;

    request.len = nb_sectors * 512;

    nbd_coroutine_start(client, &request);

    ret = nbd_co_send_request(client, &request, qiov, offset);

    if (ret < 0) {

        reply.error = -ret;

    } else {

        nbd_co_receive_reply(client, &request, &reply, NULL, 0);

    }

    nbd_coroutine_end(client, &request);

    return -reply.error;

}


void qemu_input_event_send_key(QemuConsole *src, KeyValue *key, bool down)

{

    InputEvent *evt;

    evt = qemu_input_event_new_key(key, down);

    if (QTAILQ_EMPTY(&kbd_queue)) {

        qemu_input_event_send(src, evt);

        qemu_input_event_sync();

        qapi_free_InputEvent(evt);

    } else {

        qemu_input_queue_event(&kbd_queue, src, evt);

        qemu_input_queue_sync(&kbd_queue);

    }

}


int av_strerror(int errnum, char *errbuf, size_t errbuf_size)

{

    int ret = 0, i;

    struct error_entry *entry = NULL;

    for (i = 0; i < FF_ARRAY_ELEMS(error_entries); i++) {

        if (errnum == error_entries[i].num) {

            entry = &error_entries[i];

            break;

        }

    }

    if (entry) {

        av_strlcpy(errbuf, entry->str, errbuf_size);

    } else {

#if HAVE_STRERROR_R

        ret = strerror_r(AVUNERROR(errnum), errbuf, errbuf_size);

#else

        ret = -1;

#endif

        if (ret < 0)

            snprintf(errbuf, errbuf_size, "Error number %d occurred", errnum);

    }

    return ret;

}


int blk_insert_bs(BlockBackend *blk, BlockDriverState *bs, Error **errp)

{

    blk->root = bdrv_root_attach_child(bs, "root", &child_root,

                                       blk->perm, blk->shared_perm, blk, errp);

    if (blk->root == NULL) {

        return -EPERM;

    }

    bdrv_ref(bs);

    notifier_list_notify(&blk->insert_bs_notifiers, blk);

    if (blk->public.throttle_group_member.throttle_state) {

        throttle_timers_attach_aio_context(

            &blk->public.throttle_group_member.throttle_timers,

            bdrv_get_aio_context(bs));

    }

    return 0;

}


void rgb15tobgr24(const uint8_t *src, uint8_t *dst, long src_size)

{

	const uint16_t *end;

	uint8_t *d = (uint8_t *)dst;

	const uint16_t *s = (uint16_t *)src;

	end = s + src_size/2;

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

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

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

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

	}

}


int ff_xvmc_field_start(MpegEncContext *s, AVCodecContext *avctx)

{

    struct xvmc_pix_fmt *last, *next, *render = (struct xvmc_pix_fmt*)s->current_picture.f.data[2];

    const int mb_block_count = 4 + (1 << s->chroma_format);

    assert(avctx);

    if (!render || render->xvmc_id != AV_XVMC_ID ||

        !render->data_blocks || !render->mv_blocks ||

        (unsigned int)render->allocated_mv_blocks   > INT_MAX/(64*6) ||

        (unsigned int)render->allocated_data_blocks > INT_MAX/64     ||

        !render->p_surface) {

        av_log(avctx, AV_LOG_ERROR,

               "Render token doesn't look as expected.\n");

        return -1; // make sure that this is a render packet

    }

    if (render->filled_mv_blocks_num) {

        av_log(avctx, AV_LOG_ERROR,

               "Rendering surface contains %i unprocessed blocks.\n",

               render->filled_mv_blocks_num);

        return -1;

    }

    if (render->allocated_mv_blocks   < 1 ||

        render->allocated_data_blocks <  render->allocated_mv_blocks*mb_block_count ||

        render->start_mv_blocks_num   >= render->allocated_mv_blocks                ||

        render->next_free_data_block_num >

                        render->allocated_data_blocks -

                        mb_block_count*(render->allocated_mv_blocks-render->start_mv_blocks_num)) {

        av_log(avctx, AV_LOG_ERROR,

               "Rendering surface doesn't provide enough block structures to work with.\n");

        return -1;

    }

    render->picture_structure = s->picture_structure;

    render->flags             = s->first_field ? 0 : XVMC_SECOND_FIELD;

    render->p_future_surface  = NULL;

    render->p_past_surface    = NULL;

    switch(s->pict_type) {

        case  AV_PICTURE_TYPE_I:

            return 0; // no prediction from other frames

        case  AV_PICTURE_TYPE_B:

            next = (struct xvmc_pix_fmt*)s->next_picture.f.data[2];

            if (!next)

                return -1;

            if (next->xvmc_id != AV_XVMC_ID)

                return -1;

            render->p_future_surface = next->p_surface;

            // no return here, going to set forward prediction

        case  AV_PICTURE_TYPE_P:

            last = (struct xvmc_pix_fmt*)s->last_picture.f.data[2];

            if (!last)

                last = render; // predict second field from the first

            if (last->xvmc_id != AV_XVMC_ID)

                return -1;

            render->p_past_surface = last->p_surface;

            return 0;

    }

return -1;

}


static int handle_dependencies(BlockDriverState *bs, uint64_t guest_offset,

    uint64_t *cur_bytes)

{

    BDRVQcowState *s = bs->opaque;

    QCowL2Meta *old_alloc;

    uint64_t bytes = *cur_bytes;

    QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {

        uint64_t start = guest_offset;

        uint64_t end = start + bytes;

        uint64_t old_start = l2meta_cow_start(old_alloc);

        uint64_t old_end = l2meta_cow_end(old_alloc);

        if (end <= old_start || start >= old_end) {

            /* No intersection */

        } else {

            if (start < old_start) {

                /* Stop at the start of a running allocation */

                bytes = old_start - start;

            } else {

                bytes = 0;

            }

            if (bytes == 0) {

                /* Wait for the dependency to complete. We need to recheck

                 * the free/allocated clusters when we continue. */

                qemu_co_mutex_unlock(&s->lock);

                qemu_co_queue_wait(&old_alloc->dependent_requests);

                qemu_co_mutex_lock(&s->lock);

                return -EAGAIN;

            }

        }

    }

    /* Make sure that existing clusters and new allocations are only used up to

     * the next dependency if we shortened the request above */

    *cur_bytes = bytes;

    return 0;

}


void scsi_req_data(SCSIRequest *req, int len)

{

    trace_scsi_req_data(req->dev->id, req->lun, req->tag, len);

    req->bus->ops->complete(req->bus, SCSI_REASON_DATA, req->tag, len);

}


static int compute_mask(int step, uint32_t *mask)

{

    int i, z, ret = 0;

    int counter_size = sizeof(uint32_t) * (2 * step + 1);

    uint32_t *temp1_counter, *temp2_counter, **counter;

    temp1_counter = av_mallocz(counter_size);

    if (!temp1_counter) {

        ret = AVERROR(ENOMEM);

        goto end;

    }

    temp2_counter = av_mallocz(counter_size);

    if (!temp2_counter) {

        ret = AVERROR(ENOMEM);

        goto end;

    }

    counter = av_mallocz_array(2 * step + 1, sizeof(uint32_t *));

    if (!counter) {

        ret = AVERROR(ENOMEM);

        goto end;

    }

    for (i = 0; i < 2 * step + 1; i++) {

        counter[i] = av_mallocz(counter_size);

        if (!counter[i]) {

            ret = AVERROR(ENOMEM);

            goto end;

        }

    }

    for (i = 0; i < 2 * step + 1; i++) {

        memset(temp1_counter, 0, counter_size);

        temp1_counter[i] = 1;

        for (z = 0; z < step * 2; z += 2) {

            add_mask_counter(temp2_counter, counter[z], temp1_counter, step * 2);

            memcpy(counter[z], temp1_counter, counter_size);

            add_mask_counter(temp1_counter, counter[z + 1], temp2_counter, step * 2);

            memcpy(counter[z + 1], temp2_counter, counter_size);

        }

    }

    memcpy(mask, temp1_counter, counter_size);

end:

    av_freep(&temp1_counter);

    av_freep(&temp2_counter);

    for (i = 0; i < 2 * step + 1; i++) {

        av_freep(&counter[i]);

    }

    av_freep(&counter);

    return ret;

}


static int encode_end(AVCodecContext *avctx)

{

    FFV1Context *s = avctx->priv_data;

    common_end(s);

    return 0;

}


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

{

    ISADevice *isadev = ISA_DEVICE(dev);

    ISAVGAState *d = ISA_VGA(dev);

    VGACommonState *s = &d->state;

    MemoryRegion *vga_io_memory;

    const MemoryRegionPortio *vga_ports, *vbe_ports;

    vga_common_init(s, OBJECT(dev), true);

    s->legacy_address_space = isa_address_space(isadev);

    vga_io_memory = vga_init_io(s, OBJECT(dev), &vga_ports, &vbe_ports);

    isa_register_portio_list(isadev, 0x3b0, vga_ports, s, "vga");

    if (vbe_ports) {

        isa_register_portio_list(isadev, 0x1ce, vbe_ports, s, "vbe");

    }

    memory_region_add_subregion_overlap(isa_address_space(isadev),

                                        0x000a0000,

                                        vga_io_memory, 1);

    memory_region_set_coalescing(vga_io_memory);

    s->con = graphic_console_init(DEVICE(dev), 0, s->hw_ops, s);

    vga_init_vbe(s, OBJECT(dev), isa_address_space(isadev));

    /* ROM BIOS */

    rom_add_vga(VGABIOS_FILENAME);

}


static int read_matrix_params(MLPDecodeContext *m, unsigned int substr, GetBitContext *gbp)

{

    SubStream *s = &m->substream[substr];

    unsigned int mat, ch;

    const int max_primitive_matrices = m->avctx->codec_id == AV_CODEC_ID_MLP

                                     ? MAX_MATRICES_MLP

                                     : MAX_MATRICES_TRUEHD;

    if (m->matrix_changed++ > 1) {

        av_log(m->avctx, AV_LOG_ERROR, "Matrices may change only once per access unit.\n");

        return AVERROR_INVALIDDATA;

    }

    s->num_primitive_matrices = get_bits(gbp, 4);

    if (s->num_primitive_matrices > max_primitive_matrices) {

        av_log(m->avctx, AV_LOG_ERROR,

               "Number of primitive matrices cannot be greater than %d.\n",

               max_primitive_matrices);

        return AVERROR_INVALIDDATA;

    }

    for (mat = 0; mat < s->num_primitive_matrices; mat++) {

        int frac_bits, max_chan;

        s->matrix_out_ch[mat] = get_bits(gbp, 4);

        frac_bits             = get_bits(gbp, 4);

        s->lsb_bypass   [mat] = get_bits1(gbp);

        if (s->matrix_out_ch[mat] > s->max_matrix_channel) {

            av_log(m->avctx, AV_LOG_ERROR,

                    "Invalid channel %d specified as output from matrix.\n",

                    s->matrix_out_ch[mat]);

            return AVERROR_INVALIDDATA;

        }

        if (frac_bits > 14) {

            av_log(m->avctx, AV_LOG_ERROR,

                    "Too many fractional bits specified.\n");

            return AVERROR_INVALIDDATA;

        }

        max_chan = s->max_matrix_channel;

        if (!s->noise_type)

            max_chan+=2;

        for (ch = 0; ch <= max_chan; ch++) {

            int coeff_val = 0;

            if (get_bits1(gbp))

                coeff_val = get_sbits(gbp, frac_bits + 2);

            s->matrix_coeff[mat][ch] = coeff_val * (1 << (14 - frac_bits));

        }

        if (s->noise_type)

            s->matrix_noise_shift[mat] = get_bits(gbp, 4);

        else

            s->matrix_noise_shift[mat] = 0;

    }

    return 0;

}


int spapr_tce_dma_write(VIOsPAPRDevice *dev, uint64_t taddr, const void *buf,

                        uint32_t size)

{

#ifdef DEBUG_TCE

    fprintf(stderr, "spapr_tce_dma_write taddr=0x%llx size=0x%x\n",

            (unsigned long long)taddr, size);

#endif

    /* Check for bypass */

    if (dev->flags & VIO_PAPR_FLAG_DMA_BYPASS) {

        cpu_physical_memory_write(taddr, buf, size);

        return 0;

    }

    while (size) {

        uint64_t tce;

        uint32_t lsize;

        uint64_t txaddr;

        /* Check if we are in bound */

        if (taddr >= dev->rtce_window_size) {

#ifdef DEBUG_TCE

            fprintf(stderr, "spapr_tce_dma_write out of bounds\n");

#endif

            return H_DEST_PARM;

        }

        tce = dev->rtce_table[taddr >> SPAPR_VIO_TCE_PAGE_SHIFT].tce;

        /* How much til end of page ? */

        lsize = MIN(size, ((~taddr) & SPAPR_VIO_TCE_PAGE_MASK) + 1);

        /* Check TCE */

        if (!(tce & 2)) {

            return H_DEST_PARM;

        }

        /* Translate */

        txaddr = (tce & ~SPAPR_VIO_TCE_PAGE_MASK) |

            (taddr & SPAPR_VIO_TCE_PAGE_MASK);

#ifdef DEBUG_TCE

        fprintf(stderr, " -> write to txaddr=0x%llx, size=0x%x\n",

                (unsigned long long)txaddr, lsize);

#endif

        /* Do it */

        cpu_physical_memory_write(txaddr, buf, lsize);

        buf += lsize;

        taddr += lsize;

        size -= lsize;

    }

    return 0;

}


static void compare_refcounts(BlockDriverState *bs, BdrvCheckResult *res,

                              BdrvCheckMode fix, int64_t *highest_cluster,

                              uint16_t *refcount_table, int64_t nb_clusters)

{

    BDRVQcowState *s = bs->opaque;

    int64_t i;

    int refcount1, refcount2, ret;

    for (i = 0, *highest_cluster = 0; i < nb_clusters; i++) {

        refcount1 = get_refcount(bs, i);

        if (refcount1 < 0) {

            fprintf(stderr, "Can't get refcount for cluster %" PRId64 ": %s\n",

                i, strerror(-refcount1));

            res->check_errors++;

            continue;

        }

        refcount2 = refcount_table[i];

        if (refcount1 > 0 || refcount2 > 0) {

            *highest_cluster = i;

        }

        if (refcount1 != refcount2) {

            /* Check if we're allowed to fix the mismatch */

            int *num_fixed = NULL;

            if (refcount1 > refcount2 && (fix & BDRV_FIX_LEAKS)) {

                num_fixed = &res->leaks_fixed;

            } else if (refcount1 < refcount2 && (fix & BDRV_FIX_ERRORS)) {

                num_fixed = &res->corruptions_fixed;

            }

            fprintf(stderr, "%s cluster %" PRId64 " refcount=%d reference=%d\n",

                   num_fixed != NULL     ? "Repairing" :

                   refcount1 < refcount2 ? "ERROR" :

                                           "Leaked",

                   i, refcount1, refcount2);

            if (num_fixed) {

                ret = update_refcount(bs, i << s->cluster_bits, 1,

                                      refcount2 - refcount1,

                                      QCOW2_DISCARD_ALWAYS);

                if (ret >= 0) {

                    (*num_fixed)++;

                    continue;

                }

            }

            /* And if we couldn't, print an error */

            if (refcount1 < refcount2) {

                res->corruptions++;

            } else {

                res->leaks++;

            }

        }

    }

}


int kvmppc_get_hypercall(CPUPPCState *env, uint8_t *buf, int buf_len)

{

    uint32_t *hc = (uint32_t*)buf;

    struct kvm_ppc_pvinfo pvinfo;

    if (!kvmppc_get_pvinfo(env, &pvinfo)) {

        memcpy(buf, pvinfo.hcall, buf_len);

        return 0;

    }

    /*

     * Fallback to always fail hypercalls regardless of endianness:

     *

     *     tdi 0,r0,72 (becomes b .+8 in wrong endian, nop in good endian)

     *     li r3, -1

     *     b .+8       (becomes nop in wrong endian)

     *     bswap32(li r3, -1)

     */

    hc[0] = cpu_to_be32(0x08000048);

    hc[1] = cpu_to_be32(0x3860ffff);

    hc[2] = cpu_to_be32(0x48000008);

    hc[3] = cpu_to_be32(bswap32(0x3860ffff));

    return 0;

}


static void parse_presentation_segment(AVCodecContext *avctx,

                                       const uint8_t *buf, int buf_size)

{

    PGSSubContext *ctx = avctx->priv_data;

    int x, y;

    int w = bytestream_get_be16(&buf);

    int h = bytestream_get_be16(&buf);

    av_dlog(avctx, "Video Dimensions %dx%d\n",

            w, h);

    if (av_image_check_size(w, h, 0, avctx) >= 0)

        avcodec_set_dimensions(avctx, w, h);

    /* Skip 1 bytes of unknown, frame rate? */

    buf++;

    ctx->presentation.id_number = bytestream_get_be16(&buf);

    /*

     * Skip 3 bytes of unknown:

     *     state

     *     palette_update_flag (0x80),

     *     palette_id_to_use,

     */

    buf += 3;

    ctx->presentation.object_number = bytestream_get_byte(&buf);

    if (!ctx->presentation.object_number)

        return;

    /*

     * Skip 4 bytes of unknown:

     *     object_id_ref (2 bytes),

     *     window_id_ref,

     *     composition_flag (0x80 - object cropped, 0x40 - object forced)

     */

    buf += 4;

    x = bytestream_get_be16(&buf);

    y = bytestream_get_be16(&buf);

    /* TODO If cropping, cropping_x, cropping_y, cropping_width, cropping_height (all 2 bytes).*/

    av_dlog(avctx, "Subtitle Placement x=%d, y=%d\n", x, y);

    if (x > avctx->width || y > avctx->height) {

        av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",

               x, y, avctx->width, avctx->height);

        x = 0; y = 0;

    }

    /* Fill in dimensions */

    ctx->presentation.x = x;

    ctx->presentation.y = y;

}


void virtio_init(VirtIODevice *vdev, const char *name,

                 uint16_t device_id, size_t config_size)

{

    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    int i;

    int nvectors = k->query_nvectors ? k->query_nvectors(qbus->parent) : 0;

    if (nvectors) {

        vdev->vector_queues =

            g_malloc0(sizeof(*vdev->vector_queues) * nvectors);

    }

    vdev->device_id = device_id;

    vdev->status = 0;

    vdev->isr = 0;

    vdev->queue_sel = 0;

    vdev->config_vector = VIRTIO_NO_VECTOR;

    vdev->vq = g_malloc0(sizeof(VirtQueue) * VIRTIO_QUEUE_MAX);

    vdev->vm_running = runstate_is_running();

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

        vdev->vq[i].vector = VIRTIO_NO_VECTOR;

        vdev->vq[i].vdev = vdev;

        vdev->vq[i].queue_index = i;

    }

    vdev->name = name;

    vdev->config_len = config_size;

    if (vdev->config_len) {

        vdev->config = g_malloc0(config_size);

    } else {

        vdev->config = NULL;

    }

    vdev->vmstate = qemu_add_vm_change_state_handler(virtio_vmstate_change,

                                                     vdev);

    vdev->device_endian = virtio_default_endian();

    vdev->use_guest_notifier_mask = true;

}


static int mon_init_func(QemuOpts *opts, void *opaque)

{

    CharDriverState *chr;

    const char *chardev;

    const char *mode;

    int flags;

    mode = qemu_opt_get(opts, "mode");

    if (mode == NULL) {

        mode = "readline";

    }

    if (strcmp(mode, "readline") == 0) {

        flags = MONITOR_USE_READLINE;

    } else if (strcmp(mode, "control") == 0) {

        flags = MONITOR_USE_CONTROL;

    } else {

        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);

        exit(1);

    }

    if (qemu_opt_get_bool(opts, "pretty", 0))

        flags |= MONITOR_USE_PRETTY;

    if (qemu_opt_get_bool(opts, "default", 0))

        flags |= MONITOR_IS_DEFAULT;

    chardev = qemu_opt_get(opts, "chardev");

    chr = qemu_chr_find(chardev);

    if (chr == NULL) {

        fprintf(stderr, "chardev \"%s\" not found\n", chardev);

        exit(1);

    }

    monitor_init(chr, flags);

    return 0;

}


void ga_unset_frozen(GAState *s)

{

    if (!ga_is_frozen(s)) {

        return;

    }

    /* if we delayed creation/opening of pid/log files due to being

     * in a frozen state at start up, do it now

     */

    if (s->deferred_options.log_filepath) {

        s->log_file = fopen(s->deferred_options.log_filepath, "a");

        if (!s->log_file) {

            s->log_file = stderr;

        }

        s->deferred_options.log_filepath = NULL;

    }

    ga_enable_logging(s);

    g_warning("logging re-enabled due to filesystem unfreeze");

    if (s->deferred_options.pid_filepath) {

        if (!ga_open_pidfile(s->deferred_options.pid_filepath)) {

            g_warning("failed to create/open pid file");

        }

        s->deferred_options.pid_filepath = NULL;

    }

    /* enable all disabled, non-blacklisted commands */

    ga_enable_non_blacklisted(s->blacklist);

    s->frozen = false;

    if (!ga_delete_file(s->state_filepath_isfrozen)) {

        g_warning("unable to delete %s, fsfreeze may not function properly",

                  s->state_filepath_isfrozen);

    }

}


static int local_remove(FsContext *ctx, const char *path)

{

    int err;

    struct stat stbuf;

    char *buffer;

    if (ctx->export_flags & V9FS_SM_MAPPED_FILE) {

        buffer = rpath(ctx, path);

        err =  lstat(buffer, &stbuf);

        g_free(buffer);

        if (err) {

            goto err_out;

        }

        /*

         * If directory remove .virtfs_metadata contained in the

         * directory

         */

        if (S_ISDIR(stbuf.st_mode)) {

            buffer = g_strdup_printf("%s/%s/%s", ctx->fs_root,

                                     path, VIRTFS_META_DIR);

            err = remove(buffer);

            g_free(buffer);

            if (err < 0 && errno != ENOENT) {

                /*

                 * We didn't had the .virtfs_metadata file. May be file created

                 * in non-mapped mode ?. Ignore ENOENT.

                 */

                goto err_out;

            }

        }

        /*

         * Now remove the name from parent directory

         * .virtfs_metadata directory

         */

        buffer = local_mapped_attr_path(ctx, path);

        err = remove(buffer);

        g_free(buffer);

        if (err < 0 && errno != ENOENT) {

            /*

             * We didn't had the .virtfs_metadata file. May be file created

             * in non-mapped mode ?. Ignore ENOENT.

             */

            goto err_out;

        }

    }

    buffer = rpath(ctx, path);

    err = remove(buffer);

    g_free(buffer);

err_out:

    return err;

}


static int t37(InterplayACMContext *s, unsigned ind, unsigned col)

{

    GetBitContext *gb = &s->gb;

    unsigned i, b;

    int n1, n2;

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

        /* b = (x1) + (x2 * 11) */

        b = get_bits(gb, 7);

        n1 =  (mul_2x11[b] & 0x0F) - 5;

        n2 = ((mul_2x11[b] >> 4) & 0x0F) - 5;

        set_pos(s, i++, col, n1);

        if (i >= s->rows)

            break;

        set_pos(s, i, col, n2);

    return 0;


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

{

  uint8_t *dest = dst;

  const uint8_t *s = src;

  const uint8_t *end;

#ifdef HAVE_MMX

  const uint8_t *mm_end;

#endif

  end = s + src_size;

#ifdef HAVE_MMX

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

  mm_end = end - 23;

  __asm __volatile("movq	%0, %%mm7"::"m"(mask32):"memory");

  while(s < mm_end)

  {

    __asm __volatile(

	PREFETCH"	32%1\n\t"

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

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

	"movd	6%1, %%mm1\n\t"

	"punpckldq 9%1, %%mm1\n\t"

	"movd	12%1, %%mm2\n\t"

	"punpckldq 15%1, %%mm2\n\t"

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

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

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

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

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

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

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

	MOVNTQ"	%%mm1, 8%0\n\t"

	MOVNTQ"	%%mm2, 16%0\n\t"

	MOVNTQ"	%%mm3, 24%0"

	:"=m"(*dest)

	:"m"(*s)

	:"memory");

    dest += 32;

    s += 24;

  }

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

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

#endif

  while(s < end)

  {

#ifdef WORDS_BIGENDIAN

    /* RGB24 (= R,G,B) -> RGB32 (= A,B,G,R) */

    *dest++ = 0;

    *dest++ = s[2];

    *dest++ = s[1];

    *dest++ = s[0];

    s+=3;

#else

    *dest++ = *s++;

    *dest++ = *s++;

    *dest++ = *s++;

    *dest++ = 0;

#endif

  }

}


void do_subfmeo (void)

{

    T1 = T0;

    T0 = ~T0 + xer_ca - 1;

    if (likely(!((uint32_t)~T1 & ((uint32_t)~T1 ^ (uint32_t)T0) &

                 (1UL << 31)))) {

        xer_ov = 0;

    } else {

        xer_so = 1;

        xer_ov = 1;

    }

    if (likely((uint32_t)T1 != UINT32_MAX))

        xer_ca = 1;

}


static void spapr_memory_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,

                                  Error **errp)

{

    PCDIMMDevice *dimm = PC_DIMM(dev);

    PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm);

    MemoryRegion *mr = ddc->get_memory_region(dimm);

    uint64_t size = memory_region_size(mr);

    char *mem_dev;

    if (size % SPAPR_MEMORY_BLOCK_SIZE) {

        error_setg(errp, "Hotplugged memory size must be a multiple of "

                      "%lld MB", SPAPR_MEMORY_BLOCK_SIZE / M_BYTE);

        return;

    }

    mem_dev = object_property_get_str(OBJECT(dimm), PC_DIMM_MEMDEV_PROP, NULL);

    if (mem_dev && !kvmppc_is_mem_backend_page_size_ok(mem_dev)) {

        error_setg(errp, "Memory backend has bad page size. "

                   "Use 'memory-backend-file' with correct mem-path.");

        return;

    }

}


static inline void RENAME(rgb24toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,

                                       long width, long height,

                                       long lumStride, long chromStride, long srcStride)

{

    long y;

    const x86_reg chromWidth= width>>1;

#if COMPILE_TEMPLATE_MMX

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

        long i;

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

            __asm__ volatile(

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

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

                "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"

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

                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"   \n\t"

                ".p2align                    4              \n\t"

                "1:                                         \n\t"

                PREFETCH"    64(%0, %%"REG_d")              \n\t"

                "movd          (%0, %%"REG_d"), %%mm0       \n\t"

                "movd         3(%0, %%"REG_d"), %%mm1       \n\t"

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

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

                "movd         6(%0, %%"REG_d"), %%mm2       \n\t"

                "movd         9(%0, %%"REG_d"), %%mm3       \n\t"

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

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

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

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

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

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

#ifndef FAST_BGR2YV12

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

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

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

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

#endif

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

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

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

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

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

                "psraw                      $7, %%mm0       \n\t"

                "movd        12(%0, %%"REG_d"), %%mm4       \n\t"

                "movd        15(%0, %%"REG_d"), %%mm1       \n\t"

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

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

                "movd        18(%0, %%"REG_d"), %%mm2       \n\t"

                "movd        21(%0, %%"REG_d"), %%mm3       \n\t"

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

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

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

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

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

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

#ifndef FAST_BGR2YV12

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

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

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

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

#endif

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

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

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

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

                "add                       $24, %%"REG_d"   \n\t"

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

                "psraw                      $7, %%mm4       \n\t"

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

                "paddusb "MANGLE(ff_bgr2YOffset)", %%mm0    \n\t"

                MOVNTQ"                  %%mm0, (%1, %%"REG_a") \n\t"

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

                " js                        1b                  \n\t"

                : : "r" (src+width*3), "r" (ydst+width), "g" ((x86_reg)-width)

                : "%"REG_a, "%"REG_d

            );

            ydst += lumStride;

            src  += srcStride;

        }

        src -= srcStride*2;

        __asm__ volatile(

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

            "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"

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

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

            "lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"   \n\t"

            "add                 %%"REG_d", %%"REG_d"   \n\t"

            ".p2align                    4              \n\t"

            "1:                                         \n\t"

            PREFETCH"    64(%0, %%"REG_d")              \n\t"

            PREFETCH"    64(%1, %%"REG_d")              \n\t"

#if COMPILE_TEMPLATE_MMX2 || COMPILE_TEMPLATE_AMD3DNOW

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

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

            "movq         6(%0, %%"REG_d"), %%mm2       \n\t"

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

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

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

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

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

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

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

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

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

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

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

#else

            "movd          (%0, %%"REG_d"), %%mm0       \n\t"

            "movd          (%1, %%"REG_d"), %%mm1       \n\t"

            "movd         3(%0, %%"REG_d"), %%mm2       \n\t"

            "movd         3(%1, %%"REG_d"), %%mm3       \n\t"

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

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

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

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

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

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

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

            "movd         6(%0, %%"REG_d"), %%mm4       \n\t"

            "movd         6(%1, %%"REG_d"), %%mm1       \n\t"

            "movd         9(%0, %%"REG_d"), %%mm2       \n\t"

            "movd         9(%1, %%"REG_d"), %%mm3       \n\t"

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

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

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

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

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

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

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

            "psrlw                      $2, %%mm0       \n\t"

            "psrlw                      $2, %%mm2       \n\t"

#endif

            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm1       \n\t"

            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm3       \n\t"

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

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

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

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

#ifndef FAST_BGR2YV12

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

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

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

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

#endif

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

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

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

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

            "packssdw                %%mm1, %%mm0       \n\t" // V1 V0 U1 U0

            "psraw                      $7, %%mm0       \n\t"

#if COMPILE_TEMPLATE_MMX2 || COMPILE_TEMPLATE_AMD3DNOW

            "movq        12(%0, %%"REG_d"), %%mm4       \n\t"

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

            "movq        18(%0, %%"REG_d"), %%mm2       \n\t"

            "movq        18(%1, %%"REG_d"), %%mm3       \n\t"

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

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

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

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

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

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

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

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

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

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

#else

            "movd        12(%0, %%"REG_d"), %%mm4       \n\t"

            "movd        12(%1, %%"REG_d"), %%mm1       \n\t"

            "movd        15(%0, %%"REG_d"), %%mm2       \n\t"

            "movd        15(%1, %%"REG_d"), %%mm3       \n\t"

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

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

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

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

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

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

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

            "movd        18(%0, %%"REG_d"), %%mm5       \n\t"

            "movd        18(%1, %%"REG_d"), %%mm1       \n\t"

            "movd        21(%0, %%"REG_d"), %%mm2       \n\t"

            "movd        21(%1, %%"REG_d"), %%mm3       \n\t"

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

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

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

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

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

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

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

            "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"

            "psrlw                      $2, %%mm4       \n\t"

            "psrlw                      $2, %%mm2       \n\t"

#endif

            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm1       \n\t"

            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm3       \n\t"

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

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

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

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

#ifndef FAST_BGR2YV12

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

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

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

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

#endif

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

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

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

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

            "add                       $24, %%"REG_d"   \n\t"

            "packssdw                %%mm1, %%mm4       \n\t" // V3 V2 U3 U2

            "psraw                      $7, %%mm4       \n\t"

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

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

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

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

            "paddb "MANGLE(ff_bgr2UVOffset)", %%mm0         \n\t"

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

            "punpckhdq               %%mm0, %%mm0           \n\t"

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

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

            " js                        1b                  \n\t"

            : : "r" (src+chromWidth*6), "r" (src+srcStride+chromWidth*6), "r" (udst+chromWidth), "r" (vdst+chromWidth), "g" (-chromWidth)

            : "%"REG_a, "%"REG_d

        );

        udst += chromStride;

        vdst += chromStride;

        src  += srcStride*2;

    }

    __asm__ volatile(EMMS"       \n\t"

                     SFENCE"     \n\t"

                     :::"memory");

#else

    y=0;

#endif

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

        long i;

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

            unsigned int b = src[6*i+0];

            unsigned int g = src[6*i+1];

            unsigned int r = src[6*i+2];

            unsigned int Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;

            unsigned int V  =  ((RV*r + GV*g + BV*b)>>RGB2YUV_SHIFT) + 128;

            unsigned int U  =  ((RU*r + GU*g + BU*b)>>RGB2YUV_SHIFT) + 128;

            udst[i]     = U;

            vdst[i]     = V;

            ydst[2*i]   = Y;

            b = src[6*i+3];

            g = src[6*i+4];

            r = src[6*i+5];

            Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;

            ydst[2*i+1]     = Y;

        }

        ydst += lumStride;

        src  += srcStride;

        if(y+1 == height)

            break;

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

            unsigned int b = src[6*i+0];

            unsigned int g = src[6*i+1];

            unsigned int r = src[6*i+2];

            unsigned int Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;

            ydst[2*i]     = Y;

            b = src[6*i+3];

            g = src[6*i+4];

            r = src[6*i+5];

            Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;

            ydst[2*i+1]     = Y;

        }

        udst += chromStride;

        vdst += chromStride;

        ydst += lumStride;

        src  += srcStride;

    }

}