static void decouple_info(COOKContext *q, COOKSubpacket *p, int *decouple_tab)

{

    int i;

    int vlc    = get_bits1(&q->gb);

    int start  = cplband[p->js_subband_start];

    int end    = cplband[p->subbands - 1];

    int length = end - start + 1;

    if (start > end)

        return;

    if (vlc)

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

            decouple_tab[start + i] = get_vlc2(&q->gb, p->ccpl.table, p->ccpl.bits, 2);

    else

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

            decouple_tab[start + i] = get_bits(&q->gb, p->js_vlc_bits);

}


static int prepare_packet(AVPacket *pkt,const FailingMuxerPacketData *pkt_data, int64_t pts)

{

    int ret;

    FailingMuxerPacketData *data = av_malloc(sizeof(*data));

    memcpy(data, pkt_data, sizeof(FailingMuxerPacketData));

    ret = av_packet_from_data(pkt, (uint8_t*) data, sizeof(*data));

    pkt->pts = pkt->dts = pts;

    pkt->duration = 1;

    return ret;


static void find_best_state(uint8_t best_state[256][256], const uint8_t one_state[256]){

    int i,j,k,m;

    double l2tab[256];

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

        l2tab[i]= log2(i/256.0);

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

        double best_len[256];

        double p= i/256.0;

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

            best_len[j]= 1<<30;

        for(j=FFMAX(i-10,1); j<FFMIN(i+11,256); j++){

            double occ[256]={0};

            double len=0;

            occ[j]=1.0;

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

                double newocc[256]={0};

                for(m=0; m<256; m++){

                    if(occ[m]){

                        len -=occ[m]*(     p *l2tab[    m]

                                      + (1-p)*l2tab[256-m]);

                    }

                }

                if(len < best_len[k]){

                    best_len[k]= len;

                    best_state[i][k]= j;

                }

                for(m=0; m<256; m++){

                    if(occ[m]){

                        newocc[    one_state[    m]] += occ[m]*   p ;

                        newocc[256-one_state[256-m]] += occ[m]*(1-p);

                    }

                }

                memcpy(occ, newocc, sizeof(occ));

            }

        }

    }

}


static int get_pcm(HEVCContext *s, int x, int y)

{

    int log2_min_pu_size = s->sps->log2_min_pu_size;

    int x_pu             = x >> log2_min_pu_size;

    int y_pu             = y >> log2_min_pu_size;

    if (x < 0 || x_pu >= s->sps->min_pu_width ||

        y < 0 || y_pu >= s->sps->min_pu_height)

        return 2;

    return s->is_pcm[y_pu * s->sps->min_pu_width + x_pu];

}


static int h264_decode_frame(AVCodecContext *avctx, void *data,

                             int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    H264Context *h     = avctx->priv_data;

    AVFrame *pict      = data;

    int buf_index      = 0;

    int ret;

    const uint8_t *new_extradata;

    int new_extradata_size;

    h->flags = avctx->flags;

    h->setup_finished = 0;

    /* end of stream, output what is still in the buffers */

out:

    if (buf_size == 0) {

        H264Picture *out;

        int i, out_idx;

        h->cur_pic_ptr = NULL;

        // FIXME factorize this with the output code below

        out     = h->delayed_pic[0];

        out_idx = 0;

        for (i = 1;

             h->delayed_pic[i] &&

             !h->delayed_pic[i]->f->key_frame &&

             !h->delayed_pic[i]->mmco_reset;

             i++)

            if (h->delayed_pic[i]->poc < out->poc) {

                out     = h->delayed_pic[i];

                out_idx = i;

            }

        for (i = out_idx; h->delayed_pic[i]; i++)

            h->delayed_pic[i] = h->delayed_pic[i + 1];

        if (out) {

            ret = output_frame(h, pict, out->f);

            if (ret < 0)

                return ret;

            *got_frame = 1;

        }

        return buf_index;

    }

    new_extradata_size = 0;

    new_extradata = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,

                                            &new_extradata_size);

    if (new_extradata_size > 0 && new_extradata) {

        ret = ff_h264_decode_extradata(new_extradata, new_extradata_size,

                                       &h->ps, &h->is_avc, &h->nal_length_size,

                                       avctx->err_recognition, avctx);

        if (ret < 0)

            return ret;

    }

    buf_index = decode_nal_units(h, buf, buf_size);

    if (buf_index < 0)

        return AVERROR_INVALIDDATA;

    if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {

        buf_size = 0;

        goto out;

    }

    if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {

        if (avctx->skip_frame >= AVDISCARD_NONREF)

            return 0;

        av_log(avctx, AV_LOG_ERROR, "no frame!\n");

        return AVERROR_INVALIDDATA;

    }

    if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||

        (h->mb_y >= h->mb_height && h->mb_height)) {

        if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)

            decode_postinit(h, 1);

        ff_h264_field_end(h, &h->slice_ctx[0], 0);

        *got_frame = 0;

        if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||

                                   h->next_output_pic->recovered)) {

            if (!h->next_output_pic->recovered)

                h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;

            ret = output_frame(h, pict, h->next_output_pic->f);

            if (ret < 0)

                return ret;

            *got_frame = 1;

        }

    }

    assert(pict->buf[0] || !*got_frame);

    return get_consumed_bytes(buf_index, buf_size);

}


static inline int16_t calc_lowcomp(int16_t a, int16_t b0, int16_t b1, uint8_t bin)

{

    if (bin < 7) {

        if ((b0 + 256) == b1)

            a = 384;

        else if (b0 > b1)

            a = FFMAX(0, a - 64);

    }

    else if (bin < 20) {

        if ((b0 + 256) == b1)

            a = 320;

        else if (b0 > b1)

            a = FFMAX(0, a - 64);

    }

    else {

        a = FFMAX(0, a - 128);

    }

    return a;

}


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

                                      long width, long height,

                                      long lumStride, long chromStride, long srcStride)

{

    long y;

    const x86_reg chromWidth= width>>1;

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

#if COMPILE_TEMPLATE_MMX

        __asm__ volatile(

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

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

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

            ".p2align                    4              \n\t"

            "1:                \n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            " jb                        1b              \n\t"

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

            : "memory", "%"REG_a

        );

        ydst += lumStride;

        src  += srcStride;

        __asm__ volatile(

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

            ".p2align                    4              \n\t"

            "1:                                         \n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            " jb                        1b              \n\t"

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

            : "memory", "%"REG_a

        );

#else

        long i;

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

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

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

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

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

        }

        ydst += lumStride;

        src  += srcStride;

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

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

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

        }

#endif

        udst += chromStride;

        vdst += chromStride;

        ydst += lumStride;

        src  += srcStride;

    }

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(EMMS"       \n\t"

                     SFENCE"     \n\t"

                     :::"memory");

#endif

}


static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,

                                                  const char *name,

                                                  BlockDriverState **pbs,

                                                  AioContext **paio,

                                                  Error **errp)

{

    BlockDriverState *bs;

    BdrvDirtyBitmap *bitmap;

    AioContext *aio_context;

    if (!node) {

        error_setg(errp, "Node cannot be NULL");

        return NULL;

    }

    if (!name) {

        error_setg(errp, "Bitmap name cannot be NULL");

        return NULL;

    }

    bs = bdrv_lookup_bs(node, node, NULL);

    if (!bs) {

        error_setg(errp, "Node '%s' not found", node);

        return NULL;

    }

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    bitmap = bdrv_find_dirty_bitmap(bs, name);

    if (!bitmap) {

        error_setg(errp, "Dirty bitmap '%s' not found", name);

        goto fail;

    }

    if (pbs) {

        *pbs = bs;

    }

    if (paio) {

        *paio = aio_context;

    } else {

        aio_context_release(aio_context);

    }

    return bitmap;

 fail:

    aio_context_release(aio_context);

    return NULL;

}


void ppce500_init(MachineState *machine, PPCE500Params *params)

{

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    PCIBus *pci_bus;

    CPUPPCState *env = NULL;

    uint64_t loadaddr;

    hwaddr kernel_base = -1LL;

    int kernel_size = 0;

    hwaddr dt_base = 0;

    hwaddr initrd_base = 0;

    int initrd_size = 0;

    hwaddr cur_base = 0;

    char *filename;

    hwaddr bios_entry = 0;

    target_long bios_size;

    struct boot_info *boot_info;

    int dt_size;

    int i;

    /* irq num for pin INTA, INTB, INTC and INTD is 1, 2, 3 and

     * 4 respectively */

    unsigned int pci_irq_nrs[PCI_NUM_PINS] = {1, 2, 3, 4};

    qemu_irq **irqs, *mpic;

    DeviceState *dev;

    CPUPPCState *firstenv = NULL;

    MemoryRegion *ccsr_addr_space;

    SysBusDevice *s;

    PPCE500CCSRState *ccsr;

    /* Setup CPUs */

    if (machine->cpu_model == NULL) {

        machine->cpu_model = "e500v2_v30";

    }

    irqs = g_malloc0(smp_cpus * sizeof(qemu_irq *));

    irqs[0] = g_malloc0(smp_cpus * sizeof(qemu_irq) * OPENPIC_OUTPUT_NB);

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

        PowerPCCPU *cpu;

        CPUState *cs;

        qemu_irq *input;

        cpu = cpu_ppc_init(machine->cpu_model);

        if (cpu == NULL) {

            fprintf(stderr, "Unable to initialize CPU!\n");

            exit(1);

        }

        env = &cpu->env;

        cs = CPU(cpu);

        if (!firstenv) {

            firstenv = env;

        }

        irqs[i] = irqs[0] + (i * OPENPIC_OUTPUT_NB);

        input = (qemu_irq *)env->irq_inputs;

        irqs[i][OPENPIC_OUTPUT_INT] = input[PPCE500_INPUT_INT];

        irqs[i][OPENPIC_OUTPUT_CINT] = input[PPCE500_INPUT_CINT];

        env->spr_cb[SPR_BOOKE_PIR].default_value = cs->cpu_index = i;

        env->mpic_iack = params->ccsrbar_base +

                         MPC8544_MPIC_REGS_OFFSET + 0xa0;

        ppc_booke_timers_init(cpu, 400000000, PPC_TIMER_E500);

        /* Register reset handler */

        if (!i) {

            /* Primary CPU */

            struct boot_info *boot_info;

            boot_info = g_malloc0(sizeof(struct boot_info));

            qemu_register_reset(ppce500_cpu_reset, cpu);

            env->load_info = boot_info;

        } else {

            /* Secondary CPUs */

            qemu_register_reset(ppce500_cpu_reset_sec, cpu);

        }

    }

    env = firstenv;

    /* Fixup Memory size on a alignment boundary */

    ram_size &= ~(RAM_SIZES_ALIGN - 1);

    machine->ram_size = ram_size;

    /* Register Memory */

    memory_region_allocate_system_memory(ram, NULL, "mpc8544ds.ram", ram_size);

    memory_region_add_subregion(address_space_mem, 0, ram);

    dev = qdev_create(NULL, "e500-ccsr");

    object_property_add_child(qdev_get_machine(), "e500-ccsr",

                              OBJECT(dev), NULL);

    qdev_init_nofail(dev);

    ccsr = CCSR(dev);

    ccsr_addr_space = &ccsr->ccsr_space;

    memory_region_add_subregion(address_space_mem, params->ccsrbar_base,

                                ccsr_addr_space);

    mpic = ppce500_init_mpic(params, ccsr_addr_space, irqs);

    /* Serial */

    if (serial_hds[0]) {

        serial_mm_init(ccsr_addr_space, MPC8544_SERIAL0_REGS_OFFSET,

                       0, mpic[42], 399193,

                       serial_hds[0], DEVICE_BIG_ENDIAN);

    }

    if (serial_hds[1]) {

        serial_mm_init(ccsr_addr_space, MPC8544_SERIAL1_REGS_OFFSET,

                       0, mpic[42], 399193,

                       serial_hds[1], DEVICE_BIG_ENDIAN);

    }

    /* General Utility device */

    dev = qdev_create(NULL, "mpc8544-guts");

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

    memory_region_add_subregion(ccsr_addr_space, MPC8544_UTIL_OFFSET,

                                sysbus_mmio_get_region(s, 0));

    /* PCI */

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

    qdev_prop_set_uint32(dev, "first_slot", params->pci_first_slot);

    qdev_prop_set_uint32(dev, "first_pin_irq", pci_irq_nrs[0]);

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

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

        sysbus_connect_irq(s, i, mpic[pci_irq_nrs[i]]);

    }

    memory_region_add_subregion(ccsr_addr_space, MPC8544_PCI_REGS_OFFSET,

                                sysbus_mmio_get_region(s, 0));

    pci_bus = (PCIBus *)qdev_get_child_bus(dev, "pci.0");

    if (!pci_bus)

        printf("couldn't create PCI controller!\n");

    if (pci_bus) {

        /* Register network interfaces. */

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

            pci_nic_init_nofail(&nd_table[i], pci_bus, "virtio", NULL);

        }

    }

    /* Register spinning region */

    sysbus_create_simple("e500-spin", params->spin_base, NULL);

    if (cur_base < (32 * 1024 * 1024)) {

        /* u-boot occupies memory up to 32MB, so load blobs above */

        cur_base = (32 * 1024 * 1024);

    }

    if (params->has_mpc8xxx_gpio) {

        qemu_irq poweroff_irq;

        dev = qdev_create(NULL, "mpc8xxx_gpio");

        s = SYS_BUS_DEVICE(dev);

        qdev_init_nofail(dev);

        sysbus_connect_irq(s, 0, mpic[MPC8XXX_GPIO_IRQ]);

        memory_region_add_subregion(ccsr_addr_space, MPC8XXX_GPIO_OFFSET,

                                    sysbus_mmio_get_region(s, 0));

        /* Power Off GPIO at Pin 0 */

        poweroff_irq = qemu_allocate_irq(ppce500_power_off, NULL, 0);

        qdev_connect_gpio_out(dev, 0, poweroff_irq);

    }

    /* Platform Bus Device */

    if (params->has_platform_bus) {

        dev = qdev_create(NULL, TYPE_PLATFORM_BUS_DEVICE);

        dev->id = TYPE_PLATFORM_BUS_DEVICE;

        qdev_prop_set_uint32(dev, "num_irqs", params->platform_bus_num_irqs);

        qdev_prop_set_uint32(dev, "mmio_size", params->platform_bus_size);

        qdev_init_nofail(dev);

        s = SYS_BUS_DEVICE(dev);

        for (i = 0; i < params->platform_bus_num_irqs; i++) {

            int irqn = params->platform_bus_first_irq + i;

            sysbus_connect_irq(s, i, mpic[irqn]);

        }

        memory_region_add_subregion(address_space_mem,

                                    params->platform_bus_base,

                                    sysbus_mmio_get_region(s, 0));

    }

    /* Load kernel. */

    if (machine->kernel_filename) {

        kernel_base = cur_base;

        kernel_size = load_image_targphys(machine->kernel_filename,

                                          cur_base,

                                          ram_size - cur_base);

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    machine->kernel_filename);

            exit(1);

        }

        cur_base += kernel_size;

    }

    /* Load initrd. */

    if (machine->initrd_filename) {

        initrd_base = (cur_base + INITRD_LOAD_PAD) & ~INITRD_PAD_MASK;

        initrd_size = load_image_targphys(machine->initrd_filename, initrd_base,

                                          ram_size - initrd_base);

        if (initrd_size < 0) {

            fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",

                    machine->initrd_filename);

            exit(1);

        }

        cur_base = initrd_base + initrd_size;

    }

    /*

     * Smart firmware defaults ahead!

     *

     * We follow the following table to select which payload we execute.

     *

     *  -kernel | -bios | payload

     * ---------+-------+---------

     *     N    |   Y   | u-boot

     *     N    |   N   | u-boot

     *     Y    |   Y   | u-boot

     *     Y    |   N   | kernel

     *

     * This ensures backwards compatibility with how we used to expose

     * -kernel to users but allows them to run through u-boot as well.

     */

    if (bios_name == NULL) {

        if (machine->kernel_filename) {

            bios_name = machine->kernel_filename;

        } else {

            bios_name = "u-boot.e500";

        }

    }

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    bios_size = load_elf(filename, NULL, NULL, &bios_entry, &loadaddr, NULL,

                         1, ELF_MACHINE, 0);

    if (bios_size < 0) {

        /*

         * Hrm. No ELF image? Try a uImage, maybe someone is giving us an

         * ePAPR compliant kernel

         */

        kernel_size = load_uimage(filename, &bios_entry, &loadaddr, NULL,

                                  NULL, NULL);

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load firmware '%s'\n", filename);

            exit(1);

        }

    }

    /* Reserve space for dtb */

    dt_base = (loadaddr + bios_size + DTC_LOAD_PAD) & ~DTC_PAD_MASK;

    dt_size = ppce500_prep_device_tree(machine, params, dt_base,

                                       initrd_base, initrd_size,

                                       kernel_base, kernel_size);

    if (dt_size < 0) {

        fprintf(stderr, "couldn't load device tree\n");

        exit(1);

    }

    assert(dt_size < DTB_MAX_SIZE);

    boot_info = env->load_info;

    boot_info->entry = bios_entry;

    boot_info->dt_base = dt_base;

    boot_info->dt_size = dt_size;

    if (kvm_enabled()) {

        kvmppc_init();

    }

}


static av_always_inline int coeff_abs_level_remaining_decode(HEVCContext *s, int rc_rice_param)

{

    int prefix = 0;

    int suffix = 0;

    int last_coeff_abs_level_remaining;

    int i;

    while (prefix < CABAC_MAX_BIN && get_cabac_bypass(&s->HEVClc->cc))

        prefix++;

    if (prefix < 3) {

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

            suffix = (suffix << 1) | get_cabac_bypass(&s->HEVClc->cc);

        last_coeff_abs_level_remaining = (prefix << rc_rice_param) + suffix;

    } else {

        int prefix_minus3 = prefix - 3;

        if (prefix == CABAC_MAX_BIN) {

            av_log(s->avctx, AV_LOG_ERROR, "CABAC_MAX_BIN : %d\n", prefix);

            return 0;

        }

        for (i = 0; i < prefix_minus3 + rc_rice_param; i++)

            suffix = (suffix << 1) | get_cabac_bypass(&s->HEVClc->cc);

        last_coeff_abs_level_remaining = (((1 << prefix_minus3) + 3 - 1)

                                              << rc_rice_param) + suffix;

    }

    return last_coeff_abs_level_remaining;

}


static int segment_hls_window(AVFormatContext *s, int last)

{

    SegmentContext *seg = s->priv_data;

    int i, ret = 0;

    char buf[1024];

    if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,

                              &s->interrupt_callback, NULL)) < 0)

        goto fail;

    avio_printf(seg->pb, "#EXTM3U\n");

    avio_printf(seg->pb, "#EXT-X-VERSION:3\n");

    avio_printf(seg->pb, "#EXT-X-TARGETDURATION:%d\n", (int)seg->time);

    avio_printf(seg->pb, "#EXT-X-MEDIA-SEQUENCE:%d\n",

                FFMAX(0, seg->number - seg->size));

    av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",

           FFMAX(0, seg->number - seg->size));

    for (i = FFMAX(0, seg->number - seg->size);

         i < seg->number; i++) {

        avio_printf(seg->pb, "#EXTINF:%d,\n", (int)seg->time);

        if (seg->entry_prefix) {

            avio_printf(seg->pb, "%s", seg->entry_prefix);

        }

        ret = av_get_frame_filename(buf, sizeof(buf), s->filename, i);

        if (ret < 0) {

            ret = AVERROR(EINVAL);

            goto fail;

        }

        avio_printf(seg->pb, "%s\n", buf);

    }

    if (last)

        avio_printf(seg->pb, "#EXT-X-ENDLIST\n");

fail:

    avio_closep(&seg->pb);

    return ret;

}


static inline int cris_addc_pi_m(int a, int **b)

{

	asm volatile ("addc [%1+], %0\n" : "+r" (a), "+b" (*b));

	return a;

}


static void vmgenid_query_monitor_test(void)

{

    QemuUUID expected, measured;

    gchar *cmd;

    g_assert(qemu_uuid_parse(VGID_GUID, &expected) == 0);

    cmd = g_strdup_printf("-machine accel=tcg -device vmgenid,id=testvgid,"

                          "guid=%s", VGID_GUID);

    qtest_start(cmd);

    /* Read the GUID via the monitor */

    read_guid_from_monitor(&measured);

    g_assert(memcmp(measured.data, expected.data, sizeof(measured.data)) == 0);

    qtest_quit(global_qtest);

    g_free(cmd);

}


static int decode_frame_byterun1(AVCodecContext *avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    IffContext *s = avctx->priv_data;

    const uint8_t *buf = avpkt->size >= 2 ? avpkt->data + AV_RB16(avpkt->data) : NULL;

    const int buf_size = avpkt->size >= 2 ? avpkt->size - AV_RB16(avpkt->data) : 0;

    const uint8_t *buf_end = buf+buf_size;

    int y, plane, res;

    if ((res = extract_header(avctx, avpkt)) < 0)

        return res;

    if (s->init) {

        if ((res = avctx->reget_buffer(avctx, &s->frame)) < 0) {

            av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");

            return res;

        }

    } else if ((res = avctx->get_buffer(avctx, &s->frame)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return res;

    } else if (avctx->bits_per_coded_sample <= 8 && avctx->pix_fmt != PIX_FMT_GRAY8) {

        if ((res = ff_cmap_read_palette(avctx, (uint32_t*)s->frame.data[1])) < 0)

            return res;

    }

    s->init = 1;

    if (avctx->codec_tag == MKTAG('I','L','B','M')) { //interleaved

        if (avctx->pix_fmt == PIX_FMT_PAL8 || avctx->pix_fmt == PIX_FMT_GRAY8) {

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

                uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ];

                memset(row, 0, avctx->width);

                for (plane = 0; plane < s->bpp; plane++) {

                    buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);

                    decodeplane8(row, s->planebuf, s->planesize, plane);

                }

            }

        } else if (s->ham) { // HAM to PIX_FMT_BGR32

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

                uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];

                memset(s->ham_buf, 0, avctx->width);

                for (plane = 0; plane < s->bpp; plane++) {

                    buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);

                    decodeplane8(s->ham_buf, s->planebuf, s->planesize, plane);

                }

                decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, s->planesize);

            }

        } else { //PIX_FMT_BGR32

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

                uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];

                memset(row, 0, avctx->width << 2);

                for (plane = 0; plane < s->bpp; plane++) {

                    buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);

                    decodeplane32((uint32_t *) row, s->planebuf, s->planesize, plane);

                }

            }

        }

    } else if (avctx->pix_fmt == PIX_FMT_PAL8 || avctx->pix_fmt == PIX_FMT_GRAY8) { // IFF-PBM

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

            uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];

            buf += decode_byterun(row, avctx->width, buf, buf_end);

        }

    } else { // IFF-PBM: HAM to PIX_FMT_BGR32

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

            uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];

            buf += decode_byterun(s->ham_buf, avctx->width, buf, buf_end);

            decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, avctx->width);

        }

    }

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = s->frame;

    return buf_size;

}


int alloc_picture(MpegEncContext *s, Picture *pic, int shared){

    const int big_mb_num= s->mb_stride*(s->mb_height+1) + 1; //the +1 is needed so memset(,,stride*height) does not sig11

    const int mb_array_size= s->mb_stride*s->mb_height;

    const int b8_array_size= s->b8_stride*s->mb_height*2;

    const int b4_array_size= s->b4_stride*s->mb_height*4;

    int i;

    if(shared){

        assert(pic->data[0]);

        assert(pic->type == 0 || pic->type == FF_BUFFER_TYPE_SHARED);

        pic->type= FF_BUFFER_TYPE_SHARED;

    }else{

        int r;

        assert(!pic->data[0]);

        r= s->avctx->get_buffer(s->avctx, (AVFrame*)pic);

        if(r<0 || !pic->age || !pic->type || !pic->data[0]){

            av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (%d %d %d %p)\n", r, pic->age, pic->type, pic->data[0]);

            return -1;

        }

        if(s->linesize && (s->linesize != pic->linesize[0] || s->uvlinesize != pic->linesize[1])){

            av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (stride changed)\n");

            return -1;

        }

        if(pic->linesize[1] != pic->linesize[2]){

            av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (uv stride mismatch)\n");

            return -1;

        }

        s->linesize  = pic->linesize[0];

        s->uvlinesize= pic->linesize[1];

    }

    if(pic->qscale_table==NULL){

        if (s->encoding) {

            CHECKED_ALLOCZ(pic->mb_var   , mb_array_size * sizeof(int16_t))

            CHECKED_ALLOCZ(pic->mc_mb_var, mb_array_size * sizeof(int16_t))

            CHECKED_ALLOCZ(pic->mb_mean  , mb_array_size * sizeof(int8_t))

        }

        CHECKED_ALLOCZ(pic->mbskip_table , mb_array_size * sizeof(uint8_t)+2) //the +2 is for the slice end check

        CHECKED_ALLOCZ(pic->qscale_table , mb_array_size * sizeof(uint8_t))

        CHECKED_ALLOCZ(pic->mb_type_base , big_mb_num    * sizeof(uint32_t))

        pic->mb_type= pic->mb_type_base + s->mb_stride+1;

        if(s->out_format == FMT_H264){

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

                CHECKED_ALLOCZ(pic->motion_val_base[i], 2 * (b4_array_size+4)  * sizeof(int16_t))

                pic->motion_val[i]= pic->motion_val_base[i]+4;

                CHECKED_ALLOCZ(pic->ref_index[i], b8_array_size * sizeof(uint8_t))

            }

            pic->motion_subsample_log2= 2;

        }else if(s->out_format == FMT_H263 || s->encoding || (s->avctx->debug&FF_DEBUG_MV) || (s->avctx->debug_mv)){

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

                CHECKED_ALLOCZ(pic->motion_val_base[i], 2 * (b8_array_size+4) * sizeof(int16_t))

                pic->motion_val[i]= pic->motion_val_base[i]+4;

                CHECKED_ALLOCZ(pic->ref_index[i], b8_array_size * sizeof(uint8_t))

            }

            pic->motion_subsample_log2= 3;

        }

        if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {

            CHECKED_ALLOCZ(pic->dct_coeff, 64 * mb_array_size * sizeof(DCTELEM)*6)

        }

        pic->qstride= s->mb_stride;

        CHECKED_ALLOCZ(pic->pan_scan , 1 * sizeof(AVPanScan))

    }

    /* It might be nicer if the application would keep track of these

     * but it would require an API change. */

    memmove(s->prev_pict_types+1, s->prev_pict_types, PREV_PICT_TYPES_BUFFER_SIZE-1);

    s->prev_pict_types[0]= s->pict_type;

    if(pic->age < PREV_PICT_TYPES_BUFFER_SIZE && s->prev_pict_types[pic->age] == B_TYPE)

        pic->age= INT_MAX; // Skipped MBs in B-frames are quite rare in MPEG-1/2 and it is a bit tricky to skip them anyway.

    return 0;

fail: //for the CHECKED_ALLOCZ macro

    return -1;

}


static int decode_pic_hdr(IVI5DecContext *ctx, AVCodecContext *avctx)
{
    if (get_bits(&ctx->gb, 5) != 0x1F) {
        av_log(avctx, AV_LOG_ERROR, "Invalid picture start code!\n");
        return -1;
    ctx->prev_frame_type = ctx->frame_type;
    ctx->frame_type      = get_bits(&ctx->gb, 3);
    if (ctx->frame_type >= 5) {
        av_log(avctx, AV_LOG_ERROR, "Invalid frame type: %d \n", ctx->frame_type);
        return -1;
    ctx->frame_num = get_bits(&ctx->gb, 8);
    if (ctx->frame_type == FRAMETYPE_INTRA) {
        ctx->gop_invalid = 1;
        if (decode_gop_header(ctx, avctx))
            return -1;
        ctx->gop_invalid = 0;
    if (ctx->frame_type != FRAMETYPE_NULL) {
        ctx->frame_flags = get_bits(&ctx->gb, 8);
        ctx->pic_hdr_size = (ctx->frame_flags & 1) ? get_bits_long(&ctx->gb, 24) : 0;
        ctx->checksum = (ctx->frame_flags & 0x10) ? get_bits(&ctx->gb, 16) : 0;
        /* skip unknown extension if any */
        if (ctx->frame_flags & 0x20)
            skip_hdr_extension(&ctx->gb); /* XXX: untested */
        /* decode macroblock huffman codebook */
        if (ff_ivi_dec_huff_desc(&ctx->gb, ctx->frame_flags & 0x40, IVI_MB_HUFF, &ctx->mb_vlc, avctx))
            return -1;
        skip_bits(&ctx->gb, 3); /* FIXME: unknown meaning! */
    align_get_bits(&ctx->gb);
    return 0;


static int mpegts_write_header(AVFormatContext *s)

{

    MpegTSWrite *ts = s->priv_data;

    MpegTSWriteStream *ts_st;

    MpegTSService *service;

    AVStream *st, *pcr_st = NULL;

    AVDictionaryEntry *title, *provider;

    int i, j;

    const char *service_name;

    const char *provider_name;

    int *pids;

    int ret;

    if (s->max_delay < 0) /* Not set by the caller */

        s->max_delay = 0;

    // round up to a whole number of TS packets

    ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;

    ts->tsid = ts->transport_stream_id;

    ts->onid = ts->original_network_id;

    /* allocate a single DVB service */

    title = av_dict_get(s->metadata, "service_name", NULL, 0);

    if (!title)

        title = av_dict_get(s->metadata, "title", NULL, 0);

    service_name  = title ? title->value : DEFAULT_SERVICE_NAME;

    provider      = av_dict_get(s->metadata, "service_provider", NULL, 0);

    provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;

    service       = mpegts_add_service(ts, ts->service_id,

                                       provider_name, service_name);

    if (!service)

        return AVERROR(ENOMEM);

    service->pmt.write_packet = section_write_packet;

    service->pmt.opaque       = s;

    service->pmt.cc           = 15;

    ts->pat.pid          = PAT_PID;

    /* Initialize at 15 so that it wraps and is equal to 0 for the

     * first packet we write. */

    ts->pat.cc           = 15;

    ts->pat.write_packet = section_write_packet;

    ts->pat.opaque       = s;

    ts->sdt.pid          = SDT_PID;

    ts->sdt.cc           = 15;

    ts->sdt.write_packet = section_write_packet;

    ts->sdt.opaque       = s;

    pids = av_malloc_array(s->nb_streams, sizeof(*pids));

    if (!pids) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    /* assign pids to each stream */

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

        st = s->streams[i];

        ts_st = av_mallocz(sizeof(MpegTSWriteStream));

        if (!ts_st) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        st->priv_data = ts_st;

        ts_st->user_tb = st->time_base;

        avpriv_set_pts_info(st, 33, 1, 90000);

        ts_st->payload = av_mallocz(ts->pes_payload_size);

        if (!ts_st->payload) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        ts_st->service = service;

        /* MPEG pid values < 16 are reserved. Applications which set st->id in

         * this range are assigned a calculated pid. */

        if (st->id < 16) {

            ts_st->pid = ts->start_pid + i;

        } else if (st->id < 0x1FFF) {

            ts_st->pid = st->id;

        } else {

            av_log(s, AV_LOG_ERROR,

                   "Invalid stream id %d, must be less than 8191\n", st->id);

            ret = AVERROR(EINVAL);

            goto fail;

        }

        if (ts_st->pid == service->pmt.pid) {

            av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);

            ret = AVERROR(EINVAL);

            goto fail;

        }

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

            if (pids[j] == ts_st->pid) {

                av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);

                ret = AVERROR(EINVAL);

                goto fail;

            }

        }

        pids[i]                = ts_st->pid;

        ts_st->payload_pts     = AV_NOPTS_VALUE;

        ts_st->payload_dts     = AV_NOPTS_VALUE;

        ts_st->first_pts_check = 1;

        ts_st->cc              = 15;

        /* update PCR pid by using the first video stream */

        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&

            service->pcr_pid == 0x1fff) {

            service->pcr_pid = ts_st->pid;

            pcr_st           = st;

        }

        if (st->codec->codec_id == AV_CODEC_ID_AAC &&

            st->codec->extradata_size > 0) {

            AVStream *ast;

            ts_st->amux = avformat_alloc_context();

            if (!ts_st->amux) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

            ts_st->amux->oformat =

                av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts",

                                NULL, NULL);

            if (!ts_st->amux->oformat) {

                ret = AVERROR(EINVAL);

                goto fail;

            }

            if (!(ast = avformat_new_stream(ts_st->amux, NULL))) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

            ret = avcodec_copy_context(ast->codec, st->codec);

            if (ret != 0)

                goto fail;

            ast->time_base = st->time_base;

            ret = avformat_write_header(ts_st->amux, NULL);

            if (ret < 0)

                goto fail;

        }

        if (st->codec->codec_id == AV_CODEC_ID_OPUS) {

            ts_st->opus_pending_trim_start = st->codec->initial_padding * 48000 / st->codec->sample_rate;

        }

    }

    av_freep(&pids);

    /* if no video stream, use the first stream as PCR */

    if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {

        pcr_st           = s->streams[0];

        ts_st            = pcr_st->priv_data;

        service->pcr_pid = ts_st->pid;

    } else

        ts_st = pcr_st->priv_data;

    if (ts->mux_rate > 1) {

        service->pcr_packet_period = (ts->mux_rate * ts->pcr_period) /

                                     (TS_PACKET_SIZE * 8 * 1000);

        ts->sdt_packet_period      = (ts->mux_rate * SDT_RETRANS_TIME) /

                                     (TS_PACKET_SIZE * 8 * 1000);

        ts->pat_packet_period      = (ts->mux_rate * PAT_RETRANS_TIME) /

                                     (TS_PACKET_SIZE * 8 * 1000);

        if (ts->copyts < 1)

            ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);

    } else {

        /* Arbitrary values, PAT/PMT will also be written on video key frames */

        ts->sdt_packet_period = 200;

        ts->pat_packet_period = 40;

        if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (!pcr_st->codec->frame_size) {

                av_log(s, AV_LOG_WARNING, "frame size not set\n");

                service->pcr_packet_period =

                    pcr_st->codec->sample_rate / (10 * 512);

            } else {

                service->pcr_packet_period =

                    pcr_st->codec->sample_rate / (10 * pcr_st->codec->frame_size);

            }

        } else {

            // max delta PCR 0.1s

            // TODO: should be avg_frame_rate

            service->pcr_packet_period =

                ts_st->user_tb.den / (10 * ts_st->user_tb.num);

        }

        if (!service->pcr_packet_period)

            service->pcr_packet_period = 1;

    }

    ts->last_pat_ts = AV_NOPTS_VALUE;

    ts->last_sdt_ts = AV_NOPTS_VALUE;

    // The user specified a period, use only it

    if (ts->pat_period < INT_MAX/2) {

        ts->pat_packet_period = INT_MAX;

    }

    if (ts->sdt_period < INT_MAX/2) {

        ts->sdt_packet_period = INT_MAX;

    }

    // output a PCR as soon as possible

    service->pcr_packet_count = service->pcr_packet_period;

    ts->pat_packet_count      = ts->pat_packet_period - 1;

    ts->sdt_packet_count      = ts->sdt_packet_period - 1;

    if (ts->mux_rate == 1)

        av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");

    else

        av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);

    av_log(s, AV_LOG_VERBOSE,

           "pcr every %d pkts, sdt every %d, pat/pmt every %d pkts\n",

           service->pcr_packet_period,

           ts->sdt_packet_period, ts->pat_packet_period);

    if (ts->m2ts_mode == -1) {

        if (av_match_ext(s->filename, "m2ts")) {

            ts->m2ts_mode = 1;

        } else {

            ts->m2ts_mode = 0;

        }

    }

    return 0;

fail:

    av_freep(&pids);

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

        st    = s->streams[i];

        ts_st = st->priv_data;

        if (ts_st) {

            av_freep(&ts_st->payload);

            if (ts_st->amux) {

                avformat_free_context(ts_st->amux);

                ts_st->amux = NULL;

            }

        }

        av_freep(&st->priv_data);

    }

    for (i = 0; i < ts->nb_services; i++) {

        service = ts->services[i];

        av_freep(&service->provider_name);

        av_freep(&service->name);

        av_freep(&service);

    }

    av_freep(&ts->services);

    return ret;

}


static inline void gen_op_movl_seg_T0_vm(int seg_reg)

{

    tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 0xffff);

    tcg_gen_st32_tl(cpu_T[0], cpu_env,

                    offsetof(CPUX86State,segs[seg_reg].selector));

    tcg_gen_shli_tl(cpu_T[0], cpu_T[0], 4);

    tcg_gen_st_tl(cpu_T[0], cpu_env,

                  offsetof(CPUX86State,segs[seg_reg].base));

}


static void vc1_v_overlap_c(uint8_t* src, int stride)

{

    int i;

    int a, b, c, d;

    int d1, d2;

    int rnd = 1;

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

        a = src[-2*stride];

        b = src[-stride];

        c = src[0];

        d = src[stride];

        d1 = (a - d + 3 + rnd) >> 3;

        d2 = (a - d + b - c + 4 - rnd) >> 3;

        src[-2*stride] = a - d1;

        src[-stride] = b - d2;

        src[0] = c + d2;

        src[stride] = d + d1;

        src++;

        rnd = !rnd;

    }

}


void qvirtio_pci_set_msix_configuration_vector(QVirtioPCIDevice *d,

                                        QGuestAllocator *alloc, uint16_t entry)

{

    uint16_t vector;

    uint32_t control;

    void *addr;

    g_assert(d->pdev->msix_enabled);

    addr = d->pdev->msix_table + (entry * 16);

    g_assert_cmpint(entry, >=, 0);

    g_assert_cmpint(entry, <, qpci_msix_table_size(d->pdev));

    d->config_msix_entry = entry;

    d->config_msix_data = 0x12345678;

    d->config_msix_addr = guest_alloc(alloc, 4);

    qpci_io_writel(d->pdev, addr + PCI_MSIX_ENTRY_LOWER_ADDR,

                                                    d->config_msix_addr & ~0UL);

    qpci_io_writel(d->pdev, addr + PCI_MSIX_ENTRY_UPPER_ADDR,

                                            (d->config_msix_addr >> 32) & ~0UL);

    qpci_io_writel(d->pdev, addr + PCI_MSIX_ENTRY_DATA, d->config_msix_data);

    control = qpci_io_readl(d->pdev, addr + PCI_MSIX_ENTRY_VECTOR_CTRL);

    qpci_io_writel(d->pdev, addr + PCI_MSIX_ENTRY_VECTOR_CTRL,

                                        control & ~PCI_MSIX_ENTRY_CTRL_MASKBIT);

    qpci_io_writew(d->pdev, d->addr + VIRTIO_MSI_CONFIG_VECTOR, entry);

    vector = qpci_io_readw(d->pdev, d->addr + VIRTIO_MSI_CONFIG_VECTOR);

    g_assert_cmphex(vector, !=, VIRTIO_MSI_NO_VECTOR);

}


static void gen_rdhwr(DisasContext *ctx, int rt, int rd)

{

    TCGv t0;

#if !defined(CONFIG_USER_ONLY)

    /* The Linux kernel will emulate rdhwr if it's not supported natively.

       Therefore only check the ISA in system mode.  */

    check_insn(ctx, ISA_MIPS32R2);

#endif

    t0 = tcg_temp_new();

    switch (rd) {

    case 0:

        save_cpu_state(ctx, 1);

        gen_helper_rdhwr_cpunum(t0, cpu_env);

        gen_store_gpr(t0, rt);

        break;

    case 1:

        save_cpu_state(ctx, 1);

        gen_helper_rdhwr_synci_step(t0, cpu_env);

        gen_store_gpr(t0, rt);

        break;

    case 2:

        save_cpu_state(ctx, 1);

        gen_helper_rdhwr_cc(t0, cpu_env);

        gen_store_gpr(t0, rt);

        break;

    case 3:

        save_cpu_state(ctx, 1);

        gen_helper_rdhwr_ccres(t0, cpu_env);

        gen_store_gpr(t0, rt);

        break;

    case 29:

#if defined(CONFIG_USER_ONLY)

        tcg_gen_ld_tl(t0, cpu_env, offsetof(CPUMIPSState, tls_value));

        gen_store_gpr(t0, rt);

        break;

#else

        /* XXX: Some CPUs implement this in hardware.

           Not supported yet. */

#endif

    default:            /* Invalid */

        MIPS_INVAL("rdhwr");

        generate_exception(ctx, EXCP_RI);

        break;

    }

    tcg_temp_free(t0);

}


static void usb_msd_realize_bot(USBDevice *dev, Error **errp)

{

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

    usb_desc_create_serial(dev);

    usb_desc_init(dev);

    scsi_bus_new(&s->bus, sizeof(s->bus), DEVICE(dev),

                 &usb_msd_scsi_info_bot, NULL);

    s->bus.qbus.allow_hotplug = 0;

    usb_msd_handle_reset(dev);

}


static int decode_slice_header(FFV1Context *f, FFV1Context *fs)

{

    RangeCoder *c = &fs->c;

    uint8_t state[CONTEXT_SIZE];

    unsigned ps, i, context_count;

    memset(state, 128, sizeof(state));

    if (fs->ac > 1) {

        for (i = 1; i < 256; i++) {

            fs->c.one_state[i]        = f->state_transition[i];

            fs->c.zero_state[256 - i] = 256 - fs->c.one_state[i];

        }

    }

    fs->slice_x      = get_symbol(c, state, 0) * f->width;

    fs->slice_y      = get_symbol(c, state, 0) * f->height;

    fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width + fs->slice_x;

    fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;

    fs->slice_x     /= f->num_h_slices;

    fs->slice_y     /= f->num_v_slices;

    fs->slice_width  = fs->slice_width / f->num_h_slices - fs->slice_x;

    fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y;

    if ((unsigned)fs->slice_width  > f->width ||

        (unsigned)fs->slice_height > f->height)

        return AVERROR_INVALIDDATA;

    if ((unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width ||

        (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)

        return AVERROR_INVALIDDATA;

    for (i = 0; i < f->plane_count; i++) {

        PlaneContext *const p = &fs->plane[i];

        int idx               = get_symbol(c, state, 0);

        if (idx > (unsigned)f->quant_table_count) {

            av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");

            return AVERROR_INVALIDDATA;

        }

        p->quant_table_index = idx;

        memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));

        context_count = f->context_count[idx];

        if (p->context_count < context_count) {

            av_freep(&p->state);

            av_freep(&p->vlc_state);

        }

        p->context_count = context_count;

    }

    ps = get_symbol(c, state, 0);

    if (ps == 1) {

        f->cur->interlaced_frame = 1;

        f->cur->top_field_first  = 1;

    } else if (ps == 2) {

        f->cur->interlaced_frame = 1;

        f->cur->top_field_first  = 0;

    } else if (ps == 3) {

        f->cur->interlaced_frame = 0;

    }

    f->cur->sample_aspect_ratio.num = get_symbol(c, state, 0);

    f->cur->sample_aspect_ratio.den = get_symbol(c, state, 0);

    if (av_image_check_sar(f->width, f->height,

                           f->cur->sample_aspect_ratio) < 0) {

        av_log(f->avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",

               f->cur->sample_aspect_ratio.num,

               f->cur->sample_aspect_ratio.den);

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

    }

    return 0;

}


int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)

{

    if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn,

                            sizeof(diag_501), 0) ||

        cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)diag_501,

                            sizeof(diag_501), 1)) {

        return -EINVAL;

    }

    return 0;

}


static inline uint8_t *ram_chunk_start(const RDMALocalBlock *rdma_ram_block,

                                       uint64_t i)

{

    return (uint8_t *) (((uintptr_t) rdma_ram_block->local_host_addr)

                                    + (i << RDMA_REG_CHUNK_SHIFT));

}


static int decode_element(AVCodecContext *avctx, void *data, int ch_index,

                          int channels)

{

    ALACContext *alac = avctx->priv_data;

    int has_size, bps, is_compressed, decorr_shift, decorr_left_weight, ret;

    uint32_t output_samples;

    int i, ch;

    skip_bits(&alac->gb, 4);  /* element instance tag */

    skip_bits(&alac->gb, 12); /* unused header bits */

    /* the number of output samples is stored in the frame */

    has_size = get_bits1(&alac->gb);

    alac->extra_bits = get_bits(&alac->gb, 2) << 3;

    bps = alac->sample_size - alac->extra_bits + channels - 1;

    if (bps > 32) {

        av_log(avctx, AV_LOG_ERROR, "bps is unsupported: %d\n", bps);

        return AVERROR_PATCHWELCOME;

    }

    /* whether the frame is compressed */

    is_compressed = !get_bits1(&alac->gb);

    if (has_size)

        output_samples = get_bits_long(&alac->gb, 32);

    else

        output_samples = alac->max_samples_per_frame;

    if (!output_samples || output_samples > alac->max_samples_per_frame) {

        av_log(avctx, AV_LOG_ERROR, "invalid samples per frame: %d\n",

               output_samples);

        return AVERROR_INVALIDDATA;

    }

    if (!alac->nb_samples) {

        /* get output buffer */

        alac->frame.nb_samples = output_samples;

        if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {

            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

            return ret;

        }

    } else if (output_samples != alac->nb_samples) {

        av_log(avctx, AV_LOG_ERROR, "sample count mismatch: %u != %d\n",

               output_samples, alac->nb_samples);

        return AVERROR_INVALIDDATA;

    }

    alac->nb_samples = output_samples;

    if (alac->direct_output) {

        for (ch = 0; ch < channels; ch++)

            alac->output_samples_buffer[ch] = (int32_t *)alac->frame.extended_data[ch_index + ch];

    }

    if (is_compressed) {

        int16_t lpc_coefs[2][32];

        int lpc_order[2];

        int prediction_type[2];

        int lpc_quant[2];

        int rice_history_mult[2];

        decorr_shift       = get_bits(&alac->gb, 8);

        decorr_left_weight = get_bits(&alac->gb, 8);

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

            prediction_type[ch]   = get_bits(&alac->gb, 4);

            lpc_quant[ch]         = get_bits(&alac->gb, 4);

            rice_history_mult[ch] = get_bits(&alac->gb, 3);

            lpc_order[ch]         = get_bits(&alac->gb, 5);

            /* read the predictor table */

            for (i = lpc_order[ch] - 1; i >= 0; i--)

                lpc_coefs[ch][i] = get_sbits(&alac->gb, 16);

        }

        if (alac->extra_bits) {

            for (i = 0; i < alac->nb_samples; i++) {

                if(get_bits_left(&alac->gb) <= 0)

                    return -1;

                for (ch = 0; ch < channels; ch++)

                    alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);

            }

        }

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

            int ret=rice_decompress(alac, alac->predict_error_buffer[ch],

                            alac->nb_samples, bps,

                            rice_history_mult[ch] * alac->rice_history_mult / 4);

            if(ret<0)

                return ret;

            /* adaptive FIR filter */

            if (prediction_type[ch] == 15) {

                /* Prediction type 15 runs the adaptive FIR twice.

                 * The first pass uses the special-case coef_num = 31, while

                 * the second pass uses the coefs from the bitstream.

                 *

                 * However, this prediction type is not currently used by the

                 * reference encoder.

                 */

                lpc_prediction(alac->predict_error_buffer[ch],

                               alac->predict_error_buffer[ch],

                               alac->nb_samples, bps, NULL, 31, 0);

            } else if (prediction_type[ch] > 0) {

                av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",

                       prediction_type[ch]);

            }

            lpc_prediction(alac->predict_error_buffer[ch],

                           alac->output_samples_buffer[ch], alac->nb_samples,

                           bps, lpc_coefs[ch], lpc_order[ch], lpc_quant[ch]);

        }

    } else {

        /* not compressed, easy case */

        for (i = 0; i < alac->nb_samples; i++) {

            if(get_bits_left(&alac->gb) <= 0)

                return -1;

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

                alac->output_samples_buffer[ch][i] =

                         get_sbits_long(&alac->gb, alac->sample_size);

            }

        }

        alac->extra_bits   = 0;

        decorr_shift       = 0;

        decorr_left_weight = 0;

    }

    if (channels == 2 && decorr_left_weight) {

        decorrelate_stereo(alac->output_samples_buffer, alac->nb_samples,

                           decorr_shift, decorr_left_weight);

    }

    if (alac->extra_bits) {

        append_extra_bits(alac->output_samples_buffer, alac->extra_bits_buffer,

                          alac->extra_bits, channels, alac->nb_samples);

    }

    if(av_sample_fmt_is_planar(avctx->sample_fmt)) {

    switch(alac->sample_size) {

    case 16: {

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

            int16_t *outbuffer = (int16_t *)alac->frame.extended_data[ch_index + ch];

            for (i = 0; i < alac->nb_samples; i++)

                *outbuffer++ = alac->output_samples_buffer[ch][i];

        }}

        break;

    case 24: {

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

            for (i = 0; i < alac->nb_samples; i++)

                alac->output_samples_buffer[ch][i] <<= 8;

        }}

        break;

    }

    }else{

        switch(alac->sample_size) {

        case 16: {

            int16_t *outbuffer = ((int16_t *)alac->frame.extended_data[0]) + ch_index;

            for (i = 0; i < alac->nb_samples; i++) {

                for (ch = 0; ch < channels; ch++)

                    *outbuffer++ = alac->output_samples_buffer[ch][i];

                outbuffer += alac->channels - channels;

            }

            }

            break;

        case 24: {

            int32_t *outbuffer = ((int32_t *)alac->frame.extended_data[0]) + ch_index;

            for (i = 0; i < alac->nb_samples; i++) {

                for (ch = 0; ch < channels; ch++)

                    *outbuffer++ = alac->output_samples_buffer[ch][i] << 8;

                outbuffer += alac->channels - channels;

            }

            }

            break;

        case 32: {

            int32_t *outbuffer = ((int32_t *)alac->frame.extended_data[0]) + ch_index;

            for (i = 0; i < alac->nb_samples; i++) {

                for (ch = 0; ch < channels; ch++)

                    *outbuffer++ = alac->output_samples_buffer[ch][i];

                outbuffer += alac->channels - channels;

            }

            }

            break;

        }

    }

    return 0;

}


static av_always_inline float quantize_and_encode_band_cost_template(

                                struct AACEncContext *s,

                                PutBitContext *pb, const float *in,

                                const float *scaled, int size, int scale_idx,

                                int cb, const float lambda, const float uplim,

                                int *bits, int BT_ZERO, int BT_UNSIGNED,

                                int BT_PAIR, int BT_ESC)

{

    const float IQ = ff_aac_pow2sf_tab[200 + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];

    const float  Q = ff_aac_pow2sf_tab[200 - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];

    const float CLIPPED_ESCAPE = 165140.0f*IQ;

    int i, j, k;

    float cost = 0;

    const int dim = BT_PAIR ? 2 : 4;

    int resbits = 0;

    const float  Q34 = sqrtf(Q * sqrtf(Q));

    const int range  = aac_cb_range[cb];

    const int maxval = aac_cb_maxval[cb];

    int off;

    if (BT_ZERO) {

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

            cost += in[i]*in[i];

        if (bits)

            *bits = 0;

        return cost * lambda;

    }

    if (!scaled) {

        abs_pow34_v(s->scoefs, in, size);

        scaled = s->scoefs;

    }

    quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, maxval);

    if (BT_UNSIGNED) {

        off = 0;

    } else {

        off = maxval;

    }

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

        const float *vec;

        int *quants = s->qcoefs + i;

        int curidx = 0;

        int curbits;

        float rd = 0.0f;

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

            curidx *= range;

            curidx += quants[j] + off;

        }

        curbits =  ff_aac_spectral_bits[cb-1][curidx];

        vec     = &ff_aac_codebook_vectors[cb-1][curidx*dim];

        if (BT_UNSIGNED) {

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

                float t = fabsf(in[i+k]);

                float di;

                if (BT_ESC && vec[k] == 64.0f) { //FIXME: slow

                    if (t >= CLIPPED_ESCAPE) {

                        di = t - CLIPPED_ESCAPE;

                        curbits += 21;

                    } else {

                        int c = av_clip(quant(t, Q), 0, 8191);

                        di = t - c*cbrtf(c)*IQ;

                        curbits += av_log2(c)*2 - 4 + 1;

                    }

                } else {

                    di = t - vec[k]*IQ;

                }

                if (vec[k] != 0.0f)

                    curbits++;

                rd += di*di;

            }

        } else {

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

                float di = in[i+k] - vec[k]*IQ;

                rd += di*di;

            }

        }

        cost    += rd * lambda + curbits;

        resbits += curbits;

        if (cost >= uplim)

            return uplim;

        if (pb) {

            put_bits(pb, ff_aac_spectral_bits[cb-1][curidx], ff_aac_spectral_codes[cb-1][curidx]);

            if (BT_UNSIGNED)

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

                    if (ff_aac_codebook_vectors[cb-1][curidx*dim+j] != 0.0f)

                        put_bits(pb, 1, in[i+j] < 0.0f);

            if (BT_ESC) {

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

                    if (ff_aac_codebook_vectors[cb-1][curidx*2+j] == 64.0f) {

                        int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191);

                        int len = av_log2(coef);

                        put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);

                        put_bits(pb, len, coef & ((1 << len) - 1));

                    }

                }

            }

        }

    }

    if (bits)

        *bits = resbits;

    return cost;

}


static void event_loop(VideoState *cur_stream)

{

    SDL_Event event;

    double incr, pos, frac;

    for(;;) {

        double x;

        SDL_WaitEvent(&event);

        switch(event.type) {

        case SDL_KEYDOWN:

            if (exit_on_keydown) {

                do_exit(cur_stream);

                break;

            }

            switch(event.key.keysym.sym) {

            case SDLK_ESCAPE:

            case SDLK_q:

                do_exit(cur_stream);

                break;

            case SDLK_f:

                toggle_full_screen(cur_stream);

                break;

            case SDLK_p:

            case SDLK_SPACE:

                if (cur_stream)

                    toggle_pause(cur_stream);

                break;

            case SDLK_s: //S: Step to next frame

                if (cur_stream)

                    step_to_next_frame(cur_stream);

                break;

            case SDLK_a:

                if (cur_stream)

                    stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);

                break;

            case SDLK_v:

                if (cur_stream)

                    stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);

                break;

            case SDLK_t:

                if (cur_stream)

                    stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);

                break;

            case SDLK_w:

                if (cur_stream)

                    toggle_audio_display(cur_stream);

                break;

            case SDLK_LEFT:

                incr = -10.0;

                goto do_seek;

            case SDLK_RIGHT:

                incr = 10.0;

                goto do_seek;

            case SDLK_UP:

                incr = 60.0;

                goto do_seek;

            case SDLK_DOWN:

                incr = -60.0;

            do_seek:

                if (cur_stream) {

                    if (seek_by_bytes) {

                        if (cur_stream->video_stream >= 0 && cur_stream->video_current_pos>=0){

                            pos= cur_stream->video_current_pos;

                        }else if(cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos>=0){

                            pos= cur_stream->audio_pkt.pos;

                        }else

                            pos = avio_tell(cur_stream->ic->pb);

                        if (cur_stream->ic->bit_rate)

                            incr *= cur_stream->ic->bit_rate / 8.0;

                        else

                            incr *= 180000.0;

                        pos += incr;

                        stream_seek(cur_stream, pos, incr, 1);

                    } else {

                        pos = get_master_clock(cur_stream);

                        pos += incr;

                        stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0);

                    }

                }

                break;

            default:

                break;

            }

            break;

        case SDL_MOUSEBUTTONDOWN:

            if (exit_on_mousedown) {

                do_exit(cur_stream);

                break;

            }

        case SDL_MOUSEMOTION:

            if(event.type ==SDL_MOUSEBUTTONDOWN){

                x= event.button.x;

            }else{

                if(event.motion.state != SDL_PRESSED)

                    break;

                x= event.motion.x;

            }

            if (cur_stream) {

                if(seek_by_bytes || cur_stream->ic->duration<=0){

                    uint64_t size=  avio_size(cur_stream->ic->pb);

                    stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);

                }else{

                    int64_t ts;

                    int ns, hh, mm, ss;

                    int tns, thh, tmm, tss;

                    tns = cur_stream->ic->duration/1000000LL;

                    thh = tns/3600;

                    tmm = (tns%3600)/60;

                    tss = (tns%60);

                    frac = x/cur_stream->width;

                    ns = frac*tns;

                    hh = ns/3600;

                    mm = (ns%3600)/60;

                    ss = (ns%60);

                    fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d)       \n", frac*100,

                            hh, mm, ss, thh, tmm, tss);

                    ts = frac*cur_stream->ic->duration;

                    if (cur_stream->ic->start_time != AV_NOPTS_VALUE)

                        ts += cur_stream->ic->start_time;

                    stream_seek(cur_stream, ts, 0, 0);

                }

            }

            break;

        case SDL_VIDEORESIZE:

            if (cur_stream) {

                screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,

                                          SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);

                screen_width = cur_stream->width = event.resize.w;

                screen_height= cur_stream->height= event.resize.h;

            }

            break;

        case SDL_QUIT:

        case FF_QUIT_EVENT:

            do_exit(cur_stream);

            break;

        case FF_ALLOC_EVENT:

            video_open(event.user.data1);

            alloc_picture(event.user.data1);

            break;

        case FF_REFRESH_EVENT:

            video_refresh(event.user.data1);

            cur_stream->refresh=0;

            break;

        default:

            break;

        }

    }

}


static int sox_read_packet(AVFormatContext *s,

                           AVPacket *pkt)

{

    int ret, size;

    if (url_feof(s->pb))

        return AVERROR_EOF;

    size = SOX_SAMPLES*s->streams[0]->codec->block_align;

    ret = av_get_packet(s->pb, pkt, size);

    if (ret < 0)

        return AVERROR(EIO);

    pkt->stream_index = 0;

    pkt->size = ret;

    return 0;

}


static av_cold int svq1_encode_init(AVCodecContext *avctx)

{

    SVQ1Context * const s = avctx->priv_data;

    dsputil_init(&s->dsp, avctx);

    avctx->coded_frame= (AVFrame*)&s->picture;

    s->frame_width = avctx->width;

    s->frame_height = avctx->height;

    s->y_block_width = (s->frame_width + 15) / 16;

    s->y_block_height = (s->frame_height + 15) / 16;

    s->c_block_width = (s->frame_width / 4 + 15) / 16;

    s->c_block_height = (s->frame_height / 4 + 15) / 16;

    s->avctx= avctx;

    s->m.avctx= avctx;

    s->m.me.scratchpad= av_mallocz((avctx->width+64)*2*16*2*sizeof(uint8_t));

    s->m.me.map       = av_mallocz(ME_MAP_SIZE*sizeof(uint32_t));

    s->m.me.score_map = av_mallocz(ME_MAP_SIZE*sizeof(uint32_t));

    s->mb_type        = av_mallocz((s->y_block_width+1)*s->y_block_height*sizeof(int16_t));

    s->dummy          = av_mallocz((s->y_block_width+1)*s->y_block_height*sizeof(int32_t));

    h263_encode_init(&s->m); //mv_penalty

    return 0;

}


static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset)

{

    AHCICmdHdr *cmd = ad->cur_cmd;

    uint32_t opts = le32_to_cpu(cmd->opts);

    uint64_t prdt_addr = le64_to_cpu(cmd->tbl_addr) + 0x80;

    int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN;

    dma_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG));

    dma_addr_t real_prdt_len = prdt_len;

    uint8_t *prdt;

    int i;

    int r = 0;

    int sum = 0;

    int off_idx = -1;

    int off_pos = -1;

    int tbl_entry_size;

    IDEBus *bus = &ad->port;

    BusState *qbus = BUS(bus);

    if (!sglist_alloc_hint) {

        DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts);

        return -1;

    }

    /* map PRDT */

    if (!(prdt = dma_memory_map(ad->hba->as, prdt_addr, &prdt_len,

                                DMA_DIRECTION_TO_DEVICE))){

        DPRINTF(ad->port_no, "map failed\n");

        return -1;

    }

    if (prdt_len < real_prdt_len) {

        DPRINTF(ad->port_no, "mapped less than expected\n");

        r = -1;

        goto out;

    }

    /* Get entries in the PRDT, init a qemu sglist accordingly */

    if (sglist_alloc_hint > 0) {

        AHCI_SG *tbl = (AHCI_SG *)prdt;

        sum = 0;

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

            /* flags_size is zero-based */

            tbl_entry_size = (le32_to_cpu(tbl[i].flags_size) + 1);

            if (offset <= (sum + tbl_entry_size)) {

                off_idx = i;

                off_pos = offset - sum;

                break;

            }

            sum += tbl_entry_size;

        }

        if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) {

            DPRINTF(ad->port_no, "%s: Incorrect offset! "

                            "off_idx: %d, off_pos: %d\n",

                            __func__, off_idx, off_pos);

            r = -1;

            goto out;

        }

        qemu_sglist_init(sglist, qbus->parent, (sglist_alloc_hint - off_idx),

                         ad->hba->as);

        qemu_sglist_add(sglist, le64_to_cpu(tbl[off_idx].addr + off_pos),

                        le32_to_cpu(tbl[off_idx].flags_size) + 1 - off_pos);

        for (i = off_idx + 1; i < sglist_alloc_hint; i++) {

            /* flags_size is zero-based */

            qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr),

                            le32_to_cpu(tbl[i].flags_size) + 1);

        }

    }

out:

    dma_memory_unmap(ad->hba->as, prdt, prdt_len,

                     DMA_DIRECTION_TO_DEVICE, prdt_len);

    return r;

}


static av_always_inline void mpeg_motion_lowres(MpegEncContext *s,

                                                uint8_t *dest_y,

                                                uint8_t *dest_cb,

                                                uint8_t *dest_cr,

                                                int field_based,

                                                int bottom_field,

                                                int field_select,

                                                uint8_t **ref_picture,

                                                h264_chroma_mc_func *pix_op,

                                                int motion_x, int motion_y,

                                                int h, int mb_y)

{

    uint8_t *ptr_y, *ptr_cb, *ptr_cr;

    int mx, my, src_x, src_y, uvsrc_x, uvsrc_y, uvlinesize, linesize, sx, sy,

        uvsx, uvsy;

    const int lowres     = s->avctx->lowres;

    const int op_index   = FFMIN(lowres, 2);

    const int block_s    = 8>>lowres;

    const int s_mask     = (2 << lowres) - 1;

    const int h_edge_pos = s->h_edge_pos >> lowres;

    const int v_edge_pos = s->v_edge_pos >> lowres;

    linesize   = s->current_picture.f.linesize[0] << field_based;

    uvlinesize = s->current_picture.f.linesize[1] << field_based;

    // FIXME obviously not perfect but qpel will not work in lowres anyway

    if (s->quarter_sample) {

        motion_x /= 2;

        motion_y /= 2;

    }

    if (field_based) {

        motion_y += (bottom_field - field_select) * (1 << lowres - 1);

    }

    sx = motion_x & s_mask;

    sy = motion_y & s_mask;

    src_x = s->mb_x * 2 * block_s + (motion_x >> lowres + 1);

    src_y = (mb_y * 2 * block_s >> field_based) + (motion_y >> lowres + 1);

    if (s->out_format == FMT_H263) {

        uvsx    = ((motion_x >> 1) & s_mask) | (sx & 1);

        uvsy    = ((motion_y >> 1) & s_mask) | (sy & 1);

        uvsrc_x = src_x >> 1;

        uvsrc_y = src_y >> 1;

    } else if (s->out_format == FMT_H261) {

        // even chroma mv's are full pel in H261

        mx      = motion_x / 4;

        my      = motion_y / 4;

        uvsx    = (2 * mx) & s_mask;

        uvsy    = (2 * my) & s_mask;

        uvsrc_x = s->mb_x * block_s + (mx >> lowres);

        uvsrc_y =    mb_y * block_s + (my >> lowres);

    } else {

        mx      = motion_x / 2;

        my      = motion_y / 2;

        uvsx    = mx & s_mask;

        uvsy    = my & s_mask;

        uvsrc_x = s->mb_x * block_s                 + (mx >> lowres + 1);

        uvsrc_y =   (mb_y * block_s >> field_based) + (my >> lowres + 1);

    }

    ptr_y  = ref_picture[0] + src_y   * linesize   + src_x;

    ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;

    ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;

    if ((unsigned) src_x >  h_edge_pos - (!!sx) - 2 * block_s ||

        (unsigned) src_y > (v_edge_pos >> field_based) - (!!sy) - h) {

        s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y,

                                s->linesize, 17, 17 + field_based,

                                src_x, src_y << field_based, h_edge_pos,

                                v_edge_pos);

        ptr_y = s->edge_emu_buffer;

        if (!CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {

            uint8_t *uvbuf = s->edge_emu_buffer + 18 * s->linesize;

            s->dsp.emulated_edge_mc(uvbuf , ptr_cb, s->uvlinesize, 9,

                                    9 + field_based,

                                    uvsrc_x, uvsrc_y << field_based,

                                    h_edge_pos >> 1, v_edge_pos >> 1);

            s->dsp.emulated_edge_mc(uvbuf + 16, ptr_cr, s->uvlinesize, 9,

                                    9 + field_based,

                                    uvsrc_x, uvsrc_y << field_based,

                                    h_edge_pos >> 1, v_edge_pos >> 1);

            ptr_cb = uvbuf;

            ptr_cr = uvbuf + 16;

        }

    }

    // FIXME use this for field pix too instead of the obnoxious hack which changes picture.f.data

    if (bottom_field) {

        dest_y  += s->linesize;

        dest_cb += s->uvlinesize;

        dest_cr += s->uvlinesize;

    }

    if (field_select) {

        ptr_y   += s->linesize;

        ptr_cb  += s->uvlinesize;

        ptr_cr  += s->uvlinesize;

    }

    sx = (sx << 2) >> lowres;

    sy = (sy << 2) >> lowres;

    pix_op[lowres - 1](dest_y, ptr_y, linesize, h, sx, sy);

    if (!CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {

        uvsx = (uvsx << 2) >> lowres;

        uvsy = (uvsy << 2) >> lowres;

        pix_op[op_index](dest_cb, ptr_cb, uvlinesize, h >> s->chroma_y_shift,

                         uvsx, uvsy);

        pix_op[op_index](dest_cr, ptr_cr, uvlinesize, h >> s->chroma_y_shift,

                         uvsx, uvsy);

    }

    // FIXME h261 lowres loop filter

}


static int decode_frame(AVCodecContext *avctx,

                        void *data,

                        int *got_frame,

                        AVPacket *avpkt)

{

    const uint8_t *buf      = avpkt->data;

    unsigned int   buf_size = avpkt->size;

    const uint8_t *buf_end  = buf + buf_size;

    const AVPixFmtDescriptor *desc;

    EXRContext *const s = avctx->priv_data;

    AVFrame *picture  = data;

    AVFrame *const p = &s->picture;

    uint8_t *ptr;

    int i, x, y, stride, magic_number, version, flags, ret;

    int w = 0;

    int h = 0;

    unsigned int xmin   = ~0;

    unsigned int xmax   = ~0;

    unsigned int ymin   = ~0;

    unsigned int ymax   = ~0;

    unsigned int xdelta = ~0;

    int out_line_size;

    int bxmin, axmax;

    int scan_lines_per_block;

    unsigned long scan_line_size;

    unsigned long uncompressed_size;

    unsigned int current_channel_offset = 0;

    s->channel_offsets[0] = -1;

    s->channel_offsets[1] = -1;

    s->channel_offsets[2] = -1;

    s->channel_offsets[3] = -1;

    s->bits_per_color_id = -1;

    s->compr = -1;

    if (buf_size < 10) {

        av_log(avctx, AV_LOG_ERROR, "Too short header to parse\n");

        return AVERROR_INVALIDDATA;

    }

    magic_number = bytestream_get_le32(&buf);

    if (magic_number != 20000630) { // As per documentation of OpenEXR it's supposed to be int 20000630 little-endian

        av_log(avctx, AV_LOG_ERROR, "Wrong magic number %d\n", magic_number);

        return AVERROR_INVALIDDATA;

    }

    version = bytestream_get_byte(&buf);

    if (version != 2) {

        av_log(avctx, AV_LOG_ERROR, "Unsupported version %d\n", version);

        return AVERROR_PATCHWELCOME;

    }

    flags = bytestream_get_le24(&buf);

    if (flags & 0x2) {

        av_log(avctx, AV_LOG_ERROR, "Tile based images are not supported\n");

        return AVERROR_PATCHWELCOME;

    }

    // Parse the header

    while (buf < buf_end && buf[0]) {

        unsigned int variable_buffer_data_size;

        // Process the channel list

        if (check_header_variable(avctx, &buf, buf_end, "channels", "chlist", 38, &variable_buffer_data_size) >= 0) {

            const uint8_t *channel_list_end;

            if (!variable_buffer_data_size)

                return AVERROR_INVALIDDATA;

            channel_list_end = buf + variable_buffer_data_size;

            while (channel_list_end - buf >= 19) {

                int current_bits_per_color_id = -1;

                int channel_index = -1;

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

                    channel_index = 0;

                else if (!strcmp(buf, "G"))

                    channel_index = 1;

                else if (!strcmp(buf, "B"))

                    channel_index = 2;

                else if (!strcmp(buf, "A"))

                    channel_index = 3;

                else

                    av_log(avctx, AV_LOG_WARNING, "Unsupported channel %.256s\n", buf);

                while (bytestream_get_byte(&buf) && buf < channel_list_end)

                    continue; /* skip */

                if (channel_list_end - * &buf < 4) {

                    av_log(avctx, AV_LOG_ERROR, "Incomplete header\n");

                    return AVERROR_INVALIDDATA;

                }

                current_bits_per_color_id = bytestream_get_le32(&buf);

                if (current_bits_per_color_id > 2) {

                    av_log(avctx, AV_LOG_ERROR, "Unknown color format\n");

                    return AVERROR_INVALIDDATA;

                }

                if (channel_index >= 0) {

                    if (s->bits_per_color_id != -1 && s->bits_per_color_id != current_bits_per_color_id) {

                        av_log(avctx, AV_LOG_ERROR, "RGB channels not of the same depth\n");

                        return AVERROR_INVALIDDATA;

                    }

                    s->bits_per_color_id  = current_bits_per_color_id;

                    s->channel_offsets[channel_index] = current_channel_offset;

                }

                current_channel_offset += 1 << current_bits_per_color_id;

                buf += 12;

            }

            /* Check if all channels are set with an offset or if the channels

             * are causing an overflow  */

            if (FFMIN3(s->channel_offsets[0],

                       s->channel_offsets[1],

                       s->channel_offsets[2]) < 0) {

                if (s->channel_offsets[0] < 0)

                    av_log(avctx, AV_LOG_ERROR, "Missing red channel\n");

                if (s->channel_offsets[1] < 0)

                    av_log(avctx, AV_LOG_ERROR, "Missing green channel\n");

                if (s->channel_offsets[2] < 0)

                    av_log(avctx, AV_LOG_ERROR, "Missing blue channel\n");

                return AVERROR_INVALIDDATA;

            }

            buf = channel_list_end;

            continue;

        } else if (check_header_variable(avctx, &buf, buf_end, "dataWindow", "box2i", 31, &variable_buffer_data_size) >= 0) {

            if (!variable_buffer_data_size)

                return AVERROR_INVALIDDATA;

            xmin = AV_RL32(buf);

            ymin = AV_RL32(buf + 4);

            xmax = AV_RL32(buf + 8);

            ymax = AV_RL32(buf + 12);

            xdelta = (xmax-xmin) + 1;

            buf += variable_buffer_data_size;

            continue;

        } else if (check_header_variable(avctx, &buf, buf_end, "displayWindow", "box2i", 34, &variable_buffer_data_size) >= 0) {

            if (!variable_buffer_data_size)

                return AVERROR_INVALIDDATA;

            w = AV_RL32(buf + 8) + 1;

            h = AV_RL32(buf + 12) + 1;

            buf += variable_buffer_data_size;

            continue;

        } else if (check_header_variable(avctx, &buf, buf_end, "lineOrder", "lineOrder", 25, &variable_buffer_data_size) >= 0) {

            if (!variable_buffer_data_size)

                return AVERROR_INVALIDDATA;

            if (*buf) {

                av_log(avctx, AV_LOG_ERROR, "Doesn't support this line order : %d\n", *buf);

                return AVERROR_PATCHWELCOME;

            }

            buf += variable_buffer_data_size;

            continue;

        } else if (check_header_variable(avctx, &buf, buf_end, "pixelAspectRatio", "float", 31, &variable_buffer_data_size) >= 0) {

            if (!variable_buffer_data_size)

                return AVERROR_INVALIDDATA;

            avctx->sample_aspect_ratio = av_d2q(av_int2float(AV_RL32(buf)), 255);

            buf += variable_buffer_data_size;

            continue;

        } else if (check_header_variable(avctx, &buf, buf_end, "compression", "compression", 29, &variable_buffer_data_size) >= 0) {

            if (!variable_buffer_data_size)

                return AVERROR_INVALIDDATA;

            if (s->compr == -1)

                s->compr = *buf;

            else

                av_log(avctx, AV_LOG_WARNING, "Found more than one compression attribute\n");

            buf += variable_buffer_data_size;

            continue;

        }

        // Check if there is enough bytes for a header

        if (buf_end - buf <= 9) {

            av_log(avctx, AV_LOG_ERROR, "Incomplete header\n");

            return AVERROR_INVALIDDATA;

        }

        // Process unknown variables

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

            // Skip variable name/type

            while (++buf < buf_end)

                if (buf[0] == 0x0)

                    break;

        }

        buf++;

        // Skip variable length

        if (buf_end - buf >= 5) {

            variable_buffer_data_size = get_header_variable_length(&buf, buf_end);

            if (!variable_buffer_data_size) {

                av_log(avctx, AV_LOG_ERROR, "Incomplete header\n");

                return AVERROR_INVALIDDATA;

            }

            buf += variable_buffer_data_size;

        }

    }

    if (s->compr == -1) {

        av_log(avctx, AV_LOG_ERROR, "Missing compression attribute\n");

        return AVERROR_INVALIDDATA;

    }

    if (buf >= buf_end) {

        av_log(avctx, AV_LOG_ERROR, "Incomplete frame\n");

        return AVERROR_INVALIDDATA;

    }

    buf++;

    switch (s->bits_per_color_id) {

    case 2: // 32-bit

    case 1: // 16-bit

        if (s->channel_offsets[3] >= 0)

            avctx->pix_fmt = AV_PIX_FMT_RGBA64;

        else

            avctx->pix_fmt = AV_PIX_FMT_RGB48;

        break;

    // 8-bit

    case 0:

        av_log_missing_feature(avctx, "8-bit OpenEXR", 1);

        return AVERROR_PATCHWELCOME;

    default:

        av_log(avctx, AV_LOG_ERROR, "Unknown color format : %d\n", s->bits_per_color_id);

        return AVERROR_INVALIDDATA;

    }

    switch (s->compr) {

    case EXR_RAW:

    case EXR_RLE:

    case EXR_ZIP1:

        scan_lines_per_block = 1;

        break;

    case EXR_ZIP16:

        scan_lines_per_block = 16;

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Compression type %d is not supported\n", s->compr);

        return AVERROR_PATCHWELCOME;

    }

    if (s->picture.data[0])

        ff_thread_release_buffer(avctx, &s->picture);

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

        return AVERROR_INVALIDDATA;

    // Verify the xmin, xmax, ymin, ymax and xdelta before setting the actual image size

    if (xmin > xmax || ymin > ymax || xdelta != xmax - xmin + 1 || xmax >= w || ymax >= h) {

        av_log(avctx, AV_LOG_ERROR, "Wrong sizing or missing size information\n");

        return AVERROR_INVALIDDATA;

    }

    if (w != avctx->width || h != avctx->height) {

        avcodec_set_dimensions(avctx, w, h);

    }

    desc = av_pix_fmt_desc_get(avctx->pix_fmt);

    bxmin = xmin * 2 * desc->nb_components;

    axmax = (avctx->width - (xmax + 1)) * 2 * desc->nb_components;

    out_line_size = avctx->width * 2 * desc->nb_components;

    scan_line_size = xdelta * current_channel_offset;

    uncompressed_size = scan_line_size * scan_lines_per_block;

    if (s->compr != EXR_RAW) {

        av_fast_padded_malloc(&s->uncompressed_data, &s->uncompressed_size, uncompressed_size);

        av_fast_padded_malloc(&s->tmp, &s->tmp_size, uncompressed_size);

        if (!s->uncompressed_data || !s->tmp)

            return AVERROR(ENOMEM);

    }

    if ((ret = ff_thread_get_buffer(avctx, p)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return ret;

    }

    ptr    = p->data[0];

    stride = p->linesize[0];

    // Zero out the start if ymin is not 0

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

        memset(ptr, 0, out_line_size);

        ptr += stride;

    }

    // Process the actual scan line blocks

    for (y = ymin; y <= ymax; y += scan_lines_per_block) {

        uint16_t *ptr_x = (uint16_t *)ptr;

        if (buf_end - buf > 8) {

            /* Read the lineoffset from the line offset table and add 8 bytes

               to skip the coordinates and data size fields */

            const uint64_t line_offset = bytestream_get_le64(&buf) + 8;

            int32_t data_size;

            // Check if the buffer has the required bytes needed from the offset

            if ((line_offset > buf_size) ||

                (s->compr == EXR_RAW && line_offset > avpkt->size - xdelta * current_channel_offset) ||

                (s->compr != EXR_RAW && line_offset > buf_size - (data_size = AV_RL32(avpkt->data + line_offset - 4)))) {

                // Line offset is probably wrong and not inside the buffer

                av_log(avctx, AV_LOG_WARNING, "Line offset for line %d is out of reach setting it to black\n", y);

                for (i = 0; i < scan_lines_per_block && y + i <= ymax; i++, ptr += stride) {

                    ptr_x = (uint16_t *)ptr;

                    memset(ptr_x, 0, out_line_size);

                }

            } else {

                const uint8_t *red_channel_buffer, *green_channel_buffer, *blue_channel_buffer, *alpha_channel_buffer = 0;

                if (scan_lines_per_block > 1)

                    uncompressed_size = scan_line_size * FFMIN(scan_lines_per_block, ymax - y + 1);

                if ((s->compr == EXR_ZIP1 || s->compr == EXR_ZIP16) && data_size < uncompressed_size) {

                    unsigned long dest_len = uncompressed_size;

                    if (uncompress(s->tmp, &dest_len, avpkt->data + line_offset, data_size) != Z_OK ||

                        dest_len != uncompressed_size) {

                        av_log(avctx, AV_LOG_ERROR, "error during zlib decompression\n");

                        return AVERROR(EINVAL);

                    }

                } else if (s->compr == EXR_RLE && data_size < uncompressed_size) {

                    if (rle_uncompress(avpkt->data + line_offset, data_size, s->tmp, uncompressed_size)) {

                        av_log(avctx, AV_LOG_ERROR, "error during rle decompression\n");

                        return AVERROR(EINVAL);

                    }

                }

                if (s->compr != EXR_RAW && data_size < uncompressed_size) {

                    predictor(s->tmp, uncompressed_size);

                    reorder_pixels(s->tmp, s->uncompressed_data, uncompressed_size);

                    red_channel_buffer   = s->uncompressed_data + xdelta * s->channel_offsets[0];

                    green_channel_buffer = s->uncompressed_data + xdelta * s->channel_offsets[1];

                    blue_channel_buffer  = s->uncompressed_data + xdelta * s->channel_offsets[2];

                    if (s->channel_offsets[3] >= 0)

                        alpha_channel_buffer = s->uncompressed_data + xdelta * s->channel_offsets[3];

                } else {

                    red_channel_buffer   = avpkt->data + line_offset + xdelta * s->channel_offsets[0];

                    green_channel_buffer = avpkt->data + line_offset + xdelta * s->channel_offsets[1];

                    blue_channel_buffer  = avpkt->data + line_offset + xdelta * s->channel_offsets[2];

                    if (s->channel_offsets[3] >= 0)

                        alpha_channel_buffer = avpkt->data + line_offset + xdelta * s->channel_offsets[3];

                }

                for (i = 0; i < scan_lines_per_block && y + i <= ymax; i++, ptr += stride) {

                    const uint8_t *r, *g, *b, *a;

                    r = red_channel_buffer;

                    g = green_channel_buffer;

                    b = blue_channel_buffer;

                    if (alpha_channel_buffer)

                        a = alpha_channel_buffer;

                    ptr_x = (uint16_t *)ptr;

                    // Zero out the start if xmin is not 0

                    memset(ptr_x, 0, bxmin);

                    ptr_x += xmin * desc->nb_components;

                    if (s->bits_per_color_id == 2) {

                        // 32-bit

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

                            *ptr_x++ = exr_flt2uint(bytestream_get_le32(&r));

                            *ptr_x++ = exr_flt2uint(bytestream_get_le32(&g));

                            *ptr_x++ = exr_flt2uint(bytestream_get_le32(&b));

                            if (alpha_channel_buffer)

                                *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));

                        }

                    } else {

                        // 16-bit

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

                            *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&r));

                            *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&g));

                            *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&b));

                            if (alpha_channel_buffer)

                                *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&a));

                        }

                    }

                    // Zero out the end if xmax+1 is not w

                    memset(ptr_x, 0, axmax);

                    red_channel_buffer   += scan_line_size;

                    green_channel_buffer += scan_line_size;

                    blue_channel_buffer  += scan_line_size;

                    if (alpha_channel_buffer)

                        alpha_channel_buffer += scan_line_size;

                }

            }

        }

    }

    // Zero out the end if ymax+1 is not h

    for (y = ymax + 1; y < avctx->height; y++) {

        memset(ptr, 0, out_line_size);

        ptr += stride;

    }

    *picture   = s->picture;

    *got_frame = 1;

    return buf_size;

}


static void csrhci_reset(struct csrhci_s *s)

{

    s->out_len = 0;

    s->out_size = FIFO_LEN;

    s->in_len = 0;

    s->baud_delay = NANOSECONDS_PER_SECOND;

    s->enable = 0;

    s->in_hdr = INT_MAX;

    s->in_data = INT_MAX;

    s->modem_state = 0;

    /* After a while... (but sooner than 10ms) */

    s->modem_state |= CHR_TIOCM_CTS;

    memset(&s->bd_addr, 0, sizeof(bdaddr_t));

}


void rgb15tobgr15(const uint8_t *src, uint8_t *dst, unsigned int src_size)

{

	unsigned i;

	unsigned num_pixels = src_size >> 1;

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

	{

	    unsigned b,g,r;

	    register uint16_t rgb;

	    rgb = src[2*i];

	    r = rgb&0x1F;

	    g = (rgb&0x3E0)>>5;

	    b = (rgb&0x7C00)>>10;

	    dst[2*i] = (b&0x1F) | ((g&0x1F)<<5) | ((r&0x1F)<<10);

	}

}


int net_init_vhost_user(const Netdev *netdev, const char *name,

                        NetClientState *peer, Error **errp)

{

    int queues;

    const NetdevVhostUserOptions *vhost_user_opts;

    CharDriverState *chr;

    assert(netdev->type == NET_CLIENT_DRIVER_VHOST_USER);

    vhost_user_opts = &netdev->u.vhost_user;

    chr = net_vhost_parse_chardev(vhost_user_opts, errp);

    if (!chr) {

        return -1;

    }

    /* verify net frontend */

    if (qemu_opts_foreach(qemu_find_opts("device"), net_vhost_check_net,

                          (char *)name, errp)) {

        return -1;

    }

    queues = vhost_user_opts->has_queues ? vhost_user_opts->queues : 1;

    if (queues < 1 || queues > MAX_QUEUE_NUM) {

        error_setg(errp,

                   "vhost-user number of queues must be in range [1, %d]",

                   MAX_QUEUE_NUM);

        return -1;

    }

    return net_vhost_user_init(peer, "vhost_user", name, chr, queues);

}


static int lag_decode_prob(GetBitContext *gb, uint32_t *value)

{

    static const uint8_t series[] = { 1, 2, 3, 5, 8, 13, 21 };

    int i;

    int bit     = 0;

    int bits    = 0;

    int prevbit = 0;

    unsigned val;

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

        if (prevbit && bit)

            break;

        prevbit = bit;

        bit = get_bits1(gb);

        if (bit && !prevbit)

            bits += series[i];

    }

    bits--;

    if (bits < 0 || bits > 31) {

        *value = 0;

        return -1;

    } else if (bits == 0) {

        *value = 0;

        return 0;

    }

    val  = get_bits_long(gb, bits);

    val |= 1 << bits;

    *value = val - 1;

    return 0;

}


static void check_add_res(HEVCDSPContext h, int bit_depth)

{

    int i;

    LOCAL_ALIGNED_32(int16_t, res0, [32 * 32]);

    LOCAL_ALIGNED_32(int16_t, res1, [32 * 32]);

    LOCAL_ALIGNED_32(uint8_t, dst0, [32 * 32 * 2]);

    LOCAL_ALIGNED_32(uint8_t, dst1, [32 * 32 * 2]);

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

        int block_size = 1 << i;

        int size = block_size * block_size;

        ptrdiff_t stride = block_size << (bit_depth > 8);

        declare_func_emms(AV_CPU_FLAG_MMX, void, uint8_t *dst, int16_t *res, ptrdiff_t stride);

        randomize_buffers(res0, size);

        randomize_buffers2(dst0, size);

        memcpy(res1, res0, sizeof(*res0) * size);

        memcpy(dst1, dst0, size);

        if (check_func(h.add_residual[i - 2], "add_res_%dx%d_%d", block_size, block_size, bit_depth)) {

            call_ref(dst0, res0, stride);

            call_new(dst1, res1, stride);

            if (memcmp(dst0, dst1, size))

                fail();

            bench_new(dst1, res1, stride);

        }

    }

}


static void test_validate_fail_union_flat(TestInputVisitorData *data,

                                          const void *unused)

{

    UserDefFlatUnion *tmp = NULL;

    Error *errp = NULL;

    Visitor *v;

    v = validate_test_init(data, "{ 'string': 'c', 'integer': 41, 'boolean': true }");

    visit_type_UserDefFlatUnion(v, &tmp, NULL, &errp);

    g_assert(error_is_set(&errp));

    qapi_free_UserDefFlatUnion(tmp);

}


void cpu_x86_update_cr4(CPUX86State *env, uint32_t new_cr4)

{

#if defined(DEBUG_MMU)

    printf("CR4 update: CR4=%08x\n", (uint32_t)env->cr[4]);

#endif

    if ((new_cr4 & (CR4_PGE_MASK | CR4_PAE_MASK | CR4_PSE_MASK)) !=

        (env->cr[4] & (CR4_PGE_MASK | CR4_PAE_MASK | CR4_PSE_MASK))) {

        tlb_flush(env, 1);

    }

    /* SSE handling */

    if (!(env->cpuid_features & CPUID_SSE))

        new_cr4 &= ~CR4_OSFXSR_MASK;

    if (new_cr4 & CR4_OSFXSR_MASK)

        env->hflags |= HF_OSFXSR_MASK;

    else

        env->hflags &= ~HF_OSFXSR_MASK;

    env->cr[4] = new_cr4;

}