static ssize_t qio_channel_websock_readv(QIOChannel *ioc,

                                         const struct iovec *iov,

                                         size_t niov,

                                         int **fds,

                                         size_t *nfds,

                                         Error **errp)

{

    QIOChannelWebsock *wioc = QIO_CHANNEL_WEBSOCK(ioc);

    size_t i;

    ssize_t got = 0;

    ssize_t ret;

    if (wioc->io_err) {

        *errp = error_copy(wioc->io_err);

        return -1;

    }

    if (!wioc->rawinput.offset) {

        ret = qio_channel_websock_read_wire(QIO_CHANNEL_WEBSOCK(ioc), errp);

        if (ret < 0) {

            return ret;

        }

    }

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

        size_t want = iov[i].iov_len;

        if (want > (wioc->rawinput.offset - got)) {

            want = (wioc->rawinput.offset - got);

        }

        memcpy(iov[i].iov_base,

               wioc->rawinput.buffer + got,

               want);

        got += want;

        if (want < iov[i].iov_len) {

            break;

        }

    }

    buffer_advance(&wioc->rawinput, got);

    qio_channel_websock_set_watch(wioc);

    return got;

}


static void ppc_core99_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    const char *boot_device = machine->boot_order;

    PowerPCCPU *cpu = NULL;

    CPUPPCState *env = NULL;

    char *filename;

    qemu_irq *pic, **openpic_irqs;

    MemoryRegion *isa = g_new(MemoryRegion, 1);

    MemoryRegion *unin_memory = g_new(MemoryRegion, 1);

    MemoryRegion *unin2_memory = g_new(MemoryRegion, 1);

    int linux_boot, i, j, k;

    MemoryRegion *ram = g_new(MemoryRegion, 1), *bios = g_new(MemoryRegion, 1);

    hwaddr kernel_base, initrd_base, cmdline_base = 0;

    long kernel_size, initrd_size;

    PCIBus *pci_bus;

    PCIDevice *macio;

    MACIOIDEState *macio_ide;

    BusState *adb_bus;

    MacIONVRAMState *nvr;

    int bios_size;

    MemoryRegion *pic_mem, *escc_mem;

    MemoryRegion *escc_bar = g_new(MemoryRegion, 1);

    int ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    void *fw_cfg;

    int machine_arch;

    SysBusDevice *s;

    DeviceState *dev;

    int *token = g_new(int, 1);

    hwaddr nvram_addr = 0xFFF04000;

    uint64_t tbfreq;

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL)

#ifdef TARGET_PPC64

        cpu_model = "970fx";

#else

        cpu_model = "G4";

#endif

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

        cpu = cpu_ppc_init(cpu_model);

        if (cpu == NULL) {

            fprintf(stderr, "Unable to find PowerPC CPU definition\n");

            exit(1);

        }

        env = &cpu->env;

        /* Set time-base frequency to 100 Mhz */

        cpu_ppc_tb_init(env, TBFREQ);

        qemu_register_reset(ppc_core99_reset, cpu);

    }

    /* allocate RAM */

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

    memory_region_add_subregion(get_system_memory(), 0, ram);

    /* allocate and load BIOS */

    memory_region_init_ram(bios, NULL, "ppc_core99.bios", BIOS_SIZE,

                           &error_abort);

    vmstate_register_ram_global(bios);

    if (bios_name == NULL)

        bios_name = PROM_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    memory_region_set_readonly(bios, true);

    memory_region_add_subregion(get_system_memory(), PROM_ADDR, bios);

    /* Load OpenBIOS (ELF) */

    if (filename) {

        bios_size = load_elf(filename, NULL, NULL, NULL,

                             NULL, NULL, 1, ELF_MACHINE, 0);

        g_free(filename);

    } else {

        bios_size = -1;

    }

    if (bios_size < 0 || bios_size > BIOS_SIZE) {

        hw_error("qemu: could not load PowerPC bios '%s'\n", bios_name);

        exit(1);

    }

    if (linux_boot) {

        uint64_t lowaddr = 0;

        int bswap_needed;

#ifdef BSWAP_NEEDED

        bswap_needed = 1;

#else

        bswap_needed = 0;

#endif

        kernel_base = KERNEL_LOAD_ADDR;

        kernel_size = load_elf(kernel_filename, translate_kernel_address, NULL,

                               NULL, &lowaddr, NULL, 1, ELF_MACHINE, 0);

        if (kernel_size < 0)

            kernel_size = load_aout(kernel_filename, kernel_base,

                                    ram_size - kernel_base, bswap_needed,

                                    TARGET_PAGE_SIZE);

        if (kernel_size < 0)

            kernel_size = load_image_targphys(kernel_filename,

                                              kernel_base,

                                              ram_size - kernel_base);

        if (kernel_size < 0) {

            hw_error("qemu: could not load kernel '%s'\n", kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = round_page(kernel_base + kernel_size + KERNEL_GAP);

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

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

                         initrd_filename);

                exit(1);

            }

            cmdline_base = round_page(initrd_base + initrd_size);

        } else {

            initrd_base = 0;

            initrd_size = 0;

            cmdline_base = round_page(kernel_base + kernel_size + KERNEL_GAP);

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

        /* We consider that NewWorld PowerMac never have any floppy drive

         * For now, OHW cannot boot from the network.

         */

        for (i = 0; boot_device[i] != '\0'; i++) {

            if (boot_device[i] >= 'c' && boot_device[i] <= 'f') {

                ppc_boot_device = boot_device[i];

                break;

            }

        }

        if (ppc_boot_device == '\0') {

            fprintf(stderr, "No valid boot device for Mac99 machine\n");

            exit(1);

        }

    }

    /* Register 8 MB of ISA IO space */

    memory_region_init_alias(isa, NULL, "isa_mmio",

                             get_system_io(), 0, 0x00800000);

    memory_region_add_subregion(get_system_memory(), 0xf2000000, isa);

    /* UniN init: XXX should be a real device */

    memory_region_init_io(unin_memory, NULL, &unin_ops, token, "unin", 0x1000);

    memory_region_add_subregion(get_system_memory(), 0xf8000000, unin_memory);

    memory_region_init_io(unin2_memory, NULL, &unin_ops, token, "unin", 0x1000);

    memory_region_add_subregion(get_system_memory(), 0xf3000000, unin2_memory);

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

    openpic_irqs[0] =

        g_malloc0(smp_cpus * sizeof(qemu_irq) * OPENPIC_OUTPUT_NB);

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

        /* Mac99 IRQ connection between OpenPIC outputs pins

         * and PowerPC input pins

         */

        switch (PPC_INPUT(env)) {

        case PPC_FLAGS_INPUT_6xx:

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

            openpic_irqs[i][OPENPIC_OUTPUT_INT] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_CINT] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_MCK] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_MCP];

            /* Not connected ? */

            openpic_irqs[i][OPENPIC_OUTPUT_DEBUG] = NULL;

            /* Check this */

            openpic_irqs[i][OPENPIC_OUTPUT_RESET] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_HRESET];

            break;

#if defined(TARGET_PPC64)

        case PPC_FLAGS_INPUT_970:

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

            openpic_irqs[i][OPENPIC_OUTPUT_INT] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_CINT] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_MCK] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_MCP];

            /* Not connected ? */

            openpic_irqs[i][OPENPIC_OUTPUT_DEBUG] = NULL;

            /* Check this */

            openpic_irqs[i][OPENPIC_OUTPUT_RESET] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_HRESET];

            break;

#endif /* defined(TARGET_PPC64) */

        default:

            hw_error("Bus model not supported on mac99 machine\n");

            exit(1);

        }

    }

    pic = g_new0(qemu_irq, 64);

    dev = qdev_create(NULL, TYPE_OPENPIC);

    qdev_prop_set_uint32(dev, "model", OPENPIC_MODEL_RAVEN);

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

    pic_mem = s->mmio[0].memory;

    k = 0;

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

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

            sysbus_connect_irq(s, k++, openpic_irqs[i][j]);

        }

    }

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

        pic[i] = qdev_get_gpio_in(dev, i);

    }

    if (PPC_INPUT(env) == PPC_FLAGS_INPUT_970) {

        /* 970 gets a U3 bus */

        pci_bus = pci_pmac_u3_init(pic, get_system_memory(), get_system_io());

        machine_arch = ARCH_MAC99_U3;

        machine->usb |= defaults_enabled();

    } else {

        pci_bus = pci_pmac_init(pic, get_system_memory(), get_system_io());

        machine_arch = ARCH_MAC99;

    }

    /* Timebase Frequency */

    if (kvm_enabled()) {

        tbfreq = kvmppc_get_tbfreq();

    } else {

        tbfreq = TBFREQ;

    }

    /* init basic PC hardware */

    escc_mem = escc_init(0, pic[0x25], pic[0x24],

                         serial_hds[0], serial_hds[1], ESCC_CLOCK, 4);

    memory_region_init_alias(escc_bar, NULL, "escc-bar",

                             escc_mem, 0, memory_region_size(escc_mem));

    macio = pci_create(pci_bus, -1, TYPE_NEWWORLD_MACIO);

    dev = DEVICE(macio);

    qdev_connect_gpio_out(dev, 0, pic[0x19]); /* CUDA */

    qdev_connect_gpio_out(dev, 1, pic[0x0d]); /* IDE */

    qdev_connect_gpio_out(dev, 2, pic[0x02]); /* IDE DMA */

    qdev_connect_gpio_out(dev, 3, pic[0x0e]); /* IDE */

    qdev_connect_gpio_out(dev, 4, pic[0x03]); /* IDE DMA */

    qdev_prop_set_uint64(dev, "frequency", tbfreq);

    macio_init(macio, pic_mem, escc_bar);

    /* We only emulate 2 out of 3 IDE controllers for now */

    ide_drive_get(hd, ARRAY_SIZE(hd));

    macio_ide = MACIO_IDE(object_resolve_path_component(OBJECT(macio),

                                                        "ide[0]"));

    macio_ide_init_drives(macio_ide, hd);

    macio_ide = MACIO_IDE(object_resolve_path_component(OBJECT(macio),

                                                        "ide[1]"));

    macio_ide_init_drives(macio_ide, &hd[MAX_IDE_DEVS]);

    dev = DEVICE(object_resolve_path_component(OBJECT(macio), "cuda"));

    adb_bus = qdev_get_child_bus(dev, "adb.0");

    dev = qdev_create(adb_bus, TYPE_ADB_KEYBOARD);

    qdev_init_nofail(dev);

    dev = qdev_create(adb_bus, TYPE_ADB_MOUSE);

    qdev_init_nofail(dev);

    if (machine->usb) {

        pci_create_simple(pci_bus, -1, "pci-ohci");

        /* U3 needs to use USB for input because Linux doesn't support via-cuda

        on PPC64 */

        if (machine_arch == ARCH_MAC99_U3) {

            USBBus *usb_bus = usb_bus_find(-1);

            usb_create_simple(usb_bus, "usb-kbd");

            usb_create_simple(usb_bus, "usb-mouse");

        }

    }

    pci_vga_init(pci_bus);

    if (graphic_depth != 15 && graphic_depth != 32 && graphic_depth != 8) {

        graphic_depth = 15;

    }

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

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

    }

    /* The NewWorld NVRAM is not located in the MacIO device */

#ifdef CONFIG_KVM

    if (kvm_enabled() && getpagesize() > 4096) {

        /* We can't combine read-write and read-only in a single page, so

           move the NVRAM out of ROM again for KVM */

        nvram_addr = 0xFFE00000;

    }

#endif

    dev = qdev_create(NULL, TYPE_MACIO_NVRAM);

    qdev_prop_set_uint32(dev, "size", 0x2000);

    qdev_prop_set_uint32(dev, "it_shift", 1);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, nvram_addr);

    nvr = MACIO_NVRAM(dev);

    pmac_format_nvram_partition(nvr, 0x2000);

    /* No PCI init: the BIOS will do it */

    fw_cfg = fw_cfg_init_mem(CFG_ADDR, CFG_ADDR + 2);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MAX_CPUS, (uint16_t)max_cpus);

    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, machine_arch);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);

    if (kernel_cmdline) {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, cmdline_base);

        pstrcpy_targphys("cmdline", cmdline_base, TARGET_PAGE_SIZE, kernel_cmdline);

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, 0);

    }

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, ppc_boot_device);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_WIDTH, graphic_width);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_HEIGHT, graphic_height);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_DEPTH, graphic_depth);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_IS_KVM, kvm_enabled());

    if (kvm_enabled()) {

#ifdef CONFIG_KVM

        uint8_t *hypercall;

        hypercall = g_malloc(16);

        kvmppc_get_hypercall(env, hypercall, 16);

        fw_cfg_add_bytes(fw_cfg, FW_CFG_PPC_KVM_HC, hypercall, 16);

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_KVM_PID, getpid());

#endif

    }

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, tbfreq);

    /* Mac OS X requires a "known good" clock-frequency value; pass it one. */

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_CLOCKFREQ, CLOCKFREQ);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_BUSFREQ, BUSFREQ);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_NVRAM_ADDR, nvram_addr);

    qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);

}


static CoroutineThreadState *coroutine_get_thread_state(void)

{

    CoroutineThreadState *s = pthread_getspecific(thread_state_key);

    if (!s) {

        s = g_malloc0(sizeof(*s));

        s->current = &s->leader.base;

        QLIST_INIT(&s->pool);

        pthread_setspecific(thread_state_key, s);

    }

    return s;

}


void swri_resample_dsp_init(ResampleContext *c)

{

#define FNIDX(fmt) (AV_SAMPLE_FMT_##fmt - AV_SAMPLE_FMT_S16P)

    c->dsp.resample_one[FNIDX(S16P)] = (resample_one_fn) resample_one_int16;

    c->dsp.resample_one[FNIDX(S32P)] = (resample_one_fn) resample_one_int32;

    c->dsp.resample_one[FNIDX(FLTP)] = (resample_one_fn) resample_one_float;

    c->dsp.resample_one[FNIDX(DBLP)] = (resample_one_fn) resample_one_double;

    c->dsp.resample_common[FNIDX(S16P)] = (resample_fn) resample_common_int16;

    c->dsp.resample_common[FNIDX(S32P)] = (resample_fn) resample_common_int32;

    c->dsp.resample_common[FNIDX(FLTP)] = (resample_fn) resample_common_float;

    c->dsp.resample_common[FNIDX(DBLP)] = (resample_fn) resample_common_double;

    c->dsp.resample_linear[FNIDX(S16P)] = (resample_fn) resample_linear_int16;

    c->dsp.resample_linear[FNIDX(S32P)] = (resample_fn) resample_linear_int32;

    c->dsp.resample_linear[FNIDX(FLTP)] = (resample_fn) resample_linear_float;

    c->dsp.resample_linear[FNIDX(DBLP)] = (resample_fn) resample_linear_double;

    if (ARCH_X86) swri_resample_dsp_x86_init(c);

}


static int qxl_init_primary(PCIDevice *dev)

{

    PCIQXLDevice *qxl = DO_UPCAST(PCIQXLDevice, pci, dev);

    VGACommonState *vga = &qxl->vga;

    PortioList *qxl_vga_port_list = g_new(PortioList, 1);

    DisplayState *ds;

    int rc;

    qxl->id = 0;

    qxl_init_ramsize(qxl);

    vga->vram_size_mb = qxl->vga.vram_size >> 20;

    vga_common_init(vga);

    vga_init(vga, pci_address_space(dev), pci_address_space_io(dev), false);

    portio_list_init(qxl_vga_port_list, qxl_vga_portio_list, vga, "vga");

    portio_list_add(qxl_vga_port_list, pci_address_space_io(dev), 0x3b0);

    vga->con = graphic_console_init(qxl_hw_update, qxl_hw_invalidate,

                                    qxl_hw_screen_dump, qxl_hw_text_update,

                                    qxl);

    qxl->ssd.con = vga->con,

    qemu_spice_display_init_common(&qxl->ssd);

    rc = qxl_init_common(qxl);

    if (rc != 0) {

        return rc;

    }

    qxl->ssd.dcl.ops = &display_listener_ops;

    ds = qemu_console_displaystate(vga->con);

    register_displaychangelistener(ds, &qxl->ssd.dcl);

    return rc;

}


int zipl_load(void)

{

    struct mbr *mbr = (void*)sec;

    uint8_t *ns, *ns_end;

    int program_table_entries = 0;

    int pte_len = sizeof(struct scsi_blockptr);

    struct scsi_blockptr *prog_table_entry;

    const char *error = "";

    /* Grab the MBR */

    virtio_read(0, (void*)mbr);

    dputs("checking magic\n");

    if (!zipl_magic(mbr->magic)) {

        error = "zipl_magic 1";

        goto fail;

    }

    debug_print_int("program table", mbr->blockptr.blockno);

    /* Parse the program table */

    if (virtio_read(mbr->blockptr.blockno, sec)) {

        error = "virtio_read";

        goto fail;

    }

    if (!zipl_magic(sec)) {

        error = "zipl_magic 2";

        goto fail;

    }

    ns_end = sec + SECTOR_SIZE;

    for (ns = (sec + pte_len); (ns + pte_len) < ns_end; ns++) {

        prog_table_entry = (struct scsi_blockptr *)ns;

        if (!prog_table_entry->blockno) {

            break;

        }

        program_table_entries++;

    }

    debug_print_int("program table entries", program_table_entries);

    if (!program_table_entries) {

        goto fail;

    }

    /* Run the default entry */

    prog_table_entry = (struct scsi_blockptr *)(sec + pte_len);

    return zipl_run(prog_table_entry);

fail:

    sclp_print("failed loading zipl: ");

    sclp_print(error);

    sclp_print("\n");

    return -1;

}


static void sdhci_data_transfer(void *opaque)

{

    SDHCIState *s = (SDHCIState *)opaque;

    if (s->trnmod & SDHC_TRNS_DMA) {

        switch (SDHC_DMA_TYPE(s->hostctl)) {

        case SDHC_CTRL_SDMA:

            if ((s->trnmod & SDHC_TRNS_MULTI) &&

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

                break;

            }

            if ((s->blkcnt == 1) || !(s->trnmod & SDHC_TRNS_MULTI)) {

                sdhci_sdma_transfer_single_block(s);

            } else {

                sdhci_sdma_transfer_multi_blocks(s);

            }

            break;

        case SDHC_CTRL_ADMA1_32:

            if (!(s->capareg & SDHC_CAN_DO_ADMA1)) {

                ERRPRINT("ADMA1 not supported\n");

                break;

            }

            sdhci_do_adma(s);

            break;

        case SDHC_CTRL_ADMA2_32:

            if (!(s->capareg & SDHC_CAN_DO_ADMA2)) {

                ERRPRINT("ADMA2 not supported\n");

                break;

            }

            sdhci_do_adma(s);

            break;

        case SDHC_CTRL_ADMA2_64:

            if (!(s->capareg & SDHC_CAN_DO_ADMA2) ||

                    !(s->capareg & SDHC_64_BIT_BUS_SUPPORT)) {

                ERRPRINT("64 bit ADMA not supported\n");

                break;

            }

            sdhci_do_adma(s);

            break;

        default:

            ERRPRINT("Unsupported DMA type\n");

            break;

        }

    } else {

        if ((s->trnmod & SDHC_TRNS_READ) && sdbus_data_ready(&s->sdbus)) {

            s->prnsts |= SDHC_DOING_READ | SDHC_DATA_INHIBIT |

                    SDHC_DAT_LINE_ACTIVE;

            sdhci_read_block_from_card(s);

        } else {

            s->prnsts |= SDHC_DOING_WRITE | SDHC_DAT_LINE_ACTIVE |

                    SDHC_SPACE_AVAILABLE | SDHC_DATA_INHIBIT;

            sdhci_write_block_to_card(s);

        }

    }

}


static const char *keyval_parse_one(QDict *qdict, const char *params,

                                    const char *implied_key,

                                    Error **errp)

{

    const char *key, *key_end, *s;

    size_t len;

    char key_in_cur[128];

    QDict *cur;

    QObject *next;

    QString *val;

    key = params;

    len = strcspn(params, "=,");

    if (implied_key && len && key[len] != '=') {

        /* Desugar implied key */

        key = implied_key;

        len = strlen(implied_key);

    }

    key_end = key + len;

    /*

     * Loop over key fragments: @s points to current fragment, it

     * applies to @cur.  @key_in_cur[] holds the previous fragment.

     */

    cur = qdict;

    s = key;

    for (;;) {

        for (len = 0; s + len < key_end && s[len] != '.'; len++) {

        }

        if (!len) {

            assert(key != implied_key);

            error_setg(errp, "Invalid parameter '%.*s'",

                       (int)(key_end - key), key);

            return NULL;

        }

        if (len >= sizeof(key_in_cur)) {

            assert(key != implied_key);

            error_setg(errp, "Parameter%s '%.*s' is too long",

                       s != key || s + len != key_end ? " fragment" : "",

                       (int)len, s);

            return NULL;

        }

        if (s != key) {

            next = keyval_parse_put(cur, key_in_cur, NULL,

                                    key, s - 1, errp);

            if (!next) {

                return NULL;

            }

            cur = qobject_to_qdict(next);

            assert(cur);

        }

        memcpy(key_in_cur, s, len);

        key_in_cur[len] = 0;

        s += len;

        if (*s != '.') {

            break;

        }

        s++;

    }

    if (key == implied_key) {

        assert(!*s);

        s = params;

    } else {

        if (*s != '=') {

            error_setg(errp, "Expected '=' after parameter '%.*s'",

                       (int)(s - key), key);

            return NULL;

        }

        s++;

    }

    val = qstring_new();

    for (;;) {

        if (!*s) {

            break;

        } else if (*s == ',') {

            s++;

            if (*s != ',') {

                break;

            }

        }

        qstring_append_chr(val, *s++);

    }

    if (!keyval_parse_put(cur, key_in_cur, val, key, key_end, errp)) {

        return NULL;

    }

    return s;

}


void kvm_s390_cmma_reset(void)

{

    int rc;

    struct kvm_device_attr attr = {

        .group = KVM_S390_VM_MEM_CTRL,

        .attr = KVM_S390_VM_MEM_CLR_CMMA,

    };

    if (mem_path || !kvm_s390_cmma_available()) {

        return;

    }

    rc = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);

    trace_kvm_clear_cmma(rc);

}


static void nested_struct_compare(UserDefTwo *udnp1, UserDefTwo *udnp2)

{

    g_assert(udnp1);

    g_assert(udnp2);

    g_assert_cmpstr(udnp1->string0, ==, udnp2->string0);

    g_assert_cmpstr(udnp1->dict1->string1, ==, udnp2->dict1->string1);

    g_assert_cmpint(udnp1->dict1->dict2->userdef->base->integer, ==,

                    udnp2->dict1->dict2->userdef->base->integer);

    g_assert_cmpstr(udnp1->dict1->dict2->userdef->string, ==,

                    udnp2->dict1->dict2->userdef->string);

    g_assert_cmpstr(udnp1->dict1->dict2->string, ==,

                    udnp2->dict1->dict2->string);

    g_assert(udnp1->dict1->has_dict3 == udnp2->dict1->has_dict3);

    g_assert_cmpint(udnp1->dict1->dict3->userdef->base->integer, ==,

                    udnp2->dict1->dict3->userdef->base->integer);

    g_assert_cmpstr(udnp1->dict1->dict3->userdef->string, ==,

                    udnp2->dict1->dict3->userdef->string);

    g_assert_cmpstr(udnp1->dict1->dict3->string, ==,

                    udnp2->dict1->dict3->string);

}


static int scsi_generic_initfn(SCSIDevice *s)

{

    int rc;

    int sg_version;

    struct sg_scsi_id scsiid;

    if (!s->conf.bs) {

        error_report("drive property not set");

        return -1;

    }

    if (bdrv_get_on_error(s->conf.bs, 0) != BLOCKDEV_ON_ERROR_ENOSPC) {

        error_report("Device doesn't support drive option werror");

        return -1;

    }

    if (bdrv_get_on_error(s->conf.bs, 1) != BLOCKDEV_ON_ERROR_REPORT) {

        error_report("Device doesn't support drive option rerror");

        return -1;

    }

    /* check we are using a driver managing SG_IO (version 3 and after */

    rc = bdrv_ioctl(s->conf.bs, SG_GET_VERSION_NUM, &sg_version);

    if (rc < 0) {

        error_report("cannot get SG_IO version number: %s.  "

                     "Is this a SCSI device?",

                     strerror(-rc));

        return -1;

    }

    if (sg_version < 30000) {

        error_report("scsi generic interface too old");

        return -1;

    }

    /* get LUN of the /dev/sg? */

    if (bdrv_ioctl(s->conf.bs, SG_GET_SCSI_ID, &scsiid)) {

        error_report("SG_GET_SCSI_ID ioctl failed");

        return -1;

    }

    /* define device state */

    s->type = scsiid.scsi_type;

    DPRINTF("device type %d\n", s->type);

    if (s->type == TYPE_DISK || s->type == TYPE_ROM) {

        add_boot_device_path(s->conf.bootindex, &s->qdev, NULL);

    }

    switch (s->type) {

    case TYPE_TAPE:

        s->blocksize = get_stream_blocksize(s->conf.bs);

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

            s->blocksize = 0;

        }

        break;

        /* Make a guess for block devices, we'll fix it when the guest sends.

         * READ CAPACITY.  If they don't, they likely would assume these sizes

         * anyway. (TODO: they could also send MODE SENSE).

         */

    case TYPE_ROM:

    case TYPE_WORM:

        s->blocksize = 2048;

        break;

    default:

        s->blocksize = 512;

        break;

    }

    DPRINTF("block size %d\n", s->blocksize);

    return 0;

}


VIOsPAPRDevice *spapr_vty_get_default(VIOsPAPRBus *bus)

{

    VIOsPAPRDevice *sdev, *selected;

    DeviceState *iter;

    /*

     * To avoid the console bouncing around we want one VTY to be

     * the "default". We haven't really got anything to go on, so

     * arbitrarily choose the one with the lowest reg value.

     */

    selected = NULL;

    QTAILQ_FOREACH(iter, &bus->bus.children, sibling) {

        /* Only look at VTY devices */

        if (qdev_get_info(iter) != &spapr_vty_info.qdev) {

            continue;

        }

        sdev = DO_UPCAST(VIOsPAPRDevice, qdev, iter);

        /* First VTY we've found, so it is selected for now */

        if (!selected) {

            selected = sdev;

            continue;

        }

        /* Choose VTY with lowest reg value */

        if (sdev->reg < selected->reg) {

            selected = sdev;

        }

    }

    return selected;

}


static int decode_ext_header(Wmv2Context *w){

    MpegEncContext * const s= &w->s;

    GetBitContext gb;

    int fps;

    int code;

    if(s->avctx->extradata_size<4) return -1;

    init_get_bits(&gb, s->avctx->extradata, s->avctx->extradata_size*8);

    fps                = get_bits(&gb, 5);

    s->bit_rate        = get_bits(&gb, 11)*1024;

    w->mspel_bit       = get_bits1(&gb);

    w->flag3           = get_bits1(&gb);

    w->abt_flag        = get_bits1(&gb);

    w->j_type_bit      = get_bits1(&gb);

    w->top_left_mv_flag= get_bits1(&gb);

    w->per_mb_rl_bit   = get_bits1(&gb);

    code               = get_bits(&gb, 3);

    if(code==0) return -1;

    s->slice_height = s->mb_height / code;

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

        av_log(s->avctx, AV_LOG_DEBUG, "fps:%d, br:%d, qpbit:%d, abt_flag:%d, j_type_bit:%d, tl_mv_flag:%d, mbrl_bit:%d, code:%d, flag3:%d, slices:%d\n",

        fps, s->bit_rate, w->mspel_bit, w->abt_flag, w->j_type_bit, w->top_left_mv_flag, w->per_mb_rl_bit, code, w->flag3,

        code);

    }

    return 0;

}


void fw_cfg_add_file(FWCfgState *s,  const char *filename, uint8_t *data,

                     uint32_t len)

{

    int i, index;

    if (!s->files) {

        int dsize = sizeof(uint32_t) + sizeof(FWCfgFile) * FW_CFG_FILE_SLOTS;

        s->files = g_malloc0(dsize);

        fw_cfg_add_bytes(s, FW_CFG_FILE_DIR, (uint8_t*)s->files, dsize);

    }

    index = be32_to_cpu(s->files->count);

    assert(index < FW_CFG_FILE_SLOTS);

    fw_cfg_add_bytes(s, FW_CFG_FILE_FIRST + index, data, len);

    pstrcpy(s->files->f[index].name, sizeof(s->files->f[index].name),

            filename);

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

        if (strcmp(s->files->f[index].name, s->files->f[i].name) == 0) {

            trace_fw_cfg_add_file_dupe(s, s->files->f[index].name);

            return;

        }

    }

    s->files->f[index].size   = cpu_to_be32(len);

    s->files->f[index].select = cpu_to_be16(FW_CFG_FILE_FIRST + index);

    trace_fw_cfg_add_file(s, index, s->files->f[index].name, len);

    s->files->count = cpu_to_be32(index+1);

}


static int tls_open(URLContext *h, const char *uri, int flags)

{

    TLSContext *c = h->priv_data;

    int ret;

    int port;

    char buf[200], host[200];

    int numerichost = 0;

    struct addrinfo hints = { 0 }, *ai = NULL;

    const char *proxy_path;

    int use_proxy;

    ff_tls_init();

    av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0, uri);

    ff_url_join(buf, sizeof(buf), "tcp", NULL, host, port, NULL);

    hints.ai_flags = AI_NUMERICHOST;

    if (!getaddrinfo(host, NULL, &hints, &ai)) {

        numerichost = 1;

        freeaddrinfo(ai);

    }

    proxy_path = getenv("http_proxy");

    use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), host) &&

                proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);

    if (use_proxy) {

        char proxy_host[200], proxy_auth[200], dest[200];

        int proxy_port;

        av_url_split(NULL, 0, proxy_auth, sizeof(proxy_auth),

                     proxy_host, sizeof(proxy_host), &proxy_port, NULL, 0,

                     proxy_path);

        ff_url_join(dest, sizeof(dest), NULL, NULL, host, port, NULL);

        ff_url_join(buf, sizeof(buf), "httpproxy", proxy_auth, proxy_host,

                    proxy_port, "/%s", dest);

    }

    ret = ffurl_open(&c->tcp, buf, AVIO_FLAG_READ_WRITE,

                     &h->interrupt_callback, NULL);

    if (ret)

        goto fail;

    c->fd = ffurl_get_file_handle(c->tcp);

#if CONFIG_GNUTLS

    gnutls_init(&c->session, GNUTLS_CLIENT);

    if (!numerichost)

        gnutls_server_name_set(c->session, GNUTLS_NAME_DNS, host, strlen(host));

    gnutls_certificate_allocate_credentials(&c->cred);

    gnutls_certificate_set_verify_flags(c->cred, 0);

    gnutls_credentials_set(c->session, GNUTLS_CRD_CERTIFICATE, c->cred);

    gnutls_transport_set_ptr(c->session, (gnutls_transport_ptr_t)

                                         (intptr_t) c->fd);

    gnutls_priority_set_direct(c->session, "NORMAL", NULL);

    while (1) {

        ret = gnutls_handshake(c->session);

        if (ret == 0)

            break;

        if ((ret = do_tls_poll(h, ret)) < 0)

            goto fail;

    }

#elif CONFIG_OPENSSL

    c->ctx = SSL_CTX_new(TLSv1_client_method());

    if (!c->ctx) {

        av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));

        ret = AVERROR(EIO);

        goto fail;

    }

    c->ssl = SSL_new(c->ctx);

    if (!c->ssl) {

        av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));

        ret = AVERROR(EIO);

        goto fail;

    }

    SSL_set_fd(c->ssl, c->fd);

    if (!numerichost)

        SSL_set_tlsext_host_name(c->ssl, host);

    while (1) {

        ret = SSL_connect(c->ssl);

        if (ret > 0)

            break;

        if (ret == 0) {

            av_log(h, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session\n");

            ret = AVERROR(EIO);

            goto fail;

        }

        if ((ret = do_tls_poll(h, ret)) < 0)

            goto fail;

    }

#endif

    return 0;

fail:

    TLS_free(c);

    if (c->tcp)

        ffurl_close(c->tcp);

    ff_tls_deinit();

    return ret;

}


void OPPROTO op_fdivr_STN_ST0(void)

{

    CPU86_LDouble *p;

    p = &ST(PARAM1);

    *p = ST0 / *p;

}


static int output_packet(AVFormatContext *ctx, int flush){

    MpegMuxContext *s = ctx->priv_data;

    AVStream *st;

    StreamInfo *stream;

    int i, avail_space=0, es_size, trailer_size;

    int best_i= -1;

    int best_score= INT_MIN;

    int ignore_constraints=0;

    int64_t scr= s->last_scr;

    PacketDesc *timestamp_packet;

    const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);

retry:

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

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

        StreamInfo *stream = st->priv_data;

        const int avail_data=  av_fifo_size(stream->fifo);

        const int space= stream->max_buffer_size - stream->buffer_index;

        int rel_space= 1024LL*space / stream->max_buffer_size;

        PacketDesc *next_pkt= stream->premux_packet;

        /* for subtitle, a single PES packet must be generated,

           so we flush after every single subtitle packet */

        if(s->packet_size > avail_data && !flush

           && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)

            return 0;

        if(avail_data==0)

            continue;

        av_assert0(avail_data>0);

        if(space < s->packet_size && !ignore_constraints)

            continue;

        if(next_pkt && next_pkt->dts - scr > max_delay)

            continue;

        if(rel_space > best_score){

            best_score= rel_space;

            best_i = i;

            avail_space= space;

        }

    }

    if(best_i < 0){

        int64_t best_dts= INT64_MAX;

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

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

            StreamInfo *stream = st->priv_data;

            PacketDesc *pkt_desc= stream->predecode_packet;

            if(pkt_desc && pkt_desc->dts < best_dts)

                best_dts= pkt_desc->dts;

        }

        av_dlog(ctx, "bumping scr, scr:%f, dts:%f\n",

                scr / 90000.0, best_dts / 90000.0);

        if(best_dts == INT64_MAX)

            return 0;

        if(scr >= best_dts+1 && !ignore_constraints){

            av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");

            ignore_constraints= 1;

        }

        scr= FFMAX(best_dts+1, scr);

        if(remove_decoded_packets(ctx, scr) < 0)

            return -1;

        goto retry;

    }

    assert(best_i >= 0);

    st = ctx->streams[best_i];

    stream = st->priv_data;

    assert(av_fifo_size(stream->fifo) > 0);

    assert(avail_space >= s->packet_size || ignore_constraints);

    timestamp_packet= stream->premux_packet;

    if(timestamp_packet->unwritten_size == timestamp_packet->size){

        trailer_size= 0;

    }else{

        trailer_size= timestamp_packet->unwritten_size;

        timestamp_packet= timestamp_packet->next;

    }

    if(timestamp_packet){

        av_dlog(ctx, "dts:%f pts:%f scr:%f stream:%d\n",

                timestamp_packet->dts / 90000.0,

                timestamp_packet->pts / 90000.0,

                scr / 90000.0, best_i);

        es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);

    }else{

        assert(av_fifo_size(stream->fifo) == trailer_size);

        es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);

    }

    if (s->is_vcd) {

        /* Write one or more padding sectors, if necessary, to reach

           the constant overall bitrate.*/

        int vcd_pad_bytes;

        while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here

            put_vcd_padding_sector(ctx);

            s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet

        }

    }

    stream->buffer_index += es_size;

    s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet

    while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){

        es_size -= stream->premux_packet->unwritten_size;

        stream->premux_packet= stream->premux_packet->next;

    }

    if(es_size)

        stream->premux_packet->unwritten_size -= es_size;

    if(remove_decoded_packets(ctx, s->last_scr) < 0)

        return -1;

    return 1;

}


static void openpic_src_write(void *opaque, hwaddr addr, uint64_t val,

                              unsigned len)

{

    OpenPICState *opp = opaque;

    int idx;

    DPRINTF("%s: addr %08x <= %08x\n", __func__, addr, val);

    if (addr & 0xF)

        return;

    addr = addr & 0xFFF0;

    idx = addr >> 5;

    if (addr & 0x10) {

        /* EXDE / IFEDE / IEEDE */

        write_IRQreg_ide(opp, idx, val);

    } else {

        /* EXVP / IFEVP / IEEVP */

        write_IRQreg_ipvp(opp, idx, val);

    }

}


uint64_t helper_addlv(CPUAlphaState *env, uint64_t op1, uint64_t op2)

{

    uint64_t tmp = op1;

    op1 = (uint32_t)(op1 + op2);

    if (unlikely((tmp ^ op2 ^ (-1UL)) & (tmp ^ op1) & (1UL << 31))) {

        arith_excp(env, GETPC(), EXC_M_IOV, 0);

    }

    return op1;

}


static int ahci_dma_prepare_buf(IDEDMA *dma, int is_write)

{

    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);

    IDEState *s = &ad->port.ifs[0];

    ahci_populate_sglist(ad, &s->sg);

    s->io_buffer_size = s->sg.size;

    DPRINTF(ad->port_no, "len=%#x\n", s->io_buffer_size);

    return s->io_buffer_size != 0;

}


int av_vsrc_buffer_add_frame(AVFilterContext *buffer_src, const AVFrame *frame)

{

    int ret;

    AVFilterBufferRef *picref =

        avfilter_get_video_buffer_ref_from_frame(frame, AV_PERM_WRITE);

    if (!picref)

        return AVERROR(ENOMEM);

    ret = av_vsrc_buffer_add_video_buffer_ref(buffer_src, picref);

    picref->buf->data[0] = NULL;

    avfilter_unref_buffer(picref);

    return ret;

}


static ssize_t mp_user_getxattr(FsContext *ctx, const char *path,

                                const char *name, void *value, size_t size)

{

    char *buffer;

    ssize_t ret;

    if (strncmp(name, "user.virtfs.", 12) == 0) {

        /*

         * Don't allow fetch of user.virtfs namesapce

         * in case of mapped security

         */

        errno = ENOATTR;

        return -1;

    }

    buffer = rpath(ctx, path);

    ret = lgetxattr(buffer, name, value, size);

    g_free(buffer);

    return ret;

}


static int mpeg_decode_slice(AVCodecContext *avctx,

                              AVFrame *pict,

                              int start_code,

                              UINT8 *buf, int buf_size)

{

    Mpeg1Context *s1 = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    int ret;

    start_code = (start_code - 1) & 0xff;

    if (start_code >= s->mb_height){

        fprintf(stderr, "slice below image (%d >= %d)\n", start_code, s->mb_height);

        return DECODE_SLICE_ERROR;

    }

    s->last_dc[0] = 1 << (7 + s->intra_dc_precision);

    s->last_dc[1] = s->last_dc[0];

    s->last_dc[2] = s->last_dc[0];

    memset(s->last_mv, 0, sizeof(s->last_mv));

    /* start frame decoding */

    if (s->first_slice) {

        s->first_slice = 0;

        if(MPV_frame_start(s, avctx) < 0)

            return DECODE_SLICE_FATAL_ERROR;

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

             printf("qp:%d fc:%2d%2d%2d%2d %s %s %s %s dc:%d pstruct:%d fdct:%d cmv:%d qtype:%d ivlc:%d rff:%d %s\n",

                 s->qscale, s->mpeg_f_code[0][0],s->mpeg_f_code[0][1],s->mpeg_f_code[1][0],s->mpeg_f_code[1][1],

                 s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")),

                 s->progressive_sequence ? "pro" :"", s->alternate_scan ? "alt" :"", s->top_field_first ? "top" :"",

                 s->intra_dc_precision, s->picture_structure, s->frame_pred_frame_dct, s->concealment_motion_vectors,

                 s->q_scale_type, s->intra_vlc_format, s->repeat_first_field, s->chroma_420_type ? "420" :"");

        }

    }

    init_get_bits(&s->gb, buf, buf_size);

    s->qscale = get_qscale(s);

    /* extra slice info */

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

        skip_bits(&s->gb, 8);

    }

    s->mb_x=0;

    for(;;) {

        int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);

        if (code < 0)

            return -1; /* error = end of slice, but empty slice is bad or?*/

        if (code >= 33) {

            if (code == 33) {

                s->mb_x += 33;

            }

            /* otherwise, stuffing, nothing to do */

        } else {

            s->mb_x += code;

            break;

        }

    }

    s->mb_y = start_code;

    s->mb_incr= 1;

    for(;;) {

	s->dsp.clear_blocks(s->block[0]);

        ret = mpeg_decode_mb(s, s->block);

        dprintf("ret=%d\n", ret);

        if (ret < 0)

            return -1;

        MPV_decode_mb(s, s->block);

        if (++s->mb_x >= s->mb_width) {

            ff_draw_horiz_band(s);

            s->mb_x = 0;

            s->mb_y++;

            PRINT_QP("%s", "\n");

        }

        PRINT_QP("%2d", s->qscale);

        /* skip mb handling */

        if (s->mb_incr == 0) {

            /* read again increment */

            s->mb_incr = 1;

            for(;;) {

                int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);

                if (code < 0)

                    goto eos; /* error = end of slice */

                if (code >= 33) {

                    if (code == 33) {

                        s->mb_incr += 33;

                    }

                    /* otherwise, stuffing, nothing to do */

                } else {

                    s->mb_incr += code;

                    break;

                }

            }

        }

        if(s->mb_y >= s->mb_height){

            fprintf(stderr, "slice too long\n");

            return DECODE_SLICE_ERROR;

        }

    }

eos: //end of slice

    emms_c();

    /* end of slice reached */

    if (/*s->mb_x == 0 &&*/

        s->mb_y == s->mb_height) {

        /* end of image */

        if(s->mpeg2)

            s->qscale >>=1;

        MPV_frame_end(s);

        if (s->pict_type == B_TYPE || s->low_delay) {

            *pict= *(AVFrame*)&s->current_picture;

        } else {

            s->picture_number++;

            /* latency of 1 frame for I and P frames */

            /* XXX: use another variable than picture_number */

            if (s->last_picture.data[0] == NULL) {

                return DECODE_SLICE_OK;

            } else {

                *pict= *(AVFrame*)&s->last_picture;

            }

        }

        return DECODE_SLICE_EOP;

    } else {

        return DECODE_SLICE_OK;

    }

}


static void generate_codebook(RoqContext *enc, RoqTempdata *tempdata,

                              int *points, int inputCount, roq_cell *results,

                              int size, int cbsize)

{

    int i, j, k;

    int c_size = size*size/4;

    int *buf;

    int *codebook = av_malloc(6*c_size*cbsize*sizeof(int));

    int *closest_cb;

    if (size == 4)

        closest_cb = av_malloc(6*c_size*inputCount*sizeof(int));

    else

        closest_cb = tempdata->closest_cb2;

    ff_init_elbg(points, 6*c_size, inputCount, codebook, cbsize, 1, closest_cb, &enc->randctx);

    ff_do_elbg(points, 6*c_size, inputCount, codebook, cbsize, 1, closest_cb, &enc->randctx);

    if (size == 4)

        av_free(closest_cb);

    buf = codebook;

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

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

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

                results->y[j] = *buf++;

            results->u =    (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;

            results->v =    (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;

            results++;

        }

    av_free(codebook);

}


static av_cold int xma_decode_init(AVCodecContext *avctx)

{

    XMADecodeCtx *s = avctx->priv_data;

    int i, ret;

    for (i = 0; i < avctx->channels / 2; i++) {

        ret = decode_init(&s->xma[i], avctx);

        s->frames[i] = av_frame_alloc();

        if (!s->frames[i])

            return AVERROR(ENOMEM);

        s->frames[i]->nb_samples = 512;

        if ((ret = ff_get_buffer(avctx, s->frames[i], 0)) < 0) {

            return AVERROR(ENOMEM);

        }

    }

    return ret;

}


int main (int argc, char *argv[])

{

  char *fnam = argv[0];

  FILE *f;

  if (argv[0][0] != '/')

    {

      fnam = malloc (strlen (argv[0]) + 2);

      if (fnam == NULL)

	abort ();

      strcpy (fnam, "/");

      strcat (fnam, argv[0]);

    }

  f = fopen (fnam, "rb");

  if (f == NULL)

    abort ();

  close (f);

  /* Cover another execution path.  */

  if (fopen ("/nonexistent", "rb") != NULL

      || errno != ENOENT)

    abort ();

  printf ("pass\n");

  return 0;

}


int xbzrle_decode_buffer(uint8_t *src, int slen, uint8_t *dst, int dlen)

{

    int i = 0, d = 0;

    int ret;

    uint32_t count = 0;

    while (i < slen) {

        /* zrun */

        if ((slen - i) < 2) {

            return -1;

        }

        ret = uleb128_decode_small(src + i, &count);

        if (ret < 0 || (i && !count)) {

            return -1;

        }

        i += ret;

        d += count;

        /* overflow */

        if (d > dlen) {

            return -1;

        }

        /* nzrun */

        if ((slen - i) < 2) {

            return -1;

        }

        ret = uleb128_decode_small(src + i, &count);

        if (ret < 0 || !count) {

            return -1;

        }

        i += ret;

        /* overflow */

        if (d + count > dlen || i + count > slen) {

            return -1;

        }

        memcpy(dst + d, src + i, count);

        d += count;

        i += count;

    }

    return d;

}


av_cold void ff_vp8dsp_init(VP8DSPContext *dsp)

{

    dsp->vp8_luma_dc_wht    = vp8_luma_dc_wht_c;

    dsp->vp8_luma_dc_wht_dc = vp8_luma_dc_wht_dc_c;

    dsp->vp8_idct_add       = vp8_idct_add_c;

    dsp->vp8_idct_dc_add    = vp8_idct_dc_add_c;

    dsp->vp8_idct_dc_add4y  = vp8_idct_dc_add4y_c;

    dsp->vp8_idct_dc_add4uv = vp8_idct_dc_add4uv_c;

    dsp->vp8_v_loop_filter16y = vp8_v_loop_filter16_c;

    dsp->vp8_h_loop_filter16y = vp8_h_loop_filter16_c;

    dsp->vp8_v_loop_filter8uv = vp8_v_loop_filter8uv_c;

    dsp->vp8_h_loop_filter8uv = vp8_h_loop_filter8uv_c;

    dsp->vp8_v_loop_filter16y_inner = vp8_v_loop_filter16_inner_c;

    dsp->vp8_h_loop_filter16y_inner = vp8_h_loop_filter16_inner_c;

    dsp->vp8_v_loop_filter8uv_inner = vp8_v_loop_filter8uv_inner_c;

    dsp->vp8_h_loop_filter8uv_inner = vp8_h_loop_filter8uv_inner_c;

    dsp->vp8_v_loop_filter_simple = vp8_v_loop_filter_simple_c;

    dsp->vp8_h_loop_filter_simple = vp8_h_loop_filter_simple_c;

    VP8_MC_FUNC(0, 16);

    VP8_MC_FUNC(1, 8);

    VP8_MC_FUNC(2, 4);

    VP8_BILINEAR_MC_FUNC(0, 16);

    VP8_BILINEAR_MC_FUNC(1, 8);

    VP8_BILINEAR_MC_FUNC(2, 4);

    if (ARCH_ARM)

        ff_vp8dsp_init_arm(dsp);

    if (ARCH_PPC)

        ff_vp8dsp_init_ppc(dsp);

    if (ARCH_X86)

        ff_vp8dsp_init_x86(dsp);

}


static void throttle_fix_bucket(LeakyBucket *bkt)

{

    double min;

    /* zero bucket level */

    bkt->level = bkt->burst_level = 0;

    /* The following is done to cope with the Linux CFQ block scheduler

     * which regroup reads and writes by block of 100ms in the guest.

     * When they are two process one making reads and one making writes cfq

     * make a pattern looking like the following:

     * WWWWWWWWWWWRRRRRRRRRRRRRRWWWWWWWWWWWWWwRRRRRRRRRRRRRRRRR

     * Having a max burst value of 100ms of the average will help smooth the

     * throttling

     */

    min = bkt->avg / 10;

    if (bkt->avg && !bkt->max) {

        bkt->max = min;

    }

}


int net_client_init(const char *device, const char *p)

{

    static const char * const fd_params[] = {

        "vlan", "name", "fd", NULL

    };

    char buf[1024];

    int vlan_id, ret;

    VLANState *vlan;

    char *name = NULL;

    vlan_id = 0;

    if (get_param_value(buf, sizeof(buf), "vlan", p)) {

        vlan_id = strtol(buf, NULL, 0);

    }

    vlan = qemu_find_vlan(vlan_id);

    if (get_param_value(buf, sizeof(buf), "name", p)) {

        name = strdup(buf);

    }

    if (!strcmp(device, "nic")) {

        static const char * const nic_params[] = {

            "vlan", "name", "macaddr", "model", NULL

        };

        NICInfo *nd;

        uint8_t *macaddr;

        int idx = nic_get_free_idx();

        if (check_params(nic_params, p) < 0) {

            fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);

            return -1;

        }

        if (idx == -1 || nb_nics >= MAX_NICS) {

            fprintf(stderr, "Too Many NICs\n");

            ret = -1;

            goto out;

        }

        nd = &nd_table[idx];

        macaddr = nd->macaddr;

        macaddr[0] = 0x52;

        macaddr[1] = 0x54;

        macaddr[2] = 0x00;

        macaddr[3] = 0x12;

        macaddr[4] = 0x34;

        macaddr[5] = 0x56 + idx;

        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {

            if (parse_macaddr(macaddr, buf) < 0) {

                fprintf(stderr, "invalid syntax for ethernet address\n");

                ret = -1;

                goto out;

            }

        }

        if (get_param_value(buf, sizeof(buf), "model", p)) {

            nd->model = strdup(buf);

        }

        nd->vlan = vlan;

        nd->name = name;

        nd->used = 1;

        name = NULL;

        nb_nics++;

        vlan->nb_guest_devs++;

        ret = idx;

    } else

    if (!strcmp(device, "none")) {

        if (*p != '\0') {

            fprintf(stderr, "qemu: 'none' takes no parameters\n");

            return -1;

        }

        /* does nothing. It is needed to signal that no network cards

           are wanted */

        ret = 0;

    } else

#ifdef CONFIG_SLIRP

    if (!strcmp(device, "user")) {

        static const char * const slirp_params[] = {

            "vlan", "name", "hostname", "restrict", "ip", NULL

        };

        if (check_params(slirp_params, p) < 0) {

            fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);

            return -1;

        }

        if (get_param_value(buf, sizeof(buf), "hostname", p)) {

            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);

        }

        if (get_param_value(buf, sizeof(buf), "restrict", p)) {

            slirp_restrict = (buf[0] == 'y') ? 1 : 0;

        }

        if (get_param_value(buf, sizeof(buf), "ip", p)) {

            slirp_ip = strdup(buf);

        }

        vlan->nb_host_devs++;

        ret = net_slirp_init(vlan, device, name);

    } else if (!strcmp(device, "channel")) {

        long port;

        char name[20], *devname;

        struct VMChannel *vmc;

        port = strtol(p, &devname, 10);

        devname++;

        if (port < 1 || port > 65535) {

            fprintf(stderr, "vmchannel wrong port number\n");

            ret = -1;

            goto out;

        }

        vmc = malloc(sizeof(struct VMChannel));

        snprintf(name, 20, "vmchannel%ld", port);

        vmc->hd = qemu_chr_open(name, devname, NULL);

        if (!vmc->hd) {

            fprintf(stderr, "qemu: could not open vmchannel device"

                    "'%s'\n", devname);

            ret = -1;

            goto out;

        }

        vmc->port = port;

        slirp_add_exec(3, vmc->hd, 4, port);

        qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,

                NULL, vmc);

        ret = 0;

    } else

#endif

#ifdef _WIN32

    if (!strcmp(device, "tap")) {

        static const char * const tap_params[] = {

            "vlan", "name", "ifname", NULL

        };

        char ifname[64];

        if (check_params(tap_params, p) < 0) {

            fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);

            return -1;

        }

        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {

            fprintf(stderr, "tap: no interface name\n");

            ret = -1;

            goto out;

        }

        vlan->nb_host_devs++;

        ret = tap_win32_init(vlan, device, name, ifname);

    } else

#elif defined (_AIX)

#else

    if (!strcmp(device, "tap")) {

        char ifname[64];

        char setup_script[1024], down_script[1024];

        int fd;

        vlan->nb_host_devs++;

        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {

            if (check_params(fd_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);

                return -1;

            }

            fd = strtol(buf, NULL, 0);

            fcntl(fd, F_SETFL, O_NONBLOCK);

            net_tap_fd_init(vlan, device, name, fd);

            ret = 0;

        } else {

            static const char * const tap_params[] = {

                "vlan", "name", "ifname", "script", "downscript", NULL

            };

            if (check_params(tap_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);

                return -1;

            }

            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {

                ifname[0] = '\0';

            }

            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {

                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);

            }

            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {

                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);

            }

            ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);

        }

    } else

#endif

    if (!strcmp(device, "socket")) {

        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {

            int fd;

            if (check_params(fd_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);

                return -1;

            }

            fd = strtol(buf, NULL, 0);

            ret = -1;

            if (net_socket_fd_init(vlan, device, name, fd, 1))

                ret = 0;

        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {

            static const char * const listen_params[] = {

                "vlan", "name", "listen", NULL

            };

            if (check_params(listen_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);

                return -1;

            }

            ret = net_socket_listen_init(vlan, device, name, buf);

        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {

            static const char * const connect_params[] = {

                "vlan", "name", "connect", NULL

            };

            if (check_params(connect_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);

                return -1;

            }

            ret = net_socket_connect_init(vlan, device, name, buf);

        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {

            static const char * const mcast_params[] = {

                "vlan", "name", "mcast", NULL

            };

            if (check_params(mcast_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);

                return -1;

            }

            ret = net_socket_mcast_init(vlan, device, name, buf);

        } else {

            fprintf(stderr, "Unknown socket options: %s\n", p);

            ret = -1;

            goto out;

        }

        vlan->nb_host_devs++;

    } else

#ifdef CONFIG_VDE

    if (!strcmp(device, "vde")) {

        static const char * const vde_params[] = {

            "vlan", "name", "sock", "port", "group", "mode", NULL

        };

        char vde_sock[1024], vde_group[512];

	int vde_port, vde_mode;

        if (check_params(vde_params, p) < 0) {

            fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);

            return -1;

        }

        vlan->nb_host_devs++;

        if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {

	    vde_sock[0] = '\0';

	}

	if (get_param_value(buf, sizeof(buf), "port", p) > 0) {

	    vde_port = strtol(buf, NULL, 10);

	} else {

	    vde_port = 0;

	}

	if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {

	    vde_group[0] = '\0';

	}

	if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {

	    vde_mode = strtol(buf, NULL, 8);

	} else {

	    vde_mode = 0700;

	}

	ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);

    } else

#endif

    if (!strcmp(device, "dump")) {

        int len = 65536;

        if (get_param_value(buf, sizeof(buf), "len", p) > 0) {

            len = strtol(buf, NULL, 0);

        }

        if (!get_param_value(buf, sizeof(buf), "file", p)) {

            snprintf(buf, sizeof(buf), "qemu-vlan%d.pcap", vlan_id);

        }

        ret = net_dump_init(vlan, device, name, buf, len);

    } else {

        fprintf(stderr, "Unknown network device: %s\n", device);

        ret = -1;

        goto out;

    }

    if (ret < 0) {

        fprintf(stderr, "Could not initialize device '%s'\n", device);

    }

out:

    if (name)

        free(name);

    return ret;

}


int MPA_encode_init(AVCodecContext *avctx)

{

    MpegAudioContext *s = avctx->priv_data;

    int freq = avctx->sample_rate;

    int bitrate = avctx->bit_rate;

    int channels = avctx->channels;

    int i, v, table;

    float a;

    if (channels > 2)

        return -1;

    bitrate = bitrate / 1000;

    s->nb_channels = channels;

    s->freq = freq;

    s->bit_rate = bitrate * 1000;

    avctx->frame_size = MPA_FRAME_SIZE;

    avctx->key_frame = 1; /* always key frame */

    /* encoding freq */

    s->lsf = 0;

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

        if (mpa_freq_tab[i] == freq)

            break;

        if ((mpa_freq_tab[i] / 2) == freq) {

            s->lsf = 1;

            break;

        }

    }

    if (i == 3)

        return -1;

    s->freq_index = i;

    /* encoding bitrate & frequency */

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

        if (mpa_bitrate_tab[s->lsf][1][i] == bitrate)

            break;

    }

    if (i == 15)

        return -1;

    s->bitrate_index = i;

    /* compute total header size & pad bit */

    a = (float)(bitrate * 1000 * MPA_FRAME_SIZE) / (freq * 8.0);

    s->frame_size = ((int)a) * 8;

    /* frame fractional size to compute padding */

    s->frame_frac = 0;

    s->frame_frac_incr = (int)((a - floor(a)) * 65536.0);

    /* select the right allocation table */

    table = l2_select_table(bitrate, s->nb_channels, freq, s->lsf);

    /* number of used subbands */

    s->sblimit = sblimit_table[table];

    s->alloc_table = alloc_tables[table];

#ifdef DEBUG

    printf("%d kb/s, %d Hz, frame_size=%d bits, table=%d, padincr=%x\n",

           bitrate, freq, s->frame_size, table, s->frame_frac_incr);

#endif

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

        s->samples_offset[i] = 0;

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

        int v;

        v = (mpa_enwindow[i] + 2) >> 2;

        filter_bank[i] = v;

        if ((i & 63) != 0)

            v = -v;

        if (i != 0)

            filter_bank[512 - i] = v;

    }

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

        v = (int)(pow(2.0, (3 - i) / 3.0) * (1 << 20));

        if (v <= 0)

            v = 1;

        scale_factor_table[i] = v;

#ifdef USE_FLOATS

        scale_factor_inv_table[i] = pow(2.0, -(3 - i) / 3.0) / (float)(1 << 20);

#else

#define P 15

        scale_factor_shift[i] = 21 - P - (i / 3);

        scale_factor_mult[i] = (1 << P) * pow(2.0, (i % 3) / 3.0);

#endif

    }

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

        v = i - 64;

        if (v <= -3)

            v = 0;

        else if (v < 0)

            v = 1;

        else if (v == 0)

            v = 2;

        else if (v < 3)

            v = 3;

        else

            v = 4;

        scale_diff_table[i] = v;

    }

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

        v = quant_bits[i];

        if (v < 0)

            v = -v;

        else

            v = v * 3;

        total_quant_bits[i] = 12 * v;

    }

    return 0;

}


static void rv40_v_strong_loop_filter(uint8_t *src, const int stride,

                                      const int alpha, const int lims,

                                      const int dmode, const int chroma)

{

    rv40_strong_loop_filter(src, 1, stride, alpha, lims, dmode, chroma);

}


static int mode_sense_page(SCSIRequest *req, int page, uint8_t *p)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);

    BlockDriverState *bdrv = s->bs;

    int cylinders, heads, secs;

    switch (page) {

    case 4: /* Rigid disk device geometry page. */

        p[0] = 4;

        p[1] = 0x16;

        /* if a geometry hint is available, use it */

        bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);

        p[2] = (cylinders >> 16) & 0xff;

        p[3] = (cylinders >> 8) & 0xff;

        p[4] = cylinders & 0xff;

        p[5] = heads & 0xff;

        /* Write precomp start cylinder, disabled */

        p[6] = (cylinders >> 16) & 0xff;

        p[7] = (cylinders >> 8) & 0xff;

        p[8] = cylinders & 0xff;

        /* Reduced current start cylinder, disabled */

        p[9] = (cylinders >> 16) & 0xff;

        p[10] = (cylinders >> 8) & 0xff;

        p[11] = cylinders & 0xff;

        /* Device step rate [ns], 200ns */

        p[12] = 0;

        p[13] = 200;

        /* Landing zone cylinder */

        p[14] = 0xff;

        p[15] =  0xff;

        p[16] = 0xff;

        /* Medium rotation rate [rpm], 5400 rpm */

        p[20] = (5400 >> 8) & 0xff;

        p[21] = 5400 & 0xff;

        return 0x16;

    case 5: /* Flexible disk device geometry page. */

        p[0] = 5;

        p[1] = 0x1e;

        /* Transfer rate [kbit/s], 5Mbit/s */

        p[2] = 5000 >> 8;

        p[3] = 5000 & 0xff;

        /* if a geometry hint is available, use it */

        bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);

        p[4] = heads & 0xff;

        p[5] = secs & 0xff;

        p[6] = s->cluster_size * 2;

        p[8] = (cylinders >> 8) & 0xff;

        p[9] = cylinders & 0xff;

        /* Write precomp start cylinder, disabled */

        p[10] = (cylinders >> 8) & 0xff;

        p[11] = cylinders & 0xff;

        /* Reduced current start cylinder, disabled */

        p[12] = (cylinders >> 8) & 0xff;

        p[13] = cylinders & 0xff;

        /* Device step rate [100us], 100us */

        p[14] = 0;

        p[15] = 1;

        /* Device step pulse width [us], 1us */

        p[16] = 1;

        /* Device head settle delay [100us], 100us */

        p[17] = 0;

        p[18] = 1;

        /* Motor on delay [0.1s], 0.1s */

        p[19] = 1;

        /* Motor off delay [0.1s], 0.1s */

        p[20] = 1;

        /* Medium rotation rate [rpm], 5400 rpm */

        p[28] = (5400 >> 8) & 0xff;

        p[29] = 5400 & 0xff;

        return 0x1e;

    case 8: /* Caching page.  */

        p[0] = 8;

        p[1] = 0x12;

        if (bdrv_enable_write_cache(s->bs)) {

            p[2] = 4; /* WCE */

        }

        return 20;

    case 0x2a: /* CD Capabilities and Mechanical Status page. */

        if (bdrv_get_type_hint(bdrv) != BDRV_TYPE_CDROM)

            return 0;

        p[0] = 0x2a;

        p[1] = 0x14;

        p[2] = 3; // CD-R & CD-RW read

        p[3] = 0; // Writing not supported

        p[4] = 0x7f; /* Audio, composite, digital out,

                        mode 2 form 1&2, multi session */

        p[5] = 0xff; /* CD DA, DA accurate, RW supported,

                        RW corrected, C2 errors, ISRC,

                        UPC, Bar code */

        p[6] = 0x2d | (bdrv_is_locked(s->bs)? 2 : 0);

        /* Locking supported, jumper present, eject, tray */

        p[7] = 0; /* no volume & mute control, no

                     changer */

        p[8] = (50 * 176) >> 8; // 50x read speed

        p[9] = (50 * 176) & 0xff;

        p[10] = 0 >> 8; // No volume

        p[11] = 0 & 0xff;

        p[12] = 2048 >> 8; // 2M buffer

        p[13] = 2048 & 0xff;

        p[14] = (16 * 176) >> 8; // 16x read speed current

        p[15] = (16 * 176) & 0xff;

        p[18] = (16 * 176) >> 8; // 16x write speed

        p[19] = (16 * 176) & 0xff;

        p[20] = (16 * 176) >> 8; // 16x write speed current

        p[21] = (16 * 176) & 0xff;

        return 22;

    default:

        return 0;

    }

}


static av_cold int init(AVFilterContext *ctx)

{

    SendCmdContext *sendcmd = ctx->priv;

    int ret, i, j;

    if (sendcmd->commands_filename && sendcmd->commands_str) {

        av_log(ctx, AV_LOG_ERROR,

               "Only one of the filename or commands options must be specified\n");

        return AVERROR(EINVAL);

    }

    if (sendcmd->commands_filename) {

        uint8_t *file_buf, *buf;

        size_t file_bufsize;

        ret = av_file_map(sendcmd->commands_filename,

                          &file_buf, &file_bufsize, 0, ctx);

        if (ret < 0)

            return ret;

        /* create a 0-terminated string based on the read file */

        buf = av_malloc(file_bufsize + 1);

        if (!buf) {

            av_file_unmap(file_buf, file_bufsize);

            return AVERROR(ENOMEM);

        }

        memcpy(buf, file_buf, file_bufsize);

        buf[file_bufsize] = 0;

        av_file_unmap(file_buf, file_bufsize);

        sendcmd->commands_str = buf;

    }

    if ((ret = parse_intervals(&sendcmd->intervals, &sendcmd->nb_intervals,

                               sendcmd->commands_str, ctx)) < 0)

        return ret;

    if (sendcmd->nb_intervals == 0) {

        av_log(ctx, AV_LOG_ERROR, "No commands\n");

        return AVERROR(EINVAL);

    }

    qsort(sendcmd->intervals, sendcmd->nb_intervals, sizeof(Interval), cmp_intervals);

    av_log(ctx, AV_LOG_DEBUG, "Parsed commands:\n");

    for (i = 0; i < sendcmd->nb_intervals; i++) {

        AVBPrint pbuf;

        Interval *interval = &sendcmd->intervals[i];

        av_log(ctx, AV_LOG_VERBOSE, "start_time:%f end_time:%f index:%d\n",

               (double)interval->start_ts/1000000, (double)interval->end_ts/1000000, interval->index);

        for (j = 0; j < interval->nb_commands; j++) {

            Command *cmd = &interval->commands[j];

            av_log(ctx, AV_LOG_VERBOSE,

                   "    [%s] target:%s command:%s arg:%s index:%d\n",

                   make_command_flags_str(&pbuf, cmd->flags), cmd->target, cmd->command, cmd->arg, cmd->index);

        }

    }

    return 0;

}


int scsi_build_sense(uint8_t *in_buf, int in_len,

                     uint8_t *buf, int len, bool fixed)

{

    bool fixed_in;

    SCSISense sense;

    if (!fixed && len < 8) {

        return 0;

    }

    if (in_len == 0) {

        sense.key = NO_SENSE;

        sense.asc = 0;

        sense.ascq = 0;

    } else {

        fixed_in = (in_buf[0] & 2) == 0;

        if (fixed == fixed_in) {

            memcpy(buf, in_buf, MIN(len, in_len));

            return MIN(len, in_len);

        }

        if (fixed_in) {

            sense.key = in_buf[2];

            sense.asc = in_buf[12];

            sense.ascq = in_buf[13];

        } else {

            sense.key = in_buf[1];

            sense.asc = in_buf[2];

            sense.ascq = in_buf[3];

        }

    }

    memset(buf, 0, len);

    if (fixed) {

        /* Return fixed format sense buffer */

        buf[0] = 0x70;

        buf[2] = sense.key;

        buf[7] = 10;

        buf[12] = sense.asc;

        buf[13] = sense.ascq;

        return MIN(len, 18);

    } else {

        /* Return descriptor format sense buffer */

        buf[0] = 0x72;

        buf[1] = sense.key;

        buf[2] = sense.asc;

        buf[3] = sense.ascq;

        return 8;

    }

}


static void move_audio(vorbis_enc_context *venc, float *audio, int *samples, int sf_size)

{

    AVFrame *cur = NULL;

    int frame_size = 1 << (venc->log2_blocksize[1] - 1);

    int subframes = frame_size / sf_size;

    for (int sf = 0; sf < subframes; sf++) {

        cur = ff_bufqueue_get(&venc->bufqueue);

        *samples += cur->nb_samples;

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

            const float *input = (float *) cur->extended_data[ch];

            const size_t len  = cur->nb_samples * sizeof(float);

            memcpy(audio + ch*frame_size + sf*sf_size, input, len);

        }

        av_frame_free(&cur);

    }

}


static int push_single_pic(AVFilterLink *outlink)
{
    AVFilterContext *ctx = outlink->src;
    AVFilterLink *inlink = ctx->inputs[0];
    ShowWavesContext *showwaves = ctx->priv;
    int64_t n = 0, max_samples = showwaves->total_samples / outlink->w;
    AVFrame *out = showwaves->outpicref;
    struct frame_node *node;
    const int nb_channels = inlink->channels;
    const int x = 255 / (showwaves->split_channels ? 1 : nb_channels);
    const int ch_height = showwaves->split_channels ? outlink->h / nb_channels : outlink->h;
    const int linesize = out->linesize[0];
    int col = 0;
    int64_t *sum = showwaves->sum;
    av_log(ctx, AV_LOG_DEBUG, "Create frame averaging %"PRId64" samples per column\n", max_samples);
    memset(sum, 0, nb_channels);
    for (node = showwaves->audio_frames; node; node = node->next) {
        int i;
        const AVFrame *frame = node->frame;
        const int16_t *p = (const int16_t *)frame->data[0];
        for (i = 0; i < frame->nb_samples; i++) {
            int ch;
            for (ch = 0; ch < nb_channels; ch++)
                sum[ch] += abs(p[ch + i*nb_channels]) << 1;
            if (n++ == max_samples) {
                for (ch = 0; ch < nb_channels; ch++) {
                    int16_t sample = sum[ch] / max_samples;
                    uint8_t *buf = out->data[0] + col;
                    if (showwaves->split_channels)
                        buf += ch*ch_height*linesize;
                    av_assert0(col < outlink->w);
                    showwaves->draw_sample(buf, ch_height, linesize, sample, &showwaves->buf_idy[ch], x);
                    sum[ch] = 0;
                col++;
                n = 0;
    return push_frame(outlink);


static void host_signal_handler(int host_signum, siginfo_t *info,

                                void *puc)

{

    int sig;

    target_siginfo_t tinfo;

    /* the CPU emulator uses some host signals to detect exceptions,

       we we forward to it some signals */

    if (host_signum == SIGSEGV || host_signum == SIGBUS) {

        if (cpu_signal_handler(host_signum, info, puc))

            return;

    }

    /* get target signal number */

    sig = host_to_target_signal(host_signum);

    if (sig < 1 || sig > TARGET_NSIG)

        return;

#if defined(DEBUG_SIGNAL)

    fprintf(stderr, "qemu: got signal %d\n", sig);

    dump_regs(puc);

#endif

    host_to_target_siginfo_noswap(&tinfo, info);

    if (queue_signal(sig, &tinfo) == 1) {

        /* interrupt the virtual CPU as soon as possible */

        cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);

    }

}


int ff_j2k_dwt_init(DWTContext *s, uint16_t border[2][2], int decomp_levels, int type)

{

    int i, j, lev = decomp_levels, maxlen,

        b[2][2];

    if (decomp_levels >= FF_DWT_MAX_DECLVLS)

        return AVERROR_INVALIDDATA;

    s->ndeclevels = decomp_levels;

    s->type = type;

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

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

            b[i][j] = border[i][j];

    maxlen = FFMAX(b[0][1] - b[0][0],

                   b[1][1] - b[1][0]);

    while(--lev >= 0){

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

            s->linelen[lev][i] = b[i][1] - b[i][0];

            s->mod[lev][i] = b[i][0] & 1;

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

                b[i][j] = (b[i][j] + 1) >> 1;

        }

    }

    if (type == FF_DWT97)

        s->linebuf = av_malloc((maxlen + 12) * sizeof(float));

    else if (type == FF_DWT53)

        s->linebuf = av_malloc((maxlen + 6) * sizeof(int));

    else

        return -1;

    if (!s->linebuf)

        return AVERROR(ENOMEM);

    return 0;

}


static int read_block_types(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)

{

    int t, v;

    int last = 0;

    const uint8_t *dec_end;

    CHECK_READ_VAL(gb, b, t);

    dec_end = b->cur_dec + t;

    if (dec_end > b->data_end) {

        av_log(avctx, AV_LOG_ERROR, "Too many block type values\n");

        return -1;

    }

    if (get_bits1(gb)) {

        v = get_bits(gb, 4);

        memset(b->cur_dec, v, t);

        b->cur_dec += t;

    } else {

        do {

            v = GET_HUFF(gb, b->tree);

            if (v < 12) {

                last = v;

                *b->cur_dec++ = v;

            } else {

                int run = bink_rlelens[v - 12];

                memset(b->cur_dec, last, run);

                b->cur_dec += run;

            }

        } while (b->cur_dec < dec_end);

    }

    return 0;

}


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

                             int *got_frame, AVPacket *avpkt)

{

    AVFrame *pic = data;

    uint8_t *src = avpkt->data;

    uint8_t *y, *u, *v;

    int i, j, ret;

    if (avpkt->size < 3LL * avctx->height * avctx->width / 2) {

        av_log(avctx, AV_LOG_ERROR, "Insufficient input data.\n");

        return AVERROR(EINVAL);

    }

    if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)

        return ret;

    pic->key_frame = 1;

    pic->pict_type = AV_PICTURE_TYPE_I;

    for (i = avctx->height - 1; i >= 0 ; i--) {

        y = &pic->data[0][i * pic->linesize[0]];

        u = &pic->data[1][i * pic->linesize[1]];

        v = &pic->data[2][i * pic->linesize[2]];

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

            *(u++) = *src++;

            *(y++) = *src++;

            *(v++) = *src++;

            *(y++) = *src++;

            *(u++) = *src++;

            *(y++) = *src++;

            *(v++) = *src++;

            *(y++) = *src++;

            *(y++) = *src++;

            *(y++) = *src++;

            *(y++) = *src++;

            *(y++) = *src++;

        }

    }

    *got_frame = 1;

    return avpkt->size;

}


static void gen_msgsnd(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    gen_helper_msgsnd(cpu_gpr[rB(ctx->opcode)]);

#endif

}


int ff_MPV_common_frame_size_change(MpegEncContext *s)

{

    int i, err = 0;

    if (s->slice_context_count > 1) {

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

            free_duplicate_context(s->thread_context[i]);

        }

        for (i = 1; i < s->slice_context_count; i++) {

            av_freep(&s->thread_context[i]);

        }

    } else

        free_duplicate_context(s);

    if ((err = free_context_frame(s)) < 0)

        return err;

    if (s->picture)

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

                s->picture[i].needs_realloc = 1;

        }

    s->last_picture_ptr         =

    s->next_picture_ptr         =

    s->current_picture_ptr      = NULL;

    // init

    if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)

        s->mb_height = (s->height + 31) / 32 * 2;

    else

        s->mb_height = (s->height + 15) / 16;

    if ((s->width || s->height) &&

        av_image_check_size(s->width, s->height, 0, s->avctx))

        return AVERROR_INVALIDDATA;

    if ((err = init_context_frame(s)))

        goto fail;

    s->thread_context[0]   = s;

    if (s->width && s->height) {

        int nb_slices = s->slice_context_count;

        if (nb_slices > 1) {

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

                s->thread_context[i] = av_malloc(sizeof(MpegEncContext));

                memcpy(s->thread_context[i], s, sizeof(MpegEncContext));

            }

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

                if (init_duplicate_context(s->thread_context[i]) < 0)

                    goto fail;

                    s->thread_context[i]->start_mb_y =

                        (s->mb_height * (i) + nb_slices / 2) / nb_slices;

                    s->thread_context[i]->end_mb_y   =

                        (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;

            }

        } else {

            if (init_duplicate_context(s) < 0)

                goto fail;

            s->start_mb_y = 0;

            s->end_mb_y   = s->mb_height;

        }

        s->slice_context_count = nb_slices;

    }

    return 0;

 fail:

    ff_MPV_common_end(s);

    return err;

}


static void pc_isa_bios_init(MemoryRegion *rom_memory,

                             MemoryRegion *flash_mem,

                             int ram_size)

{

    int isa_bios_size;

    MemoryRegion *isa_bios;

    uint64_t flash_size;

    void *flash_ptr, *isa_bios_ptr;

    flash_size = memory_region_size(flash_mem);

    /* map the last 128KB of the BIOS in ISA space */

    isa_bios_size = flash_size;

    if (isa_bios_size > (128 * 1024)) {

        isa_bios_size = 128 * 1024;

    }

    isa_bios = g_malloc(sizeof(*isa_bios));

    memory_region_init_ram(isa_bios, NULL, "isa-bios", isa_bios_size);

    vmstate_register_ram_global(isa_bios);

    memory_region_add_subregion_overlap(rom_memory,

                                        0x100000 - isa_bios_size,

                                        isa_bios,

                                        1);

    /* copy ISA rom image from top of flash memory */

    flash_ptr = memory_region_get_ram_ptr(flash_mem);

    isa_bios_ptr = memory_region_get_ram_ptr(isa_bios);

    memcpy(isa_bios_ptr,

           ((uint8_t*)flash_ptr) + (flash_size - isa_bios_size),

           isa_bios_size);

    memory_region_set_readonly(isa_bios, true);

}


static void gen_tlbivax_booke206(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    t0 = tcg_temp_new();

    gen_addr_reg_index(ctx, t0);

    gen_helper_booke206_tlbivax(cpu_env, t0);

    tcg_temp_free(t0);

#endif

}


void helper_ldf_asi(target_ulong addr, int asi, int size, int rd)
{
    unsigned int i;
    target_ulong val;
    helper_check_align(addr, 3);
    addr = asi_address_mask(env, asi, addr);
    switch (asi) {
    case 0xf0: // Block load primary
    case 0xf1: // Block load secondary
    case 0xf8: // Block load primary LE
    case 0xf9: // Block load secondary LE
            *(uint32_t *)&env->fpr[rd++] = helper_ld_asi(addr, asi & 0x8f, 4,
    default:
        break;
    val = helper_ld_asi(addr, asi, size, 0);
    switch(size) {
    default:
    case 4:
        *((uint32_t *)&env->fpr[rd]) = val;
        break;
    case 8:
        *((int64_t *)&DT0) = val;
        break;
    case 16:
        // XXX
        break;


static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,

                                            int se, int Ah, int Al)

{

    int mb_x, mb_y;

    int EOBRUN = 0;

    int c = s->comp_index[0];

    uint8_t *data = s->picture_ptr->data[c];

    int linesize  = s->linesize[c];

    int last_scan = 0;

    int16_t *quant_matrix = s->quant_matrixes[s->quant_sindex[0]];

    int bytes_per_pixel = 1 + (s->bits > 8);

    av_assert0(ss>=0 && Ah>=0 && Al>=0);

    if (se < ss || se > 63) {

        av_log(s->avctx, AV_LOG_ERROR, "SS/SE %d/%d is invalid\n", ss, se);

        return AVERROR_INVALIDDATA;

    }

    if (!Al) {

        s->coefs_finished[c] |= (2LL << se) - (1LL << ss);

        last_scan = !~s->coefs_finished[c];

    }

    if (s->interlaced && s->bottom_field)

        data += linesize >> 1;

    s->restart_count = 0;

    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {

        uint8_t *ptr     = data + (mb_y * linesize * 8 >> s->avctx->lowres);

        int block_idx    = mb_y * s->block_stride[c];

        int16_t (*block)[64] = &s->blocks[c][block_idx];

        uint8_t *last_nnz    = &s->last_nnz[c][block_idx];

        for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {

                int ret;

                if (s->restart_interval && !s->restart_count)

                    s->restart_count = s->restart_interval;

                if (Ah)

                    ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],

                                                  quant_matrix, ss, se, Al, &EOBRUN);

                else

                    ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],

                                                   quant_matrix, ss, se, Al, &EOBRUN);

                if (ret < 0) {

                    av_log(s->avctx, AV_LOG_ERROR,

                           "error y=%d x=%d\n", mb_y, mb_x);

                    return AVERROR_INVALIDDATA;

                }

            if (last_scan) {

                    s->dsp.idct_put(ptr, linesize, *block);

                    if (s->bits & 7)

                        shift_output(s, ptr, linesize);

                    ptr += bytes_per_pixel*8 >> s->avctx->lowres;

            }

            if (handle_rstn(s, 0))

                EOBRUN = 0;

        }

    }

    return 0;

}


struct omap_dss_s *omap_dss_init(struct omap_target_agent_s *ta,

                MemoryRegion *sysmem,

                hwaddr l3_base,

                qemu_irq irq, qemu_irq drq,

                omap_clk fck1, omap_clk fck2, omap_clk ck54m,

                omap_clk ick1, omap_clk ick2)

{

    struct omap_dss_s *s = (struct omap_dss_s *)

            g_malloc0(sizeof(struct omap_dss_s));

    s->irq = irq;

    s->drq = drq;

    omap_dss_reset(s);

    memory_region_init_io(&s->iomem_diss1, NULL, &omap_diss_ops, s, "omap.diss1",

                          omap_l4_region_size(ta, 0));

    memory_region_init_io(&s->iomem_disc1, NULL, &omap_disc_ops, s, "omap.disc1",

                          omap_l4_region_size(ta, 1));

    memory_region_init_io(&s->iomem_rfbi1, NULL, &omap_rfbi_ops, s, "omap.rfbi1",

                          omap_l4_region_size(ta, 2));

    memory_region_init_io(&s->iomem_venc1, NULL, &omap_venc_ops, s, "omap.venc1",

                          omap_l4_region_size(ta, 3));

    memory_region_init_io(&s->iomem_im3, NULL, &omap_im3_ops, s,

                          "omap.im3", 0x1000);

    omap_l4_attach(ta, 0, &s->iomem_diss1);

    omap_l4_attach(ta, 1, &s->iomem_disc1);

    omap_l4_attach(ta, 2, &s->iomem_rfbi1);

    omap_l4_attach(ta, 3, &s->iomem_venc1);

    memory_region_add_subregion(sysmem, l3_base, &s->iomem_im3);

#if 0

    s->state = graphic_console_init(omap_update_display,

                                    omap_invalidate_display, omap_screen_dump, s);

#endif

    return s;

}


int attribute_align_arg sws_scale(struct SwsContext *c,
                                  const uint8_t * const srcSlice[],
                                  const int srcStride[], int srcSliceY,
                                  int srcSliceH, uint8_t *const dst[],
                                  const int dstStride[])
{
    int i, ret;
    const uint8_t *src2[4];
    uint8_t *dst2[4];
    uint8_t *rgb0_tmp = NULL;
    if (!srcStride || !dstStride || !dst || !srcSlice) {
        av_log(c, AV_LOG_ERROR, "One of the input parameters to sws_scale() is NULL, please check the calling code\n");
        return 0;
    if (c->gamma_flag && c->cascaded_context[0]) {
        ret = sws_scale(c->cascaded_context[0],
                    srcSlice, srcStride, srcSliceY, srcSliceH,
                    c->cascaded_tmp, c->cascaded_tmpStride);
        if (ret < 0)
            return ret;
        if (c->cascaded_context[2])
            ret = sws_scale(c->cascaded_context[1], (const uint8_t * const *)c->cascaded_tmp, c->cascaded_tmpStride, srcSliceY, srcSliceH, c->cascaded1_tmp, c->cascaded1_tmpStride);
        else
            ret = sws_scale(c->cascaded_context[1], (const uint8_t * const *)c->cascaded_tmp, c->cascaded_tmpStride, srcSliceY, srcSliceH, dst, dstStride);
        if (ret < 0)
            return ret;
        if (c->cascaded_context[2]) {
            ret = sws_scale(c->cascaded_context[2],
                        (const uint8_t * const *)c->cascaded1_tmp, c->cascaded1_tmpStride, c->cascaded_context[1]->dstY - ret, c->cascaded_context[1]->dstY,
                        dst, dstStride);
        return ret;
    if (c->cascaded_context[0] && srcSliceY == 0 && srcSliceH == c->cascaded_context[0]->srcH) {
        ret = sws_scale(c->cascaded_context[0],
                        srcSlice, srcStride, srcSliceY, srcSliceH,
                        c->cascaded_tmp, c->cascaded_tmpStride);
        if (ret < 0)
            return ret;
        ret = sws_scale(c->cascaded_context[1],
                        (const uint8_t * const * )c->cascaded_tmp, c->cascaded_tmpStride, 0, c->cascaded_context[0]->dstH,
                        dst, dstStride);
        return ret;
    memcpy(src2, srcSlice, sizeof(src2));
    memcpy(dst2, dst, sizeof(dst2));
    // do not mess up sliceDir if we have a "trailing" 0-size slice
    if (srcSliceH == 0)
        return 0;
    if (!check_image_pointers(srcSlice, c->srcFormat, srcStride)) {
        av_log(c, AV_LOG_ERROR, "bad src image pointers\n");
        return 0;
    if (!check_image_pointers((const uint8_t* const*)dst, c->dstFormat, dstStride)) {
        av_log(c, AV_LOG_ERROR, "bad dst image pointers\n");
        return 0;
    if (c->sliceDir == 0 && srcSliceY != 0 && srcSliceY + srcSliceH != c->srcH) {
        av_log(c, AV_LOG_ERROR, "Slices start in the middle!\n");
        return 0;
    if (c->sliceDir == 0) {
        if (srcSliceY == 0) c->sliceDir = 1; else c->sliceDir = -1;
    if (usePal(c->srcFormat)) {
        for (i = 0; i < 256; i++) {
            int r, g, b, y, u, v, a = 0xff;
            if (c->srcFormat == AV_PIX_FMT_PAL8) {
                uint32_t p = ((const uint32_t *)(srcSlice[1]))[i];
                a = (p >> 24) & 0xFF;
                r = (p >> 16) & 0xFF;
                g = (p >>  8) & 0xFF;
                b =  p        & 0xFF;
            } else if (c->srcFormat == AV_PIX_FMT_RGB8) {
                r = ( i >> 5     ) * 36;
                g = ((i >> 2) & 7) * 36;
                b = ( i       & 3) * 85;
            } else if (c->srcFormat == AV_PIX_FMT_BGR8) {
                b = ( i >> 6     ) * 85;
                g = ((i >> 3) & 7) * 36;
                r = ( i       & 7) * 36;
            } else if (c->srcFormat == AV_PIX_FMT_RGB4_BYTE) {
                r = ( i >> 3     ) * 255;
                g = ((i >> 1) & 3) * 85;
                b = ( i       & 1) * 255;
            } else if (c->srcFormat == AV_PIX_FMT_GRAY8 || c->srcFormat == AV_PIX_FMT_GRAY8A) {
                r = g = b = i;
            } else {
                av_assert1(c->srcFormat == AV_PIX_FMT_BGR4_BYTE);
                b = ( i >> 3     ) * 255;
                g = ((i >> 1) & 3) * 85;
                r = ( i       & 1) * 255;
#define RGB2YUV_SHIFT 15
#define BY ( (int) (0.114 * 219 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))
#define BV (-(int) (0.081 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))
#define BU ( (int) (0.500 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))
#define GY ( (int) (0.587 * 219 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))
#define GV (-(int) (0.419 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))
#define GU (-(int) (0.331 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))
#define RY ( (int) (0.299 * 219 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))
#define RV ( (int) (0.500 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))
#define RU (-(int) (0.169 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))
            y = av_clip_uint8((RY * r + GY * g + BY * b + ( 33 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT);
            u = av_clip_uint8((RU * r + GU * g + BU * b + (257 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT);
            v = av_clip_uint8((RV * r + GV * g + BV * b + (257 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT);
            c->pal_yuv[i]= y + (u<<8) + (v<<16) + ((unsigned)a<<24);
            switch (c->dstFormat) {
            case AV_PIX_FMT_BGR32:
#if !HAVE_BIGENDIAN
            case AV_PIX_FMT_RGB24:
#endif
                c->pal_rgb[i]=  r + (g<<8) + (b<<16) + ((unsigned)a<<24);
                break;
            case AV_PIX_FMT_BGR32_1:
#if HAVE_BIGENDIAN
            case AV_PIX_FMT_BGR24:
#endif
                c->pal_rgb[i]= a + (r<<8) + (g<<16) + ((unsigned)b<<24);
                break;
            case AV_PIX_FMT_RGB32_1:
#if HAVE_BIGENDIAN
            case AV_PIX_FMT_RGB24:
#endif
                c->pal_rgb[i]= a + (b<<8) + (g<<16) + ((unsigned)r<<24);
                break;
            case AV_PIX_FMT_RGB32:
#if !HAVE_BIGENDIAN
            case AV_PIX_FMT_BGR24:
#endif
            default:
                c->pal_rgb[i]=  b + (g<<8) + (r<<16) + ((unsigned)a<<24);
    if (c->src0Alpha && !c->dst0Alpha && isALPHA(c->dstFormat)) {
        uint8_t *base;
        int x,y;
        rgb0_tmp = av_malloc(FFABS(srcStride[0]) * srcSliceH + 32);
        if (!rgb0_tmp)
            return AVERROR(ENOMEM);
        base = srcStride[0] < 0 ? rgb0_tmp - srcStride[0] * (srcSliceH-1) : rgb0_tmp;
        for (y=0; y<srcSliceH; y++){
            memcpy(base + srcStride[0]*y, src2[0] + srcStride[0]*y, 4*c->srcW);
            for (x=c->src0Alpha-1; x<4*c->srcW; x+=4) {
                base[ srcStride[0]*y + x] = 0xFF;
        src2[0] = base;
    if (c->srcXYZ && !(c->dstXYZ && c->srcW==c->dstW && c->srcH==c->dstH)) {
        uint8_t *base;
        rgb0_tmp = av_malloc(FFABS(srcStride[0]) * srcSliceH + 32);
        if (!rgb0_tmp)
            return AVERROR(ENOMEM);
        base = srcStride[0] < 0 ? rgb0_tmp - srcStride[0] * (srcSliceH-1) : rgb0_tmp;
        xyz12Torgb48(c, (uint16_t*)base, (const uint16_t*)src2[0], srcStride[0]/2, srcSliceH);
        src2[0] = base;
    if (!srcSliceY && (c->flags & SWS_BITEXACT) && c->dither == SWS_DITHER_ED && c->dither_error[0])
        for (i = 0; i < 4; i++)
            memset(c->dither_error[i], 0, sizeof(c->dither_error[0][0]) * (c->dstW+2));
    // copy strides, so they can safely be modified
    if (c->sliceDir == 1) {
        // slices go from top to bottom
        int srcStride2[4] = { srcStride[0], srcStride[1], srcStride[2],
                              srcStride[3] };
        int dstStride2[4] = { dstStride[0], dstStride[1], dstStride[2],
                              dstStride[3] };
        reset_ptr(src2, c->srcFormat);
        reset_ptr((void*)dst2, c->dstFormat);
        /* reset slice direction at end of frame */
        if (srcSliceY + srcSliceH == c->srcH)
            c->sliceDir = 0;
        ret = c->swscale(c, src2, srcStride2, srcSliceY, srcSliceH, dst2,
                          dstStride2);
    } else {
        // slices go from bottom to top => we flip the image internally
        int srcStride2[4] = { -srcStride[0], -srcStride[1], -srcStride[2],
                              -srcStride[3] };
        int dstStride2[4] = { -dstStride[0], -dstStride[1], -dstStride[2],
                              -dstStride[3] };
        src2[0] += (srcSliceH - 1) * srcStride[0];
        if (!usePal(c->srcFormat))
            src2[1] += ((srcSliceH >> c->chrSrcVSubSample) - 1) * srcStride[1];
        src2[2] += ((srcSliceH >> c->chrSrcVSubSample) - 1) * srcStride[2];
        src2[3] += (srcSliceH - 1) * srcStride[3];
        dst2[0] += ( c->dstH                         - 1) * dstStride[0];
        dst2[1] += ((c->dstH >> c->chrDstVSubSample) - 1) * dstStride[1];
        dst2[2] += ((c->dstH >> c->chrDstVSubSample) - 1) * dstStride[2];
        dst2[3] += ( c->dstH                         - 1) * dstStride[3];
        reset_ptr(src2, c->srcFormat);
        reset_ptr((void*)dst2, c->dstFormat);
        /* reset slice direction at end of frame */
        if (!srcSliceY)
            c->sliceDir = 0;
        ret = c->swscale(c, src2, srcStride2, c->srcH-srcSliceY-srcSliceH,
                          srcSliceH, dst2, dstStride2);
    if (c->dstXYZ && !(c->srcXYZ && c->srcW==c->dstW && c->srcH==c->dstH)) {
        /* replace on the same data */
        rgb48Toxyz12(c, (uint16_t*)dst2[0], (const uint16_t*)dst2[0], dstStride[0]/2, ret);
    av_free(rgb0_tmp);
    return ret;


static int select_voice(cst_voice **voice, const char *voice_name, void *log_ctx)

{

    int i;

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

        struct voice_entry *entry = &voice_entries[i];

        if (!strcmp(entry->name, voice_name)) {

            *voice = entry->register_fn(NULL);

            if (!*voice) {

                av_log(log_ctx, AV_LOG_ERROR,

                       "Could not register voice '%s'\n", voice_name);

                return AVERROR_UNKNOWN;

            }

            return 0;

        }

    }

    av_log(log_ctx, AV_LOG_ERROR, "Could not find voice '%s'\n", voice_name);

    av_log(log_ctx, AV_LOG_INFO, "Choose between the voices: ");

    list_voices(log_ctx, ", ");

    return AVERROR(EINVAL);

}


int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,

              int flags, BlockDriver *drv)

{

    int ret;

    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */

    char tmp_filename[PATH_MAX + 1];

    BlockDriverState *file = NULL;

    QDict *file_options = NULL;

    /* NULL means an empty set of options */

    if (options == NULL) {

        options = qdict_new();

    }

    bs->options = options;

    options = qdict_clone_shallow(options);

    /* For snapshot=on, create a temporary qcow2 overlay */

    if (flags & BDRV_O_SNAPSHOT) {

        BlockDriverState *bs1;

        int64_t total_size;

        BlockDriver *bdrv_qcow2;

        QEMUOptionParameter *create_options;

        char backing_filename[PATH_MAX];

        if (qdict_size(options) != 0) {

            error_report("Can't use snapshot=on with driver-specific options");

            ret = -EINVAL;

            goto fail;

        }

        assert(filename != NULL);

        /* if snapshot, we create a temporary backing file and open it

           instead of opening 'filename' directly */

        /* if there is a backing file, use it */

        bs1 = bdrv_new("");

        ret = bdrv_open(bs1, filename, NULL, 0, drv);

        if (ret < 0) {

            bdrv_delete(bs1);

            goto fail;

        }

        total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;

        bdrv_delete(bs1);

        ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));

        if (ret < 0) {

            goto fail;

        }

        /* Real path is meaningless for protocols */

        if (path_has_protocol(filename)) {

            snprintf(backing_filename, sizeof(backing_filename),

                     "%s", filename);

        } else if (!realpath(filename, backing_filename)) {

            ret = -errno;

            goto fail;

        }

        bdrv_qcow2 = bdrv_find_format("qcow2");

        create_options = parse_option_parameters("", bdrv_qcow2->create_options,

                                                 NULL);

        set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);

        set_option_parameter(create_options, BLOCK_OPT_BACKING_FILE,

                             backing_filename);

        if (drv) {

            set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT,

                drv->format_name);

        }

        ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options);

        free_option_parameters(create_options);

        if (ret < 0) {

            goto fail;

        }

        filename = tmp_filename;

        drv = bdrv_qcow2;

        bs->is_temporary = 1;

    }

    /* Open image file without format layer */

    if (flags & BDRV_O_RDWR) {

        flags |= BDRV_O_ALLOW_RDWR;

    }

    extract_subqdict(options, &file_options, "file.");

    ret = bdrv_file_open(&file, filename, file_options,

                         bdrv_open_flags(bs, flags));

    if (ret < 0) {

        goto fail;

    }

    /* Find the right image format driver */

    if (!drv) {

        ret = find_image_format(file, filename, &drv);

    }

    if (!drv) {

        goto unlink_and_fail;

    }

    /* Open the image */

    ret = bdrv_open_common(bs, file, filename, options, flags, drv);

    if (ret < 0) {

        goto unlink_and_fail;

    }

    if (bs->file != file) {

        bdrv_delete(file);

        file = NULL;

    }

    /* If there is a backing file, use it */

    if ((flags & BDRV_O_NO_BACKING) == 0) {

        ret = bdrv_open_backing_file(bs);

        if (ret < 0) {

            goto close_and_fail;

        }

    }

    /* Check if any unknown options were used */

    if (qdict_size(options) != 0) {

        const QDictEntry *entry = qdict_first(options);

        qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block format '%s' used by "

            "device '%s' doesn't support the option '%s'",

            drv->format_name, bs->device_name, entry->key);

        ret = -EINVAL;

        goto close_and_fail;

    }

    QDECREF(options);

    if (!bdrv_key_required(bs)) {

        bdrv_dev_change_media_cb(bs, true);

    }

    /* throttling disk I/O limits */

    if (bs->io_limits_enabled) {

        bdrv_io_limits_enable(bs);

    }

    return 0;

unlink_and_fail:

    if (file != NULL) {

        bdrv_delete(file);

    }

    if (bs->is_temporary) {

        unlink(filename);

    }

fail:

    QDECREF(bs->options);

    QDECREF(options);

    bs->options = NULL;

    return ret;

close_and_fail:

    bdrv_close(bs);

    QDECREF(options);

    return ret;

}