static void pci_info_device(PCIBus *bus, PCIDevice *d)

{

    Monitor *mon = cur_mon;

    int i, class;

    PCIIORegion *r;

    const pci_class_desc *desc;

    monitor_printf(mon, "  Bus %2d, device %3d, function %d:\n",

                   pci_bus_num(d->bus),

                   PCI_SLOT(d->devfn), PCI_FUNC(d->devfn));

    class = pci_get_word(d->config + PCI_CLASS_DEVICE);

    monitor_printf(mon, "    ");

    desc = pci_class_descriptions;

    while (desc->desc && class != desc->class)

        desc++;

    if (desc->desc) {

        monitor_printf(mon, "%s", desc->desc);

    } else {

        monitor_printf(mon, "Class %04x", class);

    }

    monitor_printf(mon, ": PCI device %04x:%04x\n",

           pci_get_word(d->config + PCI_VENDOR_ID),

           pci_get_word(d->config + PCI_DEVICE_ID));

    if (d->config[PCI_INTERRUPT_PIN] != 0) {

        monitor_printf(mon, "      IRQ %d.\n",

                       d->config[PCI_INTERRUPT_LINE]);

    }

    if (class == 0x0604) {

        uint64_t base;

        uint64_t limit;

        monitor_printf(mon, "      BUS %d.\n", d->config[0x19]);

        monitor_printf(mon, "      secondary bus %d.\n",

                       d->config[PCI_SECONDARY_BUS]);

        monitor_printf(mon, "      subordinate bus %d.\n",

                       d->config[PCI_SUBORDINATE_BUS]);

        base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_IO);

        limit = pci_bridge_get_limit(d, PCI_BASE_ADDRESS_SPACE_IO);

        monitor_printf(mon, "      IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",

                       base, limit);

        base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_MEMORY);

        limit= pci_config_get_memory_base(d, PCI_BASE_ADDRESS_SPACE_MEMORY);

        monitor_printf(mon,

                       "      memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",

                       base, limit);

        base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_MEMORY |

                                   PCI_BASE_ADDRESS_MEM_PREFETCH);

        limit = pci_bridge_get_limit(d, PCI_BASE_ADDRESS_SPACE_MEMORY |

                                     PCI_BASE_ADDRESS_MEM_PREFETCH);

        monitor_printf(mon, "      prefetchable memory range "

                       "[0x%08"PRIx64", 0x%08"PRIx64"]\n", base, limit);

    }

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

        r = &d->io_regions[i];

        if (r->size != 0) {

            monitor_printf(mon, "      BAR%d: ", i);

            if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {

                monitor_printf(mon, "I/O at 0x%04"FMT_PCIBUS

                               " [0x%04"FMT_PCIBUS"].\n",

                               r->addr, r->addr + r->size - 1);

            } else {

                const char *type = r->type & PCI_BASE_ADDRESS_MEM_TYPE_64 ?

                    "64 bit" : "32 bit";

                const char *prefetch =

                    r->type & PCI_BASE_ADDRESS_MEM_PREFETCH ?

                    " prefetchable" : "";

                monitor_printf(mon, "%s%s memory at 0x%08"FMT_PCIBUS

                               " [0x%08"FMT_PCIBUS"].\n",

                               type, prefetch,

                               r->addr, r->addr + r->size - 1);

            }

        }

    }

    monitor_printf(mon, "      id \"%s\"\n", d->qdev.id ? d->qdev.id : "");

    if (class == 0x0604 && d->config[0x19] != 0) {

        pci_for_each_device(bus, d->config[0x19], pci_info_device);

    }

}


int av_write_frame(AVFormatContext *s, AVPacket *pkt)

{

    int ret;

    compute_pkt_fields2(s->streams[pkt->stream_index], pkt);

    truncate_ts(s->streams[pkt->stream_index], pkt);

    ret= s->oformat->write_packet(s, pkt);

    if(!ret)

        ret= url_ferror(&s->pb);

    return ret;

}


static void revert_cdlms(WmallDecodeCtx *s, int tile_size)

{

    int icoef, ich;

    int32_t pred, channel_coeff;

    int ilms, num_lms;

    for (ich = 0; ich < s->num_channels; ich++) {

        if (!s->is_channel_coded[ich])

            continue;

        for (icoef = 0; icoef < tile_size; icoef++) {

            num_lms = s->cdlms_ttl[ich];

            channel_coeff = s->channel_residues[ich][icoef];

            if (icoef == s->transient_pos[ich]) {

                s->transient[ich] = 1;

                use_high_update_speed(s, ich);

            }

            for (ilms = num_lms; ilms >= 0; ilms--) {

                pred = lms_predict(s, ich, ilms);

                channel_coeff += pred;

                lms_update(s, ich, ilms, channel_coeff, pred);

            }

            if (s->transient[ich]) {

                --s->channel[ich].transient_counter;

                if(!s->channel[ich].transient_counter)

                    use_normal_update_speed(s, ich);

            }

            s->channel_coeffs[ich][icoef] = channel_coeff;

        }

    }

}


static void decode_mb_b(AVSContext *h, enum cavs_mb mb_type) {

    int block;

    enum cavs_sub_mb sub_type[4];

    int flags;

    ff_cavs_init_mb(h);

    /* reset all MVs */

    h->mv[MV_FWD_X0] = ff_cavs_dir_mv;

    set_mvs(&h->mv[MV_FWD_X0], BLK_16X16);

    h->mv[MV_BWD_X0] = ff_cavs_dir_mv;

    set_mvs(&h->mv[MV_BWD_X0], BLK_16X16);

    switch(mb_type) {

    case B_SKIP:

    case B_DIRECT:

        if(!h->col_type_base[h->mbidx]) {

            /* intra MB at co-location, do in-plane prediction */

            ff_cavs_mv(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_BSKIP, BLK_16X16, 1);

            ff_cavs_mv(h, MV_BWD_X0, MV_BWD_C2, MV_PRED_BSKIP, BLK_16X16, 0);

        } else

            /* direct prediction from co-located P MB, block-wise */

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

                mv_pred_direct(h,&h->mv[mv_scan[block]],

                                 &h->col_mv[h->mbidx*4 + block]);

        break;

    case B_FWD_16X16:

        ff_cavs_mv(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_MEDIAN, BLK_16X16, 1);

        break;

    case B_SYM_16X16:

        ff_cavs_mv(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_MEDIAN, BLK_16X16, 1);

        mv_pred_sym(h, &h->mv[MV_FWD_X0], BLK_16X16);

        break;

    case B_BWD_16X16:

        ff_cavs_mv(h, MV_BWD_X0, MV_BWD_C2, MV_PRED_MEDIAN, BLK_16X16, 0);

        break;

    case B_8X8:

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

            sub_type[block] = get_bits(&h->s.gb,2);

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

            switch(sub_type[block]) {

            case B_SUB_DIRECT:

                if(!h->col_type_base[h->mbidx]) {

                    /* intra MB at co-location, do in-plane prediction */

                    ff_cavs_mv(h, mv_scan[block], mv_scan[block]-3,

                            MV_PRED_BSKIP, BLK_8X8, 1);

                    ff_cavs_mv(h, mv_scan[block]+MV_BWD_OFFS,

                            mv_scan[block]-3+MV_BWD_OFFS,

                            MV_PRED_BSKIP, BLK_8X8, 0);

                } else

                    mv_pred_direct(h,&h->mv[mv_scan[block]],

                                   &h->col_mv[h->mbidx*4 + block]);

                break;

            case B_SUB_FWD:

                ff_cavs_mv(h, mv_scan[block], mv_scan[block]-3,

                        MV_PRED_MEDIAN, BLK_8X8, 1);

                break;

            case B_SUB_SYM:

                ff_cavs_mv(h, mv_scan[block], mv_scan[block]-3,

                        MV_PRED_MEDIAN, BLK_8X8, 1);

                mv_pred_sym(h, &h->mv[mv_scan[block]], BLK_8X8);

                break;

            }

        }

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

            if(sub_type[block] == B_SUB_BWD)

                ff_cavs_mv(h, mv_scan[block]+MV_BWD_OFFS,

                        mv_scan[block]+MV_BWD_OFFS-3,

                        MV_PRED_MEDIAN, BLK_8X8, 0);

        }

        break;

    default:

        av_assert2((mb_type > B_SYM_16X16) && (mb_type < B_8X8));

        flags = ff_cavs_partition_flags[mb_type];

        if(mb_type & 1) { /* 16x8 macroblock types */

            if(flags & FWD0)

                ff_cavs_mv(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_TOP,  BLK_16X8, 1);

            if(flags & SYM0)

                mv_pred_sym(h, &h->mv[MV_FWD_X0], BLK_16X8);

            if(flags & FWD1)

                ff_cavs_mv(h, MV_FWD_X2, MV_FWD_A1, MV_PRED_LEFT, BLK_16X8, 1);

            if(flags & SYM1)

                mv_pred_sym(h, &h->mv[MV_FWD_X2], BLK_16X8);

            if(flags & BWD0)

                ff_cavs_mv(h, MV_BWD_X0, MV_BWD_C2, MV_PRED_TOP,  BLK_16X8, 0);

            if(flags & BWD1)

                ff_cavs_mv(h, MV_BWD_X2, MV_BWD_A1, MV_PRED_LEFT, BLK_16X8, 0);

        } else {          /* 8x16 macroblock types */

            if(flags & FWD0)

                ff_cavs_mv(h, MV_FWD_X0, MV_FWD_B3, MV_PRED_LEFT, BLK_8X16, 1);

            if(flags & SYM0)

                mv_pred_sym(h, &h->mv[MV_FWD_X0], BLK_8X16);

            if(flags & FWD1)

                ff_cavs_mv(h,MV_FWD_X1,MV_FWD_C2,MV_PRED_TOPRIGHT,BLK_8X16,1);

            if(flags & SYM1)

                mv_pred_sym(h, &h->mv[MV_FWD_X1], BLK_8X16);

            if(flags & BWD0)

                ff_cavs_mv(h, MV_BWD_X0, MV_BWD_B3, MV_PRED_LEFT, BLK_8X16, 0);

            if(flags & BWD1)

                ff_cavs_mv(h,MV_BWD_X1,MV_BWD_C2,MV_PRED_TOPRIGHT,BLK_8X16,0);

        }

    }

    ff_cavs_inter(h, mb_type);

    set_intra_mode_default(h);

    if(mb_type != B_SKIP)

        decode_residual_inter(h);

    ff_cavs_filter(h,mb_type);

}


static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)

{

    AVFrame *decoded_frame;

    AVCodecContext *avctx = ist->st->codec;

    int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);

    int i, ret;

    if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))

        return AVERROR(ENOMEM);

    else

        avcodec_get_frame_defaults(ist->decoded_frame);

    decoded_frame = ist->decoded_frame;

    ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);

    if (ret < 0) {

        return ret;

    }

    if (!*got_output) {

        /* no audio frame */

        return ret;

    }

    /* if the decoder provides a pts, use it instead of the last packet pts.

       the decoder could be delaying output by a packet or more. */

    if (decoded_frame->pts != AV_NOPTS_VALUE)

        ist->next_dts = decoded_frame->pts;

    /* increment next_dts to use for the case where the input stream does not

       have timestamps or there are multiple frames in the packet */

    ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /

                     avctx->sample_rate;

    // preprocess audio (volume)

    if (audio_volume != 256) {

        int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;

        void *samples = decoded_frame->data[0];

        switch (avctx->sample_fmt) {

        case AV_SAMPLE_FMT_U8:

        {

            uint8_t *volp = samples;

            for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;

                *volp++ = av_clip_uint8(v);

            }

            break;

        }

        case AV_SAMPLE_FMT_S16:

        {

            int16_t *volp = samples;

            for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                int v = ((*volp) * audio_volume + 128) >> 8;

                *volp++ = av_clip_int16(v);

            }

            break;

        }

        case AV_SAMPLE_FMT_S32:

        {

            int32_t *volp = samples;

            for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);

                *volp++ = av_clipl_int32(v);

            }

            break;

        }

        case AV_SAMPLE_FMT_FLT:

        {

            float *volp = samples;

            float scale = audio_volume / 256.f;

            for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                *volp++ *= scale;

            }

            break;

        }

        case AV_SAMPLE_FMT_DBL:

        {

            double *volp = samples;

            double scale = audio_volume / 256.;

            for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                *volp++ *= scale;

            }

            break;

        }

        default:

            av_log(NULL, AV_LOG_FATAL,

                   "Audio volume adjustment on sample format %s is not supported.\n",

                   av_get_sample_fmt_name(ist->st->codec->sample_fmt));

            exit_program(1);

        }

    }

    rate_emu_sleep(ist);

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

        OutputStream *ost = output_streams[i];

        if (!check_output_constraints(ist, ost) || !ost->encoding_needed)

            continue;

        do_audio_out(output_files[ost->file_index]->ctx, ost, ist, decoded_frame);

    }

    return ret;

}


static inline void store_cpu_offset(TCGv var, int offset)

{

    tcg_gen_st_i32(var, cpu_env, offset);

    dead_tmp(var);

}


static void test_cipher_speed(const void *opaque)

{

    QCryptoCipher *cipher;

    Error *err = NULL;

    double total = 0.0;

    size_t chunk_size = (size_t)opaque;

    uint8_t *key = NULL, *iv = NULL;

    uint8_t *plaintext = NULL, *ciphertext = NULL;

    size_t nkey = qcrypto_cipher_get_key_len(QCRYPTO_CIPHER_ALG_AES_128);

    size_t niv = qcrypto_cipher_get_iv_len(QCRYPTO_CIPHER_ALG_AES_128,

                                           QCRYPTO_CIPHER_MODE_CBC);

    key = g_new0(uint8_t, nkey);

    memset(key, g_test_rand_int(), nkey);

    iv = g_new0(uint8_t, niv);

    memset(iv, g_test_rand_int(), niv);

    ciphertext = g_new0(uint8_t, chunk_size);

    plaintext = g_new0(uint8_t, chunk_size);

    memset(plaintext, g_test_rand_int(), chunk_size);

    cipher = qcrypto_cipher_new(QCRYPTO_CIPHER_ALG_AES_128,

                                QCRYPTO_CIPHER_MODE_CBC,

                                key, nkey, &err);

    g_assert(cipher != NULL);

    g_assert(qcrypto_cipher_setiv(cipher,

                                  iv, niv,

                                  &err) == 0);

    g_test_timer_start();

    do {

        g_assert(qcrypto_cipher_encrypt(cipher,

                                        plaintext,

                                        ciphertext,

                                        chunk_size,

                                        &err) == 0);

        total += chunk_size;

    } while (g_test_timer_elapsed() < 5.0);

    total /= 1024 * 1024; /* to MB */

    g_print("cbc(aes128): ");

    g_print("Testing chunk_size %ld bytes ", chunk_size);

    g_print("done: %.2f MB in %.2f secs: ", total, g_test_timer_last());

    g_print("%.2f MB/sec\n", total / g_test_timer_last());

    qcrypto_cipher_free(cipher);

    g_free(plaintext);

    g_free(ciphertext);

    g_free(iv);

    g_free(key);

}


static void s390_init(ram_addr_t my_ram_size,
                      const char *boot_device,
                      const char *kernel_filename,
                      const char *kernel_cmdline,
                      const char *initrd_filename,
                      const char *cpu_model)
{
    CPUState *env = NULL;
    MemoryRegion *sysmem = get_system_memory();
    MemoryRegion *ram = g_new(MemoryRegion, 1);
    ram_addr_t kernel_size = 0;
    ram_addr_t initrd_offset;
    ram_addr_t initrd_size = 0;
    int shift = 0;
    uint8_t *storage_keys;
    void *virtio_region;
    target_phys_addr_t virtio_region_len;
    target_phys_addr_t virtio_region_start;
    int i;
    /* s390x ram size detection needs a 16bit multiplier + an increment. So
       guests > 64GB can be specified in 2MB steps etc. */
    while ((my_ram_size >> (20 + shift)) > 65535) {
        shift++;
    }
    my_ram_size = my_ram_size >> (20 + shift) << (20 + shift);
    /* lets propagate the changed ram size into the global variable. */
    ram_size = my_ram_size;
    /* get a BUS */
    s390_bus = s390_virtio_bus_init(&my_ram_size);
    /* allocate RAM */
    memory_region_init_ram(ram, NULL, "s390.ram", my_ram_size);
    memory_region_add_subregion(sysmem, 0, ram);
    /* allocate storage keys */
    storage_keys = g_malloc0(my_ram_size / TARGET_PAGE_SIZE);
    /* init CPUs */
    if (cpu_model == NULL) {
        cpu_model = "host";
    }
    ipi_states = g_malloc(sizeof(CPUState *) * smp_cpus);
    for (i = 0; i < smp_cpus; i++) {
        CPUState *tmp_env;
        tmp_env = cpu_init(cpu_model);
        if (!env) {
            env = tmp_env;
        }
        ipi_states[i] = tmp_env;
        tmp_env->halted = 1;
        tmp_env->exception_index = EXCP_HLT;
        tmp_env->storage_keys = storage_keys;
    }
    /* One CPU has to run */
    s390_add_running_cpu(env);
    if (kernel_filename) {
        kernel_size = load_image(kernel_filename, qemu_get_ram_ptr(0));
        if (lduw_be_phys(KERN_IMAGE_START) != 0x0dd0) {
            fprintf(stderr, "Specified image is not an s390 boot image\n");
            exit(1);
        }
        env->psw.addr = KERN_IMAGE_START;
        env->psw.mask = 0x0000000180000000ULL;
    } else {
        ram_addr_t bios_size = 0;
        char *bios_filename;
        /* Load zipl bootloader */
        if (bios_name == NULL) {
            bios_name = ZIPL_FILENAME;
        }
        bios_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
        bios_size = load_image(bios_filename, qemu_get_ram_ptr(ZIPL_LOAD_ADDR));
        g_free(bios_filename);
        if ((long)bios_size < 0) {
            hw_error("could not load bootloader '%s'\n", bios_name);
        }
        if (bios_size > 4096) {
            hw_error("stage1 bootloader is > 4k\n");
        }
        env->psw.addr = ZIPL_START;
        env->psw.mask = 0x0000000180000000ULL;
    }
    if (initrd_filename) {
        initrd_offset = INITRD_START;
        while (kernel_size + 0x100000 > initrd_offset) {
            initrd_offset += 0x100000;
        }
        initrd_size = load_image(initrd_filename, qemu_get_ram_ptr(initrd_offset));
        stq_be_phys(INITRD_PARM_START, initrd_offset);
        stq_be_phys(INITRD_PARM_SIZE, initrd_size);
    }
    if (kernel_cmdline) {
        cpu_physical_memory_write(KERN_PARM_AREA, kernel_cmdline,
                                  strlen(kernel_cmdline) + 1);
    }
    /* Create VirtIO network adapters */
    for(i = 0; i < nb_nics; i++) {
        NICInfo *nd = &nd_table[i];
        DeviceState *dev;
        if (!nd->model) {
            nd->model = g_strdup("virtio");
        }
        if (strcmp(nd->model, "virtio")) {
            fprintf(stderr, "S390 only supports VirtIO nics\n");
            exit(1);
        }
        dev = qdev_create((BusState *)s390_bus, "virtio-net-s390");
        qdev_set_nic_properties(dev, nd);
        qdev_init_nofail(dev);
    }
    /* Create VirtIO disk drives */
    for(i = 0; i < MAX_BLK_DEVS; i++) {
        DriveInfo *dinfo;
        DeviceState *dev;
        dinfo = drive_get(IF_IDE, 0, i);
        if (!dinfo) {
            continue;
        }
        dev = qdev_create((BusState *)s390_bus, "virtio-blk-s390");
        qdev_prop_set_drive_nofail(dev, "drive", dinfo->bdrv);
        qdev_init_nofail(dev);
    }
}


void host_to_target_siginfo(target_siginfo_t *tinfo, const siginfo_t *info)

{

    host_to_target_siginfo_noswap(tinfo, info);

    tswap_siginfo(tinfo, tinfo);

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = ioapic_common_realize;

    dc->vmsd = &vmstate_ioapic_common;

    dc->no_user = 1;

}


uint64_t helper_cmpbge(uint64_t op1, uint64_t op2)

{

#if defined(__SSE2__)

    uint64_t r;

    /* The cmpbge instruction is heavily used in the implementation of

       every string function on Alpha.  We can do much better than either

       the default loop below, or even an unrolled version by using the

       native vector support.  */

    {

        typedef uint64_t Q __attribute__((vector_size(16)));

        typedef uint8_t B __attribute__((vector_size(16)));

        Q q1 = (Q){ op1, 0 };

        Q q2 = (Q){ op2, 0 };

        q1 = (Q)((B)q1 >= (B)q2);

        r = q1[0];

    }

    /* Select only one bit from each byte.  */

    r &= 0x0101010101010101;

    /* Collect the bits into the bottom byte.  */

    /* .......A.......B.......C.......D.......E.......F.......G.......H */

    r |= r >> (8 - 1);

    /* .......A......AB......BC......CD......DE......EF......FG......GH */

    r |= r >> (16 - 2);

    /* .......A......AB.....ABC....ABCD....BCDE....CDEF....DEFG....EFGH */

    r |= r >> (32 - 4);

    /* .......A......AB.....ABC....ABCD...ABCDE..ABCDEF.ABCDEFGABCDEFGH */

    /* Return only the low 8 bits.  */

    return r & 0xff;

#else

    uint8_t opa, opb, res;

    int i;

    res = 0;

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

        opa = op1 >> (i * 8);

        opb = op2 >> (i * 8);

        if (opa >= opb) {

            res |= 1 << i;

        }

    }

    return res;

#endif

}


int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,

                                int bytes, BdrvRequestFlags flags)

{

    NBDClientSession *client = nbd_get_client_session(bs);

    NBDRequest request = {

        .type = NBD_CMD_WRITE_ZEROES,

        .from = offset,

        .len = bytes,

    };

    if (!(client->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {

        return -ENOTSUP;

    }

    if (flags & BDRV_REQ_FUA) {

        assert(client->info.flags & NBD_FLAG_SEND_FUA);

        request.flags |= NBD_CMD_FLAG_FUA;

    }

    if (!(flags & BDRV_REQ_MAY_UNMAP)) {

        request.flags |= NBD_CMD_FLAG_NO_HOLE;

    }

    return nbd_co_request(bs, &request, NULL);

}


static uint32_t get_cmd(ESPState *s, uint8_t *buf)

{

    uint32_t dmalen;

    int target;

    dmalen = s->rregs[ESP_TCLO] | (s->rregs[ESP_TCMID] << 8);

    target = s->wregs[ESP_WBUSID] & 7;

    DPRINTF("get_cmd: len %d target %d\n", dmalen, target);

    if (s->dma) {

        s->dma_memory_read(s->dma_opaque, buf, dmalen);

    } else {

        buf[0] = 0;

        memcpy(&buf[1], s->ti_buf, dmalen);

        dmalen++;

    }

    s->ti_size = 0;

    s->ti_rptr = 0;

    s->ti_wptr = 0;

    if (s->current_dev) {

        /* Started a new command before the old one finished.  Cancel it.  */

        s->current_dev->cancel_io(s->current_dev, 0);

        s->async_len = 0;

    }

    if (target >= ESP_MAX_DEVS || !s->scsi_dev[target]) {

        // No such drive

        s->rregs[ESP_RSTAT] = 0;

        s->rregs[ESP_RINTR] = INTR_DC;

        s->rregs[ESP_RSEQ] = SEQ_0;

        esp_raise_irq(s);

        return 0;

    }

    s->current_dev = s->scsi_dev[target];

    return dmalen;

}


static int opt_preset(const char *opt, const char *arg)

{

    FILE *f=NULL;

    char tmp[1000], tmp2[1000], line[1000];

    int i;

    const char *base[3]= { getenv("HOME"),

                           "/usr/local/share",

                           "/usr/share",

                         };

    for(i=!base[0]; i<3 && !f; i++){

        snprintf(tmp, sizeof(tmp), "%s/%sffmpeg/%s.ffpreset", base[i], i ? "" : ".", arg);

        f= fopen(tmp, "r");

        if(!f){

            char *codec_name= *opt == 'v' ? video_codec_name :

                              *opt == 'a' ? audio_codec_name :

                                            subtitle_codec_name;

              snprintf(tmp, sizeof(tmp), "%s/%sffmpeg/%s-%s.ffpreset", base[i],  i ? "" : ".", codec_name, arg);

            f= fopen(tmp, "r");

        }

    }

    if(!f && ((arg[0]=='.' && arg[1]=='/') || arg[0]=='/')){

        f= fopen(arg, "r");

    }

    if(!f){

        fprintf(stderr, "Preset file not found\n");

        av_exit(1);

    }

    while(!feof(f)){

        int e= fscanf(f, "%999[^\n]\n", line) - 1;

        if(line[0] == '#' && !e)

            continue;

        e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;

        if(e){

            fprintf(stderr, "Preset file invalid\n");

            av_exit(1);

        }

        if(!strcmp(tmp, "acodec")){

            opt_audio_codec(tmp2);

        }else if(!strcmp(tmp, "vcodec")){

            opt_video_codec(tmp2);

        }else if(!strcmp(tmp, "scodec")){

            opt_subtitle_codec(tmp2);

        }else

            opt_default(tmp, tmp2);

    }

    fclose(f);

    return 0;

}


static USBDevice *usb_msd_init(USBBus *bus, const char *filename)

{

    static int nr=0;

    char id[8];

    QemuOpts *opts;

    DriveInfo *dinfo;

    USBDevice *dev;

    const char *p1;

    char fmt[32];

    /* parse -usbdevice disk: syntax into drive opts */

    snprintf(id, sizeof(id), "usb%d", nr++);

    opts = qemu_opts_create(qemu_find_opts("drive"), id, 0);

    p1 = strchr(filename, ':');

    if (p1++) {

        const char *p2;

        if (strstart(filename, "format=", &p2)) {

            int len = MIN(p1 - p2, sizeof(fmt));

            pstrcpy(fmt, len, p2);

            qemu_opt_set(opts, "format", fmt);

        } else if (*filename != ':') {

            printf("unrecognized USB mass-storage option %s\n", filename);

            return NULL;

        }

        filename = p1;

    }

    if (!*filename) {

        printf("block device specification needed\n");

        return NULL;

    }

    qemu_opt_set(opts, "file", filename);

    qemu_opt_set(opts, "if", "none");

    /* create host drive */

    dinfo = drive_init(opts, 0);

    if (!dinfo) {

        qemu_opts_del(opts);

        return NULL;

    }

    /* create guest device */

    dev = usb_create(bus, "usb-storage");

    if (!dev) {

        return NULL;

    }

    if (qdev_prop_set_drive(&dev->qdev, "drive", dinfo->bdrv) < 0) {

        qdev_free(&dev->qdev);

        return NULL;

    }

    if (qdev_init(&dev->qdev) < 0)

        return NULL;

    return dev;

}


static void codebook_trellis_rate(AACEncContext *s, SingleChannelElement *sce,

                                  int win, int group_len, const float lambda)

{

    BandCodingPath path[120][12];

    int w, swb, cb, start, size;

    int i, j;

    const int max_sfb  = sce->ics.max_sfb;

    const int run_bits = sce->ics.num_windows == 1 ? 5 : 3;

    const int run_esc  = (1 << run_bits) - 1;

    int idx, ppos, count;

    int stackrun[120], stackcb[120], stack_len;

    float next_minbits = INFINITY;

    int next_mincb = 0;

    abs_pow34_v(s->scoefs, sce->coeffs, 1024);

    start = win*128;

    for (cb = 0; cb < 12; cb++) {

        path[0][cb].cost     = run_bits+4;

        path[0][cb].prev_idx = -1;

        path[0][cb].run      = 0;

    }

    for (swb = 0; swb < max_sfb; swb++) {

        size = sce->ics.swb_sizes[swb];

        if (sce->zeroes[win*16 + swb]) {

            float cost_stay_here = path[swb][0].cost;

            float cost_get_here  = next_minbits + run_bits + 4;

            if (   run_value_bits[sce->ics.num_windows == 8][path[swb][0].run]

                != run_value_bits[sce->ics.num_windows == 8][path[swb][0].run+1])

                cost_stay_here += run_bits;

            if (cost_get_here < cost_stay_here) {

                path[swb+1][0].prev_idx = next_mincb;

                path[swb+1][0].cost     = cost_get_here;

                path[swb+1][0].run      = 1;

            } else {

                path[swb+1][0].prev_idx = 0;

                path[swb+1][0].cost     = cost_stay_here;

                path[swb+1][0].run      = path[swb][0].run + 1;

            }

            next_minbits = path[swb+1][0].cost;

            next_mincb = 0;

            for (cb = 1; cb < 12; cb++) {

                path[swb+1][cb].cost = 61450;

                path[swb+1][cb].prev_idx = -1;

                path[swb+1][cb].run = 0;

            }

        } else {

            float minbits = next_minbits;

            int mincb = next_mincb;

            int startcb = sce->band_type[win*16+swb];

            next_minbits = INFINITY;

            next_mincb = 0;

            for (cb = 0; cb < startcb; cb++) {

                path[swb+1][cb].cost = 61450;

                path[swb+1][cb].prev_idx = -1;

                path[swb+1][cb].run = 0;

            }

            for (cb = startcb; cb < 12; cb++) {

                float cost_stay_here, cost_get_here;

                float bits = 0.0f;

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

                    bits += quantize_band_cost(s, sce->coeffs + start + w*128,

                                               s->scoefs + start + w*128, size,

                                               sce->sf_idx[(win+w)*16+swb], cb,

                                               0, INFINITY, NULL);

                }

                cost_stay_here = path[swb][cb].cost + bits;

                cost_get_here  = minbits            + bits + run_bits + 4;

                if (   run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run]

                    != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1])

                    cost_stay_here += run_bits;

                if (cost_get_here < cost_stay_here) {

                    path[swb+1][cb].prev_idx = mincb;

                    path[swb+1][cb].cost     = cost_get_here;

                    path[swb+1][cb].run      = 1;

                } else {

                    path[swb+1][cb].prev_idx = cb;

                    path[swb+1][cb].cost     = cost_stay_here;

                    path[swb+1][cb].run      = path[swb][cb].run + 1;

                }

                if (path[swb+1][cb].cost < next_minbits) {

                    next_minbits = path[swb+1][cb].cost;

                    next_mincb = cb;

                }

            }

        }

        start += sce->ics.swb_sizes[swb];

    }

    //convert resulting path from backward-linked list

    stack_len = 0;

    idx       = 0;

    for (cb = 1; cb < 12; cb++)

        if (path[max_sfb][cb].cost < path[max_sfb][idx].cost)

            idx = cb;

    ppos = max_sfb;

    while (ppos > 0) {

        av_assert1(idx >= 0);

        cb = idx;

        stackrun[stack_len] = path[ppos][cb].run;

        stackcb [stack_len] = cb;

        idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx;

        ppos -= path[ppos][cb].run;

        stack_len++;

    }

    //perform actual band info encoding

    start = 0;

    for (i = stack_len - 1; i >= 0; i--) {

        put_bits(&s->pb, 4, stackcb[i]);

        count = stackrun[i];

        memset(sce->zeroes + win*16 + start, !stackcb[i], count);

        //XXX: memset when band_type is also uint8_t

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

            sce->band_type[win*16 + start] =  stackcb[i];

            start++;

        }

        while (count >= run_esc) {

            put_bits(&s->pb, run_bits, run_esc);

            count -= run_esc;

        }

        put_bits(&s->pb, run_bits, count);

    }

}


av_cold void ff_mlpdsp_init_arm(MLPDSPContext *c)

{

    int cpu_flags = av_get_cpu_flags();

    if (have_armv5te(cpu_flags)) {

        c->mlp_filter_channel = ff_mlp_filter_channel_arm;

    }

}


void slirp_pollfds_poll(GArray *pollfds, int select_error)

{

    Slirp *slirp;

    struct socket *so, *so_next;

    int ret;

    if (QTAILQ_EMPTY(&slirp_instances)) {

        return;

    }

    curtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);

    QTAILQ_FOREACH(slirp, &slirp_instances, entry) {

        /*

         * See if anything has timed out

         */

        if (slirp->time_fasttimo &&

            ((curtime - slirp->time_fasttimo) >= TIMEOUT_FAST)) {

            tcp_fasttimo(slirp);

            slirp->time_fasttimo = 0;

        }

        if (slirp->do_slowtimo &&

            ((curtime - slirp->last_slowtimo) >= TIMEOUT_SLOW)) {

            ip_slowtimo(slirp);

            tcp_slowtimo(slirp);

            slirp->last_slowtimo = curtime;

        }

        /*

         * Check sockets

         */

        if (!select_error) {

            /*

             * Check TCP sockets

             */

            for (so = slirp->tcb.so_next; so != &slirp->tcb;

                    so = so_next) {

                int revents;

                so_next = so->so_next;

                revents = 0;

                if (so->pollfds_idx != -1) {

                    revents = g_array_index(pollfds, GPollFD,

                                            so->pollfds_idx).revents;

                }

                if (so->so_state & SS_NOFDREF || so->s == -1) {

                    continue;

                }

                /*

                 * Check for URG data

                 * This will soread as well, so no need to

                 * test for G_IO_IN below if this succeeds

                 */

                if (revents & G_IO_PRI) {

                    sorecvoob(so);

                }

                /*

                 * Check sockets for reading

                 */

                else if (revents & (G_IO_IN | G_IO_HUP | G_IO_ERR)) {

                    /*

                     * Check for incoming connections

                     */

                    if (so->so_state & SS_FACCEPTCONN) {

                        tcp_connect(so);

                        continue;

                    } /* else */

                    ret = soread(so);

                    /* Output it if we read something */

                    if (ret > 0) {

                        tcp_output(sototcpcb(so));

                    }

                }

                /*

                 * Check sockets for writing

                 */

                if (!(so->so_state & SS_NOFDREF) &&

                        (revents & (G_IO_OUT | G_IO_ERR))) {

                    /*

                     * Check for non-blocking, still-connecting sockets

                     */

                    if (so->so_state & SS_ISFCONNECTING) {

                        /* Connected */

                        so->so_state &= ~SS_ISFCONNECTING;

                        ret = send(so->s, (const void *) &ret, 0, 0);

                        if (ret < 0) {

                            /* XXXXX Must fix, zero bytes is a NOP */

                            if (errno == EAGAIN || errno == EWOULDBLOCK ||

                                errno == EINPROGRESS || errno == ENOTCONN) {

                                continue;

                            }

                            /* else failed */

                            so->so_state &= SS_PERSISTENT_MASK;

                            so->so_state |= SS_NOFDREF;

                        }

                        /* else so->so_state &= ~SS_ISFCONNECTING; */

                        /*

                         * Continue tcp_input

                         */

                        tcp_input((struct mbuf *)NULL, sizeof(struct ip), so,

                                  so->so_ffamily);

                        /* continue; */

                    } else {

                        ret = sowrite(so);

                    }

                    /*

                     * XXXXX If we wrote something (a lot), there

                     * could be a need for a window update.

                     * In the worst case, the remote will send

                     * a window probe to get things going again

                     */

                }

                /*

                 * Probe a still-connecting, non-blocking socket

                 * to check if it's still alive

                 */

#ifdef PROBE_CONN

                if (so->so_state & SS_ISFCONNECTING) {

                    ret = qemu_recv(so->s, &ret, 0, 0);

                    if (ret < 0) {

                        /* XXX */

                        if (errno == EAGAIN || errno == EWOULDBLOCK ||

                            errno == EINPROGRESS || errno == ENOTCONN) {

                            continue; /* Still connecting, continue */

                        }

                        /* else failed */

                        so->so_state &= SS_PERSISTENT_MASK;

                        so->so_state |= SS_NOFDREF;

                        /* tcp_input will take care of it */

                    } else {

                        ret = send(so->s, &ret, 0, 0);

                        if (ret < 0) {

                            /* XXX */

                            if (errno == EAGAIN || errno == EWOULDBLOCK ||

                                errno == EINPROGRESS || errno == ENOTCONN) {

                                continue;

                            }

                            /* else failed */

                            so->so_state &= SS_PERSISTENT_MASK;

                            so->so_state |= SS_NOFDREF;

                        } else {

                            so->so_state &= ~SS_ISFCONNECTING;

                        }

                    }

                    tcp_input((struct mbuf *)NULL, sizeof(struct ip), so,

                              so->so_ffamily);

                } /* SS_ISFCONNECTING */

#endif

            }

            /*

             * Now UDP sockets.

             * Incoming packets are sent straight away, they're not buffered.

             * Incoming UDP data isn't buffered either.

             */

            for (so = slirp->udb.so_next; so != &slirp->udb;

                    so = so_next) {

                int revents;

                so_next = so->so_next;

                revents = 0;

                if (so->pollfds_idx != -1) {

                    revents = g_array_index(pollfds, GPollFD,

                            so->pollfds_idx).revents;

                }

                if (so->s != -1 &&

                    (revents & (G_IO_IN | G_IO_HUP | G_IO_ERR))) {

                    sorecvfrom(so);

                }

            }

            /*

             * Check incoming ICMP relies.

             */

            for (so = slirp->icmp.so_next; so != &slirp->icmp;

                    so = so_next) {

                    int revents;

                    so_next = so->so_next;

                    revents = 0;

                    if (so->pollfds_idx != -1) {

                        revents = g_array_index(pollfds, GPollFD,

                                                so->pollfds_idx).revents;

                    }

                    if (so->s != -1 &&

                        (revents & (G_IO_IN | G_IO_HUP | G_IO_ERR))) {

                    icmp_receive(so);

                }

            }

        }

        if_start(slirp);

    }

}


SwsFunc yuv2rgb_init_mlib(SwsContext *c)

{

	switch(c->dstFormat){

	case PIX_FMT_RGB24: return mlib_YUV2RGB420_24;

	case PIX_FMT_BGR32: return mlib_YUV2ARGB420_32;

	case PIX_FMT_RGB32: return mlib_YUV2ABGR420_32;

	default: return NULL;

	}

}


int ffio_ensure_seekback(AVIOContext *s, int64_t buf_size)

{

    uint8_t *buffer;

    int max_buffer_size = s->max_packet_size ?

                          s->max_packet_size : IO_BUFFER_SIZE;

    int filled = s->buf_end - s->buffer;

    ptrdiff_t checksum_ptr_offset = s->checksum_ptr ? s->checksum_ptr - s->buffer : -1;

    buf_size += s->buf_ptr - s->buffer + max_buffer_size;

    if (buf_size < filled || s->seekable || !s->read_packet)

        return 0;

    av_assert0(!s->write_flag);

    buffer = av_malloc(buf_size);

    if (!buffer)

        return AVERROR(ENOMEM);

    memcpy(buffer, s->buffer, filled);

    av_free(s->buffer);

    s->buf_ptr = buffer + (s->buf_ptr - s->buffer);

    s->buf_end = buffer + (s->buf_end - s->buffer);

    s->buffer = buffer;

    s->buffer_size = buf_size;

    return 0;

}


static void raise_mmu_exception(CPUMIPSState *env, target_ulong address,

                                int rw, int tlb_error)

{

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

    int exception = 0, error_code = 0;

    if (rw == MMU_INST_FETCH) {

        error_code |= EXCP_INST_NOTAVAIL;

    }

    switch (tlb_error) {

    default:

    case TLBRET_BADADDR:

        /* Reference to kernel address from user mode or supervisor mode */

        /* Reference to supervisor address from user mode */

        if (rw == MMU_DATA_STORE) {

            exception = EXCP_AdES;

        } else {

            exception = EXCP_AdEL;

        }

        break;

    case TLBRET_NOMATCH:

        /* No TLB match for a mapped address */

        if (rw == MMU_DATA_STORE) {

            exception = EXCP_TLBS;

        } else {

            exception = EXCP_TLBL;

        }

        error_code |= EXCP_TLB_NOMATCH;

        break;

    case TLBRET_INVALID:

        /* TLB match with no valid bit */

        if (rw == MMU_DATA_STORE) {

            exception = EXCP_TLBS;

        } else {

            exception = EXCP_TLBL;

        }

        break;

    case TLBRET_DIRTY:

        /* TLB match but 'D' bit is cleared */

        exception = EXCP_LTLBL;

        break;

    case TLBRET_XI:

        /* Execute-Inhibit Exception */

        if (env->CP0_PageGrain & (1 << CP0PG_IEC)) {

            exception = EXCP_TLBXI;

        } else {

            exception = EXCP_TLBL;

        }

        break;

    case TLBRET_RI:

        /* Read-Inhibit Exception */

        if (env->CP0_PageGrain & (1 << CP0PG_IEC)) {

            exception = EXCP_TLBRI;

        } else {

            exception = EXCP_TLBL;

        }

        break;

    }

    /* Raise exception */

    env->CP0_BadVAddr = address;

    env->CP0_Context = (env->CP0_Context & ~0x007fffff) |

                       ((address >> 9) & 0x007ffff0);

    env->CP0_EntryHi = (env->CP0_EntryHi & env->CP0_EntryHi_ASID_mask) |

                       (address & (TARGET_PAGE_MASK << 1));

#if defined(TARGET_MIPS64)

    env->CP0_EntryHi &= env->SEGMask;

    env->CP0_XContext =

        /* PTEBase */   (env->CP0_XContext & ((~0ULL) << (env->SEGBITS - 7))) |

        /* R */         (extract64(address, 62, 2) << (env->SEGBITS - 9)) |

        /* BadVPN2 */   (extract64(address, 13, env->SEGBITS - 13) << 4);

#endif

    cs->exception_index = exception;

    env->error_code = error_code;

}


static int decode_frame(WmallDecodeCtx *s)

{

    GetBitContext* gb = &s->gb;

    int more_frames = 0;

    int len = 0;

    int i;

    /** check for potential output buffer overflow */

    if (s->num_channels * s->samples_per_frame > s->samples_end - s->samples) {

        /** return an error if no frame could be decoded at all */

        av_log(s->avctx, AV_LOG_ERROR,

               "not enough space for the output samples\n");

        s->packet_loss = 1;

        return 0;

    }

    /** get frame length */

    if (s->len_prefix)

        len = get_bits(gb, s->log2_frame_size);

    /** decode tile information */

    if (decode_tilehdr(s)) {

        s->packet_loss = 1;

        return 0;

    }

    /** read drc info */

    if (s->dynamic_range_compression) {

        s->drc_gain = get_bits(gb, 8);

    }

    /** no idea what these are for, might be the number of samples

        that need to be skipped at the beginning or end of a stream */

    if (get_bits1(gb)) {

        int skip;

        /** usually true for the first frame */

        if (get_bits1(gb)) {

            skip = get_bits(gb, av_log2(s->samples_per_frame * 2));

            dprintf(s->avctx, "start skip: %i\n", skip);

        }

        /** sometimes true for the last frame */

        if (get_bits1(gb)) {

            skip = get_bits(gb, av_log2(s->samples_per_frame * 2));

            dprintf(s->avctx, "end skip: %i\n", skip);

        }

    }

    /** reset subframe states */

    s->parsed_all_subframes = 0;

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

        s->channel[i].decoded_samples = 0;

        s->channel[i].cur_subframe    = 0;

        s->channel[i].reuse_sf        = 0;

    }

    /** decode all subframes */

    while (!s->parsed_all_subframes) {

        if (decode_subframe(s) < 0) {

            s->packet_loss = 1;

            return 0;

        }

    }

    dprintf(s->avctx, "Frame done\n");

    if (s->skip_frame) {

        s->skip_frame = 0;

    } else

        s->samples += s->num_channels * s->samples_per_frame;

    if (s->len_prefix) {

        if (len != (get_bits_count(gb) - s->frame_offset) + 2) {

            /** FIXME: not sure if this is always an error */

            av_log(s->avctx, AV_LOG_ERROR,

                   "frame[%i] would have to skip %i bits\n", s->frame_num,

                   len - (get_bits_count(gb) - s->frame_offset) - 1);

            s->packet_loss = 1;

            return 0;

        }

        /** skip the rest of the frame data */

        skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);

    } else {

/*

        while (get_bits_count(gb) < s->num_saved_bits && get_bits1(gb) == 0) {

	    dprintf(s->avctx, "skip1\n");

        }

*/

    }

    /** decode trailer bit */

    more_frames = get_bits1(gb);

    ++s->frame_num;

    return more_frames;

}


static void rv34_idct_dc_add_c(uint8_t *dst, int stride, int dc)

{

    const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    int i, j;

    cm += (13*13*dc + 0x200) >> 10;

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

    {

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

            dst[j] = cm[ dst[j] ];

        dst += stride;

    }

}


static void monitor_event(void *opaque, int event)

{

    Monitor *mon = opaque;

    switch (event) {

    case CHR_EVENT_MUX_IN:

        qemu_mutex_lock(&mon->out_lock);

        mon->mux_out = 0;

        qemu_mutex_unlock(&mon->out_lock);

        if (mon->reset_seen) {

            monitor_resume(mon);

            monitor_flush(mon);

        } else {

            mon->suspend_cnt = 0;

        }

        break;

    case CHR_EVENT_MUX_OUT:

        if (mon->reset_seen) {

            if (mon->suspend_cnt == 0) {

                monitor_printf(mon, "\n");

            }

            monitor_flush(mon);

            monitor_suspend(mon);

        } else {

            mon->suspend_cnt++;

        }

        qemu_mutex_lock(&mon->out_lock);

        mon->mux_out = 1;

        qemu_mutex_unlock(&mon->out_lock);

        break;

    case CHR_EVENT_OPENED:

        monitor_printf(mon, "QEMU %s monitor - type 'help' for more "

                       "information\n", QEMU_VERSION);

        if (!mon->mux_out) {

            readline_show_prompt(mon->rs);

        }

        mon->reset_seen = 1;

        mon_refcount++;

        break;

    case CHR_EVENT_CLOSED:

        mon_refcount--;

        monitor_fdsets_cleanup();

        break;

    }

}


static ExitStatus gen_mtpr(DisasContext *ctx, TCGv vb, int regno)

{

    TCGv tmp;

    int data;

    switch (regno) {

    case 255:

        /* TBIA */

        gen_helper_tbia(cpu_env);

        break;

    case 254:

        /* TBIS */

        gen_helper_tbis(cpu_env, vb);

        break;

    case 253:

        /* WAIT */

        tmp = tcg_const_i64(1);

        tcg_gen_st32_i64(tmp, cpu_env, -offsetof(AlphaCPU, env) +

                                       offsetof(CPUState, halted));

        return gen_excp(ctx, EXCP_HALTED, 0);

    case 252:

        /* HALT */

        gen_helper_halt(vb);

        return EXIT_PC_STALE;

    case 251:

        /* ALARM */

        gen_helper_set_alarm(cpu_env, vb);

        break;

    case 7:

        /* PALBR */

        tcg_gen_st_i64(vb, cpu_env, offsetof(CPUAlphaState, palbr));

        /* Changing the PAL base register implies un-chaining all of the TBs

           that ended with a CALL_PAL.  Since the base register usually only

           changes during boot, flushing everything works well.  */

        gen_helper_tb_flush(cpu_env);

        return EXIT_PC_STALE;

    case 32 ... 39:

        /* Accessing the "non-shadow" general registers.  */

        regno = regno == 39 ? 25 : regno - 32 + 8;

        tcg_gen_mov_i64(cpu_std_ir[regno], vb);

        break;

    case 0: /* PS */

        st_flag_byte(vb, ENV_FLAG_PS_SHIFT);

        break;

    case 1: /* FEN */

        st_flag_byte(vb, ENV_FLAG_FEN_SHIFT);

        break;

    default:

        /* The basic registers are data only, and unknown registers

           are read-zero, write-ignore.  */

        data = cpu_pr_data(regno);

        if (data != 0) {

            if (data & PR_LONG) {

                tcg_gen_st32_i64(vb, cpu_env, data & ~PR_LONG);

            } else {

                tcg_gen_st_i64(vb, cpu_env, data);

            }

        }

        break;

    }

    return NO_EXIT;

}


static bool key_is_missing(const BlockInfo *bdev)

{

    return (bdev->inserted && bdev->inserted->encryption_key_missing);

}


static int64_t ivshmem_recv_msg(IVShmemState *s, int *pfd, Error **errp)

{

    int64_t msg;

    int n, ret;

    n = 0;

    do {

        ret = qemu_chr_fe_read_all(&s->server_chr, (uint8_t *)&msg + n,

                                   sizeof(msg) - n);

        if (ret < 0) {

            if (ret == -EINTR) {

                continue;

            }

            error_setg_errno(errp, -ret, "read from server failed");

            return INT64_MIN;

        }

        n += ret;

    } while (n < sizeof(msg));

    *pfd = qemu_chr_fe_get_msgfd(&s->server_chr);

    return msg;

}


static USBDevice *usb_bt_init(USBBus *bus, const char *cmdline)

{

    USBDevice *dev;

    struct USBBtState *s;

    HCIInfo *hci;

    const char *name = "usb-bt-dongle";

    if (*cmdline) {

        hci = hci_init(cmdline);

    } else {

        hci = bt_new_hci(qemu_find_bt_vlan(0));

    }

    if (!hci)

        return NULL;

    dev = usb_create(bus, name);

    s = DO_UPCAST(struct USBBtState, dev, dev);

    s->hci = hci;

    if (qdev_init(&dev->qdev) < 0) {

        error_report("Failed to initialize USB device '%s'", name);

        return NULL;

    }

    return dev;

}


static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)

{

    AVCodecContext *dec;

    AVPicture *picture2;

    AVPicture picture_tmp;

    uint8_t *buf = 0;

    dec = ist->st->codec;

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

    if (FF_API_DEINTERLACE && do_deinterlace) {

        int size;

        /* create temporary picture */

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

        if (size < 0)

            return;

        buf  = av_malloc(size);

        if (!buf)

            return;

        picture2 = &picture_tmp;

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

        if (avpicture_deinterlace(picture2, picture,

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

            /* if error, do not deinterlace */

            av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");

            av_free(buf);

            buf = NULL;

            picture2 = picture;

        }

    } else {

        picture2 = picture;

    }

    if (picture != picture2)

        *picture = *picture2;

    *bufp = buf;

}


static int vc1_decode_p_mb_intfi(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    GetBitContext *gb = &s->gb;

    int i;

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

    int cbp = 0; /* cbp decoding stuff */

    int mqdiff, mquant; /* MB quantization */

    int ttmb = v->ttfrm; /* MB Transform type */

    int mb_has_coeffs = 1; /* last_flag */

    int dmv_x, dmv_y; /* Differential MV components */

    int val; /* temp values */

    int first_block = 1;

    int dst_idx, off;

    int pred_flag = 0;

    int block_cbp = 0, pat, block_tt = 0;

    int idx_mbmode = 0;

    mquant = v->pq; /* Lossy initialization */

    idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_IF_MBMODE_VLC_BITS, 2);

    if (idx_mbmode <= 1) { // intra MB

        v->is_intra[s->mb_x] = 0x3f; // Set the bitfield to all 1.

        s->mb_intra          = 1;

        s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][0] = 0;

        s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][1] = 0;

        s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_INTRA;

        GET_MQUANT();

        s->current_picture.qscale_table[mb_pos] = mquant;

        /* Set DC scale - y and c use the same (not sure if necessary here) */

        s->y_dc_scale = s->y_dc_scale_table[mquant];

        s->c_dc_scale = s->c_dc_scale_table[mquant];

        v->s.ac_pred  = v->acpred_plane[mb_pos] = get_bits1(gb);

        mb_has_coeffs = idx_mbmode & 1;

        if (mb_has_coeffs)

            cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_ICBPCY_VLC_BITS, 2);

        dst_idx = 0;

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

            v->a_avail = v->c_avail          = 0;

            v->mb_type[0][s->block_index[i]] = 1;

            s->dc_val[0][s->block_index[i]]  = 0;

            dst_idx += i >> 2;

            val = ((cbp >> (5 - i)) & 1);

            if (i == 2 || i == 3 || !s->first_slice_line)

                v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];

            if (i == 1 || i == 3 || s->mb_x)

                v->c_avail = v->mb_type[0][s->block_index[i] - 1];

            vc1_decode_intra_block(v, s->block[i], i, val, mquant,

                                   (i & 4) ? v->codingset2 : v->codingset);

            if ((i>3) && (s->flags & CODEC_FLAG_GRAY))

                continue;

            v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);

            off  = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);

            s->idsp.put_signed_pixels_clamped(s->block[i],

                                              s->dest[dst_idx] + off,

                                              (i & 4) ? s->uvlinesize

                                                      : s->linesize);

            // TODO: loop filter

        }

    } else {

        s->mb_intra = v->is_intra[s->mb_x] = 0;

        s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_16x16;

        for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0;

        if (idx_mbmode <= 5) { // 1-MV

            dmv_x = dmv_y = pred_flag = 0;

            if (idx_mbmode & 1) {

                get_mvdata_interlaced(v, &dmv_x, &dmv_y, &pred_flag);

            }

            ff_vc1_pred_mv(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], pred_flag, 0);

            ff_vc1_mc_1mv(v, 0);

            mb_has_coeffs = !(idx_mbmode & 2);

        } else { // 4-MV

            v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);

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

                if (i < 4) {

                    dmv_x = dmv_y = pred_flag = 0;

                    val   = ((v->fourmvbp >> (3 - i)) & 1);

                    if (val) {

                        get_mvdata_interlaced(v, &dmv_x, &dmv_y, &pred_flag);

                    }

                    ff_vc1_pred_mv(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], pred_flag, 0);

                    ff_vc1_mc_4mv_luma(v, i, 0, 0);

                } else if (i == 4)

                    ff_vc1_mc_4mv_chroma(v, 0);

            }

            mb_has_coeffs = idx_mbmode & 1;

        }

        if (mb_has_coeffs)

            cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

        if (cbp) {

            GET_MQUANT();

        }

        s->current_picture.qscale_table[mb_pos] = mquant;

        if (!v->ttmbf && cbp) {

            ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);

        }

        dst_idx = 0;

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

            s->dc_val[0][s->block_index[i]] = 0;

            dst_idx += i >> 2;

            val = ((cbp >> (5 - i)) & 1);

            off = (i & 4) ? 0 : (i & 1) * 8 + (i & 2) * 4 * s->linesize;

            if (val) {

                pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,

                                         first_block, s->dest[dst_idx] + off,

                                         (i & 4) ? s->uvlinesize : s->linesize,

                                         (i & 4) && (s->flags & CODEC_FLAG_GRAY),

                                         &block_tt);

                block_cbp |= pat << (i << 2);

                if (!v->ttmbf && ttmb < 8) ttmb = -1;

                first_block = 0;

            }

        }

    }

    if (s->mb_x == s->mb_width - 1)

        memmove(v->is_intra_base, v->is_intra, sizeof(v->is_intra_base[0]) * s->mb_stride);

    return 0;

}


static bool virtio_scsi_data_plane_handle_ctrl(VirtIODevice *vdev,

                                               VirtQueue *vq)

{

    VirtIOSCSI *s = VIRTIO_SCSI(vdev);

    assert(s->ctx && s->dataplane_started);

    return virtio_scsi_handle_ctrl_vq(s, vq);

}


static void start_tcg_kick_timer(void)

{

    if (!tcg_kick_vcpu_timer && CPU_NEXT(first_cpu)) {

        tcg_kick_vcpu_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,

                                           kick_tcg_thread, NULL);

        timer_mod(tcg_kick_vcpu_timer, qemu_tcg_next_kick());

    }

}


static void rtc_periodic_timer(void *opaque)

{

    RTCState *s = opaque;

    rtc_timer_update(s, s->next_periodic_time);

#ifdef TARGET_I386

    if ((s->cmos_data[RTC_REG_C] & 0xc0) && rtc_td_hack) {

        s->irq_coalesced++;

        return;

    }

#endif

    if (s->cmos_data[RTC_REG_B] & REG_B_PIE) {

        s->cmos_data[RTC_REG_C] |= 0xc0;

        rtc_irq_raise(s->irq);

    }

    if (s->cmos_data[RTC_REG_B] & REG_B_SQWE) {

        /* Not square wave at all but we don't want 2048Hz interrupts!

           Must be seen as a pulse.  */

        qemu_irq_raise(s->sqw_irq);

    }

}


void do_m68k_semihosting(CPUM68KState *env, int nr)

{

    uint32_t args;

    void *p;

    void *q;

    uint32_t len;

    uint32_t result;

    args = env->dregs[1];

    switch (nr) {

    case HOSTED_EXIT:

        gdb_exit(env, env->dregs[0]);

        exit(env->dregs[0]);

    case HOSTED_OPEN:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(m68k_semi_cb, "open,%s,%x,%x", ARG(0), (int)ARG(1),

                           ARG(2), ARG(3));

            return;

        } else {

            if (!(p = lock_user_string(ARG(0)))) {

                /* FIXME - check error code? */

                result = -1;

            } else {

                result = open(p, translate_openflags(ARG(2)), ARG(3));

                unlock_user(p, ARG(0), 0);

            }

        }

        break;

    case HOSTED_CLOSE:

        {

            /* Ignore attempts to close stdin/out/err.  */

            int fd = ARG(0);

            if (fd > 2) {

                if (use_gdb_syscalls()) {

                    gdb_do_syscall(m68k_semi_cb, "close,%x", ARG(0));

                    return;

                } else {

                    result = close(fd);

                }

            } else {

                result = 0;

            }

            break;

        }

    case HOSTED_READ:

        len = ARG(2);

        if (use_gdb_syscalls()) {

            gdb_do_syscall(m68k_semi_cb, "read,%x,%x,%x",

                           ARG(0), ARG(1), len);

            return;

        } else {

            if (!(p = lock_user(VERIFY_WRITE, ARG(1), len, 0))) {

                /* FIXME - check error code? */

                result = -1;

            } else {

                result = read(ARG(0), p, len);

                unlock_user(p, ARG(1), len);

            }

        }

        break;

    case HOSTED_WRITE:

        len = ARG(2);

        if (use_gdb_syscalls()) {

            gdb_do_syscall(m68k_semi_cb, "write,%x,%x,%x",

                           ARG(0), ARG(1), len);

            return;

        } else {

            if (!(p = lock_user(VERIFY_READ, ARG(1), len, 1))) {

                /* FIXME - check error code? */

                result = -1;

            } else {

                result = write(ARG(0), p, len);

                unlock_user(p, ARG(0), 0);

            }

        }

        break;

    case HOSTED_LSEEK:

        {

            uint64_t off;

            off = (uint32_t)ARG(2) | ((uint64_t)ARG(1) << 32);

            if (use_gdb_syscalls()) {

                m68k_semi_is_fseek = 1;

                gdb_do_syscall(m68k_semi_cb, "fseek,%x,%lx,%x",

                               ARG(0), off, ARG(3));

            } else {

                off = lseek(ARG(0), off, ARG(3));

                /* FIXME - handle put_user() failure */

                put_user_u32(off >> 32, args);

                put_user_u32(off, args + 4);

                put_user_u32(errno, args + 8);

            }

            return;

        }

    case HOSTED_RENAME:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(m68k_semi_cb, "rename,%s,%s",

                           ARG(0), (int)ARG(1), ARG(2), (int)ARG(3));

            return;

        } else {

            p = lock_user_string(ARG(0));

            q = lock_user_string(ARG(2));

            if (!p || !q) {

                /* FIXME - check error code? */

                result = -1;

            } else {

                result = rename(p, q);

            }

            unlock_user(p, ARG(0), 0);

            unlock_user(q, ARG(2), 0);

        }

        break;

    case HOSTED_UNLINK:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(m68k_semi_cb, "unlink,%s",

                           ARG(0), (int)ARG(1));

            return;

        } else {

            if (!(p = lock_user_string(ARG(0)))) {

                /* FIXME - check error code? */

                result = -1;

            } else {

                result = unlink(p);

                unlock_user(p, ARG(0), 0);

            }

        }

        break;

    case HOSTED_STAT:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(m68k_semi_cb, "stat,%s,%x",

                           ARG(0), (int)ARG(1), ARG(2));

            return;

        } else {

            struct stat s;

            if (!(p = lock_user_string(ARG(0)))) {

                /* FIXME - check error code? */

                result = -1;

            } else {

                result = stat(p, &s);

                unlock_user(p, ARG(0), 0);

            }

            if (result == 0) {

                translate_stat(env, ARG(2), &s);

            }

        }

        break;

    case HOSTED_FSTAT:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(m68k_semi_cb, "fstat,%x,%x",

                           ARG(0), ARG(1));

            return;

        } else {

            struct stat s;

            result = fstat(ARG(0), &s);

            if (result == 0) {

                translate_stat(env, ARG(1), &s);

            }

        }

        break;

    case HOSTED_GETTIMEOFDAY:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(m68k_semi_cb, "gettimeofday,%x,%x",

                           ARG(0), ARG(1));

            return;

        } else {

            qemu_timeval tv;

            struct gdb_timeval *p;

            result = qemu_gettimeofday(&tv);

            if (result != 0) {

                if (!(p = lock_user(VERIFY_WRITE,

                                    ARG(0), sizeof(struct gdb_timeval), 0))) {

                    /* FIXME - check error code? */

                    result = -1;

                } else {

                    p->tv_sec = cpu_to_be32(tv.tv_sec);

                    p->tv_usec = cpu_to_be64(tv.tv_usec);

                    unlock_user(p, ARG(0), sizeof(struct gdb_timeval));

                }

            }

        }

        break;

    case HOSTED_ISATTY:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(m68k_semi_cb, "isatty,%x", ARG(0));

            return;

        } else {

            result = isatty(ARG(0));

        }

        break;

    case HOSTED_SYSTEM:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(m68k_semi_cb, "system,%s",

                           ARG(0), (int)ARG(1));

            return;

        } else {

            if (!(p = lock_user_string(ARG(0)))) {

                /* FIXME - check error code? */

                result = -1;

            } else {

                result = system(p);

                unlock_user(p, ARG(0), 0);

            }

        }

        break;

    case HOSTED_INIT_SIM:

#if defined(CONFIG_USER_ONLY)

        {

        TaskState *ts = env->opaque;

        /* Allocate the heap using sbrk.  */

        if (!ts->heap_limit) {

            long ret;

            uint32_t size;

            uint32_t base;

            base = do_brk(0);

            size = SEMIHOSTING_HEAP_SIZE;

            /* Try a big heap, and reduce the size if that fails.  */

            for (;;) {

                ret = do_brk(base + size);

                if (ret != -1)

                    break;

                size >>= 1;

            }

            ts->heap_limit = base + size;

        }

        /* This call may happen before we have writable memory, so return

           values directly in registers.  */

        env->dregs[1] = ts->heap_limit;

        env->aregs[7] = ts->stack_base;

        }

#else

        /* FIXME: This is wrong for boards where RAM does not start at

           address zero.  */

        env->dregs[1] = ram_size;

        env->aregs[7] = ram_size;

#endif

        return;

    default:

        cpu_abort(env, "Unsupported semihosting syscall %d\n", nr);

        result = 0;

    }

    /* FIXME - handle put_user() failure */

    put_user_u32(result, args);

    put_user_u32(errno, args + 4);

}


static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n)

{

    uint8_t Stlm, ST, SP, tile_tlm, i;

    bytestream_get_byte(&s->buf);               /* Ztlm: skipped */

    Stlm = bytestream_get_byte(&s->buf);

    // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);

    ST = (Stlm >> 4) & 0x03;

    // TODO: Manage case of ST = 0b11 --> raise error

    SP       = (Stlm >> 6) & 0x01;

    tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);

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

        switch (ST) {

        case 0:

            break;

        case 1:

            bytestream_get_byte(&s->buf);

            break;

        case 2:

            bytestream_get_be16(&s->buf);

            break;

        case 3:

            bytestream_get_be32(&s->buf);

            break;

        }

        if (SP == 0) {

            bytestream_get_be16(&s->buf);

        } else {

            bytestream_get_be32(&s->buf);

        }

    }

    return 0;

}


static int decode_seq_header(AVSContext *h) {

    MpegEncContext *s = &h->s;

    int frame_rate_code;

    int width, height;

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

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

    skip_bits1(&s->gb); //progressive sequence

       width =           get_bits(&s->gb,14);

       height =          get_bits(&s->gb,14);

    if ((s->width || s->height) && (s->width != width || s->height != height)) {

        av_log_missing_feature(s, "Width/height changing in CAVS is", 0);

        return -1;

    s->width  = width;

    s->height = height;

    skip_bits(&s->gb,2); //chroma format

    skip_bits(&s->gb,3); //sample_precision

    h->aspect_ratio =    get_bits(&s->gb,4);

    frame_rate_code =    get_bits(&s->gb,4);

    skip_bits(&s->gb,18);//bit_rate_lower

    skip_bits1(&s->gb);  //marker_bit

    skip_bits(&s->gb,12);//bit_rate_upper

    s->low_delay =       get_bits1(&s->gb);

    h->mb_width  = (s->width  + 15) >> 4;

    h->mb_height = (s->height + 15) >> 4;

    h->s.avctx->time_base.den = avpriv_frame_rate_tab[frame_rate_code].num;

    h->s.avctx->time_base.num = avpriv_frame_rate_tab[frame_rate_code].den;

    h->s.avctx->width  = s->width;

    h->s.avctx->height = s->height;

    if(!h->top_qp)

        ff_cavs_init_top_lines(h);

    return 0;


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

{

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

    CharDriverState *chr;

    WinCharState *s;

    chr = g_malloc0(sizeof(CharDriverState));

    s = g_malloc0(sizeof(WinCharState));

    chr->opaque = s;

    chr->chr_write = win_chr_write;

    chr->chr_close = win_chr_close;

    if (win_chr_pipe_init(chr, filename) < 0) {

        g_free(s);

        g_free(chr);

        return -EIO;

    }

    qemu_chr_generic_open(chr);

    *_chr = chr;

    return 0;

}


SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,

                                                         bool has_id,

                                                         const char *id,

                                                         bool has_name,

                                                         const char *name,

                                                         Error **errp)

{

    BlockDriverState *bs = bdrv_find(device);

    QEMUSnapshotInfo sn;

    Error *local_err = NULL;

    SnapshotInfo *info = NULL;

    int ret;

    if (!bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return NULL;

    }

    if (!has_id) {

        id = NULL;

    }

    if (!has_name) {

        name = NULL;

    }

    if (!id && !name) {

        error_setg(errp, "Name or id must be provided");

        return NULL;

    }

    ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return NULL;

    }

    if (!ret) {

        error_setg(errp,

                   "Snapshot with id '%s' and name '%s' does not exist on "

                   "device '%s'",

                   STR_OR_NULL(id), STR_OR_NULL(name), device);

        return NULL;

    }

    bdrv_snapshot_delete(bs, id, name, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return NULL;

    }

    info = g_malloc0(sizeof(SnapshotInfo));

    info->id = g_strdup(sn.id_str);

    info->name = g_strdup(sn.name);

    info->date_nsec = sn.date_nsec;

    info->date_sec = sn.date_sec;

    info->vm_state_size = sn.vm_state_size;

    info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;

    info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;

    return info;

}


static int proxy_socket(const char *path, uid_t uid, gid_t gid)

{

    int sock, client;

    struct sockaddr_un proxy, qemu;

    socklen_t size;

    /* requested socket already exists, refuse to start */

    if (!access(path, F_OK)) {

        do_log(LOG_CRIT, "socket already exists\n");

        return -1;

    }

    sock = socket(AF_UNIX, SOCK_STREAM, 0);

    if (sock < 0) {

        do_perror("socket");

        return -1;

    }

    /* mask other part of mode bits */

    umask(7);

    proxy.sun_family = AF_UNIX;

    strcpy(proxy.sun_path, path);

    if (bind(sock, (struct sockaddr *)&proxy,

            sizeof(struct sockaddr_un)) < 0) {

        do_perror("bind");

        goto error;

    }

    if (chown(proxy.sun_path, uid, gid) < 0) {

        do_perror("chown");

        goto error;

    }

    if (listen(sock, 1) < 0) {

        do_perror("listen");

        goto error;

    }

    size = sizeof(qemu);

    client = accept(sock, (struct sockaddr *)&qemu, &size);

    if (client < 0) {

        do_perror("accept");

        goto error;

    }

    close(sock);

    return client;

error:

    close(sock);

    return -1;

}


void *qemu_ram_mmap(int fd, size_t size, size_t align, bool shared)

{

    /*

     * Note: this always allocates at least one extra page of virtual address

     * space, even if size is already aligned.

     */

    size_t total = size + align;

    void *ptr = mmap(0, total, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);

    size_t offset = QEMU_ALIGN_UP((uintptr_t)ptr, align) - (uintptr_t)ptr;

    void *ptr1;

    if (ptr == MAP_FAILED) {

        return NULL;

    }

    /* Make sure align is a power of 2 */

    assert(!(align & (align - 1)));

    /* Always align to host page size */

    assert(align >= getpagesize());

    ptr1 = mmap(ptr + offset, size, PROT_READ | PROT_WRITE,

                MAP_FIXED |

                (fd == -1 ? MAP_ANONYMOUS : 0) |

                (shared ? MAP_SHARED : MAP_PRIVATE),

                fd, 0);

    if (ptr1 == MAP_FAILED) {

        munmap(ptr, total);

        return NULL;

    }

    ptr += offset;

    total -= offset;

    if (offset > 0) {

        munmap(ptr - offset, offset);

    }

    /*

     * Leave a single PROT_NONE page allocated after the RAM block, to serve as

     * a guard page guarding against potential buffer overflows.

     */

    if (total > size + getpagesize()) {

        munmap(ptr + size + getpagesize(), total - size - getpagesize());

    }

    return ptr;

}


start_list(Visitor *v, const char *name, Error **errp)

{

    StringInputVisitor *siv = to_siv(v);

    parse_str(siv, errp);

    siv->cur_range = g_list_first(siv->ranges);

    if (siv->cur_range) {

        Range *r = siv->cur_range->data;

        if (r) {

            siv->cur = r->begin;

        }

    }

}


void fw_cfg_add_i16(FWCfgState *s, uint16_t key, uint16_t value)

{

    uint16_t *copy;

    copy = g_malloc(sizeof(value));

    *copy = cpu_to_le16(value);

    fw_cfg_add_bytes(s, key, (uint8_t *)copy, sizeof(value));

}


void FUNC(ff_emulated_edge_mc)(uint8_t *buf, const uint8_t *src,

                                      ptrdiff_t linesize_arg,

                                      int block_w, int block_h,

                                      int src_x, int src_y, int w, int h)

{

    int x, y;

    int start_y, start_x, end_y, end_x;

    emuedge_linesize_type linesize = linesize_arg;

    if (!w || !h)

        return;

    if (src_y >= h) {

        src -= src_y * linesize;

        src += (h - 1) * linesize;

        src_y = h - 1;

    } else if (src_y <= -block_h) {

        src -= src_y * linesize;

        src += (1 - block_h) * linesize;

        src_y = 1 - block_h;

    }

    if (src_x >= w) {

        src  += (w - 1 - src_x) * sizeof(pixel);

        src_x = w - 1;

    } else if (src_x <= -block_w) {

        src  += (1 - block_w - src_x) * sizeof(pixel);

        src_x = 1 - block_w;

    }

    start_y = FFMAX(0, -src_y);

    start_x = FFMAX(0, -src_x);

    end_y = FFMIN(block_h, h-src_y);

    end_x = FFMIN(block_w, w-src_x);

    av_assert2(start_y < end_y && block_h);

    av_assert2(start_x < end_x && block_w);

    w    = end_x - start_x;

    src += start_y * linesize + start_x * sizeof(pixel);

    buf += start_x * sizeof(pixel);

    // top

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

        memcpy(buf, src, w * sizeof(pixel));

        buf += linesize;

    }

    // copy existing part

    for (; y < end_y; y++) {

        memcpy(buf, src, w * sizeof(pixel));

        src += linesize;

        buf += linesize;

    }

    // bottom

    src -= linesize;

    for (; y < block_h; y++) {

        memcpy(buf, src, w * sizeof(pixel));

        buf += linesize;

    }

    buf -= block_h * linesize + start_x * sizeof(pixel);

    while (block_h--) {

        pixel *bufp = (pixel *) buf;

        // left

        for(x = 0; x < start_x; x++) {

            bufp[x] = bufp[start_x];

        }

        // right

        for (x = end_x; x < block_w; x++) {

            bufp[x] = bufp[end_x - 1];

        }

        buf += linesize;

    }

}


static int draw_glyphs(DrawTextContext *s, AVFrame *frame,

                       int width, int height,

                       const uint8_t rgbcolor[4], const uint8_t yuvcolor[4],

                       int x, int y)

{

    char *text = HAVE_LOCALTIME_R ? s->expanded_text : s->text;

    uint32_t code = 0;

    int i;

    uint8_t *p;

    Glyph *glyph = NULL;

    for (i = 0, p = text; *p; i++) {

        Glyph dummy = { 0 };

        GET_UTF8(code, *p++, continue;);

        /* skip new line chars, just go to new line */

        if (code == '\n' || code == '\r' || code == '\t')

            continue;

        dummy.code = code;

        glyph = av_tree_find(s->glyphs, &dummy, (void *)glyph_cmp, NULL);

        if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&

            glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)

            return AVERROR(EINVAL);

        if (s->is_packed_rgb) {

            draw_glyph_rgb(frame, &glyph->bitmap,

                           s->positions[i].x+x, s->positions[i].y+y, width, height,

                           s->pixel_step[0], rgbcolor, s->rgba_map, s->alpha);

        } else {

            draw_glyph_yuv(frame, &glyph->bitmap,

                           s->positions[i].x+x, s->positions[i].y+y, width, height,

                           yuvcolor, s->hsub, s->vsub, s->alpha);

        }

    }

    return 0;

}


static void test_lifecycle(void)

{

    Coroutine *coroutine;

    bool done = false;

    /* Create, enter, and return from coroutine */

    coroutine = qemu_coroutine_create(set_and_exit);

    qemu_coroutine_enter(coroutine, &done);

    g_assert(done); /* expect done to be true (first time) */

    /* Repeat to check that no state affects this test */

    done = false;

    coroutine = qemu_coroutine_create(set_and_exit);

    qemu_coroutine_enter(coroutine, &done);

    g_assert(done); /* expect done to be true (second time) */

}


static void decode_pitch_lag_low(int *lag_int, int *lag_frac, int pitch_index,

                                 uint8_t *base_lag_int, int subframe, enum Mode mode)

{

    if (subframe == 0 || (subframe == 2 && mode != MODE_6k60)) {

        if (pitch_index < 116) {

            *lag_int  = (pitch_index + 69) >> 1;

            *lag_frac = (pitch_index - (*lag_int << 1) + 68) << 1;

        } else {

            *lag_int  = pitch_index - 24;

            *lag_frac = 0;

        }

        // XXX: same problem as before

        *base_lag_int = av_clip(*lag_int - 8 - (*lag_frac < 0),

                                AMRWB_P_DELAY_MIN, AMRWB_P_DELAY_MAX - 15);

    } else {

        *lag_int  = (pitch_index + 1) >> 1;

        *lag_frac = (pitch_index - (*lag_int << 1)) << 1;

        *lag_int += *base_lag_int;

    }

}


void qpci_io_writel(QPCIDevice *dev, void *data, uint32_t value)

{

    uintptr_t addr = (uintptr_t)data;

    if (addr < QPCI_PIO_LIMIT) {

        dev->bus->pio_writel(dev->bus, addr, value);

    } else {

        value = cpu_to_le32(value);

        dev->bus->memwrite(dev->bus, addr, &value, sizeof(value));

    }

}


void do_store_xer (void)

{

    xer_so = (T0 >> XER_SO) & 0x01;

    xer_ov = (T0 >> XER_OV) & 0x01;

    xer_ca = (T0 >> XER_CA) & 0x01;

    xer_cmp = (T0 >> XER_CMP) & 0xFF;

    xer_bc = (T0 >> XER_BC) & 0x3F;

}


int ffurl_open(URLContext **puc, const char *filename, int flags,

               const AVIOInterruptCB *int_cb, AVDictionary **options)

{

    int ret = ffurl_alloc(puc, filename, flags, int_cb);

    if (ret < 0)

        return ret;

    if (options && (*puc)->prot->priv_data_class &&

        (ret = av_opt_set_dict((*puc)->priv_data, options)) < 0)

        goto fail;

    if ((ret = av_opt_set_dict(*puc, options)) < 0)

        goto fail;

    ret = ffurl_connect(*puc, options);

    if (!ret)

        return 0;

fail:

    ffurl_close(*puc);

    *puc = NULL;

    return ret;

}


static int mpeg4_decode_video_packet_header(MpegEncContext *s)

{

    int mb_num_bits= av_log2(s->mb_num - 1) + 1;

    int header_extension=0, mb_num, len;

    /* is there enough space left for a video packet + header */

    if( get_bits_count(&s->gb) > s->gb.size*8-20) return -1;

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

        if(get_bits1(&s->gb)) break;

    }

    if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){

        printf("marker does not match f_code\n");

        return -1;

    }

    if(s->shape != RECT_SHAPE){

        header_extension= get_bits1(&s->gb);

        //FIXME more stuff here

    }

    mb_num= get_bits(&s->gb, mb_num_bits);

    if(mb_num>=s->mb_num){

        fprintf(stderr, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);

        return -1;

    }

    s->mb_x= mb_num % s->mb_width;

    s->mb_y= mb_num / s->mb_width;

    if(s->shape != BIN_ONLY_SHAPE){

        int qscale= get_bits(&s->gb, s->quant_precision);

        if(qscale)

            s->qscale= qscale;

    }

    if(s->shape == RECT_SHAPE){

        header_extension= get_bits1(&s->gb);

    }

    if(header_extension){

        int time_increment;

        int time_incr=0;

        while (get_bits1(&s->gb) != 0)

            time_incr++;

        check_marker(&s->gb, "before time_increment in video packed header");

        time_increment= get_bits(&s->gb, s->time_increment_bits);

        check_marker(&s->gb, "before vop_coding_type in video packed header");

        skip_bits(&s->gb, 2); /* vop coding type */

        //FIXME not rect stuff here

        if(s->shape != BIN_ONLY_SHAPE){

            skip_bits(&s->gb, 3); /* intra dc vlc threshold */

//FIXME dont just ignore everything

            if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE){

                mpeg4_decode_sprite_trajectory(s);

                fprintf(stderr, "untested\n");

            }

            //FIXME reduced res stuff here

            if (s->pict_type != I_TYPE) {

                int f_code = get_bits(&s->gb, 3);	/* fcode_for */

                if(f_code==0){

                    printf("Error, video packet header damaged (f_code=0)\n");

                }

            }

            if (s->pict_type == B_TYPE) {

                int b_code = get_bits(&s->gb, 3);

                if(b_code==0){

                    printf("Error, video packet header damaged (b_code=0)\n");

                }

            }

        }

    }

    //FIXME new-pred stuff

//printf("parse ok %d %d %d %d\n", mb_num, s->mb_x + s->mb_y*s->mb_width, get_bits_count(gb), get_bits_count(&s->gb));

    return 0;

}


int avfilter_link(AVFilterContext *src, unsigned srcpad,

                  AVFilterContext *dst, unsigned dstpad)

{

    AVFilterLink *link;

    if (src->nb_outputs <= srcpad || dst->nb_inputs <= dstpad ||

        src->outputs[srcpad]      || dst->inputs[dstpad])

        return -1;

    if (src->output_pads[srcpad].type != dst->input_pads[dstpad].type) {

        av_log(src, AV_LOG_ERROR,

               "Media type mismatch between the '%s' filter output pad %d and the '%s' filter input pad %d\n",

               src->name, srcpad, dst->name, dstpad);

        return AVERROR(EINVAL);

    }

    src->outputs[srcpad] =

    dst-> inputs[dstpad] = link = av_mallocz(sizeof(AVFilterLink));

    link->src     = src;

    link->dst     = dst;

    link->srcpad  = &src->output_pads[srcpad];

    link->dstpad  = &dst->input_pads[dstpad];

    link->type    = src->output_pads[srcpad].type;

    assert(AV_PIX_FMT_NONE == -1 && AV_SAMPLE_FMT_NONE == -1);

    link->format  = -1;

    return 0;

}


static void usage(void)

{

    printf("Escape an input string, adopting the av_get_token() escaping logic\n");

    printf("usage: ffescape [OPTIONS]\n");

    printf("\n"

           "Options:\n"

           "-e                echo each input line on output\n"

           "-h                print this help\n"

           "-i INFILE         set INFILE as input file, stdin if omitted\n"

           "-l LEVEL          set the number of escaping levels, 1 if omitted\n"

           "-m ESCAPE_MODE    select escape mode between 'full', 'lazy', 'quote', default is 'lazy'\n"

           "-o OUTFILE        set OUTFILE as output file, stdout if omitted\n"

           "-p PROMPT         set output prompt, is '=> ' by default\n"

           "-s SPECIAL_CHARS  set the list of special characters\n");

}


static inline void mpeg_motion(MpegEncContext *s,

                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,

                               int dest_offset,

                               UINT8 **ref_picture, int src_offset,

                               int field_based, op_pixels_func *pix_op,

                               int motion_x, int motion_y, int h)

{

    UINT8 *ptr;

    int dxy, offset, mx, my, src_x, src_y, height, linesize;

if(s->quarter_sample)

{

    motion_x>>=1;

    motion_y>>=1;

}

    dxy = ((motion_y & 1) << 1) | (motion_x & 1);

    src_x = s->mb_x * 16 + (motion_x >> 1);

    src_y = s->mb_y * (16 >> field_based) + (motion_y >> 1);

    /* WARNING: do no forget half pels */

    height = s->height >> field_based;

    src_x = clip(src_x, -16, s->width);

    if (src_x == s->width)

        dxy &= ~1;

    src_y = clip(src_y, -16, height);

    if (src_y == height)

        dxy &= ~2;

    linesize = s->linesize << field_based;

    ptr = ref_picture[0] + (src_y * linesize) + (src_x) + src_offset;

    dest_y += dest_offset;

    pix_op[dxy](dest_y, ptr, linesize, h);

    pix_op[dxy](dest_y + 8, ptr + 8, linesize, h);

    if (s->out_format == FMT_H263) {

        dxy = 0;

        if ((motion_x & 3) != 0)

            dxy |= 1;

        if ((motion_y & 3) != 0)

            dxy |= 2;

        mx = motion_x >> 2;

        my = motion_y >> 2;

    } else {

        mx = motion_x / 2;

        my = motion_y / 2;

        dxy = ((my & 1) << 1) | (mx & 1);

        mx >>= 1;

        my >>= 1;

    }

    src_x = s->mb_x * 8 + mx;

    src_y = s->mb_y * (8 >> field_based) + my;

    src_x = clip(src_x, -8, s->width >> 1);

    if (src_x == (s->width >> 1))

        dxy &= ~1;

    src_y = clip(src_y, -8, height >> 1);

    if (src_y == (height >> 1))

        dxy &= ~2;

    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);

    ptr = ref_picture[1] + offset;

    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);

    ptr = ref_picture[2] + offset;

    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);

}


av_cold void ff_audio_convert_init_x86(AudioConvert *ac)

{

    int cpu_flags = av_get_cpu_flags();

    if (EXTERNAL_MMX(cpu_flags)) {

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S32,

                                  0, 1, 8, "MMX", ff_conv_s32_to_s16_mmx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_FLTP,

                                  6, 1, 4, "MMX", ff_conv_fltp_to_flt_6ch_mmx);

    }

    if (EXTERNAL_SSE(cpu_flags)) {

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_FLTP,

                                  6, 1, 2, "SSE", ff_conv_fltp_to_s16_6ch_sse);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_FLTP,

                                  2, 16, 8, "SSE", ff_conv_fltp_to_flt_2ch_sse);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_FLT,

                                  2, 16, 4, "SSE", ff_conv_flt_to_fltp_2ch_sse);

    }

    if (EXTERNAL_SSE2(cpu_flags)) {

        if (!(cpu_flags & AV_CPU_FLAG_SSE2SLOW)) {

            ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S32,

                                      0, 16, 16, "SSE2", ff_conv_s32_to_s16_sse2);

            ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S16P,

                                      6, 16, 8, "SSE2", ff_conv_s16p_to_s16_6ch_sse2);

            ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_FLTP,

                                      6, 16, 4, "SSE2", ff_conv_fltp_to_s16_6ch_sse2);

        } else {

            ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S16P,

                                      6, 1, 4, "SSE2SLOW", ff_conv_s16p_to_s16_6ch_sse2slow);

        }

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_S16,

                                  0, 16, 8, "SSE2", ff_conv_s16_to_s32_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16,

                                  0, 16, 8, "SSE2", ff_conv_s16_to_flt_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S32,

                                  0, 16, 8, "SSE2", ff_conv_s32_to_flt_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_FLT,

                                  0, 16, 16, "SSE2", ff_conv_flt_to_s16_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_FLT,

                                  0, 16, 16, "SSE2", ff_conv_flt_to_s32_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S16P,

                                  2, 16, 16, "SSE2", ff_conv_s16p_to_s16_2ch_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16P,

                                  2, 16, 8, "SSE2", ff_conv_s16p_to_flt_2ch_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16P,

                                  6, 16, 4, "SSE2", ff_conv_s16p_to_flt_6ch_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_FLTP,

                                  2, 16, 4, "SSE2", ff_conv_fltp_to_s16_2ch_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_S16,

                                  2, 16, 8, "SSE2", ff_conv_s16_to_s16p_2ch_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_S16,

                                  6, 16, 4, "SSE2", ff_conv_s16_to_s16p_6ch_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_S16,

                                  2, 16, 8, "SSE2", ff_conv_s16_to_fltp_2ch_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_S16,

                                  6, 16, 4, "SSE2", ff_conv_s16_to_fltp_6ch_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_FLT,

                                  2, 16, 8, "SSE2", ff_conv_flt_to_s16p_2ch_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_FLT,

                                  6, 16, 4, "SSE2", ff_conv_flt_to_s16p_6ch_sse2);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_FLT,

                                  6, 16, 4, "SSE2", ff_conv_flt_to_fltp_6ch_sse2);

    }

    if (EXTERNAL_SSSE3(cpu_flags)) {

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16P,

                                  6, 16, 4, "SSSE3", ff_conv_s16p_to_flt_6ch_ssse3);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_FLTP,

                                  2, 16, 4, "SSSE3", ff_conv_fltp_to_s16_2ch_ssse3);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_S16,

                                  2, 16, 8, "SSSE3", ff_conv_s16_to_s16p_2ch_ssse3);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_S16,

                                  6, 16, 4, "SSSE3", ff_conv_s16_to_s16p_6ch_ssse3);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_S16,

                                  6, 16, 4, "SSSE3", ff_conv_s16_to_fltp_6ch_ssse3);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_FLT,

                                  6, 16, 4, "SSSE3", ff_conv_flt_to_s16p_6ch_ssse3);

    }

    if (EXTERNAL_SSE4(cpu_flags)) {

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16,

                                  0, 16, 8, "SSE4", ff_conv_s16_to_flt_sse4);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_FLTP,

                                  6, 16, 4, "SSE4", ff_conv_fltp_to_flt_6ch_sse4);

    }

    if (EXTERNAL_AVX(cpu_flags)) {

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S32,

                                  0, 32, 16, "AVX", ff_conv_s32_to_flt_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_FLT,

                                  0, 32, 32, "AVX", ff_conv_flt_to_s32_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S16P,

                                  2, 16, 16, "AVX", ff_conv_s16p_to_s16_2ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S16P,

                                  6, 16, 8, "AVX", ff_conv_s16p_to_s16_6ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16P,

                                  2, 16, 8, "AVX", ff_conv_s16p_to_flt_2ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16P,

                                  6, 16, 4, "AVX", ff_conv_s16p_to_flt_6ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_FLTP,

                                  6, 16, 4, "AVX", ff_conv_fltp_to_s16_6ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_FLTP,

                                  6, 16, 4, "AVX", ff_conv_fltp_to_flt_6ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_S16,

                                  2, 16, 8, "AVX", ff_conv_s16_to_s16p_2ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_S16,

                                  6, 16, 4, "AVX", ff_conv_s16_to_s16p_6ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_S16,

                                  2, 16, 8, "AVX", ff_conv_s16_to_fltp_2ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_S16,

                                  6, 16, 4, "AVX", ff_conv_s16_to_fltp_6ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_FLT,

                                  2, 16, 8, "AVX", ff_conv_flt_to_s16p_2ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_FLT,

                                  6, 16, 4, "AVX", ff_conv_flt_to_s16p_6ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_FLT,

                                  2, 16, 4, "AVX", ff_conv_flt_to_fltp_2ch_avx);

        ff_audio_convert_set_func(ac, AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_FLT,

                                  6, 16, 4, "AVX", ff_conv_flt_to_fltp_6ch_avx);

    }

}


static void virtio_pci_config_write(void *opaque, hwaddr addr,

                                    uint64_t val, unsigned size)

{

    VirtIOPCIProxy *proxy = opaque;

    uint32_t config = VIRTIO_PCI_CONFIG(&proxy->pci_dev);

    VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);

    if (addr < config) {

        virtio_ioport_write(proxy, addr, val);

        return;

    }

    addr -= config;

    /*

     * Virtio-PCI is odd. Ioports are LE but config space is target native

     * endian.

     */

    switch (size) {

    case 1:

        virtio_config_writeb(vdev, addr, val);

        break;

    case 2:

        if (virtio_is_big_endian()) {

            val = bswap16(val);

        }

        virtio_config_writew(vdev, addr, val);

        break;

    case 4:

        if (virtio_is_big_endian()) {

            val = bswap32(val);

        }

        virtio_config_writel(vdev, addr, val);

        break;

    }

}


void *qpci_iomap(QPCIDevice *dev, int barno, uint64_t *sizeptr)

{

    QPCIBus *bus = dev->bus;

    static const int bar_reg_map[] = {

        PCI_BASE_ADDRESS_0, PCI_BASE_ADDRESS_1, PCI_BASE_ADDRESS_2,

        PCI_BASE_ADDRESS_3, PCI_BASE_ADDRESS_4, PCI_BASE_ADDRESS_5,

    };

    int bar_reg;

    uint32_t addr, size;

    uint32_t io_type;

    uint64_t loc;

    g_assert(barno >= 0 && barno <= 5);

    bar_reg = bar_reg_map[barno];

    qpci_config_writel(dev, bar_reg, 0xFFFFFFFF);

    addr = qpci_config_readl(dev, bar_reg);

    io_type = addr & PCI_BASE_ADDRESS_SPACE;

    if (io_type == PCI_BASE_ADDRESS_SPACE_IO) {

        addr &= PCI_BASE_ADDRESS_IO_MASK;

    } else {

        addr &= PCI_BASE_ADDRESS_MEM_MASK;

    }

    g_assert(addr); /* Must have *some* size bits */

    size = 1U << ctz32(addr);

    if (sizeptr) {

        *sizeptr = size;

    }

    if (io_type == PCI_BASE_ADDRESS_SPACE_IO) {

        loc = QEMU_ALIGN_UP(bus->pio_alloc_ptr, size);

        g_assert(loc >= bus->pio_alloc_ptr);

        g_assert(loc + size <= QPCI_PIO_LIMIT); /* Keep PIO below 64kiB */

        bus->pio_alloc_ptr = loc + size;

        qpci_config_writel(dev, bar_reg, loc | PCI_BASE_ADDRESS_SPACE_IO);

    } else {

        loc = QEMU_ALIGN_UP(bus->mmio_alloc_ptr, size);

        /* Check for space */

        g_assert(loc >= bus->mmio_alloc_ptr);

        g_assert(loc + size <= bus->mmio_limit);

        bus->mmio_alloc_ptr = loc + size;

        qpci_config_writel(dev, bar_reg, loc);

    }

    return (void *)(uintptr_t)loc;

}