DECL_IMDCT_BLOCKS(sse,sse)

#endif

DECL_IMDCT_BLOCKS(sse2,sse)

DECL_IMDCT_BLOCKS(sse3,sse)

DECL_IMDCT_BLOCKS(ssse3,sse)

#endif

#if HAVE_AVX_EXTERNAL

DECL_IMDCT_BLOCKS(avx,avx)

#endif

#endif /* HAVE_YASM */

av_cold void ff_mpadsp_init_x86(MPADSPContext *s)

{

    int cpu_flags = av_get_cpu_flags();

    int i, j;

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

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

            mdct_win_sse[0][j][4*i    ] = ff_mdct_win_float[j    ][i];

            mdct_win_sse[0][j][4*i + 1] = ff_mdct_win_float[j + 4][i];

            mdct_win_sse[0][j][4*i + 2] = ff_mdct_win_float[j    ][i];

            mdct_win_sse[0][j][4*i + 3] = ff_mdct_win_float[j + 4][i];

            mdct_win_sse[1][j][4*i    ] = ff_mdct_win_float[0    ][i];

            mdct_win_sse[1][j][4*i + 1] = ff_mdct_win_float[4    ][i];

            mdct_win_sse[1][j][4*i + 2] = ff_mdct_win_float[j    ][i];

            mdct_win_sse[1][j][4*i + 3] = ff_mdct_win_float[j + 4][i];

        }

    }

#if HAVE_6REGS && HAVE_SSE_INLINE

    if (INLINE_SSE(cpu_flags)) {

        s->apply_window_float = apply_window_mp3;

    }

#endif /* HAVE_SSE_INLINE */

#if HAVE_YASM

#if HAVE_SSE

#if ARCH_X86_32

    if (EXTERNAL_SSE(cpu_flags)) {

        s->imdct36_blocks_float = imdct36_blocks_sse;

    }

#endif

    if (EXTERNAL_SSE2(cpu_flags)) {

        s->imdct36_blocks_float = imdct36_blocks_sse2;

    }

    if (EXTERNAL_SSE3(cpu_flags)) {

        s->imdct36_blocks_float = imdct36_blocks_sse3;

    }

    if (EXTERNAL_SSSE3(cpu_flags)) {

        s->imdct36_blocks_float = imdct36_blocks_ssse3;

    }

#endif

#if HAVE_AVX_EXTERNAL

    if (EXTERNAL_AVX(cpu_flags)) {

        s->imdct36_blocks_float = imdct36_blocks_avx;

    }

#endif

#endif /* HAVE_YASM */

}


static void dirac_unpack_block_motion_data(DiracContext *s)

{

    GetBitContext *gb = &s->gb;

    uint8_t *sbsplit = s->sbsplit;

    int i, x, y, q, p;

    DiracArith arith[8];

    align_get_bits(gb);

    /* [DIRAC_STD] 11.2.4 and 12.2.1 Number of blocks and superblocks */

    s->sbwidth  = DIVRNDUP(s->source.width,  4*s->plane[0].xbsep);

    s->sbheight = DIVRNDUP(s->source.height, 4*s->plane[0].ybsep);

    s->blwidth  = 4 * s->sbwidth;

    s->blheight = 4 * s->sbheight;

    /* [DIRAC_STD] 12.3.1 Superblock splitting modes. superblock_split_modes()

       decode superblock split modes */

    ff_dirac_init_arith_decoder(arith, gb, svq3_get_ue_golomb(gb));     /* svq3_get_ue_golomb(gb) is the length */

    for (y = 0; y < s->sbheight; y++) {

        for (x = 0; x < s->sbwidth; x++) {

            int split  = dirac_get_arith_uint(arith, CTX_SB_F1, CTX_SB_DATA);

            sbsplit[x] = (split + pred_sbsplit(sbsplit+x, s->sbwidth, x, y)) % 3;

        }

        sbsplit += s->sbwidth;

    }

    /* setup arith decoding */

    ff_dirac_init_arith_decoder(arith, gb, svq3_get_ue_golomb(gb));

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

        ff_dirac_init_arith_decoder(arith + 4 + 2 * i, gb, svq3_get_ue_golomb(gb));

        ff_dirac_init_arith_decoder(arith + 5 + 2 * i, gb, svq3_get_ue_golomb(gb));

    }

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

        ff_dirac_init_arith_decoder(arith+1+i, gb, svq3_get_ue_golomb(gb));

    for (y = 0; y < s->sbheight; y++)

        for (x = 0; x < s->sbwidth; x++) {

            int blkcnt = 1 << s->sbsplit[y * s->sbwidth + x];

            int step   = 4 >> s->sbsplit[y * s->sbwidth + x];

            for (q = 0; q < blkcnt; q++)

                for (p = 0; p < blkcnt; p++) {

                    int bx = 4 * x + p*step;

                    int by = 4 * y + q*step;

                    DiracBlock *block = &s->blmotion[by*s->blwidth + bx];

                    decode_block_params(s, arith, block, s->blwidth, bx, by);

                    propagate_block_data(block, s->blwidth, step);

                }

        }

}


static void add_bytes_c(uint8_t *dst, uint8_t *src, int w){

    long i;

    for(i=0; i<=w-sizeof(long); i+=sizeof(long)){

        long a = *(long*)(src+i);

        long b = *(long*)(dst+i);

        *(long*)(dst+i) = ((a&pb_7f) + (b&pb_7f)) ^ ((a^b)&pb_80);

    }

    for(; i<w; i++)

        dst[i+0] += src[i+0];

}


static int write_f(BlockBackend *blk, int argc, char **argv)

{

    struct timeval t1, t2;

    bool Cflag = false, qflag = false, bflag = false;

    bool Pflag = false, zflag = false, cflag = false;

    int flags = 0;

    int c, cnt;

    char *buf = NULL;

    int64_t offset;

    int64_t count;

    /* Some compilers get confused and warn if this is not initialized.  */

    int64_t total = 0;

    int pattern = 0xcd;

    while ((c = getopt(argc, argv, "bcCfpP:quz")) != -1) {

        switch (c) {

        case 'b':

            bflag = true;

            break;

        case 'c':

            cflag = true;

            break;

        case 'C':

            Cflag = true;

            break;

        case 'f':

            flags |= BDRV_REQ_FUA;

            break;

        case 'p':

            /* Ignored for backwards compatibility */

            break;

        case 'P':

            Pflag = true;

            pattern = parse_pattern(optarg);

            if (pattern < 0) {

                return 0;

            }

            break;

        case 'q':

            qflag = true;

            break;

        case 'u':

            flags |= BDRV_REQ_MAY_UNMAP;

            break;

        case 'z':

            zflag = true;

            break;

        default:

            return qemuio_command_usage(&write_cmd);

        }

    }

    if (optind != argc - 2) {

        return qemuio_command_usage(&write_cmd);

    }

    if (bflag && zflag) {

        printf("-b and -z cannot be specified at the same time\n");

        return 0;

    }

    if ((flags & BDRV_REQ_FUA) && (bflag || cflag)) {

        printf("-f and -b or -c cannot be specified at the same time\n");

        return 0;

    }

    if ((flags & BDRV_REQ_MAY_UNMAP) && !zflag) {

        printf("-u requires -z to be specified\n");

        return 0;

    }

    if (zflag && Pflag) {

        printf("-z and -P cannot be specified at the same time\n");

        return 0;

    }

    offset = cvtnum(argv[optind]);

    if (offset < 0) {

        print_cvtnum_err(offset, argv[optind]);

        return 0;

    }

    optind++;

    count = cvtnum(argv[optind]);

    if (count < 0) {

        print_cvtnum_err(count, argv[optind]);

        return 0;

    } else if (count > SIZE_MAX) {

        printf("length cannot exceed %" PRIu64 ", given %s\n",

               (uint64_t) SIZE_MAX, argv[optind]);

        return 0;

    }

    if (bflag || cflag) {

        if (offset & 0x1ff) {

            printf("offset %" PRId64 " is not sector aligned\n",

                   offset);

            return 0;

        }

        if (count & 0x1ff) {

            printf("count %"PRId64" is not sector aligned\n",

                   count);

            return 0;

        }

    }

    if (!zflag) {

        buf = qemu_io_alloc(blk, count, pattern);

    }

    gettimeofday(&t1, NULL);

    if (bflag) {

        cnt = do_save_vmstate(blk, buf, offset, count, &total);

    } else if (zflag) {

        cnt = do_co_pwrite_zeroes(blk, offset, count, flags, &total);

    } else if (cflag) {

        cnt = do_write_compressed(blk, buf, offset, count, &total);

    } else {

        cnt = do_pwrite(blk, buf, offset, count, flags, &total);

    }

    gettimeofday(&t2, NULL);

    if (cnt < 0) {

        printf("write failed: %s\n", strerror(-cnt));

        goto out;

    }

    if (qflag) {

        goto out;

    }

    /* Finally, report back -- -C gives a parsable format */

    t2 = tsub(t2, t1);

    print_report("wrote", &t2, offset, count, total, cnt, Cflag);

out:

    if (!zflag) {

        qemu_io_free(buf);

    }

    return 0;

}


static int parse_audio(DBEContext *s, int start, int end, int seg_id)

{

    int ch, ret, key = parse_key(s);

    for (ch = start; ch < end; ch++) {

        if (!s->ch_size[ch]) {

            s->channels[seg_id][ch].nb_groups = 0;

            continue;

        }

        if ((ret = convert_input(s, s->ch_size[ch], key)) < 0)

            return ret;

        if ((ret = parse_channel(s, ch, seg_id)) < 0) {

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

                return ret;

            s->channels[seg_id][ch].nb_groups = 0;

        }

        skip_input(s, s->ch_size[ch]);

    }

    skip_input(s, 1);

    return 0;

}


static void qemu_input_queue_process(void *opaque)

{

    struct QemuInputEventQueueHead *queue = opaque;

    QemuInputEventQueue *item;

    g_assert(!QTAILQ_EMPTY(queue));

    item = QTAILQ_FIRST(queue);

    g_assert(item->type == QEMU_INPUT_QUEUE_DELAY);

    QTAILQ_REMOVE(queue, item, node);

    g_free(item);

    while (!QTAILQ_EMPTY(queue)) {

        item = QTAILQ_FIRST(queue);

        switch (item->type) {

        case QEMU_INPUT_QUEUE_DELAY:

            timer_mod(item->timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL)

                      + item->delay_ms);

            return;

        case QEMU_INPUT_QUEUE_EVENT:

            qemu_input_event_send(item->src, item->evt);

            qapi_free_InputEvent(item->evt);

            break;

        case QEMU_INPUT_QUEUE_SYNC:

            qemu_input_event_sync();

            break;

        }

        QTAILQ_REMOVE(queue, item, node);

        g_free(item);

    }

}


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

{

    VirtIODevice *vdev = VIRTIO_DEVICE(dev);

    VHostSCSI *s = VHOST_SCSI(dev);

    migrate_del_blocker(s->migration_blocker);

    error_free(s->migration_blocker);

    /* This will stop vhost backend. */

    vhost_scsi_set_status(vdev, 0);

    g_free(s->dev.vqs);

    virtio_scsi_common_unrealize(dev, errp);

}


static void av_noinline filter_mb_edgecv( uint8_t *pix, int stride, int16_t bS[4], unsigned int qp, H264Context *h ) {

    const unsigned int index_a = 52 + qp + h->slice_alpha_c0_offset;

    const int alpha = alpha_table[index_a];

    const int beta  = (beta_table+52)[qp + h->slice_beta_offset];

    if (alpha ==0 || beta == 0) return;

    if( bS[0] < 4 ) {

        int8_t tc[4];

        tc[0] = tc0_table[index_a][bS[0]]+1;

        tc[1] = tc0_table[index_a][bS[1]]+1;

        tc[2] = tc0_table[index_a][bS[2]]+1;

        tc[3] = tc0_table[index_a][bS[3]]+1;

        h->s.dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc);

    } else {

        h->s.dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta);

    }

}


int qemu_recvv(int sockfd, struct iovec *iov, int len, int iov_offset)

{

    return do_sendv_recvv(sockfd, iov, len, iov_offset, 0);

}


static void vmxnet3_complete_packet(VMXNET3State *s, int qidx, uint32_t tx_ridx)

{

    struct Vmxnet3_TxCompDesc txcq_descr;

    PCIDevice *d = PCI_DEVICE(s);

    VMXNET3_RING_DUMP(VMW_RIPRN, "TXC", qidx, &s->txq_descr[qidx].comp_ring);

    txcq_descr.txdIdx = tx_ridx;

    txcq_descr.gen = vmxnet3_ring_curr_gen(&s->txq_descr[qidx].comp_ring);

    vmxnet3_ring_write_curr_cell(d, &s->txq_descr[qidx].comp_ring, &txcq_descr);

    /* Flush changes in TX descriptor before changing the counter value */

    smp_wmb();

    vmxnet3_inc_tx_completion_counter(s, qidx);

    vmxnet3_trigger_interrupt(s, s->txq_descr[qidx].intr_idx);

}


static void gen_mtc0(DisasContext *ctx, TCGv arg, int reg, int sel)

{

    const char *rn = "invalid";

    if (sel != 0)

        check_insn(ctx, ISA_MIPS32);

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_start();

    }

    switch (reg) {

    case 0:

        switch (sel) {

        case 0:

            gen_helper_mtc0_index(cpu_env, arg);

            rn = "Index";

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_mvpcontrol(cpu_env, arg);

            rn = "MVPControl";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            /* ignored */

            rn = "MVPConf0";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            /* ignored */

            rn = "MVPConf1";

            CP0_CHECK(ctx->vp);

            /* ignored */

            rn = "VPControl";

        default:

            goto cp0_unimplemented;

        }

    case 1:

        switch (sel) {

        case 0:

            /* ignored */

            rn = "Random";

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpecontrol(cpu_env, arg);

            rn = "VPEControl";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpeconf0(cpu_env, arg);

            rn = "VPEConf0";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpeconf1(cpu_env, arg);

            rn = "VPEConf1";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_yqmask(cpu_env, arg);

            rn = "YQMask";

        case 5:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            tcg_gen_st_tl(arg, cpu_env,

                          offsetof(CPUMIPSState, CP0_VPESchedule));

            rn = "VPESchedule";

        case 6:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            tcg_gen_st_tl(arg, cpu_env,

                          offsetof(CPUMIPSState, CP0_VPEScheFBack));

            rn = "VPEScheFBack";

        case 7:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpeopt(cpu_env, arg);

            rn = "VPEOpt";

        default:

            goto cp0_unimplemented;

        }

        switch (sel) {

        case 0:

            gen_helper_mtc0_entrylo0(cpu_env, arg);

            rn = "EntryLo0";

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcstatus(cpu_env, arg);

            rn = "TCStatus";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcbind(cpu_env, arg);

            rn = "TCBind";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcrestart(cpu_env, arg);

            rn = "TCRestart";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tchalt(cpu_env, arg);

            rn = "TCHalt";

        case 5:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tccontext(cpu_env, arg);

            rn = "TCContext";

        case 6:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcschedule(cpu_env, arg);

            rn = "TCSchedule";

        case 7:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcschefback(cpu_env, arg);

            rn = "TCScheFBack";

        default:

            goto cp0_unimplemented;

        }

        switch (sel) {

        case 0:

            gen_helper_mtc0_entrylo1(cpu_env, arg);

            rn = "EntryLo1";

        case 1:

            CP0_CHECK(ctx->vp);

            /* ignored */

            rn = "GlobalNumber";

        default:

            goto cp0_unimplemented;

        }

        switch (sel) {

        case 0:

            gen_helper_mtc0_context(cpu_env, arg);

            rn = "Context";

        case 1:

//            gen_helper_mtc0_contextconfig(cpu_env, arg); /* SmartMIPS ASE */

            rn = "ContextConfig";

            goto cp0_unimplemented;

            CP0_CHECK(ctx->ulri);

            tcg_gen_st_tl(arg, cpu_env,

                          offsetof(CPUMIPSState, active_tc.CP0_UserLocal));

            rn = "UserLocal";

        default:

            goto cp0_unimplemented;

        }

    case 5:

        switch (sel) {

        case 0:

            gen_helper_mtc0_pagemask(cpu_env, arg);

            rn = "PageMask";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_pagegrain(cpu_env, arg);

            rn = "PageGrain";

            ctx->bstate = BS_STOP;

        default:

            goto cp0_unimplemented;

        }

    case 6:

        switch (sel) {

        case 0:

            gen_helper_mtc0_wired(cpu_env, arg);

            rn = "Wired";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf0(cpu_env, arg);

            rn = "SRSConf0";

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf1(cpu_env, arg);

            rn = "SRSConf1";

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf2(cpu_env, arg);

            rn = "SRSConf2";

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf3(cpu_env, arg);

            rn = "SRSConf3";

        case 5:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf4(cpu_env, arg);

            rn = "SRSConf4";

        default:

            goto cp0_unimplemented;

        }

    case 7:

        switch (sel) {

        case 0:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_hwrena(cpu_env, arg);

            ctx->bstate = BS_STOP;

            rn = "HWREna";

        default:

            goto cp0_unimplemented;

        }

    case 8:

        switch (sel) {

        case 0:

            /* ignored */

            rn = "BadVAddr";

        case 1:

            /* ignored */

            rn = "BadInstr";

            /* ignored */

            rn = "BadInstrP";

        default:

            goto cp0_unimplemented;

        }

    case 9:

        switch (sel) {

        case 0:

            gen_helper_mtc0_count(cpu_env, arg);

            rn = "Count";

        /* 6,7 are implementation dependent */

        default:

            goto cp0_unimplemented;

        }

    case 10:

        switch (sel) {

        case 0:

            gen_helper_mtc0_entryhi(cpu_env, arg);

            rn = "EntryHi";

        default:

            goto cp0_unimplemented;

        }

    case 11:

        switch (sel) {

        case 0:

            gen_helper_mtc0_compare(cpu_env, arg);

            rn = "Compare";

        /* 6,7 are implementation dependent */

        default:

            goto cp0_unimplemented;

        }

    case 12:

        switch (sel) {

        case 0:

            save_cpu_state(ctx, 1);

            gen_helper_mtc0_status(cpu_env, arg);

            /* BS_STOP isn't good enough here, hflags may have changed. */

            gen_save_pc(ctx->pc + 4);

            ctx->bstate = BS_EXCP;

            rn = "Status";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_intctl(cpu_env, arg);

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            rn = "IntCtl";

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsctl(cpu_env, arg);

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            rn = "SRSCtl";

            check_insn(ctx, ISA_MIPS32R2);

            gen_mtc0_store32(arg, offsetof(CPUMIPSState, CP0_SRSMap));

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            rn = "SRSMap";

        default:

            goto cp0_unimplemented;

        }

    case 13:

        switch (sel) {

        case 0:

            save_cpu_state(ctx, 1);

            gen_helper_mtc0_cause(cpu_env, arg);

            rn = "Cause";

        default:

            goto cp0_unimplemented;

        }

    case 14:

        switch (sel) {

        case 0:

            tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EPC));

            rn = "EPC";

        default:

            goto cp0_unimplemented;

        }

    case 15:

        switch (sel) {

        case 0:

            /* ignored */

            rn = "PRid";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_ebase(cpu_env, arg);

            rn = "EBase";

        default:

            goto cp0_unimplemented;

        }

    case 16:

        switch (sel) {

        case 0:

            gen_helper_mtc0_config0(cpu_env, arg);

            rn = "Config";

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

        case 1:

            /* ignored, read only */

            rn = "Config1";

            gen_helper_mtc0_config2(cpu_env, arg);

            rn = "Config2";

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            gen_helper_mtc0_config3(cpu_env, arg);

            rn = "Config3";

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            gen_helper_mtc0_config4(cpu_env, arg);

            rn = "Config4";

            ctx->bstate = BS_STOP;

        case 5:

            gen_helper_mtc0_config5(cpu_env, arg);

            rn = "Config5";

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

        /* 6,7 are implementation dependent */

        case 6:

            /* ignored */

            rn = "Config6";

        case 7:

            /* ignored */

            rn = "Config7";

        default:

            rn = "Invalid config selector";

            goto cp0_unimplemented;

        }

    case 17:

        switch (sel) {

        case 0:

            gen_helper_mtc0_lladdr(cpu_env, arg);

            rn = "LLAddr";

        case 1:

            CP0_CHECK(ctx->mrp);

            gen_helper_mtc0_maar(cpu_env, arg);

            rn = "MAAR";

            CP0_CHECK(ctx->mrp);

            gen_helper_mtc0_maari(cpu_env, arg);

            rn = "MAARI";

        default:

            goto cp0_unimplemented;

        }

    case 18:

        switch (sel) {

        case 0 ... 7:

            gen_helper_0e1i(mtc0_watchlo, arg, sel);

            rn = "WatchLo";

        default:

            goto cp0_unimplemented;

        }

    case 19:

        switch (sel) {

        case 0 ... 7:

            gen_helper_0e1i(mtc0_watchhi, arg, sel);

            rn = "WatchHi";

        default:

            goto cp0_unimplemented;

        }

    case 20:

        switch (sel) {

        case 0:

#if defined(TARGET_MIPS64)

            check_insn(ctx, ISA_MIPS3);

            gen_helper_mtc0_xcontext(cpu_env, arg);

            rn = "XContext";

#endif

        default:

            goto cp0_unimplemented;

        }

    case 21:

       /* Officially reserved, but sel 0 is used for R1x000 framemask */

        CP0_CHECK(!(ctx->insn_flags & ISA_MIPS32R6));

        switch (sel) {

        case 0:

            gen_helper_mtc0_framemask(cpu_env, arg);

            rn = "Framemask";

        default:

            goto cp0_unimplemented;

        }

    case 22:

        /* ignored */

        rn = "Diagnostic"; /* implementation dependent */

    case 23:

        switch (sel) {

        case 0:

            gen_helper_mtc0_debug(cpu_env, arg); /* EJTAG support */

            /* BS_STOP isn't good enough here, hflags may have changed. */

            gen_save_pc(ctx->pc + 4);

            ctx->bstate = BS_EXCP;

            rn = "Debug";

        case 1:

//            gen_helper_mtc0_tracecontrol(cpu_env, arg); /* PDtrace support */

            rn = "TraceControl";

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            goto cp0_unimplemented;

//            gen_helper_mtc0_tracecontrol2(cpu_env, arg); /* PDtrace support */

            rn = "TraceControl2";

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            goto cp0_unimplemented;

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

//            gen_helper_mtc0_usertracedata(cpu_env, arg); /* PDtrace support */

            rn = "UserTraceData";

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            goto cp0_unimplemented;

//            gen_helper_mtc0_tracebpc(cpu_env, arg); /* PDtrace support */

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            rn = "TraceBPC";

            goto cp0_unimplemented;

        default:

            goto cp0_unimplemented;

        }

    case 24:

        switch (sel) {

        case 0:

            /* EJTAG support */

            tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_DEPC));

            rn = "DEPC";

        default:

            goto cp0_unimplemented;

        }

    case 25:

        switch (sel) {

        case 0:

            gen_helper_mtc0_performance0(cpu_env, arg);

            rn = "Performance0";

        case 1:

//            gen_helper_mtc0_performance1(arg);

            rn = "Performance1";

            goto cp0_unimplemented;

//            gen_helper_mtc0_performance2(arg);

            rn = "Performance2";

            goto cp0_unimplemented;

//            gen_helper_mtc0_performance3(arg);

            rn = "Performance3";

            goto cp0_unimplemented;

//            gen_helper_mtc0_performance4(arg);

            rn = "Performance4";

            goto cp0_unimplemented;

        case 5:

//            gen_helper_mtc0_performance5(arg);

            rn = "Performance5";

            goto cp0_unimplemented;

        case 6:

//            gen_helper_mtc0_performance6(arg);

            rn = "Performance6";

            goto cp0_unimplemented;

        case 7:

//            gen_helper_mtc0_performance7(arg);

            rn = "Performance7";

            goto cp0_unimplemented;

        default:

            goto cp0_unimplemented;

        }

    case 26:

        switch (sel) {

        case 0:

            gen_helper_mtc0_errctl(cpu_env, arg);

            ctx->bstate = BS_STOP;

            rn = "ErrCtl";

        default:

            goto cp0_unimplemented;

        }

    case 27:

        switch (sel) {

        case 0 ... 3:

            /* ignored */

            rn = "CacheErr";

        default:

            goto cp0_unimplemented;

        }

    case 28:

        switch (sel) {

        case 0:

        case 6:

            gen_helper_mtc0_taglo(cpu_env, arg);

            rn = "TagLo";

        case 1:

        case 5:

        case 7:

            gen_helper_mtc0_datalo(cpu_env, arg);

            rn = "DataLo";

        default:

            goto cp0_unimplemented;

        }

    case 29:

        switch (sel) {

        case 0:

        case 6:

            gen_helper_mtc0_taghi(cpu_env, arg);

            rn = "TagHi";

        case 1:

        case 5:

        case 7:

            gen_helper_mtc0_datahi(cpu_env, arg);

            rn = "DataHi";

        default:

            rn = "invalid sel";

            goto cp0_unimplemented;

        }

    case 30:

        switch (sel) {

        case 0:

            tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_ErrorEPC));

            rn = "ErrorEPC";

        default:

            goto cp0_unimplemented;

        }

    case 31:

        switch (sel) {

        case 0:

            /* EJTAG support */

            gen_mtc0_store32(arg, offsetof(CPUMIPSState, CP0_DESAVE));

            rn = "DESAVE";

        case 2 ... 7:

            CP0_CHECK(ctx->kscrexist & (1 << sel));

            tcg_gen_st_tl(arg, cpu_env,

                          offsetof(CPUMIPSState, CP0_KScratch[sel-2]));

            rn = "KScratch";

        default:

            goto cp0_unimplemented;

        }

        /* Stop translation as we may have switched the execution mode */

        ctx->bstate = BS_STOP;

    default:

       goto cp0_unimplemented;

    }

    trace_mips_translate_c0("mtc0", rn, reg, sel);

    /* For simplicity assume that all writes can cause interrupts.  */

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_end();

        ctx->bstate = BS_STOP;

    }

    return;

cp0_unimplemented:

    qemu_log_mask(LOG_UNIMP, "mtc0 %s (reg %d sel %d)\n", rn, reg, sel);

}


void cpu_loop(CPUARMState *env)

{

    int trapnr;

    unsigned int n, insn;

    target_siginfo_t info;

    uint32_t addr;

    for(;;) {

        cpu_exec_start(env);

        trapnr = cpu_arm_exec(env);

        cpu_exec_end(env);

        switch(trapnr) {

        case EXCP_UDEF:

            {

                TaskState *ts = env->opaque;

                uint32_t opcode;

                int rc;

                /* we handle the FPU emulation here, as Linux */

                /* we get the opcode */

                /* FIXME - what to do if get_user() fails? */

                get_user_u32(opcode, env->regs[15]);

                rc = EmulateAll(opcode, &ts->fpa, env);

                if (rc == 0) { /* illegal instruction */

                    info.si_signo = SIGILL;

                    info.si_errno = 0;

                    info.si_code = TARGET_ILL_ILLOPN;

                    info._sifields._sigfault._addr = env->regs[15];

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

                } else if (rc < 0) { /* FP exception */

                    int arm_fpe=0;

                    /* translate softfloat flags to FPSR flags */

                    if (-rc & float_flag_invalid)

                      arm_fpe |= BIT_IOC;

                    if (-rc & float_flag_divbyzero)

                      arm_fpe |= BIT_DZC;

                    if (-rc & float_flag_overflow)

                      arm_fpe |= BIT_OFC;

                    if (-rc & float_flag_underflow)

                      arm_fpe |= BIT_UFC;

                    if (-rc & float_flag_inexact)

                      arm_fpe |= BIT_IXC;

                    FPSR fpsr = ts->fpa.fpsr;

                    //printf("fpsr 0x%x, arm_fpe 0x%x\n",fpsr,arm_fpe);

                    if (fpsr & (arm_fpe << 16)) { /* exception enabled? */

                      info.si_signo = SIGFPE;

                      info.si_errno = 0;

                      /* ordered by priority, least first */

                      if (arm_fpe & BIT_IXC) info.si_code = TARGET_FPE_FLTRES;

                      if (arm_fpe & BIT_UFC) info.si_code = TARGET_FPE_FLTUND;

                      if (arm_fpe & BIT_OFC) info.si_code = TARGET_FPE_FLTOVF;

                      if (arm_fpe & BIT_DZC) info.si_code = TARGET_FPE_FLTDIV;

                      if (arm_fpe & BIT_IOC) info.si_code = TARGET_FPE_FLTINV;

                      info._sifields._sigfault._addr = env->regs[15];

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

                    } else {

                      env->regs[15] += 4;

                    }

                    /* accumulate unenabled exceptions */

                    if ((!(fpsr & BIT_IXE)) && (arm_fpe & BIT_IXC))

                      fpsr |= BIT_IXC;

                    if ((!(fpsr & BIT_UFE)) && (arm_fpe & BIT_UFC))

                      fpsr |= BIT_UFC;

                    if ((!(fpsr & BIT_OFE)) && (arm_fpe & BIT_OFC))

                      fpsr |= BIT_OFC;

                    if ((!(fpsr & BIT_DZE)) && (arm_fpe & BIT_DZC))

                      fpsr |= BIT_DZC;

                    if ((!(fpsr & BIT_IOE)) && (arm_fpe & BIT_IOC))

                      fpsr |= BIT_IOC;

                    ts->fpa.fpsr=fpsr;

                } else { /* everything OK */

                    /* increment PC */

                    env->regs[15] += 4;

                }

            }

            break;

        case EXCP_SWI:

        case EXCP_BKPT:

            {

                env->eabi = 1;

                /* system call */

                if (trapnr == EXCP_BKPT) {

                    if (env->thumb) {

                        /* FIXME - what to do if get_user() fails? */

                        get_user_u16(insn, env->regs[15]);

                        n = insn & 0xff;

                        env->regs[15] += 2;

                    } else {

                        /* FIXME - what to do if get_user() fails? */

                        get_user_u32(insn, env->regs[15]);

                        n = (insn & 0xf) | ((insn >> 4) & 0xff0);

                        env->regs[15] += 4;

                    }

                } else {

                    if (env->thumb) {

                        /* FIXME - what to do if get_user() fails? */

                        get_user_u16(insn, env->regs[15] - 2);

                        n = insn & 0xff;

                    } else {

                        /* FIXME - what to do if get_user() fails? */

                        get_user_u32(insn, env->regs[15] - 4);

                        n = insn & 0xffffff;

                    }

                }

                if (n == ARM_NR_cacheflush) {

                    /* nop */

                } else if (n == ARM_NR_semihosting

                           || n == ARM_NR_thumb_semihosting) {

                    env->regs[0] = do_arm_semihosting (env);

                } else if (n == 0 || n >= ARM_SYSCALL_BASE

                           || (env->thumb && n == ARM_THUMB_SYSCALL)) {

                    /* linux syscall */

                    if (env->thumb || n == 0) {

                        n = env->regs[7];

                    } else {

                        n -= ARM_SYSCALL_BASE;

                        env->eabi = 0;

                    }

                    if ( n > ARM_NR_BASE) {

                        switch (n) {

                        case ARM_NR_cacheflush:

                            /* nop */

                            break;

                        case ARM_NR_set_tls:

                            cpu_set_tls(env, env->regs[0]);

                            env->regs[0] = 0;

                            break;

                        default:

                            gemu_log("qemu: Unsupported ARM syscall: 0x%x\n",

                                     n);

                            env->regs[0] = -TARGET_ENOSYS;

                            break;

                        }

                    } else {

                        env->regs[0] = do_syscall(env,

                                                  n,

                                                  env->regs[0],

                                                  env->regs[1],

                                                  env->regs[2],

                                                  env->regs[3],

                                                  env->regs[4],

                                                  env->regs[5],

                                                  0, 0);

                    }

                } else {

                    goto error;

                }

            }

            break;

        case EXCP_INTERRUPT:

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

            break;

        case EXCP_PREFETCH_ABORT:

            addr = env->cp15.c6_insn;

            goto do_segv;

        case EXCP_DATA_ABORT:

            addr = env->cp15.c6_data;

        do_segv:

            {

                info.si_signo = SIGSEGV;

                info.si_errno = 0;

                /* XXX: check env->error_code */

                info.si_code = TARGET_SEGV_MAPERR;

                info._sifields._sigfault._addr = addr;

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

            }

            break;

        case EXCP_DEBUG:

            {

                int sig;

                sig = gdb_handlesig (env, TARGET_SIGTRAP);

                if (sig)

                  {

                    info.si_signo = sig;

                    info.si_errno = 0;

                    info.si_code = TARGET_TRAP_BRKPT;

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

                  }

            }

            break;

        case EXCP_KERNEL_TRAP:

            if (do_kernel_trap(env))

              goto error;

            break;

        case EXCP_STREX:

            if (do_strex(env)) {

                addr = env->cp15.c6_data;

                goto do_segv;

            }

            break;

        default:

        error:

            fprintf(stderr, "qemu: unhandled CPU exception 0x%x - aborting\n",

                    trapnr);

            cpu_dump_state(env, stderr, fprintf, 0);

            abort();

        }

        process_pending_signals(env);

    }

}


static uint32_t cc_calc_abs_32(int32_t dst)

{

    if ((uint32_t)dst == 0x80000000UL) {

        return 3;

    } else if (dst) {

        return 1;

    } else {

        return 0;

    }

}


static int qemu_chr_open_pipe(QemuOpts *opts, CharDriverState **_chr)

{

    int fd_in, fd_out;

    char filename_in[256], filename_out[256];

    const char *filename = qemu_opt_get(opts, "path");

    if (filename == NULL) {

        fprintf(stderr, "chardev: pipe: no filename given\n");

        return -EINVAL;

    }

    snprintf(filename_in, 256, "%s.in", filename);

    snprintf(filename_out, 256, "%s.out", filename);

    TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));

    TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));

    if (fd_in < 0 || fd_out < 0) {

	if (fd_in >= 0)

	    close(fd_in);

	if (fd_out >= 0)

	    close(fd_out);

        TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));

        if (fd_in < 0) {

            return -errno;

        }

    }

    *_chr = qemu_chr_open_fd(fd_in, fd_out);

    return 0;

}


static void vp5_parse_coeff(VP56Context *s)

{

    VP56RangeCoder *c = &s->c;

    VP56Model *model = s->modelp;

    uint8_t *permute = s->idct_scantable;

    uint8_t *model1, *model2;

    int coeff, sign, coeff_idx;

    int b, i, cg, idx, ctx, ctx_last;

    int pt = 0;    /* plane type (0 for Y, 1 for U or V) */

    for (b=0; b<6; b++) {

        int ct = 1;    /* code type */

        if (b > 3) pt = 1;

        ctx = 6*s->coeff_ctx[ff_vp56_b6to4[b]][0]

              + s->above_blocks[s->above_block_idx[b]].not_null_dc;

        model1 = model->coeff_dccv[pt];

        model2 = model->coeff_dcct[pt][ctx];

        coeff_idx = 0;

        for (;;) {

            if (vp56_rac_get_prob_branchy(c, model2[0])) {

                if (vp56_rac_get_prob_branchy(c, model2[2])) {

                    if (vp56_rac_get_prob_branchy(c, model2[3])) {

                        s->coeff_ctx[ff_vp56_b6to4[b]][coeff_idx] = 4;

                        idx = vp56_rac_get_tree(c, ff_vp56_pc_tree, model1);

                        sign = vp56_rac_get(c);

                        coeff = ff_vp56_coeff_bias[idx+5];

                        for (i=ff_vp56_coeff_bit_length[idx]; i>=0; i--)

                            coeff += vp56_rac_get_prob(c, ff_vp56_coeff_parse_table[idx][i]) << i;

                    } else {

                        if (vp56_rac_get_prob_branchy(c, model2[4])) {

                            coeff = 3 + vp56_rac_get_prob(c, model1[5]);

                            s->coeff_ctx[ff_vp56_b6to4[b]][coeff_idx] = 3;

                        } else {

                            coeff = 2;

                            s->coeff_ctx[ff_vp56_b6to4[b]][coeff_idx] = 2;

                        }

                        sign = vp56_rac_get(c);

                    }

                    ct = 2;

                } else {

                    ct = 1;

                    s->coeff_ctx[ff_vp56_b6to4[b]][coeff_idx] = 1;

                    sign = vp56_rac_get(c);

                    coeff = 1;

                }

                coeff = (coeff ^ -sign) + sign;

                if (coeff_idx)

                    coeff *= s->dequant_ac;

                s->block_coeff[b][permute[coeff_idx]] = coeff;

            } else {

                if (ct && !vp56_rac_get_prob_branchy(c, model2[1]))

                    break;

                ct = 0;

                s->coeff_ctx[ff_vp56_b6to4[b]][coeff_idx] = 0;

            }

            coeff_idx++;

            if (coeff_idx >= 64)

                break;

            cg = vp5_coeff_groups[coeff_idx];

            ctx = s->coeff_ctx[ff_vp56_b6to4[b]][coeff_idx];

            model1 = model->coeff_ract[pt][ct][cg];

            model2 = cg > 2 ? model1 : model->coeff_acct[pt][ct][cg][ctx];

        }

        ctx_last = FFMIN(s->coeff_ctx_last[ff_vp56_b6to4[b]], 24);

        s->coeff_ctx_last[ff_vp56_b6to4[b]] = coeff_idx;

        if (coeff_idx < ctx_last)

            for (i=coeff_idx; i<=ctx_last; i++)

                s->coeff_ctx[ff_vp56_b6to4[b]][i] = 5;

        s->above_blocks[s->above_block_idx[b]].not_null_dc = s->coeff_ctx[ff_vp56_b6to4[b]][0];

    }

}


static int nvdec_vc1_end_frame(AVCodecContext *avctx)

{

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

    int ret = ff_nvdec_end_frame(avctx);

    ctx->bitstream = NULL;

    return ret;

}


static inline void RENAME(yuy2toyv12)(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 long chromWidth= width>>1;

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

	{

#ifdef HAVE_MMX

		asm volatile(

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

			"pcmpeqw %%mm7, %%mm7		\n\t"

			"psrlw $8, %%mm7		\n\t" // FF,00,FF,00...

			ASMALIGN16

			"1:				\n\t"

			PREFETCH" 64(%0, %%"REG_a", 4)	\n\t"

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

			"movq 8(%0, %%"REG_a", 4), %%mm1\n\t" // YUYV YUYV(4)

			"movq %%mm0, %%mm2		\n\t" // YUYV YUYV(0)

			"movq %%mm1, %%mm3		\n\t" // YUYV YUYV(4)

			"psrlw $8, %%mm0		\n\t" // U0V0 U0V0(0)

			"psrlw $8, %%mm1		\n\t" // U0V0 U0V0(4)

			"pand %%mm7, %%mm2		\n\t" // Y0Y0 Y0Y0(0)

			"pand %%mm7, %%mm3		\n\t" // Y0Y0 Y0Y0(4)

			"packuswb %%mm1, %%mm0		\n\t" // UVUV UVUV(0)

			"packuswb %%mm3, %%mm2		\n\t" // YYYY YYYY(0)

			MOVNTQ" %%mm2, (%1, %%"REG_a", 2)\n\t"

			"movq 16(%0, %%"REG_a", 4), %%mm1\n\t" // YUYV YUYV(8)

			"movq 24(%0, %%"REG_a", 4), %%mm2\n\t" // YUYV YUYV(12)

			"movq %%mm1, %%mm3		\n\t" // YUYV YUYV(8)

			"movq %%mm2, %%mm4		\n\t" // YUYV YUYV(12)

			"psrlw $8, %%mm1		\n\t" // U0V0 U0V0(8)

			"psrlw $8, %%mm2		\n\t" // U0V0 U0V0(12)

			"pand %%mm7, %%mm3		\n\t" // Y0Y0 Y0Y0(8)

			"pand %%mm7, %%mm4		\n\t" // Y0Y0 Y0Y0(12)

			"packuswb %%mm2, %%mm1		\n\t" // UVUV UVUV(8)

			"packuswb %%mm4, %%mm3		\n\t" // YYYY YYYY(8)

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

			"movq %%mm0, %%mm2		\n\t" // UVUV UVUV(0)

			"movq %%mm1, %%mm3		\n\t" // UVUV UVUV(8)

			"psrlw $8, %%mm0		\n\t" // V0V0 V0V0(0)

			"psrlw $8, %%mm1		\n\t" // V0V0 V0V0(8)

			"pand %%mm7, %%mm2		\n\t" // U0U0 U0U0(0)

			"pand %%mm7, %%mm3		\n\t" // U0U0 U0U0(8)

			"packuswb %%mm1, %%mm0		\n\t" // VVVV VVVV(0)

			"packuswb %%mm3, %%mm2		\n\t" // UUUU UUUU(0)

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

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

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

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

			" jb 1b				\n\t"

			::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)

			: "memory", "%"REG_a

		);

		ydst += lumStride;

		src  += srcStride;

		asm volatile(

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

			ASMALIGN16

			"1:				\n\t"

			PREFETCH" 64(%0, %%"REG_a", 4)	\n\t"

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

			"movq 8(%0, %%"REG_a", 4), %%mm1\n\t" // YUYV YUYV(4)

			"movq 16(%0, %%"REG_a", 4), %%mm2\n\t" // YUYV YUYV(8)

			"movq 24(%0, %%"REG_a", 4), %%mm3\n\t" // YUYV YUYV(12)

			"pand %%mm7, %%mm0		\n\t" // Y0Y0 Y0Y0(0)

			"pand %%mm7, %%mm1		\n\t" // Y0Y0 Y0Y0(4)

			"pand %%mm7, %%mm2		\n\t" // Y0Y0 Y0Y0(8)

			"pand %%mm7, %%mm3		\n\t" // Y0Y0 Y0Y0(12)

			"packuswb %%mm1, %%mm0		\n\t" // YYYY YYYY(0)

			"packuswb %%mm3, %%mm2		\n\t" // YYYY YYYY(8)

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

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

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

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

			" jb 1b				\n\t"

			::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)

			: "memory", "%"REG_a

		);

#else

		long i;

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

		{

			ydst[2*i+0] 	= src[4*i+0];

			udst[i] 	= src[4*i+1];

			ydst[2*i+1] 	= src[4*i+2];

			vdst[i] 	= src[4*i+3];

		}

		ydst += lumStride;

		src  += srcStride;

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

		{

			ydst[2*i+0] 	= src[4*i+0];

			ydst[2*i+1] 	= src[4*i+2];

		}

#endif

		udst += chromStride;

		vdst += chromStride;

		ydst += lumStride;

		src  += srcStride;

	}

#ifdef HAVE_MMX

asm volatile(   EMMS" \n\t"

        	SFENCE" \n\t"

        	:::"memory");

#endif

}


static int qtrle_decode_init(AVCodecContext *avctx)

{

    QtrleContext *s = avctx->priv_data;

    s->avctx = avctx;

    switch (avctx->bits_per_sample) {

    case 1:

    case 2:

    case 4:

    case 8:

    case 33:

    case 34:

    case 36:

    case 40:

        avctx->pix_fmt = PIX_FMT_PAL8;

        break;

    case 16:

        avctx->pix_fmt = PIX_FMT_RGB555;

        break;

    case 24:

        avctx->pix_fmt = PIX_FMT_RGB24;

        break;

    case 32:

        avctx->pix_fmt = PIX_FMT_RGB32;

        break;

    default:

        av_log (avctx, AV_LOG_ERROR, "Unsupported colorspace: %d bits/sample?\n",

            avctx->bits_per_sample);

        break;

    }

    dsputil_init(&s->dsp, avctx);

    s->frame.data[0] = NULL;

    return 0;

}


void vp8_mc_part(VP8Context *s, uint8_t *dst[3],

                 AVFrame *ref_frame, int x_off, int y_off,

                 int bx_off, int by_off,

                 int block_w, int block_h,

                 int width, int height, VP56mv *mv)

{

    VP56mv uvmv = *mv;

    /* Y */

    vp8_mc(s, 1, dst[0] + by_off * s->linesize + bx_off,

           ref_frame->data[0], mv, x_off + bx_off, y_off + by_off,

           block_w, block_h, width, height, s->linesize,

           s->put_pixels_tab[block_w == 8]);

    /* U/V */

    if (s->profile == 3) {

        uvmv.x &= ~7;

        uvmv.y &= ~7;

    }

    x_off   >>= 1; y_off   >>= 1;

    bx_off  >>= 1; by_off  >>= 1;

    width   >>= 1; height  >>= 1;

    block_w >>= 1; block_h >>= 1;

    vp8_mc(s, 0, dst[1] + by_off * s->uvlinesize + bx_off,

           ref_frame->data[1], &uvmv, x_off + bx_off, y_off + by_off,

           block_w, block_h, width, height, s->uvlinesize,

           s->put_pixels_tab[1 + (block_w == 4)]);

    vp8_mc(s, 0, dst[2] + by_off * s->uvlinesize + bx_off,

           ref_frame->data[2], &uvmv, x_off + bx_off, y_off + by_off,

           block_w, block_h, width, height, s->uvlinesize,

           s->put_pixels_tab[1 + (block_w == 4)]);

}


static int decode_p_frame(FourXContext *f, const uint8_t *buf, int length){

    int x, y;

    const int width= f->avctx->width;

    const int height= f->avctx->height;

    uint16_t *src= (uint16_t*)f->last_picture.data[0];

    uint16_t *dst= (uint16_t*)f->current_picture.data[0];

    const int stride= f->current_picture.linesize[0]>>1;

    unsigned int bitstream_size, bytestream_size, wordstream_size, extra;

    if(f->version>1){

        extra=20;

        bitstream_size= AV_RL32(buf+8);

        wordstream_size= AV_RL32(buf+12);

        bytestream_size= AV_RL32(buf+16);

    }else{

        extra=0;

        bitstream_size = AV_RL16(buf-4);

        wordstream_size= AV_RL16(buf-2);

        bytestream_size= FFMAX(length - bitstream_size - wordstream_size, 0);

    }

    if(bitstream_size+ bytestream_size+ wordstream_size + extra != length

       || bitstream_size  > (1<<26)

       || bytestream_size > (1<<26)

       || wordstream_size > (1<<26)

       ){

        av_log(f->avctx, AV_LOG_ERROR, "lengths %d %d %d %d\n", bitstream_size, bytestream_size, wordstream_size,

        bitstream_size+ bytestream_size+ wordstream_size - length);

        return -1;

    }

    av_fast_malloc(&f->bitstream_buffer, &f->bitstream_buffer_size, bitstream_size + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!f->bitstream_buffer)

        return AVERROR(ENOMEM);

    f->dsp.bswap_buf(f->bitstream_buffer, (const uint32_t*)(buf + extra), bitstream_size/4);

    memset((uint8_t*)f->bitstream_buffer + bitstream_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);

    init_get_bits(&f->gb, f->bitstream_buffer, 8*bitstream_size);

    f->wordstream= (const uint16_t*)(buf + extra + bitstream_size);

    f->bytestream= buf + extra + bitstream_size + wordstream_size;

    init_mv(f);

    for(y=0; y<height; y+=8){

        for(x=0; x<width; x+=8){

            decode_p_block(f, dst + x, src + x, 3, 3, stride);

        }

        src += 8*stride;

        dst += 8*stride;

    }

    if(   bitstream_size != (get_bits_count(&f->gb)+31)/32*4

       || (((const char*)f->wordstream - (const char*)buf + 2)&~2) != extra + bitstream_size + wordstream_size

       || (((const char*)f->bytestream - (const char*)buf + 3)&~3) != extra + bitstream_size + wordstream_size + bytestream_size)

        av_log(f->avctx, AV_LOG_ERROR, " %d %td %td bytes left\n",

            bitstream_size - (get_bits_count(&f->gb)+31)/32*4,

            -(((const char*)f->bytestream - (const char*)buf + 3)&~3) + (extra + bitstream_size + wordstream_size + bytestream_size),

            -(((const char*)f->wordstream - (const char*)buf + 2)&~2) + (extra + bitstream_size + wordstream_size)

        );

    return 0;

}


static inline int halfpel_motion_search(MpegEncContext * s,

				  int *mx_ptr, int *my_ptr, int dmin,

				  int xmin, int ymin, int xmax, int ymax,

                                  int pred_x, int pred_y, uint8_t *ref_picture)

{

    UINT16 *mv_penalty= s->mv_penalty[s->f_code] + MAX_MV; // f_code of the prev frame

    const int quant= s->qscale;

    int pen_x, pen_y;

    int mx, my, mx1, my1, d, xx, yy, dminh;

    UINT8 *pix, *ptr;

    mx = *mx_ptr;

    my = *my_ptr;

    ptr = ref_picture + (my * s->linesize) + mx;

    xx = 16 * s->mb_x;

    yy = 16 * s->mb_y;

    pix =  s->new_picture[0] + (yy * s->linesize) + xx;

    dminh = dmin;

    if (mx > xmin && mx < xmax &&

        my > ymin && my < ymax) {

        mx= mx1= 2*(mx - xx);

        my= my1= 2*(my - yy);

        if(dmin < Z_THRESHOLD && mx==0 && my==0){

            *mx_ptr = 0;

            *my_ptr = 0;

            return dmin;

        }

        pen_x= pred_x + mx;

        pen_y= pred_y + my;

        ptr-= s->linesize;

        CHECK_HALF_MV(xy2, -1, -1)

        CHECK_HALF_MV(y2 ,  0, -1)

        CHECK_HALF_MV(xy2, +1, -1)

        ptr+= s->linesize;

        CHECK_HALF_MV(x2 , -1,  0)

        CHECK_HALF_MV(x2 , +1,  0)

        CHECK_HALF_MV(xy2, -1, +1)

        CHECK_HALF_MV(y2 ,  0, +1)

        CHECK_HALF_MV(xy2, +1, +1)

    }else{

        mx= 2*(mx - xx);

        my= 2*(my - yy);

    }

    *mx_ptr = mx;

    *my_ptr = my;

    return dminh;

}


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

                                 ptrdiff_t stride)

{

    avc_luma_vt_and_aver_dst_16x16_msa(src - (stride * 2), stride, dst, stride);

}


static inline int check_input_motion(MpegEncContext * s, int mb_x, int mb_y, int p_type){

    MotionEstContext * const c= &s->me;

    Picture *p= s->current_picture_ptr;

    int mb_xy= mb_x + mb_y*s->mb_stride;

    int xy= 2*mb_x + 2*mb_y*s->b8_stride;

    int mb_type= s->current_picture.mb_type[mb_xy];

    int flags= c->flags;

    int shift= (flags&FLAG_QPEL) + 1;

    int mask= (1<<shift)-1;

    int x, y, i;

    int d=0;

    me_cmp_func cmpf= s->dsp.sse[0];

    me_cmp_func chroma_cmpf= s->dsp.sse[1];

    assert(p_type==0 || !USES_LIST(mb_type, 1));

    assert(IS_INTRA(mb_type) || USES_LIST(mb_type,0) || USES_LIST(mb_type,1));

    if(IS_INTERLACED(mb_type)){

        int xy2= xy  + s->b8_stride;

        s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTRA;

        c->stride<<=1;

        c->uvstride<<=1;

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

            av_log(c->avctx, AV_LOG_ERROR, "Interlaced macroblock selected but interlaced motion estimation disabled\n");

            return -1;

        }

        if(USES_LIST(mb_type, 0)){

            int field_select0= p->ref_index[0][xy ];

            int field_select1= p->ref_index[0][xy2];

            assert(field_select0==0 ||field_select0==1);

            assert(field_select1==0 ||field_select1==1);

            init_interlaced_ref(s, 0);

            if(p_type){

                s->p_field_select_table[0][mb_xy]= field_select0;

                s->p_field_select_table[1][mb_xy]= field_select1;

                *(uint32_t*)s->p_field_mv_table[0][field_select0][mb_xy]= *(uint32_t*)p->motion_val[0][xy ];

                *(uint32_t*)s->p_field_mv_table[1][field_select1][mb_xy]= *(uint32_t*)p->motion_val[0][xy2];

                s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTER_I;

            }else{

                s->b_field_select_table[0][0][mb_xy]= field_select0;

                s->b_field_select_table[0][1][mb_xy]= field_select1;

                *(uint32_t*)s->b_field_mv_table[0][0][field_select0][mb_xy]= *(uint32_t*)p->motion_val[0][xy ];

                *(uint32_t*)s->b_field_mv_table[0][1][field_select1][mb_xy]= *(uint32_t*)p->motion_val[0][xy2];

                s->mb_type[mb_xy]= CANDIDATE_MB_TYPE_FORWARD_I;

            }

            x= p->motion_val[0][xy ][0];

            y= p->motion_val[0][xy ][1];

            d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select0, 0, cmpf, chroma_cmpf, flags);

            x= p->motion_val[0][xy2][0];

            y= p->motion_val[0][xy2][1];

            d+= cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select1, 1, cmpf, chroma_cmpf, flags);

        }

        if(USES_LIST(mb_type, 1)){

            int field_select0= p->ref_index[1][xy ];

            int field_select1= p->ref_index[1][xy2];

            assert(field_select0==0 ||field_select0==1);

            assert(field_select1==0 ||field_select1==1);

            init_interlaced_ref(s, 2);

            s->b_field_select_table[1][0][mb_xy]= field_select0;

            s->b_field_select_table[1][1][mb_xy]= field_select1;

            *(uint32_t*)s->b_field_mv_table[1][0][field_select0][mb_xy]= *(uint32_t*)p->motion_val[1][xy ];

            *(uint32_t*)s->b_field_mv_table[1][1][field_select1][mb_xy]= *(uint32_t*)p->motion_val[1][xy2];

            if(USES_LIST(mb_type, 0)){

                s->mb_type[mb_xy]= CANDIDATE_MB_TYPE_BIDIR_I;

            }else{

                s->mb_type[mb_xy]= CANDIDATE_MB_TYPE_BACKWARD_I;

            }

            x= p->motion_val[1][xy ][0];

            y= p->motion_val[1][xy ][1];

            d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select0+2, 0, cmpf, chroma_cmpf, flags);

            x= p->motion_val[1][xy2][0];

            y= p->motion_val[1][xy2][1];

            d+= cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select1+2, 1, cmpf, chroma_cmpf, flags);

            //FIXME bidir scores

        }

        c->stride>>=1;

        c->uvstride>>=1;

    }else if(IS_8X8(mb_type)){

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

            av_log(c->avctx, AV_LOG_ERROR, "4MV macroblock selected but 4MV encoding disabled\n");

            return -1;

        }

        cmpf= s->dsp.sse[1];

        chroma_cmpf= s->dsp.sse[1];

        init_mv4_ref(c);

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

            xy= s->block_index[i];

            x= p->motion_val[0][xy][0];

            y= p->motion_val[0][xy][1];

            d+= cmp(s, x>>shift, y>>shift, x&mask, y&mask, 1, 8, i, i, cmpf, chroma_cmpf, flags);

        }

        s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTER4V;

    }else{

        if(USES_LIST(mb_type, 0)){

            if(p_type){

                *(uint32_t*)s->p_mv_table[mb_xy]= *(uint32_t*)p->motion_val[0][xy];

                s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTER;

            }else if(USES_LIST(mb_type, 1)){

                *(uint32_t*)s->b_bidir_forw_mv_table[mb_xy]= *(uint32_t*)p->motion_val[0][xy];

                *(uint32_t*)s->b_bidir_back_mv_table[mb_xy]= *(uint32_t*)p->motion_val[1][xy];

                s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_BIDIR;

            }else{

                *(uint32_t*)s->b_forw_mv_table[mb_xy]= *(uint32_t*)p->motion_val[0][xy];

                s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_FORWARD;

            }

            x= p->motion_val[0][xy][0];

            y= p->motion_val[0][xy][1];

            d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 16, 0, 0, cmpf, chroma_cmpf, flags);

        }else if(USES_LIST(mb_type, 1)){

            *(uint32_t*)s->b_back_mv_table[mb_xy]= *(uint32_t*)p->motion_val[1][xy];

            s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_BACKWARD;

            x= p->motion_val[1][xy][0];

            y= p->motion_val[1][xy][1];

            d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 16, 2, 0, cmpf, chroma_cmpf, flags);

        }else

            s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTRA;

    }

    return d;

}


void *checkasm_check_func(void *func, const char *name, ...)

{

    char name_buf[256];

    void *ref = func;

    CheckasmFuncVersion *v;

    int name_length;

    va_list arg;

    va_start(arg, name);

    name_length = vsnprintf(name_buf, sizeof(name_buf), name, arg);

    va_end(arg);

    if (!func || name_length <= 0 || name_length >= sizeof(name_buf))

        return NULL;

    state.current_func = get_func(name_buf, name_length);

    v = &state.current_func->versions;

    if (v->func) {

        CheckasmFuncVersion *prev;

        do {

            /* Only test functions that haven't already been tested */

            if (v->func == func)

                return NULL;

            if (v->ok)

                ref = v->func;

            prev = v;

        } while ((v = v->next));

        v = prev->next = checkasm_malloc(sizeof(CheckasmFuncVersion));

    }

    v->func = func;

    v->ok = 1;

    v->cpu = state.cpu_flag;

    state.current_func_ver = v;

    if (state.cpu_flag)

        state.num_checked++;

    return ref;

}


void ff_dsputil_init_mmx(DSPContext *c, AVCodecContext *avctx)

{

    int mm_flags = av_get_cpu_flags();

    if (mm_flags & AV_CPU_FLAG_MMX) {

#if HAVE_INLINE_ASM

        const int idct_algo = avctx->idct_algo;

        if (avctx->bits_per_raw_sample <= 8) {

            if (idct_algo == FF_IDCT_AUTO || idct_algo == FF_IDCT_SIMPLEMMX) {

                c->idct_put              = ff_simple_idct_put_mmx;

                c->idct_add              = ff_simple_idct_add_mmx;

                c->idct                  = ff_simple_idct_mmx;

                c->idct_permutation_type = FF_SIMPLE_IDCT_PERM;

            } else if (idct_algo == FF_IDCT_CAVS) {

                    c->idct_permutation_type = FF_TRANSPOSE_IDCT_PERM;

            } else if (idct_algo == FF_IDCT_XVIDMMX) {

                if (mm_flags & AV_CPU_FLAG_SSE2) {

                    c->idct_put              = ff_idct_xvid_sse2_put;

                    c->idct_add              = ff_idct_xvid_sse2_add;

                    c->idct                  = ff_idct_xvid_sse2;

                    c->idct_permutation_type = FF_SSE2_IDCT_PERM;

                } else if (mm_flags & AV_CPU_FLAG_MMXEXT) {

                    c->idct_put              = ff_idct_xvid_mmx2_put;

                    c->idct_add              = ff_idct_xvid_mmx2_add;

                    c->idct                  = ff_idct_xvid_mmx2;

                } else {

                    c->idct_put              = ff_idct_xvid_mmx_put;

                    c->idct_add              = ff_idct_xvid_mmx_add;

                    c->idct                  = ff_idct_xvid_mmx;

                }

            }

        }

#endif /* HAVE_INLINE_ASM */

        dsputil_init_mmx(c, avctx, mm_flags);

    }

    if (mm_flags & AV_CPU_FLAG_MMXEXT)

        dsputil_init_mmx2(c, avctx, mm_flags);

    if (mm_flags & AV_CPU_FLAG_3DNOW && HAVE_AMD3DNOW)

        dsputil_init_3dnow(c, avctx, mm_flags);

    if (mm_flags & AV_CPU_FLAG_3DNOWEXT && HAVE_AMD3DNOWEXT)

        dsputil_init_3dnowext(c, avctx, mm_flags);

    if (mm_flags & AV_CPU_FLAG_SSE && HAVE_SSE)

        dsputil_init_sse(c, avctx, mm_flags);

    if (mm_flags & AV_CPU_FLAG_SSE2)

        dsputil_init_sse2(c, avctx, mm_flags);

    if (mm_flags & AV_CPU_FLAG_SSSE3)

        dsputil_init_ssse3(c, avctx, mm_flags);

    if (mm_flags & AV_CPU_FLAG_SSE4 && HAVE_SSE)

        dsputil_init_sse4(c, avctx, mm_flags);

    if (mm_flags & AV_CPU_FLAG_AVX)

        dsputil_init_avx(c, avctx, mm_flags);

    if (CONFIG_ENCODERS)

        ff_dsputilenc_init_mmx(c, avctx);

}


QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)

{

    char host[65], port[33], width[8], height[8];

    int pos;

    const char *p;

    QemuOpts *opts;

    Error *local_err = NULL;

    opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);

    if (local_err) {

        error_report_err(local_err);

        return NULL;

    }

    if (strstart(filename, "mon:", &p)) {

        filename = p;

        qemu_opt_set(opts, "mux", "on", &error_abort);

        if (strcmp(filename, "stdio") == 0) {

            /* Monitor is muxed to stdio: do not exit on Ctrl+C by default

             * but pass it to the guest.  Handle this only for compat syntax,

             * for -chardev syntax we have special option for this.

             * This is what -nographic did, redirecting+muxing serial+monitor

             * to stdio causing Ctrl+C to be passed to guest. */

            qemu_opt_set(opts, "signal", "off", &error_abort);

        }

    }

    if (strcmp(filename, "null")    == 0 ||

        strcmp(filename, "pty")     == 0 ||

        strcmp(filename, "msmouse") == 0 ||

        strcmp(filename, "braille") == 0 ||

        strcmp(filename, "testdev") == 0 ||

        strcmp(filename, "stdio")   == 0) {

        qemu_opt_set(opts, "backend", filename, &error_abort);

        return opts;

    }

    if (strstart(filename, "vc", &p)) {

        qemu_opt_set(opts, "backend", "vc", &error_abort);

        if (*p == ':') {

            if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {

                /* pixels */

                qemu_opt_set(opts, "width", width, &error_abort);

                qemu_opt_set(opts, "height", height, &error_abort);

            } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {

                /* chars */

                qemu_opt_set(opts, "cols", width, &error_abort);

                qemu_opt_set(opts, "rows", height, &error_abort);

            } else {

                goto fail;

            }

        }

        return opts;

    }

    if (strcmp(filename, "con:") == 0) {

        qemu_opt_set(opts, "backend", "console", &error_abort);

        return opts;

    }

    if (strstart(filename, "COM", NULL)) {

        qemu_opt_set(opts, "backend", "serial", &error_abort);

        qemu_opt_set(opts, "path", filename, &error_abort);

        return opts;

    }

    if (strstart(filename, "file:", &p)) {

        qemu_opt_set(opts, "backend", "file", &error_abort);

        qemu_opt_set(opts, "path", p, &error_abort);

        return opts;

    }

    if (strstart(filename, "pipe:", &p)) {

        qemu_opt_set(opts, "backend", "pipe", &error_abort);

        qemu_opt_set(opts, "path", p, &error_abort);

        return opts;

    }

    if (strstart(filename, "tcp:", &p) ||

        strstart(filename, "telnet:", &p)) {

        if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {

            host[0] = 0;

            if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)

                goto fail;

        }

        qemu_opt_set(opts, "backend", "socket", &error_abort);

        qemu_opt_set(opts, "host", host, &error_abort);

        qemu_opt_set(opts, "port", port, &error_abort);

        if (p[pos] == ',') {

            if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)

                goto fail;

        }

        if (strstart(filename, "telnet:", &p))

            qemu_opt_set(opts, "telnet", "on", &error_abort);

        return opts;

    }

    if (strstart(filename, "udp:", &p)) {

        qemu_opt_set(opts, "backend", "udp", &error_abort);

        if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {

            host[0] = 0;

            if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {

                goto fail;

            }

        }

        qemu_opt_set(opts, "host", host, &error_abort);

        qemu_opt_set(opts, "port", port, &error_abort);

        if (p[pos] == '@') {

            p += pos + 1;

            if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {

                host[0] = 0;

                if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {

                    goto fail;

                }

            }

            qemu_opt_set(opts, "localaddr", host, &error_abort);

            qemu_opt_set(opts, "localport", port, &error_abort);

        }

        return opts;

    }

    if (strstart(filename, "unix:", &p)) {

        qemu_opt_set(opts, "backend", "socket", &error_abort);

        if (qemu_opts_do_parse(opts, p, "path") != 0)

            goto fail;

        return opts;

    }

    if (strstart(filename, "/dev/parport", NULL) ||

        strstart(filename, "/dev/ppi", NULL)) {

        qemu_opt_set(opts, "backend", "parport", &error_abort);

        qemu_opt_set(opts, "path", filename, &error_abort);

        return opts;

    }

    if (strstart(filename, "/dev/", NULL)) {

        qemu_opt_set(opts, "backend", "tty", &error_abort);

        qemu_opt_set(opts, "path", filename, &error_abort);

        return opts;

    }

fail:

    qemu_opts_del(opts);

    return NULL;

}


static int check_refcounts_l1(BlockDriverState *bs,

                              BdrvCheckResult *res,

                              uint16_t *refcount_table,

                              int refcount_table_size,

                              int64_t l1_table_offset, int l1_size,

                              int check_copied)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t *l1_table, l2_offset, l1_size2;

    int i, refcount, ret;

    l1_size2 = l1_size * sizeof(uint64_t);

    /* Mark L1 table as used */

    inc_refcounts(bs, res, refcount_table, refcount_table_size,

        l1_table_offset, l1_size2);

    /* Read L1 table entries from disk */

    if (l1_size2 == 0) {

        l1_table = NULL;

    } else {

        l1_table = g_malloc(l1_size2);

        if (bdrv_pread(bs->file, l1_table_offset,

                       l1_table, l1_size2) != l1_size2)

            goto fail;

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

            be64_to_cpus(&l1_table[i]);

    }

    /* Do the actual checks */

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

        l2_offset = l1_table[i];

        if (l2_offset) {

            /* QCOW_OFLAG_COPIED must be set iff refcount == 1 */

            if (check_copied) {

                refcount = get_refcount(bs, (l2_offset & ~QCOW_OFLAG_COPIED)

                    >> s->cluster_bits);

                if (refcount < 0) {

                    fprintf(stderr, "Can't get refcount for l2_offset %"

                        PRIx64 ": %s\n", l2_offset, strerror(-refcount));

                    goto fail;

                }

                if ((refcount == 1) != ((l2_offset & QCOW_OFLAG_COPIED) != 0)) {

                    fprintf(stderr, "ERROR OFLAG_COPIED: l2_offset=%" PRIx64

                        " refcount=%d\n", l2_offset, refcount);

                    res->corruptions++;

                }

            }

            /* Mark L2 table as used */

            l2_offset &= ~QCOW_OFLAG_COPIED;

            inc_refcounts(bs, res, refcount_table, refcount_table_size,

                l2_offset, s->cluster_size);

            /* L2 tables are cluster aligned */

            if (l2_offset & (s->cluster_size - 1)) {

                fprintf(stderr, "ERROR l2_offset=%" PRIx64 ": Table is not "

                    "cluster aligned; L1 entry corrupted\n", l2_offset);

                res->corruptions++;

            }

            /* Process and check L2 entries */

            ret = check_refcounts_l2(bs, res, refcount_table,

                refcount_table_size, l2_offset, check_copied);

            if (ret < 0) {

                goto fail;

            }

        }

    }

    g_free(l1_table);

    return 0;

fail:

    fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");

    res->check_errors++;

    g_free(l1_table);

    return -EIO;

}


static always_inline void gen_qemu_lds (TCGv t0, TCGv t1, int flags)

{

    TCGv tmp = tcg_temp_new(TCG_TYPE_I32);

    tcg_gen_qemu_ld32u(tmp, t1, flags);

    tcg_gen_helper_1_1(helper_memory_to_s, t0, tmp);

    tcg_temp_free(tmp);

}


static void pmac_ide_flush(DBDMA_io *io)

{

    MACIOIDEState *m = io->opaque;

    if (m->aiocb) {

        bdrv_drain_all();

    }

}


static void socket_start_outgoing_migration(MigrationState *s,

                                            SocketAddress *saddr,

                                            Error **errp)

{

    QIOChannelSocket *sioc = qio_channel_socket_new();

    struct SocketConnectData *data = g_new0(struct SocketConnectData, 1);

    data->s = s;

    if (saddr->type == SOCKET_ADDRESS_KIND_INET) {

        data->hostname = g_strdup(saddr->u.inet.data->host);

    }

    qio_channel_set_name(QIO_CHANNEL(sioc), "migration-socket-outgoing");

    qio_channel_socket_connect_async(sioc,

                                     saddr,

                                     socket_outgoing_migration,

                                     data,

                                     socket_connect_data_free);

    qapi_free_SocketAddress(saddr);

}


void qio_dns_resolver_lookup_async(QIODNSResolver *resolver,

                                   SocketAddressLegacy *addr,

                                   QIOTaskFunc func,

                                   gpointer opaque,

                                   GDestroyNotify notify)

{

    QIOTask *task;

    struct QIODNSResolverLookupData *data =

        g_new0(struct QIODNSResolverLookupData, 1);

    data->addr = QAPI_CLONE(SocketAddressLegacy, addr);

    task = qio_task_new(OBJECT(resolver), func, opaque, notify);

    qio_task_run_in_thread(task,

                           qio_dns_resolver_lookup_worker,

                           data,

                           qio_dns_resolver_lookup_data_free);

}


int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                          AVPacket *avpkt)

{

    AVFrame     *frame = data;

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    MJpegDecodeContext *s = avctx->priv_data;

    const uint8_t *buf_end, *buf_ptr;

    const uint8_t *unescaped_buf_ptr;

    int hshift, vshift;

    int unescaped_buf_size;

    int start_code;

    int i, index;

    int ret = 0;

    av_dict_free(&s->exif_metadata);

    av_freep(&s->stereo3d);

    buf_ptr = buf;

    buf_end = buf + buf_size;

    while (buf_ptr < buf_end) {

        /* find start next marker */

        start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,

                                          &unescaped_buf_ptr,

                                          &unescaped_buf_size);

        /* EOF */

        if (start_code < 0) {

            break;

        } else if (unescaped_buf_size > INT_MAX / 8) {

            av_log(avctx, AV_LOG_ERROR,

                   "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",

                   start_code, unescaped_buf_size, buf_size);

            return AVERROR_INVALIDDATA;

        }

        av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",

               start_code, buf_end - buf_ptr);

        ret = init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "invalid buffer\n");

            goto fail;

        }

        s->start_code = start_code;

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

            av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);

        /* process markers */

        if (start_code >= 0xd0 && start_code <= 0xd7)

            av_log(avctx, AV_LOG_DEBUG,

                   "restart marker: %d\n", start_code & 0x0f);

            /* APP fields */

        else if (start_code >= APP0 && start_code <= APP15)

            mjpeg_decode_app(s);

            /* Comment */

        else if (start_code == COM)

            mjpeg_decode_com(s);

        ret = -1;

        if (!CONFIG_JPEGLS_DECODER &&

            (start_code == SOF48 || start_code == LSE)) {

            av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");

            return AVERROR(ENOSYS);

        }

        switch (start_code) {

        case SOI:

            s->restart_interval = 0;

            s->restart_count    = 0;

            /* nothing to do on SOI */

            break;

        case DQT:

            ff_mjpeg_decode_dqt(s);

            break;

        case DHT:

            if ((ret = ff_mjpeg_decode_dht(s)) < 0) {

                av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");

                goto fail;

            }

            break;

        case SOF0:

        case SOF1:

            s->lossless    = 0;

            s->ls          = 0;

            s->progressive = 0;

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

                goto fail;

            break;

        case SOF2:

            s->lossless    = 0;

            s->ls          = 0;

            s->progressive = 1;

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

                goto fail;

            break;

        case SOF3:

            s->lossless    = 1;

            s->ls          = 0;

            s->progressive = 0;

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

                goto fail;

            break;

        case SOF48:

            s->lossless    = 1;

            s->ls          = 1;

            s->progressive = 0;

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

                goto fail;

            break;

        case LSE:

            if (!CONFIG_JPEGLS_DECODER ||

                (ret = ff_jpegls_decode_lse(s)) < 0)

                goto fail;

            break;

        case EOI:

eoi_parser:

            s->cur_scan = 0;

            if (!s->got_picture) {

                av_log(avctx, AV_LOG_WARNING,

                       "Found EOI before any SOF, ignoring\n");

                break;

            }

            if (s->interlaced) {

                s->bottom_field ^= 1;

                /* if not bottom field, do not output image yet */

                if (s->bottom_field == !s->interlace_polarity)

                    break;

            }

            if ((ret = av_frame_ref(frame, s->picture_ptr)) < 0)

                return ret;

            *got_frame = 1;

            s->got_picture = 0;

            if (!s->lossless) {

                int qp = FFMAX3(s->qscale[0],

                                s->qscale[1],

                                s->qscale[2]);

                int qpw = (s->width + 15) / 16;

                AVBufferRef *qp_table_buf = av_buffer_alloc(qpw);

                if (qp_table_buf) {

                    memset(qp_table_buf->data, qp, qpw);

                    av_frame_set_qp_table(data, qp_table_buf, 0, FF_QSCALE_TYPE_MPEG1);

                }

                if(avctx->debug & FF_DEBUG_QP)

                    av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);

            }

            goto the_end;

        case SOS:

            s->cur_scan++;

            if ((ret = ff_mjpeg_decode_sos(s, NULL, 0, NULL)) < 0 &&

                (avctx->err_recognition & AV_EF_EXPLODE))

                goto fail;

            break;

        case DRI:

            mjpeg_decode_dri(s);

            break;

        case SOF5:

        case SOF6:

        case SOF7:

        case SOF9:

        case SOF10:

        case SOF11:

        case SOF13:

        case SOF14:

        case SOF15:

        case JPG:

            av_log(avctx, AV_LOG_ERROR,

                   "mjpeg: unsupported coding type (%x)\n", start_code);

            break;

        }

        /* eof process start code */

        buf_ptr += (get_bits_count(&s->gb) + 7) / 8;

        av_log(avctx, AV_LOG_DEBUG,

               "marker parser used %d bytes (%d bits)\n",

               (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));

    }

    if (s->got_picture && s->cur_scan) {

        av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");

        goto eoi_parser;

    }

    av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");

    return AVERROR_INVALIDDATA;

fail:

    s->got_picture = 0;

    return ret;

the_end:

    if (s->upscale_h) {

        uint8_t *line = s->picture_ptr->data[s->upscale_h];

        av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV440P);

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

            for (index = s->width - 1; index; index--)

                line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;

            line += s->linesize[s->upscale_h];

        }

    }

    if (s->upscale_v) {

        uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];

        int w;

        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);

        w = s->width >> hshift;

        av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV422P);

        for (i = s->height - 1; i; i--) {

            uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];

            uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];

            if (src1 == src2) {

                memcpy(dst, src1, w);

            } else {

                for (index = 0; index < w; index++)

                    dst[index] = (src1[index] + src2[index]) >> 1;

            }

            dst -= s->linesize[s->upscale_v];

        }

    }

    if (s->flipped) {

        int j;

        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);

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

            uint8_t *dst = s->picture_ptr->data[index];

            int w = s->picture_ptr->width;

            int h = s->picture_ptr->height;

            if(index && index<3){

                w = FF_CEIL_RSHIFT(w, hshift);

                h = FF_CEIL_RSHIFT(h, vshift);

            }

            if(dst){

                uint8_t *dst2 = dst + s->linesize[index]*(h-1);

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

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

                        FFSWAP(int, dst[j], dst2[j]);

                    dst  += s->linesize[index];

                    dst2 -= s->linesize[index];

                }

            }

        }

    }

    if (s->stereo3d) {

        AVStereo3D *stereo = av_stereo3d_create_side_data(data);

        if (stereo) {

            stereo->type  = s->stereo3d->type;

            stereo->flags = s->stereo3d->flags;

        }

        av_freep(&s->stereo3d);

    }

    av_dict_copy(avpriv_frame_get_metadatap(data), s->exif_metadata, 0);

    av_dict_free(&s->exif_metadata);

    av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",

           buf_end - buf_ptr);

//  return buf_end - buf_ptr;

    return buf_ptr - buf;

}


void hpet_init(qemu_irq *irq) {

    int i, iomemtype;

    HPETState *s;

    dprintf ("hpet_init\n");

    s = qemu_mallocz(sizeof(HPETState));

    hpet_statep = s;

    s->irqs = irq;

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

        HPETTimer *timer = &s->timer[i];

        timer->qemu_timer = qemu_new_timer(vm_clock, hpet_timer, timer);

    }

    hpet_reset(s);

    vmstate_register(-1, &vmstate_hpet, s);

    qemu_register_reset(hpet_reset, s);

    /* HPET Area */

    iomemtype = cpu_register_io_memory(hpet_ram_read,

                                       hpet_ram_write, s);

    cpu_register_physical_memory(HPET_BASE, 0x400, iomemtype);

}


static void x86_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    X86CPU *cpu = X86_CPU(obj);

    X86CPUClass *xcc = X86_CPU_GET_CLASS(obj);

    CPUX86State *env = &cpu->env;

    FeatureWord w;

    cs->env_ptr = env;

    cpu_exec_init(cs, &error_abort);

    object_property_add(obj, "family", "int",

                        x86_cpuid_version_get_family,

                        x86_cpuid_version_set_family, NULL, NULL, NULL);

    object_property_add(obj, "model", "int",

                        x86_cpuid_version_get_model,

                        x86_cpuid_version_set_model, NULL, NULL, NULL);

    object_property_add(obj, "stepping", "int",

                        x86_cpuid_version_get_stepping,

                        x86_cpuid_version_set_stepping, NULL, NULL, NULL);

    object_property_add_str(obj, "vendor",

                            x86_cpuid_get_vendor,

                            x86_cpuid_set_vendor, NULL);

    object_property_add_str(obj, "model-id",

                            x86_cpuid_get_model_id,

                            x86_cpuid_set_model_id, NULL);

    object_property_add(obj, "tsc-frequency", "int",

                        x86_cpuid_get_tsc_freq,

                        x86_cpuid_set_tsc_freq, NULL, NULL, NULL);

    object_property_add(obj, "apic-id", "int",

                        x86_cpuid_get_apic_id,

                        x86_cpuid_set_apic_id, NULL, NULL, NULL);

    object_property_add(obj, "feature-words", "X86CPUFeatureWordInfo",

                        x86_cpu_get_feature_words,

                        NULL, NULL, (void *)env->features, NULL);

    object_property_add(obj, "filtered-features", "X86CPUFeatureWordInfo",

                        x86_cpu_get_feature_words,

                        NULL, NULL, (void *)cpu->filtered_features, NULL);

    cpu->hyperv_spinlock_attempts = HYPERV_SPINLOCK_NEVER_RETRY;

#ifndef CONFIG_USER_ONLY

    /* Any code creating new X86CPU objects have to set apic-id explicitly */

    cpu->apic_id = -1;

#endif

    for (w = 0; w < FEATURE_WORDS; w++) {

        int bitnr;

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

            x86_cpu_register_feature_bit_props(cpu, w, bitnr);

        }

    }

    x86_cpu_load_def(cpu, xcc->cpu_def, &error_abort);

}


build_dsdt(GArray *table_data, GArray *linker, VirtGuestInfo *guest_info)

{

    Aml *scope, *dsdt;

    const MemMapEntry *memmap = guest_info->memmap;

    const int *irqmap = guest_info->irqmap;

    dsdt = init_aml_allocator();

    /* Reserve space for header */

    acpi_data_push(dsdt->buf, sizeof(AcpiTableHeader));

    /* When booting the VM with UEFI, UEFI takes ownership of the RTC hardware.

     * While UEFI can use libfdt to disable the RTC device node in the DTB that

     * it passes to the OS, it cannot modify AML. Therefore, we won't generate

     * the RTC ACPI device at all when using UEFI.

     */

    scope = aml_scope("\\_SB");

    acpi_dsdt_add_cpus(scope, guest_info->smp_cpus);

    acpi_dsdt_add_uart(scope, &memmap[VIRT_UART],

                       (irqmap[VIRT_UART] + ARM_SPI_BASE));

    acpi_dsdt_add_flash(scope, &memmap[VIRT_FLASH]);

    acpi_dsdt_add_virtio(scope, &memmap[VIRT_MMIO],

                    (irqmap[VIRT_MMIO] + ARM_SPI_BASE), NUM_VIRTIO_TRANSPORTS);

    acpi_dsdt_add_pci(scope, memmap, (irqmap[VIRT_PCIE] + ARM_SPI_BASE),

                      guest_info->use_highmem);

    acpi_dsdt_add_gpio(scope, &memmap[VIRT_GPIO],

                       (irqmap[VIRT_GPIO] + ARM_SPI_BASE));

    acpi_dsdt_add_power_button(scope);

    aml_append(dsdt, scope);

    /* copy AML table into ACPI tables blob and patch header there */

    g_array_append_vals(table_data, dsdt->buf->data, dsdt->buf->len);

    build_header(linker, table_data,

        (void *)(table_data->data + table_data->len - dsdt->buf->len),

        "DSDT", dsdt->buf->len, 2, NULL);

    free_aml_allocator();

}


static int lag_decode_frame(AVCodecContext *avctx,

                            void *data, int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    unsigned int buf_size = avpkt->size;

    LagarithContext *l = avctx->priv_data;

    ThreadFrame frame = { .f = data };

    AVFrame *const p  = data;

    uint8_t frametype = 0;

    uint32_t offset_gu = 0, offset_bv = 0, offset_ry = 9;

    uint32_t offs[4];

    uint8_t *srcs[4], *dst;

    int i, j, planes = 3;

    int ret;

    p->key_frame = 1;

    frametype = buf[0];

    offset_gu = AV_RL32(buf + 1);

    offset_bv = AV_RL32(buf + 5);

    switch (frametype) {

    case FRAME_SOLID_RGBA:

        avctx->pix_fmt = AV_PIX_FMT_RGB32;

    case FRAME_SOLID_GRAY:

        if (frametype == FRAME_SOLID_GRAY)

            if (avctx->bits_per_coded_sample == 24) {

                avctx->pix_fmt = AV_PIX_FMT_RGB24;

            } else {

                avctx->pix_fmt = AV_PIX_FMT_0RGB32;

                planes = 4;

            }

        if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)

            return ret;

        dst = p->data[0];

        if (frametype == FRAME_SOLID_RGBA) {

        for (j = 0; j < avctx->height; j++) {

            for (i = 0; i < avctx->width; i++)

                AV_WN32(dst + i * 4, offset_gu);

            dst += p->linesize[0];

        }

        } else {

            for (j = 0; j < avctx->height; j++) {

                memset(dst, buf[1], avctx->width * planes);

                dst += p->linesize[0];

            }

        }

        break;

    case FRAME_SOLID_COLOR:

        if (avctx->bits_per_coded_sample == 24) {

            avctx->pix_fmt = AV_PIX_FMT_RGB24;

        } else {

            avctx->pix_fmt = AV_PIX_FMT_RGB32;

            offset_gu |= 0xFFU << 24;

        }

        if ((ret = ff_thread_get_buffer(avctx, &frame,0)) < 0)

            return ret;

        dst = p->data[0];

        for (j = 0; j < avctx->height; j++) {

            for (i = 0; i < avctx->width; i++)

                if (avctx->bits_per_coded_sample == 24) {

                    AV_WB24(dst + i * 3, offset_gu);

                } else {

                    AV_WN32(dst + i * 4, offset_gu);

                }

            dst += p->linesize[0];

        }

        break;

    case FRAME_ARITH_RGBA:

        avctx->pix_fmt = AV_PIX_FMT_RGB32;

        planes = 4;

        offset_ry += 4;

        offs[3] = AV_RL32(buf + 9);

    case FRAME_ARITH_RGB24:

    case FRAME_U_RGB24:

        if (frametype == FRAME_ARITH_RGB24 || frametype == FRAME_U_RGB24)

            avctx->pix_fmt = AV_PIX_FMT_RGB24;

        if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)

            return ret;

        offs[0] = offset_bv;

        offs[1] = offset_gu;

        offs[2] = offset_ry;

        l->rgb_stride = FFALIGN(avctx->width, 16);

        av_fast_malloc(&l->rgb_planes, &l->rgb_planes_allocated,

                       l->rgb_stride * avctx->height * planes + 1);

        if (!l->rgb_planes) {

            av_log(avctx, AV_LOG_ERROR, "cannot allocate temporary buffer\n");

            return AVERROR(ENOMEM);

        }

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

            srcs[i] = l->rgb_planes + (i + 1) * l->rgb_stride * avctx->height - l->rgb_stride;

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

            if (buf_size <= offs[i]) {

                av_log(avctx, AV_LOG_ERROR,

                        "Invalid frame offsets\n");

                return AVERROR_INVALIDDATA;

            }

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

            lag_decode_arith_plane(l, srcs[i],

                                   avctx->width, avctx->height,

                                   -l->rgb_stride, buf + offs[i],

                                   buf_size - offs[i]);

        dst = p->data[0];

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

            srcs[i] = l->rgb_planes + i * l->rgb_stride * avctx->height;

        for (j = 0; j < avctx->height; j++) {

            for (i = 0; i < avctx->width; i++) {

                uint8_t r, g, b, a;

                r = srcs[0][i];

                g = srcs[1][i];

                b = srcs[2][i];

                r += g;

                b += g;

                if (frametype == FRAME_ARITH_RGBA) {

                    a = srcs[3][i];

                    AV_WN32(dst + i * 4, MKBETAG(a, r, g, b));

                } else {

                    dst[i * 3 + 0] = r;

                    dst[i * 3 + 1] = g;

                    dst[i * 3 + 2] = b;

                }

            }

            dst += p->linesize[0];

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

                srcs[i] += l->rgb_stride;

        }

        break;

    case FRAME_ARITH_YUY2:

        avctx->pix_fmt = AV_PIX_FMT_YUV422P;

        if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)

            return ret;

        if (offset_ry >= buf_size ||

            offset_gu >= buf_size ||

            offset_bv >= buf_size) {

            av_log(avctx, AV_LOG_ERROR,

                   "Invalid frame offsets\n");

            return AVERROR_INVALIDDATA;

        }

        lag_decode_arith_plane(l, p->data[0], avctx->width, avctx->height,

                               p->linesize[0], buf + offset_ry,

                               buf_size - offset_ry);

        lag_decode_arith_plane(l, p->data[1], avctx->width / 2,

                               avctx->height, p->linesize[1],

                               buf + offset_gu, buf_size - offset_gu);

        lag_decode_arith_plane(l, p->data[2], avctx->width / 2,

                               avctx->height, p->linesize[2],

                               buf + offset_bv, buf_size - offset_bv);

        break;

    case FRAME_ARITH_YV12:

        avctx->pix_fmt = AV_PIX_FMT_YUV420P;

        if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)

            return ret;

        if (buf_size <= offset_ry || buf_size <= offset_gu || buf_size <= offset_bv) {

            return AVERROR_INVALIDDATA;

        }

        if (offset_ry >= buf_size ||

            offset_gu >= buf_size ||

            offset_bv >= buf_size) {

            av_log(avctx, AV_LOG_ERROR,

                   "Invalid frame offsets\n");

            return AVERROR_INVALIDDATA;

        }

        lag_decode_arith_plane(l, p->data[0], avctx->width, avctx->height,

                               p->linesize[0], buf + offset_ry,

                               buf_size - offset_ry);

        lag_decode_arith_plane(l, p->data[2], avctx->width / 2,

                               avctx->height / 2, p->linesize[2],

                               buf + offset_gu, buf_size - offset_gu);

        lag_decode_arith_plane(l, p->data[1], avctx->width / 2,

                               avctx->height / 2, p->linesize[1],

                               buf + offset_bv, buf_size - offset_bv);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR,

               "Unsupported Lagarith frame type: %#"PRIx8"\n", frametype);

        return AVERROR_PATCHWELCOME;

    }

    *got_frame = 1;

    return buf_size;

}


static int line_in_init (HWVoiceIn *hw, struct audsettings *as)

{

    SpiceVoiceIn *in = container_of (hw, SpiceVoiceIn, hw);

    struct audsettings settings;

#if SPICE_INTERFACE_RECORD_MAJOR > 2 || SPICE_INTERFACE_RECORD_MINOR >= 3

    settings.freq       = spice_server_get_best_record_rate(NULL);

#else

    settings.freq       = SPICE_INTERFACE_RECORD_FREQ;

#endif

    settings.nchannels  = SPICE_INTERFACE_RECORD_CHAN;

    settings.fmt        = AUD_FMT_S16;

    settings.endianness = AUDIO_HOST_ENDIANNESS;

    audio_pcm_init_info (&hw->info, &settings);

    hw->samples = LINE_IN_SAMPLES;

    in->active = 0;

    in->sin.base.sif = &record_sif.base;

    qemu_spice_add_interface (&in->sin.base);

#if SPICE_INTERFACE_RECORD_MAJOR > 2 || SPICE_INTERFACE_RECORD_MINOR >= 3

    spice_server_set_record_rate(&in->sin, settings.freq);

#endif

    return 0;

}


static void virtio_queue_guest_notifier_read(EventNotifier *n)

{

    VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);

    if (event_notifier_test_and_clear(n)) {

        virtio_irq(vq);

    }

}


int spapr_tce_dma_zero(VIOsPAPRDevice *dev, uint64_t taddr, uint32_t size)

{

    /* FIXME: allocating a temp buffer is nasty, but just stepping

     * through writing zeroes is awkward.  This will do for now. */

    uint8_t zeroes[size];

#ifdef DEBUG_TCE

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

            (unsigned long long)taddr, size);

#endif

    memset(zeroes, 0, size);

    return spapr_tce_dma_write(dev, taddr, zeroes, size);

}


static void do_video_out(AVFormatContext *s,

                         AVOutputStream *ost,

                         AVInputStream *ist,

                         AVPicture *picture1)

{

    int n1, n2, nb, i, ret, frame_number;

    AVPicture *picture, *picture2, *pict;

    AVPicture picture_tmp1, picture_tmp2;

    UINT8 video_buffer[128*1024];

    UINT8 *buf = NULL, *buf1 = NULL;

    AVCodecContext *enc, *dec;

    enc = &ost->st->codec;

    dec = &ist->st->codec;

    frame_number = ist->frame_number;

    /* first drop frame if needed */

    n1 = ((INT64)frame_number * enc->frame_rate) / dec->frame_rate;

    n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec->frame_rate;

    nb = n2 - n1;

    if (nb <= 0)

        return;

    /* deinterlace : must be done before any resize */

    if (do_deinterlace) {

        int size;

        /* create temporary picture */

        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);

        buf1 = malloc(size);

        if (!buf1)

            return;

        picture2 = &picture_tmp2;

        avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);

        if (avpicture_deinterlace(picture2, picture1,

                                  dec->pix_fmt, dec->width, dec->height) < 0) {

            /* if error, do not deinterlace */

            free(buf1);

            buf1 = NULL;

            picture2 = picture1;

        }

    } else {

        picture2 = picture1;

    }

    /* convert pixel format if needed */

    if (enc->pix_fmt != dec->pix_fmt) {

        int size;

        /* create temporary picture */

        size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);

        buf = malloc(size);

        if (!buf)

            return;

        pict = &picture_tmp1;

        avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);

        if (img_convert(pict, enc->pix_fmt,

                        picture2, dec->pix_fmt,

                        dec->width, dec->height) < 0) {

            fprintf(stderr, "pixel format conversion not handled\n");

            goto the_end;

        }

    } else {

        pict = picture2;

    }

    /* XXX: resampling could be done before raw format convertion in

       some cases to go faster */

    /* XXX: only works for YUV420P */

    if (ost->video_resample) {

        picture = &ost->pict_tmp;

        img_resample(ost->img_resample_ctx, picture, pict);

    } else {

        picture = pict;

    }

    /* duplicates frame if needed */

    /* XXX: pb because no interleaving */

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

        if (enc->codec_id != CODEC_ID_RAWVIDEO) {

            /* handles sameq here. This is not correct because it may

               not be a global option */

            if (same_quality) {

                enc->quality = dec->quality;

            }

            ret = avcodec_encode_video(enc,

                                       video_buffer, sizeof(video_buffer),

                                       picture);

            s->format->write_packet(s, ost->index, video_buffer, ret);

        } else {

            write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);

        }

    }

    the_end:

    if (buf)

        free(buf);

    if (buf1)

        free(buf1);

}


static void test_visitor_in_fuzz(TestInputVisitorData *data,

                                 const void *unused)

{

    int64_t ires;

    bool bres;

    double nres;

    char *sres;

    EnumOne eres;

    Error *errp = NULL;

    Visitor *v;

    unsigned int i;

    char buf[10000];

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

        unsigned int j;

        j = g_test_rand_int_range(0, sizeof(buf) - 1);

        buf[j] = '\0';

        if (j != 0) {

            for (j--; j != 0; j--) {

                buf[j - 1] = (char)g_test_rand_int_range(0, 256);

            }

        }

        v = visitor_input_test_init(data, buf);

        visit_type_int(v, &ires, NULL, &errp);

        v = visitor_input_test_init(data, buf);

        visit_type_bool(v, &bres, NULL, &errp);

        visitor_input_teardown(data, NULL);

        v = visitor_input_test_init(data, buf);

        visit_type_number(v, &nres, NULL, &errp);

        v = visitor_input_test_init(data, buf);

        visit_type_str(v, &sres, NULL, &errp);

        g_free(sres);

        v = visitor_input_test_init(data, buf);

        visit_type_EnumOne(v, &eres, NULL, &errp);

        visitor_input_teardown(data, NULL);

    }

}