static int assigned_device_pci_cap_init(PCIDevice *pci_dev)

{

    AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);

    PCIRegion *pci_region = dev->real_device.regions;

    int ret, pos;

    /* Clear initial capabilities pointer and status copied from hw */

    pci_set_byte(pci_dev->config + PCI_CAPABILITY_LIST, 0);

    pci_set_word(pci_dev->config + PCI_STATUS,

                 pci_get_word(pci_dev->config + PCI_STATUS) &

                 ~PCI_STATUS_CAP_LIST);

    /* Expose MSI capability

     * MSI capability is the 1st capability in capability config */

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSI, 0);

    if (pos != 0 && kvm_check_extension(kvm_state, KVM_CAP_ASSIGN_DEV_IRQ)) {

        if (!check_irqchip_in_kernel()) {

            return -ENOTSUP;

        }

        dev->cap.available |= ASSIGNED_DEVICE_CAP_MSI;

        /* Only 32-bit/no-mask currently supported */

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSI, pos, 10);

        if (ret < 0) {

            return ret;

        }

        pci_dev->msi_cap = pos;

        pci_set_word(pci_dev->config + pos + PCI_MSI_FLAGS,

                     pci_get_word(pci_dev->config + pos + PCI_MSI_FLAGS) &

                     PCI_MSI_FLAGS_QMASK);

        pci_set_long(pci_dev->config + pos + PCI_MSI_ADDRESS_LO, 0);

        pci_set_word(pci_dev->config + pos + PCI_MSI_DATA_32, 0);

        /* Set writable fields */

        pci_set_word(pci_dev->wmask + pos + PCI_MSI_FLAGS,

                     PCI_MSI_FLAGS_QSIZE | PCI_MSI_FLAGS_ENABLE);

        pci_set_long(pci_dev->wmask + pos + PCI_MSI_ADDRESS_LO, 0xfffffffc);

        pci_set_word(pci_dev->wmask + pos + PCI_MSI_DATA_32, 0xffff);

    }

    /* Expose MSI-X capability */

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSIX, 0);

    if (pos != 0 && kvm_device_msix_supported(kvm_state)) {

        int bar_nr;

        uint32_t msix_table_entry;

        if (!check_irqchip_in_kernel()) {

            return -ENOTSUP;

        }

        dev->cap.available |= ASSIGNED_DEVICE_CAP_MSIX;

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSIX, pos, 12);

        if (ret < 0) {

            return ret;

        }

        pci_dev->msix_cap = pos;

        pci_set_word(pci_dev->config + pos + PCI_MSIX_FLAGS,

                     pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS) &

                     PCI_MSIX_FLAGS_QSIZE);

        /* Only enable and function mask bits are writable */

        pci_set_word(pci_dev->wmask + pos + PCI_MSIX_FLAGS,

                     PCI_MSIX_FLAGS_ENABLE | PCI_MSIX_FLAGS_MASKALL);

        msix_table_entry = pci_get_long(pci_dev->config + pos + PCI_MSIX_TABLE);

        bar_nr = msix_table_entry & PCI_MSIX_FLAGS_BIRMASK;

        msix_table_entry &= ~PCI_MSIX_FLAGS_BIRMASK;

        dev->msix_table_addr = pci_region[bar_nr].base_addr + msix_table_entry;

        dev->msix_max = pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS);

        dev->msix_max &= PCI_MSIX_FLAGS_QSIZE;

        dev->msix_max += 1;

    }

    /* Minimal PM support, nothing writable, device appears to NAK changes */

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PM, 0);

    if (pos) {

        uint16_t pmc;

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_PM, pos, PCI_PM_SIZEOF);

        if (ret < 0) {

            return ret;

        }

        assigned_dev_setup_cap_read(dev, pos, PCI_PM_SIZEOF);

        pmc = pci_get_word(pci_dev->config + pos + PCI_CAP_FLAGS);

        pmc &= (PCI_PM_CAP_VER_MASK | PCI_PM_CAP_DSI);

        pci_set_word(pci_dev->config + pos + PCI_CAP_FLAGS, pmc);

        /* assign_device will bring the device up to D0, so we don't need

         * to worry about doing that ourselves here. */

        pci_set_word(pci_dev->config + pos + PCI_PM_CTRL,

                     PCI_PM_CTRL_NO_SOFT_RESET);

        pci_set_byte(pci_dev->config + pos + PCI_PM_PPB_EXTENSIONS, 0);

        pci_set_byte(pci_dev->config + pos + PCI_PM_DATA_REGISTER, 0);

    }

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_EXP, 0);

    if (pos) {

        uint8_t version, size = 0;

        uint16_t type, devctl, lnksta;

        uint32_t devcap, lnkcap;

        version = pci_get_byte(pci_dev->config + pos + PCI_EXP_FLAGS);

        version &= PCI_EXP_FLAGS_VERS;

        if (version == 1) {

            size = 0x14;

        } else if (version == 2) {

            /*

             * Check for non-std size, accept reduced size to 0x34,

             * which is what bcm5761 implemented, violating the

             * PCIe v3.0 spec that regs should exist and be read as 0,

             * not optionally provided and shorten the struct size.

             */

            size = MIN(0x3c, PCI_CONFIG_SPACE_SIZE - pos);

            if (size < 0x34) {

                error_report("%s: Invalid size PCIe cap-id 0x%x",

                             __func__, PCI_CAP_ID_EXP);

                return -EINVAL;

            } else if (size != 0x3c) {

                error_report("WARNING, %s: PCIe cap-id 0x%x has "

                             "non-standard size 0x%x; std size should be 0x3c",

                             __func__, PCI_CAP_ID_EXP, size);

            }

        } else if (version == 0) {

            uint16_t vid, did;

            vid = pci_get_word(pci_dev->config + PCI_VENDOR_ID);

            did = pci_get_word(pci_dev->config + PCI_DEVICE_ID);

            if (vid == PCI_VENDOR_ID_INTEL && did == 0x10ed) {

                /*

                 * quirk for Intel 82599 VF with invalid PCIe capability

                 * version, should really be version 2 (same as PF)

                 */

                size = 0x3c;

            }

        }

        if (size == 0) {

            error_report("%s: Unsupported PCI express capability version %d",

                         __func__, version);

            return -EINVAL;

        }

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_EXP, pos, size);

        if (ret < 0) {

            return ret;

        }

        assigned_dev_setup_cap_read(dev, pos, size);

        type = pci_get_word(pci_dev->config + pos + PCI_EXP_FLAGS);

        type = (type & PCI_EXP_FLAGS_TYPE) >> 4;

        if (type != PCI_EXP_TYPE_ENDPOINT &&

            type != PCI_EXP_TYPE_LEG_END && type != PCI_EXP_TYPE_RC_END) {

            error_report("Device assignment only supports endpoint assignment,"

                         " device type %d", type);

            return -EINVAL;

        }

        /* capabilities, pass existing read-only copy

         * PCI_EXP_FLAGS_IRQ: updated by hardware, should be direct read */

        /* device capabilities: hide FLR */

        devcap = pci_get_long(pci_dev->config + pos + PCI_EXP_DEVCAP);

        devcap &= ~PCI_EXP_DEVCAP_FLR;

        pci_set_long(pci_dev->config + pos + PCI_EXP_DEVCAP, devcap);

        /* device control: clear all error reporting enable bits, leaving

         *                 only a few host values.  Note, these are

         *                 all writable, but not passed to hw.

         */

        devctl = pci_get_word(pci_dev->config + pos + PCI_EXP_DEVCTL);

        devctl = (devctl & (PCI_EXP_DEVCTL_READRQ | PCI_EXP_DEVCTL_PAYLOAD)) |

                  PCI_EXP_DEVCTL_RELAX_EN | PCI_EXP_DEVCTL_NOSNOOP_EN;

        pci_set_word(pci_dev->config + pos + PCI_EXP_DEVCTL, devctl);

        devctl = PCI_EXP_DEVCTL_BCR_FLR | PCI_EXP_DEVCTL_AUX_PME;

        pci_set_word(pci_dev->wmask + pos + PCI_EXP_DEVCTL, ~devctl);

        /* Clear device status */

        pci_set_word(pci_dev->config + pos + PCI_EXP_DEVSTA, 0);

        /* Link capabilities, expose links and latencues, clear reporting */

        lnkcap = pci_get_long(pci_dev->config + pos + PCI_EXP_LNKCAP);

        lnkcap &= (PCI_EXP_LNKCAP_SLS | PCI_EXP_LNKCAP_MLW |

                   PCI_EXP_LNKCAP_ASPMS | PCI_EXP_LNKCAP_L0SEL |

                   PCI_EXP_LNKCAP_L1EL);

        pci_set_long(pci_dev->config + pos + PCI_EXP_LNKCAP, lnkcap);

        /* Link control, pass existing read-only copy.  Should be writable? */

        /* Link status, only expose current speed and width */

        lnksta = pci_get_word(pci_dev->config + pos + PCI_EXP_LNKSTA);

        lnksta &= (PCI_EXP_LNKSTA_CLS | PCI_EXP_LNKSTA_NLW);

        pci_set_word(pci_dev->config + pos + PCI_EXP_LNKSTA, lnksta);

        if (version >= 2) {

            /* Slot capabilities, control, status - not needed for endpoints */

            pci_set_long(pci_dev->config + pos + PCI_EXP_SLTCAP, 0);

            pci_set_word(pci_dev->config + pos + PCI_EXP_SLTCTL, 0);

            pci_set_word(pci_dev->config + pos + PCI_EXP_SLTSTA, 0);

            /* Root control, capabilities, status - not needed for endpoints */

            pci_set_word(pci_dev->config + pos + PCI_EXP_RTCTL, 0);

            pci_set_word(pci_dev->config + pos + PCI_EXP_RTCAP, 0);

            pci_set_long(pci_dev->config + pos + PCI_EXP_RTSTA, 0);

            /* Device capabilities/control 2, pass existing read-only copy */

            /* Link control 2, pass existing read-only copy */

        }

    }

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PCIX, 0);

    if (pos) {

        uint16_t cmd;

        uint32_t status;

        /* Only expose the minimum, 8 byte capability */

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_PCIX, pos, 8);

        if (ret < 0) {

            return ret;

        }

        assigned_dev_setup_cap_read(dev, pos, 8);

        /* Command register, clear upper bits, including extended modes */

        cmd = pci_get_word(pci_dev->config + pos + PCI_X_CMD);

        cmd &= (PCI_X_CMD_DPERR_E | PCI_X_CMD_ERO | PCI_X_CMD_MAX_READ |

                PCI_X_CMD_MAX_SPLIT);

        pci_set_word(pci_dev->config + pos + PCI_X_CMD, cmd);

        /* Status register, update with emulated PCI bus location, clear

         * error bits, leave the rest. */

        status = pci_get_long(pci_dev->config + pos + PCI_X_STATUS);

        status &= ~(PCI_X_STATUS_BUS | PCI_X_STATUS_DEVFN);

        status |= (pci_bus_num(pci_dev->bus) << 8) | pci_dev->devfn;

        status &= ~(PCI_X_STATUS_SPL_DISC | PCI_X_STATUS_UNX_SPL |

                    PCI_X_STATUS_SPL_ERR);

        pci_set_long(pci_dev->config + pos + PCI_X_STATUS, status);

    }

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VPD, 0);

    if (pos) {

        /* Direct R/W passthrough */

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_VPD, pos, 8);

        if (ret < 0) {

            return ret;

        }

        assigned_dev_setup_cap_read(dev, pos, 8);

        /* direct write for cap content */

        assigned_dev_direct_config_write(dev, pos + 2, 6);

    }

    /* Devices can have multiple vendor capabilities, get them all */

    for (pos = 0; (pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VNDR, pos));

        pos += PCI_CAP_LIST_NEXT) {

        uint8_t len = pci_get_byte(pci_dev->config + pos + PCI_CAP_FLAGS);

        /* Direct R/W passthrough */

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_VNDR, pos, len);

        if (ret < 0) {

            return ret;

        }

        assigned_dev_setup_cap_read(dev, pos, len);

        /* direct write for cap content */

        assigned_dev_direct_config_write(dev, pos + 2, len - 2);

    }

    /* If real and virtual capability list status bits differ, virtualize the

     * access. */

    if ((pci_get_word(pci_dev->config + PCI_STATUS) & PCI_STATUS_CAP_LIST) !=

        (assigned_dev_pci_read_byte(pci_dev, PCI_STATUS) &

         PCI_STATUS_CAP_LIST)) {

        dev->emulate_config_read[PCI_STATUS] |= PCI_STATUS_CAP_LIST;

    }

    return 0;

}


static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,

                              uint64_t value)

{

    value &= 0x3fff;

    if (env->cp15.c15_cpar != value) {

        /* Changes cp0 to cp13 behavior, so needs a TB flush.  */

        tb_flush(env);

        env->cp15.c15_cpar = value;

    }

}


static int compensate_volume(AVFilterContext *ctx)

{

    struct SOFAlizerContext *s = ctx->priv;

    float compensate;

    float energy = 0;

    float *ir;

    int m;

    if (s->sofa.ncid) {

        /* find IR at front center position in the SOFA file (IR closest to 0°,0°,1m) */

        struct NCSofa *sofa = &s->sofa;

        m = find_m(s, 0, 0, 1);

        /* get energy of that IR and compensate volume */

        ir = sofa->data_ir + 2 * m * sofa->n_samples;

        if (sofa->n_samples & 31) {

            energy = avpriv_scalarproduct_float_c(ir, ir, sofa->n_samples);

        } else {

            energy = s->fdsp->scalarproduct_float(ir, ir, sofa->n_samples);

        }

        compensate = 256 / (sofa->n_samples * sqrt(energy));

        av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", compensate);

        ir = sofa->data_ir;

        /* apply volume compensation to IRs */

        s->fdsp->vector_fmul_scalar(ir, ir, compensate, sofa->n_samples * sofa->m_dim * 2);

        emms_c();

    }

    return 0;

}


static char *qio_channel_websock_handshake_entry(const char *handshake,

                                                 size_t handshake_len,

                                                 const char *name)

{

    char *begin, *end, *ret = NULL;

    char *line = g_strdup_printf("%s%s: ",

                                 QIO_CHANNEL_WEBSOCK_HANDSHAKE_DELIM,

                                 name);

    begin = g_strstr_len(handshake, handshake_len, line);

    if (begin != NULL) {

        begin += strlen(line);

        end = g_strstr_len(begin, handshake_len - (begin - handshake),

                QIO_CHANNEL_WEBSOCK_HANDSHAKE_DELIM);

        if (end != NULL) {

            ret = g_strndup(begin, end - begin);

        }

    }

    g_free(line);

    return ret;

}


static void machvirt_init(MachineState *machine)

{

    VirtMachineState *vms = VIRT_MACHINE(machine);

    VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(machine);

    qemu_irq pic[NUM_IRQS];

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *secure_sysmem = NULL;

    int n, virt_max_cpus;

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    const char *cpu_model = machine->cpu_model;

    char **cpustr;

    ObjectClass *oc;

    const char *typename;

    CPUClass *cc;

    Error *err = NULL;

    bool firmware_loaded = bios_name || drive_get(IF_PFLASH, 0, 0);

    uint8_t clustersz;

    if (!cpu_model) {

        cpu_model = "cortex-a15";

    }

    /* We can probe only here because during property set

     * KVM is not available yet

     */

    if (!vms->gic_version) {

        if (!kvm_enabled()) {

            error_report("gic-version=host requires KVM");

            exit(1);

        }

        vms->gic_version = kvm_arm_vgic_probe();

        if (!vms->gic_version) {

            error_report("Unable to determine GIC version supported by host");

            exit(1);

        }

    }

    /* Separate the actual CPU model name from any appended features */

    cpustr = g_strsplit(cpu_model, ",", 2);

    if (!cpuname_valid(cpustr[0])) {

        error_report("mach-virt: CPU %s not supported", cpustr[0]);

        exit(1);

    }

    /* If we have an EL3 boot ROM then the assumption is that it will

     * implement PSCI itself, so disable QEMU's internal implementation

     * so it doesn't get in the way. Instead of starting secondary

     * CPUs in PSCI powerdown state we will start them all running and

     * let the boot ROM sort them out.

     * The usual case is that we do use QEMU's PSCI implementation;

     * if the guest has EL2 then we will use SMC as the conduit,

     * and otherwise we will use HVC (for backwards compatibility and

     * because if we're using KVM then we must use HVC).

     */

    if (vms->secure && firmware_loaded) {

        vms->psci_conduit = QEMU_PSCI_CONDUIT_DISABLED;

    } else if (vms->virt) {

        vms->psci_conduit = QEMU_PSCI_CONDUIT_SMC;

    } else {

        vms->psci_conduit = QEMU_PSCI_CONDUIT_HVC;

    }

    /* The maximum number of CPUs depends on the GIC version, or on how

     * many redistributors we can fit into the memory map.

     */

    if (vms->gic_version == 3) {

        virt_max_cpus = vms->memmap[VIRT_GIC_REDIST].size / 0x20000;

        clustersz = GICV3_TARGETLIST_BITS;

    } else {

        virt_max_cpus = GIC_NCPU;

        clustersz = GIC_TARGETLIST_BITS;

    }

    if (max_cpus > virt_max_cpus) {

        error_report("Number of SMP CPUs requested (%d) exceeds max CPUs "

                     "supported by machine 'mach-virt' (%d)",

                     max_cpus, virt_max_cpus);

        exit(1);

    }

    vms->smp_cpus = smp_cpus;

    if (machine->ram_size > vms->memmap[VIRT_MEM].size) {

        error_report("mach-virt: cannot model more than %dGB RAM", RAMLIMIT_GB);

        exit(1);

    }

    if (vms->virt && kvm_enabled()) {

        error_report("mach-virt: KVM does not support providing "

                     "Virtualization extensions to the guest CPU");

        exit(1);

    }

    if (vms->secure) {

        if (kvm_enabled()) {

            error_report("mach-virt: KVM does not support Security extensions");

            exit(1);

        }

        /* The Secure view of the world is the same as the NonSecure,

         * but with a few extra devices. Create it as a container region

         * containing the system memory at low priority; any secure-only

         * devices go in at higher priority and take precedence.

         */

        secure_sysmem = g_new(MemoryRegion, 1);

        memory_region_init(secure_sysmem, OBJECT(machine), "secure-memory",

                           UINT64_MAX);

        memory_region_add_subregion_overlap(secure_sysmem, 0, sysmem, -1);

    }

    create_fdt(vms);

    oc = cpu_class_by_name(TYPE_ARM_CPU, cpustr[0]);

    if (!oc) {

        error_report("Unable to find CPU definition");

        exit(1);

    }

    typename = object_class_get_name(oc);

    /* convert -smp CPU options specified by the user into global props */

    cc = CPU_CLASS(oc);

    cc->parse_features(typename, cpustr[1], &err);

    g_strfreev(cpustr);

    if (err) {

        error_report_err(err);

        exit(1);

    }

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

        Object *cpuobj = object_new(typename);

        if (!vmc->disallow_affinity_adjustment) {

            /* Adjust MPIDR like 64-bit KVM hosts, which incorporate the

             * GIC's target-list limitations. 32-bit KVM hosts currently

             * always create clusters of 4 CPUs, but that is expected to

             * change when they gain support for gicv3. When KVM is enabled

             * it will override the changes we make here, therefore our

             * purposes are to make TCG consistent (with 64-bit KVM hosts)

             * and to improve SGI efficiency.

             */

            uint8_t aff1 = n / clustersz;

            uint8_t aff0 = n % clustersz;

            object_property_set_int(cpuobj, (aff1 << ARM_AFF1_SHIFT) | aff0,

                                    "mp-affinity", NULL);

        }

        if (!vms->secure) {

            object_property_set_bool(cpuobj, false, "has_el3", NULL);

        }

        if (!vms->virt && object_property_find(cpuobj, "has_el2", NULL)) {

            object_property_set_bool(cpuobj, false, "has_el2", NULL);

        }

        if (vms->psci_conduit != QEMU_PSCI_CONDUIT_DISABLED) {

            object_property_set_int(cpuobj, vms->psci_conduit,

                                    "psci-conduit", NULL);

            /* Secondary CPUs start in PSCI powered-down state */

            if (n > 0) {

                object_property_set_bool(cpuobj, true,

                                         "start-powered-off", NULL);

            }

        }

        if (vmc->no_pmu && object_property_find(cpuobj, "pmu", NULL)) {

            object_property_set_bool(cpuobj, false, "pmu", NULL);

        }

        if (object_property_find(cpuobj, "reset-cbar", NULL)) {

            object_property_set_int(cpuobj, vms->memmap[VIRT_CPUPERIPHS].base,

                                    "reset-cbar", &error_abort);

        }

        object_property_set_link(cpuobj, OBJECT(sysmem), "memory",

                                 &error_abort);

        if (vms->secure) {

            object_property_set_link(cpuobj, OBJECT(secure_sysmem),

                                     "secure-memory", &error_abort);

        }

        object_property_set_bool(cpuobj, true, "realized", NULL);

    }

    fdt_add_timer_nodes(vms);

    fdt_add_cpu_nodes(vms);

    fdt_add_psci_node(vms);

    memory_region_allocate_system_memory(ram, NULL, "mach-virt.ram",

                                         machine->ram_size);

    memory_region_add_subregion(sysmem, vms->memmap[VIRT_MEM].base, ram);

    create_flash(vms, sysmem, secure_sysmem ? secure_sysmem : sysmem);

    create_gic(vms, pic);

    fdt_add_pmu_nodes(vms);

    create_uart(vms, pic, VIRT_UART, sysmem, serial_hds[0]);

    if (vms->secure) {

        create_secure_ram(vms, secure_sysmem);

        create_uart(vms, pic, VIRT_SECURE_UART, secure_sysmem, serial_hds[1]);

    }

    create_rtc(vms, pic);

    create_pcie(vms, pic);

    create_gpio(vms, pic);

    /* Create mmio transports, so the user can create virtio backends

     * (which will be automatically plugged in to the transports). If

     * no backend is created the transport will just sit harmlessly idle.

     */

    create_virtio_devices(vms, pic);

    vms->fw_cfg = create_fw_cfg(vms, &address_space_memory);

    rom_set_fw(vms->fw_cfg);

    vms->machine_done.notify = virt_machine_done;

    qemu_add_machine_init_done_notifier(&vms->machine_done);

    vms->bootinfo.ram_size = machine->ram_size;

    vms->bootinfo.kernel_filename = machine->kernel_filename;

    vms->bootinfo.kernel_cmdline = machine->kernel_cmdline;

    vms->bootinfo.initrd_filename = machine->initrd_filename;

    vms->bootinfo.nb_cpus = smp_cpus;

    vms->bootinfo.board_id = -1;

    vms->bootinfo.loader_start = vms->memmap[VIRT_MEM].base;

    vms->bootinfo.get_dtb = machvirt_dtb;

    vms->bootinfo.firmware_loaded = firmware_loaded;

    arm_load_kernel(ARM_CPU(first_cpu), &vms->bootinfo);

    /*

     * arm_load_kernel machine init done notifier registration must

     * happen before the platform_bus_create call. In this latter,

     * another notifier is registered which adds platform bus nodes.

     * Notifiers are executed in registration reverse order.

     */

    create_platform_bus(vms, pic);

}


static int check_refcounts_l2(BlockDriverState *bs, BdrvCheckResult *res,

    uint16_t *refcount_table, int64_t refcount_table_size, int64_t l2_offset,

    int flags)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t *l2_table, l2_entry;

    uint64_t next_contiguous_offset = 0;

    int i, l2_size, nb_csectors;

    /* Read L2 table from disk */

    l2_size = s->l2_size * sizeof(uint64_t);

    l2_table = g_malloc(l2_size);

    if (bdrv_pread(bs->file, l2_offset, l2_table, l2_size) != l2_size)

        goto fail;

    /* Do the actual checks */

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

        l2_entry = be64_to_cpu(l2_table[i]);

        switch (qcow2_get_cluster_type(l2_entry)) {

        case QCOW2_CLUSTER_COMPRESSED:

            /* Compressed clusters don't have QCOW_OFLAG_COPIED */

            if (l2_entry & QCOW_OFLAG_COPIED) {

                fprintf(stderr, "ERROR: cluster %" PRId64 ": "

                    "copied flag must never be set for compressed "

                    "clusters\n", l2_entry >> s->cluster_bits);

                l2_entry &= ~QCOW_OFLAG_COPIED;

                res->corruptions++;

            }

            /* Mark cluster as used */

            nb_csectors = ((l2_entry >> s->csize_shift) &

                           s->csize_mask) + 1;

            l2_entry &= s->cluster_offset_mask;

            inc_refcounts(bs, res, refcount_table, refcount_table_size,

                l2_entry & ~511, nb_csectors * 512);

            if (flags & CHECK_FRAG_INFO) {

                res->bfi.allocated_clusters++;

                res->bfi.compressed_clusters++;

                /* Compressed clusters are fragmented by nature.  Since they

                 * take up sub-sector space but we only have sector granularity

                 * I/O we need to re-read the same sectors even for adjacent

                 * compressed clusters.

                 */

                res->bfi.fragmented_clusters++;

            }

            break;

        case QCOW2_CLUSTER_ZERO:

            if ((l2_entry & L2E_OFFSET_MASK) == 0) {

                break;

            }

            /* fall through */

        case QCOW2_CLUSTER_NORMAL:

        {

            uint64_t offset = l2_entry & L2E_OFFSET_MASK;

            if (flags & CHECK_FRAG_INFO) {

                res->bfi.allocated_clusters++;

                if (next_contiguous_offset &&

                    offset != next_contiguous_offset) {

                    res->bfi.fragmented_clusters++;

                }

                next_contiguous_offset = offset + s->cluster_size;

            }

            /* Mark cluster as used */

            inc_refcounts(bs, res, refcount_table,refcount_table_size,

                offset, s->cluster_size);

            /* Correct offsets are cluster aligned */

            if (offset_into_cluster(s, offset)) {

                fprintf(stderr, "ERROR offset=%" PRIx64 ": Cluster is not "

                    "properly aligned; L2 entry corrupted.\n", offset);

                res->corruptions++;

            }

            break;

        }

        case QCOW2_CLUSTER_UNALLOCATED:

            break;

        default:

            abort();

        }

    }

    g_free(l2_table);

    return 0;

fail:

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

    g_free(l2_table);

    return -EIO;

}


static int get_delayed_pic(DiracContext *s, AVFrame *picture, int *got_frame)

{

    DiracFrame *out = s->delay_frames[0];

    int i, out_idx  = 0;

    int ret;

    /* find frame with lowest picture number */

    for (i = 1; s->delay_frames[i]; i++)

        if (s->delay_frames[i]->avframe->display_picture_number < out->avframe->display_picture_number) {

            out     = s->delay_frames[i];

            out_idx = i;

        }

    for (i = out_idx; s->delay_frames[i]; i++)

        s->delay_frames[i] = s->delay_frames[i+1];

    if (out) {

        out->reference ^= DELAYED_PIC_REF;

        *got_frame = 1;

        if((ret = av_frame_ref(picture, out->avframe)) < 0)

            return ret;

    }

    return 0;

}


static void do_subtitle_out(AVFormatContext *s,

                            OutputStream *ost,

                            InputStream *ist,

                            AVSubtitle *sub)

{

    int subtitle_out_max_size = 1024 * 1024;

    int subtitle_out_size, nb, i;

    AVCodecContext *enc;

    AVPacket pkt;

    int64_t pts;

    if (sub->pts == AV_NOPTS_VALUE) {

        av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");

        if (exit_on_error)

            exit_program(1);

        return;

    }

    enc = ost->enc_ctx;

    if (!subtitle_out) {

        subtitle_out = av_malloc(subtitle_out_max_size);

        if (!subtitle_out) {

            av_log(NULL, AV_LOG_FATAL, "Failed to allocate subtitle_out\n");

            exit_program(1);

        }

    }

    /* Note: DVB subtitle need one packet to draw them and one other

       packet to clear them */

    /* XXX: signal it in the codec context ? */

    if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)

        nb = 2;

    else

        nb = 1;

    /* shift timestamp to honor -ss and make check_recording_time() work with -t */

    pts = sub->pts;

    if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)

        pts -= output_files[ost->file_index]->start_time;

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

        unsigned save_num_rects = sub->num_rects;

        ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);

        if (!check_recording_time(ost))

            return;

        sub->pts = pts;

        // start_display_time is required to be 0

        sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);

        sub->end_display_time  -= sub->start_display_time;

        sub->start_display_time = 0;

        if (i == 1)

            sub->num_rects = 0;

        ost->frames_encoded++;

        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,

                                                    subtitle_out_max_size, sub);

        if (i == 1)

            sub->num_rects = save_num_rects;

        if (subtitle_out_size < 0) {

            av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");

            exit_program(1);

        }

        av_init_packet(&pkt);

        pkt.data = subtitle_out;

        pkt.size = subtitle_out_size;

        pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);

        pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);

        if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {

            /* XXX: the pts correction is handled here. Maybe handling

               it in the codec would be better */

            if (i == 0)

                pkt.pts += 90 * sub->start_display_time;

            else

                pkt.pts += 90 * sub->end_display_time;

        }

        pkt.dts = pkt.pts;

        write_frame(s, &pkt, ost);

    }

}


static int bdrv_has_snapshot(BlockDriverState *bs)

{

    return (bs &&

            !bdrv_is_removable(bs) &&

            !bdrv_is_read_only(bs));

}


static void dec_ill(DisasContext *dc)

{

    cpu_abort(dc->env, "unknown opcode 0x%02x\n", dc->opcode);

}


static int vhdx_create_new_headers(BlockDriverState *bs, uint64_t image_size,

                                   uint32_t log_size)

{

    int ret = 0;

    VHDXHeader *hdr = NULL;

    hdr = g_malloc0(sizeof(VHDXHeader));

    hdr->signature       = VHDX_HEADER_SIGNATURE;

    hdr->sequence_number = g_random_int();

    hdr->log_version     = 0;

    hdr->version         = 1;

    hdr->log_length      = log_size;

    hdr->log_offset      = VHDX_HEADER_SECTION_END;

    vhdx_guid_generate(&hdr->file_write_guid);

    vhdx_guid_generate(&hdr->data_write_guid);

    ret = vhdx_write_header(bs, hdr, VHDX_HEADER1_OFFSET, false);

    if (ret < 0) {

        goto exit;

    }

    hdr->sequence_number++;

    ret = vhdx_write_header(bs, hdr, VHDX_HEADER2_OFFSET, false);

    if (ret < 0) {

        goto exit;

    }

exit:

    g_free(hdr);

    return ret;

}


void checkasm_check_h264qpel(void)

{

    LOCAL_ALIGNED_16(uint8_t, buf0, [BUF_SIZE]);

    LOCAL_ALIGNED_16(uint8_t, buf1, [BUF_SIZE]);

    LOCAL_ALIGNED_16(uint8_t, dst0, [BUF_SIZE]);

    LOCAL_ALIGNED_16(uint8_t, dst1, [BUF_SIZE]);

    H264QpelContext h;

    int op, bit_depth, i, j;

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

        qpel_mc_func (*tab)[16] = op ? h.avg_h264_qpel_pixels_tab : h.put_h264_qpel_pixels_tab;

        const char *op_name = op ? "avg" : "put";

        for (bit_depth = 8; bit_depth <= 10; bit_depth++) {

            ff_h264qpel_init(&h, bit_depth);

            for (i = 0; i < (op ? 3 : 4); i++) {

                int size = 16 >> i;

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

                    if (check_func(tab[i][j], "%s_h264_qpel_%d_mc%d%d_%d", op_name, size, j & 3, j >> 2, bit_depth)) {

                        randomize_buffers();

                        call_ref(dst0, src0, (ptrdiff_t)size * SIZEOF_PIXEL);

                        call_new(dst1, src1, (ptrdiff_t)size * SIZEOF_PIXEL);

                        if (memcmp(buf0, buf1, BUF_SIZE) || memcmp(dst0, dst1, BUF_SIZE))

                            fail();

                        bench_new(dst1, src1, (ptrdiff_t)size * SIZEOF_PIXEL);

                    }

            }

        }

        report("%s", op_name);

    }

}


static int wma_decode_init(AVCodecContext * avctx)

{

    WMADecodeContext *s = avctx->priv_data;

    int i, flags1, flags2;

    float *window;

    uint8_t *extradata;

    float bps1, high_freq, bps;

    int sample_rate1;

    int coef_vlc_table;

    s->sample_rate = avctx->sample_rate;

    s->nb_channels = avctx->channels;

    s->bit_rate = avctx->bit_rate;

    s->block_align = avctx->block_align;

    if (avctx->codec_id == CODEC_ID_WMAV1) {

        s->version = 1;

    } else {

        s->version = 2;

    }

    /* extract flag infos */

    flags1 = 0;

    flags2 = 0;

    extradata = avctx->extradata;

    if (s->version == 1 && avctx->extradata_size >= 4) {

        flags1 = extradata[0] | (extradata[1] << 8);

        flags2 = extradata[2] | (extradata[3] << 8);

    } else if (s->version == 2 && avctx->extradata_size >= 6) {

        flags1 = extradata[0] | (extradata[1] << 8) |

            (extradata[2] << 16) | (extradata[3] << 24);

        flags2 = extradata[4] | (extradata[5] << 8);

    }

    s->use_exp_vlc = flags2 & 0x0001;

    s->use_bit_reservoir = flags2 & 0x0002;

    s->use_variable_block_len = flags2 & 0x0004;

    /* compute MDCT block size */

    if (s->sample_rate <= 16000) {

        s->frame_len_bits = 9;

    } else if (s->sample_rate <= 22050 ||

               (s->sample_rate <= 32000 && s->version == 1)) {

        s->frame_len_bits = 10;

    } else {

        s->frame_len_bits = 11;

    }

    s->frame_len = 1 << s->frame_len_bits;

    if (s->use_variable_block_len) {

        s->nb_block_sizes = s->frame_len_bits - BLOCK_MIN_BITS + 1;

    } else {

        s->nb_block_sizes = 1;

    }

    /* init rate dependant parameters */

    s->use_noise_coding = 1;

    high_freq = s->sample_rate * 0.5;

    /* if version 2, then the rates are normalized */

    sample_rate1 = s->sample_rate;

    if (s->version == 2) {

        if (sample_rate1 >= 44100)

            sample_rate1 = 44100;

        else if (sample_rate1 >= 22050)

            sample_rate1 = 22050;

        else if (sample_rate1 >= 16000)

            sample_rate1 = 16000;

        else if (sample_rate1 >= 11025)

            sample_rate1 = 11025;

        else if (sample_rate1 >= 8000)

            sample_rate1 = 8000;

    }

    bps = (float)s->bit_rate / (float)(s->nb_channels * s->sample_rate);

    s->byte_offset_bits = av_log2((int)(bps * s->frame_len / 8.0)) + 2;

    /* compute high frequency value and choose if noise coding should

       be activated */

    bps1 = bps;

    if (s->nb_channels == 2)

        bps1 = bps * 1.6;

    if (sample_rate1 == 44100) {

        if (bps1 >= 0.61)

            s->use_noise_coding = 0;

        else

            high_freq = high_freq * 0.4;

    } else if (sample_rate1 == 22050) {

        if (bps1 >= 1.16)

            s->use_noise_coding = 0;

        else if (bps1 >= 0.72)

            high_freq = high_freq * 0.7;

        else

            high_freq = high_freq * 0.6;

    } else if (sample_rate1 == 16000) {

        if (bps > 0.5)

            high_freq = high_freq * 0.5;

        else

            high_freq = high_freq * 0.3;

    } else if (sample_rate1 == 11025) {

        high_freq = high_freq * 0.7;

    } else if (sample_rate1 == 8000) {

        if (bps <= 0.625) {

            high_freq = high_freq * 0.5;

        } else if (bps > 0.75) {

            s->use_noise_coding = 0;

        } else {

            high_freq = high_freq * 0.65;

        }

    } else {

        if (bps >= 0.8) {

            high_freq = high_freq * 0.75;

        } else if (bps >= 0.6) {

            high_freq = high_freq * 0.6;

        } else {

            high_freq = high_freq * 0.5;

        }

    }

#ifdef DEBUG_PARAMS

    printf("flags1=0x%x flags2=0x%x\n", flags1, flags2);

    printf("version=%d channels=%d sample_rate=%d bitrate=%d block_align=%d\n",

           s->version, s->nb_channels, s->sample_rate, s->bit_rate,

           s->block_align);

    printf("bps=%f bps1=%f high_freq=%f bitoffset=%d\n",

           bps, bps1, high_freq, s->byte_offset_bits);

    printf("use_noise_coding=%d use_exp_vlc=%d\n",

           s->use_noise_coding, s->use_exp_vlc);

#endif

    /* compute the scale factor band sizes for each MDCT block size */

    {

        int a, b, pos, lpos, k, block_len, i, j, n;

        const uint8_t *table;

        if (s->version == 1) {

            s->coefs_start = 3;

        } else {

            s->coefs_start = 0;

        }

        for(k = 0; k < s->nb_block_sizes; k++) {

            block_len = s->frame_len >> k;

            if (s->version == 1) {

                lpos = 0;

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

                    a = wma_critical_freqs[i];

                    b = s->sample_rate;

                    pos = ((block_len * 2 * a)  + (b >> 1)) / b;

                    if (pos > block_len)

                        pos = block_len;

                    s->exponent_bands[0][i] = pos - lpos;

                    if (pos >= block_len) {

                        i++;

                        break;

                    }

                    lpos = pos;

                }

                s->exponent_sizes[0] = i;

            } else {

                /* hardcoded tables */

                table = NULL;

                a = s->frame_len_bits - BLOCK_MIN_BITS - k;

                if (a < 3) {

                    if (s->sample_rate >= 44100)

                        table = exponent_band_44100[a];

                    else if (s->sample_rate >= 32000)

                        table = exponent_band_32000[a];

                    else if (s->sample_rate >= 22050)

                        table = exponent_band_22050[a];

                }

                if (table) {

                    n = *table++;

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

                        s->exponent_bands[k][i] = table[i];

                    s->exponent_sizes[k] = n;

                } else {

                    j = 0;

                    lpos = 0;

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

                        a = wma_critical_freqs[i];

                        b = s->sample_rate;

                        pos = ((block_len * 2 * a)  + (b << 1)) / (4 * b);

                        pos <<= 2;

                        if (pos > block_len)

                            pos = block_len;

                        if (pos > lpos)

                            s->exponent_bands[k][j++] = pos - lpos;

                        if (pos >= block_len)

                            break;

                        lpos = pos;

                    }

                    s->exponent_sizes[k] = j;

                }

            }

            /* max number of coefs */

            s->coefs_end[k] = (s->frame_len - ((s->frame_len * 9) / 100)) >> k;

            /* high freq computation */

            s->high_band_start[k] = (int)((block_len * 2 * high_freq) /

                                          s->sample_rate + 0.5);

            n = s->exponent_sizes[k];

            j = 0;

            pos = 0;

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

                int start, end;

                start = pos;

                pos += s->exponent_bands[k][i];

                end = pos;

                if (start < s->high_band_start[k])

                    start = s->high_band_start[k];

                if (end > s->coefs_end[k])

                    end = s->coefs_end[k];

                if (end > start)

                    s->exponent_high_bands[k][j++] = end - start;

            }

            s->exponent_high_sizes[k] = j;

#if 0

            trace("%5d: coefs_end=%d high_band_start=%d nb_high_bands=%d: ",

                  s->frame_len >> k,

                  s->coefs_end[k],

                  s->high_band_start[k],

                  s->exponent_high_sizes[k]);

            for(j=0;j<s->exponent_high_sizes[k];j++)

                trace(" %d", s->exponent_high_bands[k][j]);

            trace("\n");

#endif

        }

    }

#ifdef DEBUG_TRACE

    {

        int i, j;

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

            trace("%5d: n=%2d:",

                   s->frame_len >> i,

                   s->exponent_sizes[i]);

            for(j=0;j<s->exponent_sizes[i];j++)

                trace(" %d", s->exponent_bands[i][j]);

            trace("\n");

        }

    }

#endif

    /* init MDCT */

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

        ff_mdct_init(&s->mdct_ctx[i], s->frame_len_bits - i + 1, 1);

    /* init MDCT windows : simple sinus window */

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

        int n, j;

        float alpha;

        n = 1 << (s->frame_len_bits - i);

        window = av_malloc(sizeof(float) * n);

        alpha = M_PI / (2.0 * n);

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

            window[n - j - 1] = sin((j + 0.5) * alpha);

        }

        s->windows[i] = window;

    }

    s->reset_block_lengths = 1;

    if (s->use_noise_coding) {

        /* init the noise generator */

        if (s->use_exp_vlc)

            s->noise_mult = 0.02;

        else

            s->noise_mult = 0.04;

#if defined(DEBUG_TRACE)

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

            s->noise_table[i] = 1.0 * s->noise_mult;

#else

        {

            unsigned int seed;

            float norm;

            seed = 1;

            norm = (1.0 / (float)(1LL << 31)) * sqrt(3) * s->noise_mult;

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

                seed = seed * 314159 + 1;

                s->noise_table[i] = (float)((int)seed) * norm;

            }

        }

#endif

        init_vlc(&s->hgain_vlc, 9, sizeof(hgain_huffbits),

                 hgain_huffbits, 1, 1,

                 hgain_huffcodes, 2, 2);

    }

    if (s->use_exp_vlc) {

        init_vlc(&s->exp_vlc, 9, sizeof(scale_huffbits),

                 scale_huffbits, 1, 1,

                 scale_huffcodes, 4, 4);

    } else {

        wma_lsp_to_curve_init(s, s->frame_len);

    }

    /* choose the VLC tables for the coefficients */

    coef_vlc_table = 2;

    if (s->sample_rate >= 32000) {

        if (bps1 < 0.72)

            coef_vlc_table = 0;

        else if (bps1 < 1.16)

            coef_vlc_table = 1;

    }

    init_coef_vlc(&s->coef_vlc[0], &s->run_table[0], &s->level_table[0],

                  &coef_vlcs[coef_vlc_table * 2]);

    init_coef_vlc(&s->coef_vlc[1], &s->run_table[1], &s->level_table[1],

                  &coef_vlcs[coef_vlc_table * 2 + 1]);

    return 0;

}


const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len)

{

    const AVOption *o = av_opt_find(obj, name, NULL, 0, 0);

    void *dst;

    uint8_t *bin;

    int len, i;

    if (!o || o->offset<=0)

        return NULL;

    if (o->type != FF_OPT_TYPE_STRING && (!buf || !buf_len))

        return NULL;

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

    if (o_out) *o_out= o;

    switch (o->type) {

    case FF_OPT_TYPE_FLAGS:     snprintf(buf, buf_len, "0x%08X",*(int    *)dst);break;

    case FF_OPT_TYPE_INT:       snprintf(buf, buf_len, "%d" , *(int    *)dst);break;

    case FF_OPT_TYPE_INT64:     snprintf(buf, buf_len, "%"PRId64, *(int64_t*)dst);break;

    case FF_OPT_TYPE_FLOAT:     snprintf(buf, buf_len, "%f" , *(float  *)dst);break;

    case FF_OPT_TYPE_DOUBLE:    snprintf(buf, buf_len, "%f" , *(double *)dst);break;

    case FF_OPT_TYPE_RATIONAL:  snprintf(buf, buf_len, "%d/%d", ((AVRational*)dst)->num, ((AVRational*)dst)->den);break;

    case FF_OPT_TYPE_STRING:    return *(void**)dst;

    case FF_OPT_TYPE_BINARY:

        len = *(int*)(((uint8_t *)dst) + sizeof(uint8_t *));

        if (len >= (buf_len + 1)/2) return NULL;

        bin = *(uint8_t**)dst;

        for (i = 0; i < len; i++) snprintf(buf + i*2, 3, "%02X", bin[i]);

        break;

    default: return NULL;

    }

    return buf;

}


static void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){

    int i;

    memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?

    /* mpeg1 */

    d->mb_incr= s->mb_incr;

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

        d->last_dc[i]= s->last_dc[i];

    /* statistics */

    d->mv_bits= s->mv_bits;

    d->i_tex_bits= s->i_tex_bits;

    d->p_tex_bits= s->p_tex_bits;

    d->i_count= s->i_count;

    d->p_count= s->p_count;

    d->skip_count= s->skip_count;

    d->misc_bits= s->misc_bits;

    d->last_bits= 0;

    d->mb_skiped= s->mb_skiped;

}


static int get_bits(Jpeg2000DecoderContext *s, int n)

{

    int res = 0;

    if (s->buf_end - s->buf < ((n - s->bit_index) >> 8))

        return AVERROR(EINVAL);

    while (--n >= 0) {

        res <<= 1;

        if (s->bit_index == 0) {

            s->bit_index = 7 + (*s->buf != 0xff);

            s->buf++;

        }

        s->bit_index--;

        res |= (*s->buf >> s->bit_index) & 1;

    }

    return res;

}


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

                           int srcSliceY, int srcSliceH, uint8_t *dst[],

                           int dstStride[])

{

    const enum PixelFormat srcFormat = c->srcFormat;

    const enum PixelFormat dstFormat = c->dstFormat;

    const int srcBpp = (c->srcFormatBpp + 7) >> 3;

    const int dstBpp = (c->dstFormatBpp + 7) >> 3;

    const int srcId = c->srcFormatBpp;

    const int dstId = c->dstFormatBpp;

    void (*conv)(const uint8_t *src, uint8_t *dst, int src_size) = NULL;

#define CONV_IS(src, dst) (srcFormat == PIX_FMT_##src && dstFormat == PIX_FMT_##dst)

    if (isRGBA32(srcFormat) && isRGBA32(dstFormat)) {

        if (     CONV_IS(ABGR, RGBA)

              || CONV_IS(ARGB, BGRA)

              || CONV_IS(BGRA, ARGB)

              || CONV_IS(RGBA, ABGR)) conv = shuffle_bytes_3210;

        else if (CONV_IS(ABGR, ARGB)

              || CONV_IS(ARGB, ABGR)) conv = shuffle_bytes_0321;

        else if (CONV_IS(ABGR, BGRA)

              || CONV_IS(ARGB, RGBA)) conv = shuffle_bytes_1230;

        else if (CONV_IS(BGRA, RGBA)

              || CONV_IS(RGBA, BGRA)) conv = shuffle_bytes_2103;

        else if (CONV_IS(BGRA, ABGR)

              || CONV_IS(RGBA, ARGB)) conv = shuffle_bytes_3012;

    } else

    /* BGR -> BGR */

    if ((isBGRinInt(srcFormat) && isBGRinInt(dstFormat)) ||

        (isRGBinInt(srcFormat) && isRGBinInt(dstFormat))) {

        switch (srcId | (dstId << 16)) {

        case 0x000F0010: conv = rgb16to15; break;

        case 0x000F0018: conv = rgb24to15; break;

        case 0x000F0020: conv = rgb32to15; break;

        case 0x0010000F: conv = rgb15to16; break;

        case 0x00100018: conv = rgb24to16; break;

        case 0x00100020: conv = rgb32to16; break;

        case 0x0018000F: conv = rgb15to24; break;

        case 0x00180010: conv = rgb16to24; break;

        case 0x00180020: conv = rgb32to24; break;

        case 0x0020000F: conv = rgb15to32; break;

        case 0x00200010: conv = rgb16to32; break;

        case 0x00200018: conv = rgb24to32; break;

        }

    } else if ((isBGRinInt(srcFormat) && isRGBinInt(dstFormat)) ||

               (isRGBinInt(srcFormat) && isBGRinInt(dstFormat))) {

        switch (srcId | (dstId << 16)) {

        case 0x000C000C: conv = rgb12tobgr12; break;

        case 0x000F000F: conv = rgb15tobgr15; break;

        case 0x000F0010: conv = rgb16tobgr15; break;

        case 0x000F0018: conv = rgb24tobgr15; break;

        case 0x000F0020: conv = rgb32tobgr15; break;

        case 0x0010000F: conv = rgb15tobgr16; break;

        case 0x00100010: conv = rgb16tobgr16; break;

        case 0x00100018: conv = rgb24tobgr16; break;

        case 0x00100020: conv = rgb32tobgr16; break;

        case 0x0018000F: conv = rgb15tobgr24; break;

        case 0x00180010: conv = rgb16tobgr24; break;

        case 0x00180018: conv = rgb24tobgr24; break;

        case 0x00180020: conv = rgb32tobgr24; break;

        case 0x0020000F: conv = rgb15tobgr32; break;

        case 0x00200010: conv = rgb16tobgr32; break;

        case 0x00200018: conv = rgb24tobgr32; break;

        }

    }

    if (!conv) {

        av_log(c, AV_LOG_ERROR, "internal error %s -> %s converter\n",

               sws_format_name(srcFormat), sws_format_name(dstFormat));

    } else {

        const uint8_t *srcPtr = src[0];

              uint8_t *dstPtr = dst[0];

        if ((srcFormat == PIX_FMT_RGB32_1 || srcFormat == PIX_FMT_BGR32_1) &&

            !isRGBA32(dstFormat))

            srcPtr += ALT32_CORR;

        if ((dstFormat == PIX_FMT_RGB32_1 || dstFormat == PIX_FMT_BGR32_1) &&

            !isRGBA32(srcFormat))

            dstPtr += ALT32_CORR;

        if (dstStride[0] * srcBpp == srcStride[0] * dstBpp && srcStride[0] > 0 &&

            !(srcStride[0] % srcBpp))

            conv(srcPtr, dstPtr + dstStride[0] * srcSliceY,

                 srcSliceH * srcStride[0]);

        else {

            int i;

            dstPtr += dstStride[0] * srcSliceY;

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

                conv(srcPtr, dstPtr, c->srcW * srcBpp);

                srcPtr += srcStride[0];

                dstPtr += dstStride[0];

            }

        }

    }

    return srcSliceH;

}


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

{

    const char *rn = "invalid";

    if (sel != 0)

        check_insn(ctx, ISA_MIPS64);

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

        gen_io_start();

    }

    switch (reg) {

    case 0:

        switch (sel) {

        case 0:

            gen_helper_mtc0_index(cpu_env, arg);

            rn = "Index";

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_mvpcontrol(cpu_env, arg);

            rn = "MVPControl";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            /* ignored */

            rn = "MVPConf0";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            /* ignored */

            rn = "MVPConf1";

            CP0_CHECK(ctx->vp);

            /* ignored */

            rn = "VPControl";

        default:

            goto cp0_unimplemented;

        }

    case 1:

        switch (sel) {

        case 0:

            /* ignored */

            rn = "Random";

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpecontrol(cpu_env, arg);

            rn = "VPEControl";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpeconf0(cpu_env, arg);

            rn = "VPEConf0";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpeconf1(cpu_env, arg);

            rn = "VPEConf1";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_yqmask(cpu_env, arg);

            rn = "YQMask";

        case 5:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

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

            rn = "VPESchedule";

        case 6:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

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

            rn = "VPEScheFBack";

        case 7:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpeopt(cpu_env, arg);

            rn = "VPEOpt";

        default:

            goto cp0_unimplemented;

        }

        switch (sel) {

        case 0:

            gen_helper_dmtc0_entrylo0(cpu_env, arg);

            rn = "EntryLo0";

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcstatus(cpu_env, arg);

            rn = "TCStatus";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcbind(cpu_env, arg);

            rn = "TCBind";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcrestart(cpu_env, arg);

            rn = "TCRestart";

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tchalt(cpu_env, arg);

            rn = "TCHalt";

        case 5:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tccontext(cpu_env, arg);

            rn = "TCContext";

        case 6:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcschedule(cpu_env, arg);

            rn = "TCSchedule";

        case 7:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcschefback(cpu_env, arg);

            rn = "TCScheFBack";

        default:

            goto cp0_unimplemented;

        }

        switch (sel) {

        case 0:

            gen_helper_dmtc0_entrylo1(cpu_env, arg);

            rn = "EntryLo1";

        case 1:

            CP0_CHECK(ctx->vp);

            /* ignored */

            rn = "GlobalNumber";

        default:

            goto cp0_unimplemented;

        }

        switch (sel) {

        case 0:

            gen_helper_mtc0_context(cpu_env, arg);

            rn = "Context";

        case 1:

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

            rn = "ContextConfig";

            goto cp0_unimplemented;

            CP0_CHECK(ctx->ulri);

            tcg_gen_st_tl(arg, cpu_env,

                          offsetof(CPUMIPSState, active_tc.CP0_UserLocal));

            rn = "UserLocal";

        default:

            goto cp0_unimplemented;

        }

    case 5:

        switch (sel) {

        case 0:

            gen_helper_mtc0_pagemask(cpu_env, arg);

            rn = "PageMask";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_pagegrain(cpu_env, arg);

            rn = "PageGrain";

        default:

            goto cp0_unimplemented;

        }

    case 6:

        switch (sel) {

        case 0:

            gen_helper_mtc0_wired(cpu_env, arg);

            rn = "Wired";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf0(cpu_env, arg);

            rn = "SRSConf0";

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf1(cpu_env, arg);

            rn = "SRSConf1";

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf2(cpu_env, arg);

            rn = "SRSConf2";

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf3(cpu_env, arg);

            rn = "SRSConf3";

        case 5:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf4(cpu_env, arg);

            rn = "SRSConf4";

        default:

            goto cp0_unimplemented;

        }

    case 7:

        switch (sel) {

        case 0:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_hwrena(cpu_env, arg);

            ctx->bstate = BS_STOP;

            rn = "HWREna";

        default:

            goto cp0_unimplemented;

        }

    case 8:

        switch (sel) {

        case 0:

            /* ignored */

            rn = "BadVAddr";

        case 1:

            /* ignored */

            rn = "BadInstr";

            /* ignored */

            rn = "BadInstrP";

        default:

            goto cp0_unimplemented;

        }

    case 9:

        switch (sel) {

        case 0:

            gen_helper_mtc0_count(cpu_env, arg);

            rn = "Count";

        /* 6,7 are implementation dependent */

        default:

            goto cp0_unimplemented;

        }

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

        ctx->bstate = BS_STOP;

    case 10:

        switch (sel) {

        case 0:

            gen_helper_mtc0_entryhi(cpu_env, arg);

            rn = "EntryHi";

        default:

            goto cp0_unimplemented;

        }

    case 11:

        switch (sel) {

        case 0:

            gen_helper_mtc0_compare(cpu_env, arg);

            rn = "Compare";

        /* 6,7 are implementation dependent */

        default:

            goto cp0_unimplemented;

        }

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

        ctx->bstate = BS_STOP;

    case 12:

        switch (sel) {

        case 0:

            save_cpu_state(ctx, 1);

            gen_helper_mtc0_status(cpu_env, arg);

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

            gen_save_pc(ctx->pc + 4);

            ctx->bstate = BS_EXCP;

            rn = "Status";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_intctl(cpu_env, arg);

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

            ctx->bstate = BS_STOP;

            rn = "IntCtl";

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsctl(cpu_env, arg);

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

            ctx->bstate = BS_STOP;

            rn = "SRSCtl";

            check_insn(ctx, ISA_MIPS32R2);

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

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

            ctx->bstate = BS_STOP;

            rn = "SRSMap";

        default:

            goto cp0_unimplemented;

        }

    case 13:

        switch (sel) {

        case 0:

            save_cpu_state(ctx, 1);

            /* Mark as an IO operation because we may trigger a software

               interrupt.  */

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

                gen_io_start();

            }

            gen_helper_mtc0_cause(cpu_env, arg);

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

                gen_io_end();

            }

            /* Stop translation as we may have triggered an intetrupt */

            ctx->bstate = BS_STOP;

            rn = "Cause";

        default:

            goto cp0_unimplemented;

        }

    case 14:

        switch (sel) {

        case 0:

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

            rn = "EPC";

        default:

            goto cp0_unimplemented;

        }

    case 15:

        switch (sel) {

        case 0:

            /* ignored */

            rn = "PRid";

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_ebase(cpu_env, arg);

            rn = "EBase";

        default:

            goto cp0_unimplemented;

        }

    case 16:

        switch (sel) {

        case 0:

            gen_helper_mtc0_config0(cpu_env, arg);

            rn = "Config";

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

            ctx->bstate = BS_STOP;

        case 1:

            /* ignored, read only */

            rn = "Config1";

            gen_helper_mtc0_config2(cpu_env, arg);

            rn = "Config2";

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

            ctx->bstate = BS_STOP;

            gen_helper_mtc0_config3(cpu_env, arg);

            rn = "Config3";

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

            ctx->bstate = BS_STOP;

            /* currently ignored */

            rn = "Config4";

        case 5:

            gen_helper_mtc0_config5(cpu_env, arg);

            rn = "Config5";

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

            ctx->bstate = BS_STOP;

        /* 6,7 are implementation dependent */

        default:

            rn = "Invalid config selector";

            goto cp0_unimplemented;

        }

    case 17:

        switch (sel) {

        case 0:

            gen_helper_mtc0_lladdr(cpu_env, arg);

            rn = "LLAddr";

        case 1:

            CP0_CHECK(ctx->mrp);

            gen_helper_mtc0_maar(cpu_env, arg);

            rn = "MAAR";

            CP0_CHECK(ctx->mrp);

            gen_helper_mtc0_maari(cpu_env, arg);

            rn = "MAARI";

        default:

            goto cp0_unimplemented;

        }

    case 18:

        switch (sel) {

        case 0 ... 7:

            gen_helper_0e1i(mtc0_watchlo, arg, sel);

            rn = "WatchLo";

        default:

            goto cp0_unimplemented;

        }

    case 19:

        switch (sel) {

        case 0 ... 7:

            gen_helper_0e1i(mtc0_watchhi, arg, sel);

            rn = "WatchHi";

        default:

            goto cp0_unimplemented;

        }

    case 20:

        switch (sel) {

        case 0:

            check_insn(ctx, ISA_MIPS3);

            gen_helper_mtc0_xcontext(cpu_env, arg);

            rn = "XContext";

        default:

            goto cp0_unimplemented;

        }

    case 21:

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

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

        switch (sel) {

        case 0:

            gen_helper_mtc0_framemask(cpu_env, arg);

            rn = "Framemask";

        default:

            goto cp0_unimplemented;

        }

    case 22:

        /* ignored */

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

    case 23:

        switch (sel) {

        case 0:

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

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

            gen_save_pc(ctx->pc + 4);

            ctx->bstate = BS_EXCP;

            rn = "Debug";

        case 1:

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

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

            ctx->bstate = BS_STOP;

            rn = "TraceControl";

            goto cp0_unimplemented;

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

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

            ctx->bstate = BS_STOP;

            rn = "TraceControl2";

            goto cp0_unimplemented;

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

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

            ctx->bstate = BS_STOP;

            rn = "UserTraceData";

            goto cp0_unimplemented;

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

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

            ctx->bstate = BS_STOP;

            rn = "TraceBPC";

            goto cp0_unimplemented;

        default:

            goto cp0_unimplemented;

        }

    case 24:

        switch (sel) {

        case 0:

            /* EJTAG support */

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

            rn = "DEPC";

        default:

            goto cp0_unimplemented;

        }

    case 25:

        switch (sel) {

        case 0:

            gen_helper_mtc0_performance0(cpu_env, arg);

            rn = "Performance0";

        case 1:

//            gen_helper_mtc0_performance1(cpu_env, arg);

            rn = "Performance1";

            goto cp0_unimplemented;

//            gen_helper_mtc0_performance2(cpu_env, arg);

            rn = "Performance2";

            goto cp0_unimplemented;

//            gen_helper_mtc0_performance3(cpu_env, arg);

            rn = "Performance3";

            goto cp0_unimplemented;

//            gen_helper_mtc0_performance4(cpu_env, arg);

            rn = "Performance4";

            goto cp0_unimplemented;

        case 5:

//            gen_helper_mtc0_performance5(cpu_env, arg);

            rn = "Performance5";

            goto cp0_unimplemented;

        case 6:

//            gen_helper_mtc0_performance6(cpu_env, arg);

            rn = "Performance6";

            goto cp0_unimplemented;

        case 7:

//            gen_helper_mtc0_performance7(cpu_env, arg);

            rn = "Performance7";

            goto cp0_unimplemented;

        default:

            goto cp0_unimplemented;

        }

    case 26:

        switch (sel) {

        case 0:

            gen_helper_mtc0_errctl(cpu_env, arg);

            ctx->bstate = BS_STOP;

            rn = "ErrCtl";

        default:

            goto cp0_unimplemented;

        }

    case 27:

        switch (sel) {

        case 0 ... 3:

            /* ignored */

            rn = "CacheErr";

        default:

            goto cp0_unimplemented;

        }

    case 28:

        switch (sel) {

        case 0:

        case 6:

            gen_helper_mtc0_taglo(cpu_env, arg);

            rn = "TagLo";

        case 1:

        case 5:

        case 7:

            gen_helper_mtc0_datalo(cpu_env, arg);

            rn = "DataLo";

        default:

            goto cp0_unimplemented;

        }

    case 29:

        switch (sel) {

        case 0:

        case 6:

            gen_helper_mtc0_taghi(cpu_env, arg);

            rn = "TagHi";

        case 1:

        case 5:

        case 7:

            gen_helper_mtc0_datahi(cpu_env, arg);

            rn = "DataHi";

        default:

            rn = "invalid sel";

            goto cp0_unimplemented;

        }

    case 30:

        switch (sel) {

        case 0:

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

            rn = "ErrorEPC";

        default:

            goto cp0_unimplemented;

        }

    case 31:

        switch (sel) {

        case 0:

            /* EJTAG support */

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

            rn = "DESAVE";

        case 2 ... 7:

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

            tcg_gen_st_tl(arg, cpu_env,

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

            rn = "KScratch";

        default:

            goto cp0_unimplemented;

        }

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

        ctx->bstate = BS_STOP;

    default:

        goto cp0_unimplemented;

    }

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

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

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

        gen_io_end();

        ctx->bstate = BS_STOP;

    }

    return;

cp0_unimplemented:

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

}


uint64_t HELPER(neon_sub_saturate_s64)(uint64_t src1, uint64_t src2)

{

    uint64_t res;

    res = src1 - src2;

    if (((res ^ src1) & SIGNBIT64) && ((src1 ^ src2) & SIGNBIT64)) {

        env->QF = 1;

        res = ((int64_t)src1 >> 63) ^ ~SIGNBIT64;

    }

    return res;

}


static int coroutine_fn copy_sectors(BlockDriverState *bs,
                                     uint64_t start_sect,
                                     uint64_t cluster_offset,
                                     int n_start, int n_end)
{
    BDRVQcowState *s = bs->opaque;
    QEMUIOVector qiov;
    struct iovec iov;
    int n, ret;
    /*
     * If this is the last cluster and it is only partially used, we must only
     * copy until the end of the image, or bdrv_check_request will fail for the
     * bdrv_read/write calls below.
     */
    if (start_sect + n_end > bs->total_sectors) {
        n_end = bs->total_sectors - start_sect;
    n = n_end - n_start;
    if (n <= 0) {
        return 0;
    iov.iov_len = n * BDRV_SECTOR_SIZE;
    iov.iov_base = qemu_blockalign(bs, iov.iov_len);
    qemu_iovec_init_external(&qiov, &iov, 1);
    BLKDBG_EVENT(bs->file, BLKDBG_COW_READ);
    /* Call .bdrv_co_readv() directly instead of using the public block-layer
     * interface.  This avoids double I/O throttling and request tracking,
     * which can lead to deadlock when block layer copy-on-read is enabled.
     */
    ret = bs->drv->bdrv_co_readv(bs, start_sect + n_start, n, &qiov);
    if (ret < 0) {
        goto out;
    if (s->crypt_method) {
        qcow2_encrypt_sectors(s, start_sect + n_start,
                        iov.iov_base, iov.iov_base, n, 1,
                        &s->aes_encrypt_key);
    ret = qcow2_pre_write_overlap_check(bs, 0,
            cluster_offset + n_start * BDRV_SECTOR_SIZE, n * BDRV_SECTOR_SIZE);
    if (ret < 0) {
        goto out;
    BLKDBG_EVENT(bs->file, BLKDBG_COW_WRITE);
    ret = bdrv_co_writev(bs->file, (cluster_offset >> 9) + n_start, n, &qiov);
    if (ret < 0) {
        goto out;
    ret = 0;
out:
    qemu_vfree(iov.iov_base);
    return ret;


static void FUNCC(pred16x16_vertical_add)(uint8_t *pix, const int *block_offset,

                                          const int16_t *block,

                                          ptrdiff_t stride)

{

    int i;

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

        FUNCC(pred4x4_vertical_add)(pix + block_offset[i], block + i*16*sizeof(pixel), stride);

}


static int ac3_parse_audio_block(AC3DecodeContext * ctx, int index)

{

    ac3_audio_block *ab = &ctx->audio_block;

    int nfchans = ctx->bsi.nfchans;

    int acmod = ctx->bsi.acmod;

    int i, bnd, rbnd, grp, seg;

    GetBitContext *gb = &ctx->gb;

    uint32_t *flags = &ab->flags;

    int bit_alloc_flags = 0;

    float drange;

    *flags = 0;

    ab->blksw = 0;

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

        ab->chcoeffs[i] = 1.0;

    for (i = 0; i < nfchans; i++) /*block switch flag */

        ab->blksw |= get_bits(gb, 1) << i;

    ab->dithflag = 0;

    for (i = 0; i < nfchans; i++) /* dithering flag */

        ab->dithflag |= get_bits(gb, 1) << i;

    if (get_bits(gb, 1)) { /* dynamic range */

        *flags |= AC3_AB_DYNRNGE;

        ab->dynrng = get_bits(gb, 8);

        drange = ((((ab->dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (ab->dynrng >> 5)]);

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

            ab->chcoeffs[i] *= drange;

    }

    if (acmod == 0x00) { /* dynamic range 1+1 mode */

        if (get_bits(gb, 1)) {

            *flags |= AC3_AB_DYNRNG2E;

            ab->dynrng2 = get_bits(gb, 8);

            drange = ((((ab->dynrng2 & 0x1f) | 0x20) << 13) * scale_factors[3 - (ab->dynrng2 >> 5)]);

            ab->chcoeffs[1] *= drange;

        }

    }

    get_downmix_coeffs(ctx);

    ab->chincpl = 0;

    if (get_bits(gb, 1)) { /* coupling strategy */

        *flags |= AC3_AB_CPLSTRE;

        ab->cplbndstrc = 0;

        if (get_bits(gb, 1)) { /* coupling in use */

            *flags |= AC3_AB_CPLINU;

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

                ab->chincpl |= get_bits(gb, 1) << i;

            if (acmod == 0x02)

                if (get_bits(gb, 1)) /* phase flag in use */

                    *flags |= AC3_AB_PHSFLGINU;

            ab->cplbegf = get_bits(gb, 4);

            ab->cplendf = get_bits(gb, 4);

            assert((ab->ncplsubnd = 3 + ab->cplendf - ab->cplbegf) > 0);

            ab->ncplbnd = ab->ncplsubnd;

            for (i = 0; i < ab->ncplsubnd - 1; i++) /* coupling band structure */

                if (get_bits(gb, 1)) {

                    ab->cplbndstrc |= 1 << i;

                    ab->ncplbnd--;

                }

        }

    }

    if (*flags & AC3_AB_CPLINU) {

        ab->cplcoe = 0;

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

            if (ab->chincpl & (1 << i))

                if (get_bits(gb, 1)) { /* coupling co-ordinates */

                    ab->cplcoe |= 1 << i;

                    ab->mstrcplco[i] = get_bits(gb, 2);

                    for (bnd = 0; bnd < ab->ncplbnd; bnd++) {

                        ab->cplcoexp[i][bnd] = get_bits(gb, 4);

                        ab->cplcomant[i][bnd] = get_bits(gb, 4);

                    }

                }

    }

    ab->phsflg = 0;

    if ((acmod == 0x02) && (*flags & AC3_AB_PHSFLGINU) && (ab->cplcoe & 1 || ab->cplcoe & (1 << 1))) {

        for (bnd = 0; bnd < ab->ncplbnd; bnd++)

            if (get_bits(gb, 1))

                ab->phsflg |= 1 << bnd;

    }

    generate_coupling_coordinates(ctx);

    ab->rematflg = 0;

    if (acmod == 0x02) /* rematrixing */

        if (get_bits(gb, 1)) {

            *flags |= AC3_AB_REMATSTR;

            if (ab->cplbegf > 2 || !(*flags & AC3_AB_CPLINU))

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

                    ab->rematflg |= get_bits(gb, 1) << bnd;

            else if (ab->cplbegf > 0 && ab->cplbegf <= 2 && *flags & AC3_AB_CPLINU)

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

                    ab->rematflg |= get_bits(gb, 1) << bnd;

            else if (!(ab->cplbegf) && *flags & AC3_AB_CPLINU)

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

                    ab->rematflg |= get_bits(gb, 1) << bnd;

        }

    if (*flags & AC3_AB_CPLINU) /* coupling exponent strategy */

        ab->cplexpstr = get_bits(gb, 2);

    for (i = 0; i < nfchans; i++) /* channel exponent strategy */

        ab->chexpstr[i] = get_bits(gb, 2);

    if (ctx->bsi.flags & AC3_BSI_LFEON) /* lfe exponent strategy */

        ab->lfeexpstr = get_bits(gb, 1);

    for (i = 0; i < nfchans; i++) /* channel bandwidth code */

        if (ab->chexpstr[i] != AC3_EXPSTR_REUSE)

            if (!(ab->chincpl & (1 << i))) {

                ab->chbwcod[i] = get_bits(gb, 6);

                assert (ab->chbwcod[i] <= 60);

            }

    if (*flags & AC3_AB_CPLINU)

        if (ab->cplexpstr != AC3_EXPSTR_REUSE) {/* coupling exponents */

            bit_alloc_flags |= 64;

            ab->cplabsexp = get_bits(gb, 4) << 1;

            ab->cplstrtmant = (ab->cplbegf * 12) + 37;

            ab->cplendmant = ((ab->cplendmant + 3) * 12) + 37;

            ab->ncplgrps = (ab->cplendmant - ab->cplstrtmant) / (3 << (ab->cplexpstr - 1));

            for (grp = 0; grp < ab->ncplgrps; grp++)

                ab->cplexps[grp] = get_bits(gb, 7);

        }

    for (i = 0; i < nfchans; i++) /* fbw channel exponents */

        if (ab->chexpstr[i] != AC3_EXPSTR_REUSE) {

            bit_alloc_flags |= 1 << i;

            if (ab->chincpl & (1 << i))

                ab->endmant[i] = (ab->cplbegf * 12) + 37;

            else

                ab->endmant[i] = ((ab->chbwcod[i] + 3) * 12) + 37;

            ab->nchgrps[i] =

                (ab->endmant[i] + (3 << (ab->chexpstr[i] - 1)) - 4) / (3 << (ab->chexpstr[i] - 1));

            ab->exps[i][0] = ab->dexps[i][0] = get_bits(gb, 4);

            for (grp = 1; grp <= ab->nchgrps[i]; grp++)

                ab->exps[i][grp] = get_bits(gb, 7);

            ab->gainrng[i] = get_bits(gb, 2);

        }

    if (ctx->bsi.flags & AC3_BSI_LFEON) /* lfe exponents */

        if (ab->lfeexpstr != AC3_EXPSTR_REUSE) {

            bit_alloc_flags |= 32;

            ab->lfeexps[0] = ab->dlfeexps[0] = get_bits(gb, 4);

            ab->lfeexps[1] = get_bits(gb, 7);

            ab->lfeexps[2] = get_bits(gb, 7);

        }

    if (decode_exponents(ctx)) {/* decode the exponents for this block */

        av_log(NULL, AV_LOG_ERROR, "Error parsing exponents\n");

        return -1;

    }

    if (get_bits(gb, 1)) { /* bit allocation information */

        *flags |= AC3_AB_BAIE;

        bit_alloc_flags |= 127;

        ab->sdcycod = get_bits(gb, 2);

        ab->fdcycod = get_bits(gb, 2);

        ab->sgaincod = get_bits(gb, 2);

        ab->dbpbcod = get_bits(gb, 2);

        ab->floorcod = get_bits(gb, 3);

    }

    if (get_bits(gb, 1)) { /* snroffset */

        *flags |= AC3_AB_SNROFFSTE;

        bit_alloc_flags |= 127;

        ab->csnroffst = get_bits(gb, 6);

        if (*flags & AC3_AB_CPLINU) { /* couling fine snr offset and fast gain code */

            ab->cplfsnroffst = get_bits(gb, 4);

            ab->cplfgaincod = get_bits(gb, 3);

        }

        for (i = 0; i < nfchans; i++) { /* channel fine snr offset and fast gain code */

            ab->fsnroffst[i] = get_bits(gb, 4);

            ab->fgaincod[i] = get_bits(gb, 3);

        }

        if (ctx->bsi.flags & AC3_BSI_LFEON) { /* lfe fine snr offset and fast gain code */

            ab->lfefsnroffst = get_bits(gb, 4);

            ab->lfefgaincod = get_bits(gb, 3);

        }

    }

    if (*flags & AC3_AB_CPLINU)

        if (get_bits(gb, 1)) { /* coupling leak information */

            bit_alloc_flags |= 64;

            *flags |= AC3_AB_CPLLEAKE;

            ab->cplfleak = get_bits(gb, 3);

            ab->cplsleak = get_bits(gb, 3);

        }

    if (get_bits(gb, 1)) { /* delta bit allocation information */

        *flags |= AC3_AB_DELTBAIE;

        bit_alloc_flags |= 127;

        if (*flags & AC3_AB_CPLINU) {

            ab->cpldeltbae = get_bits(gb, 2);

            if (ab->cpldeltbae == AC3_DBASTR_RESERVED) {

                av_log(NULL, AV_LOG_ERROR, "coupling delta bit allocation strategy reserved\n");

                return -1;

            }

        }

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

            ab->deltbae[i] = get_bits(gb, 2);

            if (ab->deltbae[i] == AC3_DBASTR_RESERVED) {

                av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");

                return -1;

            }

        }

        if (*flags & AC3_AB_CPLINU)

            if (ab->cpldeltbae == AC3_DBASTR_NEW) { /*coupling delta offset, len and bit allocation */

                ab->cpldeltnseg = get_bits(gb, 3);

                for (seg = 0; seg <= ab->cpldeltnseg; seg++) {

                    ab->cpldeltoffst[seg] = get_bits(gb, 5);

                    ab->cpldeltlen[seg] = get_bits(gb, 4);

                    ab->cpldeltba[seg] = get_bits(gb, 3);

                }

            }

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

            if (ab->deltbae[i] == AC3_DBASTR_NEW) {/*channel delta offset, len and bit allocation */

                ab->deltnseg[i] = get_bits(gb, 3);

                for (seg = 0; seg <= ab->deltnseg[i]; seg++) {

                    ab->deltoffst[i][seg] = get_bits(gb, 5);

                    ab->deltlen[i][seg] = get_bits(gb, 4);

                    ab->deltba[i][seg] = get_bits(gb, 3);

                }

            }

    }

    if (do_bit_allocation (ctx, bit_alloc_flags)) /* perform the bit allocation */ {

        av_log(NULL, AV_LOG_ERROR, "Error in bit allocation routine\n");

        return -1;

    }

    if (get_bits(gb, 1)) { /* unused dummy data */

        *flags |= AC3_AB_SKIPLE;

        ab->skipl = get_bits(gb, 9);

        while (ab->skipl) {

            get_bits(gb, 8);

            ab->skipl--;

        }

    }

    /* unpack the transform coefficients

     * * this also uncouples channels if coupling is in use.

     */

    if (get_transform_coeffs(ctx)) {

        av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");

        return -1;

    }

    /* recover coefficients if rematrixing is in use */

    if (*flags & AC3_AB_REMATSTR)

        do_rematrixing(ctx);

    if (ctx->output != AC3_OUTPUT_UNMODIFIED)

        do_downmix(ctx);

    return 0;

}


static void h264_free_extradata(PayloadContext *data)

{

#ifdef DEBUG

    int ii;

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

        if (data->packet_types_received[ii])

            av_log(NULL, AV_LOG_DEBUG, "Received %d packets of type %d\n",

                   data->packet_types_received[ii], ii);

    }

#endif

    assert(data);

    assert(data->cookie == MAGIC_COOKIE);

    // avoid stale pointers (assert)

    data->cookie = DEAD_COOKIE;

    // and clear out this...

    av_free(data);

}


static int net_socket_connect_init(VLANState *vlan,

                                   const char *model,

                                   const char *name,

                                   const char *host_str)

{

    NetSocketState *s;

    int fd, connected, ret, err;

    struct sockaddr_in saddr;

    if (parse_host_port(&saddr, host_str) < 0)

        return -1;

    fd = socket(PF_INET, SOCK_STREAM, 0);

    if (fd < 0) {

        perror("socket");

        return -1;

    }

    socket_set_nonblock(fd);

    connected = 0;

    for(;;) {

        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));

        if (ret < 0) {

            err = socket_error();

            if (err == EINTR || err == EWOULDBLOCK) {

            } else if (err == EINPROGRESS) {

                break;

#ifdef _WIN32

            } else if (err == WSAEALREADY) {

                break;

#endif

            } else {

                perror("connect");

                closesocket(fd);

                return -1;

            }

        } else {

            connected = 1;

            break;

        }

    }

    s = net_socket_fd_init(vlan, model, name, fd, connected);

    if (!s)

        return -1;

    snprintf(s->nc.info_str, sizeof(s->nc.info_str),

             "socket: connect to %s:%d",

             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));

    return 0;

}


static int kvm_update_routing_entry(KVMState *s,

                                    struct kvm_irq_routing_entry *new_entry)

{

    struct kvm_irq_routing_entry *entry;

    int n;

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

        entry = &s->irq_routes->entries[n];

        if (entry->gsi != new_entry->gsi) {

            continue;

        }

        entry->type = new_entry->type;

        entry->flags = new_entry->flags;

        entry->u = new_entry->u;

        kvm_irqchip_commit_routes(s);

        return 0;

    }

    return -ESRCH;

}


int nbd_client_session_co_discard(NbdClientSession *client, int64_t sector_num,

    int nb_sectors)

{

    struct nbd_request request;

    struct nbd_reply reply;

    ssize_t ret;

    if (!(client->nbdflags & NBD_FLAG_SEND_TRIM)) {

        return 0;

    }

    request.type = NBD_CMD_TRIM;

    request.from = sector_num * 512;

    request.len = nb_sectors * 512;

    nbd_coroutine_start(client, &request);

    ret = nbd_co_send_request(client, &request, NULL, 0);

    if (ret < 0) {

        reply.error = -ret;

    } else {

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

    }

    nbd_coroutine_end(client, &request);

    return -reply.error;

}


ssize_t vnc_client_io_error(VncState *vs, ssize_t ret, Error **errp)

{

    if (ret <= 0) {

        if (ret == 0) {

            VNC_DEBUG("Closing down client sock: EOF\n");

        } else if (ret != QIO_CHANNEL_ERR_BLOCK) {

            VNC_DEBUG("Closing down client sock: ret %zd (%s)\n",

                      ret, errp ? error_get_pretty(*errp) : "Unknown");

        }

        vnc_disconnect_start(vs);

        if (errp) {

            error_free(*errp);

            *errp = NULL;

        }

        return 0;

    }

    return ret;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);

    k->init = pl031_init;

    dc->no_user = 1;

    dc->vmsd = &vmstate_pl031;

}


static inline void fimd_swap_data(unsigned int swap_ctl, uint64_t *data)

{

    int i;

    uint64_t res;

    uint64_t x = *data;

    if (swap_ctl & FIMD_WINCON_SWAP_BITS) {

        res = 0;

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

            if (x & (1ULL << (64 - i))) {

                res |= (1ULL << i);

            }

        }

        x = res;

    }

    if (swap_ctl & FIMD_WINCON_SWAP_BYTE) {

        x = bswap64(x);

    }

    if (swap_ctl & FIMD_WINCON_SWAP_HWORD) {

        x = ((x & 0x000000000000FFFFULL) << 48) |

            ((x & 0x00000000FFFF0000ULL) << 16) |

            ((x & 0x0000FFFF00000000ULL) >> 16) |

            ((x & 0xFFFF000000000000ULL) >> 48);

    }

    if (swap_ctl & FIMD_WINCON_SWAP_WORD) {

        x = ((x & 0x00000000FFFFFFFFULL) << 32) |

            ((x & 0xFFFFFFFF00000000ULL) >> 32);

    }

    *data = x;

}


static int sdl_write_header(AVFormatContext *s)

{

    SDLContext *sdl = s->priv_data;

    AVStream *st = s->streams[0];

    AVCodecContext *encctx = st->codec;

    AVRational sar, dar; /* sample and display aspect ratios */

    int i, ret;

    int flags = SDL_SWSURFACE | sdl->window_fullscreen ? SDL_FULLSCREEN : 0;

    if (!sdl->window_title)

        sdl->window_title = av_strdup(s->filename);

    if (!sdl->icon_title)

        sdl->icon_title = av_strdup(sdl->window_title);

    if (SDL_WasInit(SDL_INIT_VIDEO)) {

        av_log(s, AV_LOG_ERROR,

               "SDL video subsystem was already inited, aborting\n");

        sdl->sdl_was_already_inited = 1;

        ret = AVERROR(EINVAL);

        goto fail;

    }

    if (SDL_Init(SDL_INIT_VIDEO) != 0) {

        av_log(s, AV_LOG_ERROR, "Unable to initialize SDL: %s\n", SDL_GetError());

        ret = AVERROR(EINVAL);

        goto fail;

    }

    if (   s->nb_streams > 1

        || encctx->codec_type != AVMEDIA_TYPE_VIDEO

        || encctx->codec_id   != AV_CODEC_ID_RAWVIDEO) {

        av_log(s, AV_LOG_ERROR, "Only supports one rawvideo stream\n");

        ret = AVERROR(EINVAL);

        goto fail;

    }

    for (i = 0; sdl_overlay_pix_fmt_map[i].pix_fmt != AV_PIX_FMT_NONE; i++) {

        if (sdl_overlay_pix_fmt_map[i].pix_fmt == encctx->pix_fmt) {

            sdl->overlay_fmt = sdl_overlay_pix_fmt_map[i].overlay_fmt;

            break;

        }

    }

    if (!sdl->overlay_fmt) {

        av_log(s, AV_LOG_ERROR,

               "Unsupported pixel format '%s', choose one of yuv420p, yuyv422, or uyvy422\n",

               av_get_pix_fmt_name(encctx->pix_fmt));

        ret = AVERROR(EINVAL);

        goto fail;

    }

    /* compute overlay width and height from the codec context information */

    sar = st->sample_aspect_ratio.num ? st->sample_aspect_ratio : (AVRational){ 1, 1 };

    dar = av_mul_q(sar, (AVRational){ encctx->width, encctx->height });

    /* we suppose the screen has a 1/1 sample aspect ratio */

    if (sdl->window_width && sdl->window_height) {

        /* fit in the window */

        if (av_cmp_q(dar, (AVRational){ sdl->window_width, sdl->window_height }) > 0) {

            /* fit in width */

            sdl->overlay_width  = sdl->window_width;

            sdl->overlay_height = av_rescale(sdl->overlay_width, dar.den, dar.num);

        } else {

            /* fit in height */

            sdl->overlay_height = sdl->window_height;

            sdl->overlay_width  = av_rescale(sdl->overlay_height, dar.num, dar.den);

        }

    } else {

        if (sar.num > sar.den) {

            sdl->overlay_width  = encctx->width;

            sdl->overlay_height = av_rescale(sdl->overlay_width, dar.den, dar.num);

        } else {

            sdl->overlay_height = encctx->height;

            sdl->overlay_width  = av_rescale(sdl->overlay_height, dar.num, dar.den);

        }

        sdl->window_width  = sdl->overlay_width;

        sdl->window_height = sdl->overlay_height;

    }

    sdl->overlay_x = (sdl->window_width  - sdl->overlay_width ) / 2;

    sdl->overlay_y = (sdl->window_height - sdl->overlay_height) / 2;

    SDL_WM_SetCaption(sdl->window_title, sdl->icon_title);

    sdl->surface = SDL_SetVideoMode(sdl->window_width, sdl->window_height,

                                    24, flags);

    if (!sdl->surface) {

        av_log(s, AV_LOG_ERROR, "Unable to set video mode: %s\n", SDL_GetError());

        ret = AVERROR(EINVAL);

        goto fail;

    }

    sdl->overlay = SDL_CreateYUVOverlay(encctx->width, encctx->height,

                                        sdl->overlay_fmt, sdl->surface);

    if (!sdl->overlay || sdl->overlay->pitches[0] < encctx->width) {

        av_log(s, AV_LOG_ERROR,

               "SDL does not support an overlay with size of %dx%d pixels\n",

               encctx->width, encctx->height);

        ret = AVERROR(EINVAL);

        goto fail;

    }

    av_log(s, AV_LOG_VERBOSE, "w:%d h:%d fmt:%s sar:%d/%d -> w:%d h:%d\n",

           encctx->width, encctx->height, av_get_pix_fmt_name(encctx->pix_fmt), sar.num, sar.den,

           sdl->overlay_width, sdl->overlay_height);

    return 0;

fail:

    sdl_write_trailer(s);

    return ret;

}


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

{

    BusClass *k = BUS_CLASS(klass);

    /* AUXSlave has an MMIO so we need to change the way we print information

     * in monitor.

     */

    k->print_dev = aux_slave_dev_print;

}


static int ape_decode_frame(AVCodecContext * avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    APEContext *s = avctx->priv_data;

    int16_t *samples = data;

    int nblocks;

    int i, n;

    int blockstodecode;

    int bytes_used;

    if (buf_size == 0 && !s->samples) {

        *data_size = 0;

        return 0;

    }

    /* should not happen but who knows */

    if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {

        av_log (avctx, AV_LOG_ERROR, "Packet size is too big to be handled in lavc! (max is %d where you have %d)\n", *data_size, s->samples * 2 * avctx->channels);

        return -1;

    }

    if(!s->samples){

        s->data = av_realloc(s->data, (buf_size + 3) & ~3);

        s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);

        s->ptr = s->last_ptr = s->data;

        s->data_end = s->data + buf_size;

        nblocks = s->samples = bytestream_get_be32(&s->ptr);

        n =  bytestream_get_be32(&s->ptr);

        if(n < 0 || n > 3){

            av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");

            s->data = NULL;

            return -1;

        }

        s->ptr += n;

        s->currentframeblocks = nblocks;

        buf += 4;

        if (s->samples <= 0) {

            *data_size = 0;

            return buf_size;

        }

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

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

        /* Initialize the frame decoder */

        init_frame_decoder(s);

    }

    if (!s->data) {

        *data_size = 0;

        return buf_size;

    }

    nblocks = s->samples;

    blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);

    s->error=0;

    if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))

        ape_unpack_mono(s, blockstodecode);

    else

        ape_unpack_stereo(s, blockstodecode);

    emms_c();

    if(s->error || s->ptr > s->data_end){

        s->samples=0;

        av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");

        return -1;

    }

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

        *samples++ = s->decoded0[i];

        if(s->channels == 2)

            *samples++ = s->decoded1[i];

    }

    s->samples -= blockstodecode;

    *data_size = blockstodecode * 2 * s->channels;

    bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;

    s->last_ptr = s->ptr;

    return bytes_used;

}


static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)

{

    int long_gop = avctx->gop_size > 1 || avctx->has_b_frames;

    if (avctx->profile == 4) { // Main

        if (avctx->level == 8) // Main

            return &mxf_mpeg2_codec_uls[0+long_gop];

        else if (avctx->level == 4) // High

            return &mxf_mpeg2_codec_uls[4+long_gop];

        else if (avctx->level == 6) // High 14

            return &mxf_mpeg2_codec_uls[8+long_gop];

    } else if (avctx->profile == 0) { // 422

        if (avctx->level == 5) // Main

            return &mxf_mpeg2_codec_uls[2+long_gop];

        else if (avctx->level == 2) // High

            return &mxf_mpeg2_codec_uls[6+long_gop];

    }

    return NULL;

}


static void free_packet_list(AVPacketList *pktl)

{

    AVPacketList *cur;

    while (pktl) {

        cur = pktl;

        pktl = cur->next;

        av_free_packet(&cur->pkt);

        av_free(cur);

    }

}


static int encode_frame(AVCodecContext *avctx, unsigned char *buf,

                        int buf_size, void *data)

{

    const AVFrame *pic = data;

    int aligned_width = ((avctx->width + 47) / 48) * 48;

    int stride = aligned_width * 8 / 3;

    int h, w;

    const uint16_t *y = (const uint16_t*)pic->data[0];

    const uint16_t *u = (const uint16_t*)pic->data[1];

    const uint16_t *v = (const uint16_t*)pic->data[2];

    uint8_t *p = buf;

    uint8_t *pdst = buf;

    if (buf_size < aligned_width * avctx->height * 8 / 3) {

        av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");

        return -1;

    }

#define CLIP(v) av_clip(v, 4, 1019)

#define WRITE_PIXELS(a, b, c)           \

    do {                                \

        val =   CLIP(*a++);             \

        val |= (CLIP(*b++) << 10) |     \

               (CLIP(*c++) << 20);      \

        bytestream_put_le32(&p, val);   \

    } while (0)

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

        uint32_t val;

        for (w = 0; w < avctx->width - 5; w += 6) {

            WRITE_PIXELS(u, y, v);

            WRITE_PIXELS(y, u, y);

            WRITE_PIXELS(v, y, u);

            WRITE_PIXELS(y, v, y);

        }

        if (w < avctx->width - 1) {

            WRITE_PIXELS(u, y, v);

            val = CLIP(*y++);

            if (w == avctx->width - 2)

                bytestream_put_le32(&p, val);

        }

        if (w < avctx->width - 3) {

            val |= (CLIP(*u++) << 10) | (CLIP(*y++) << 20);

            bytestream_put_le32(&p, val);

            val = CLIP(*v++) | (CLIP(*y++) << 10);

            bytestream_put_le32(&p, val);

        }

        pdst += stride;

        memset(p, 0, pdst - p);

        p = pdst;

        y += pic->linesize[0] / 2 - avctx->width;

        u += pic->linesize[1] / 2 - avctx->width / 2;

        v += pic->linesize[2] / 2 - avctx->width / 2;

    }

    return p - buf;

}


static void pc_init_pci_no_kvmclock(MachineState *machine)

{

    has_pci_info = false;

    has_acpi_build = false;

    smbios_defaults = false;

    x86_cpu_compat_disable_kvm_features(FEAT_KVM, KVM_FEATURE_PV_EOI);

    enable_compat_apic_id_mode();

    pc_init1(machine, 1, 0);

}


static void ide_sector_read_cb(void *opaque, int ret)

{

    IDEState *s = opaque;

    int n;

    s->pio_aiocb = NULL;

    s->status &= ~BUSY_STAT;

    if (ret == -ECANCELED) {

        return;

    }

    block_acct_done(blk_get_stats(s->blk), &s->acct);

    if (ret != 0) {

        if (ide_handle_rw_error(s, -ret, IDE_RETRY_PIO |

                                IDE_RETRY_READ)) {

            return;

        }

    }

    n = s->nsector;

    if (n > s->req_nb_sectors) {

        n = s->req_nb_sectors;

    }

    ide_set_sector(s, ide_get_sector(s) + n);

    s->nsector -= n;

    /* Allow the guest to read the io_buffer */

    ide_transfer_start(s, s->io_buffer, n * BDRV_SECTOR_SIZE, ide_sector_read);

    ide_set_irq(s->bus);

}


av_cold void INIT_FUNC(VP9DSPContext *dsp, int bitexact)

{

#if HAVE_YASM

    int cpu_flags = av_get_cpu_flags();

#define init_lpf_8_func(idx1, idx2, dir, wd, bpp, opt) \

    dsp->loop_filter_8[idx1][idx2] = ff_vp9_loop_filter_##dir##_##wd##_##bpp##_##opt

#define init_lpf_16_func(idx, dir, bpp, opt) \

    dsp->loop_filter_16[idx] = loop_filter_##dir##_16_##bpp##_##opt

#define init_lpf_mix2_func(idx1, idx2, idx3, dir, wd1, wd2, bpp, opt) \

    dsp->loop_filter_mix2[idx1][idx2][idx3] = loop_filter_##dir##_##wd1##wd2##_##bpp##_##opt

#define init_lpf_funcs(bpp, opt) \

    init_lpf_8_func(0, 0, h,  4, bpp, opt); \

    init_lpf_8_func(0, 1, v,  4, bpp, opt); \

    init_lpf_8_func(1, 0, h,  8, bpp, opt); \

    init_lpf_8_func(1, 1, v,  8, bpp, opt); \

    init_lpf_8_func(2, 0, h, 16, bpp, opt); \

    init_lpf_8_func(2, 1, v, 16, bpp, opt); \

    init_lpf_16_func(0, h, bpp, opt); \

    init_lpf_16_func(1, v, bpp, opt); \

    init_lpf_mix2_func(0, 0, 0, h, 4, 4, bpp, opt); \

    init_lpf_mix2_func(0, 1, 0, h, 4, 8, bpp, opt); \

    init_lpf_mix2_func(1, 0, 0, h, 8, 4, bpp, opt); \

    init_lpf_mix2_func(1, 1, 0, h, 8, 8, bpp, opt); \

    init_lpf_mix2_func(0, 0, 1, v, 4, 4, bpp, opt); \

    init_lpf_mix2_func(0, 1, 1, v, 4, 8, bpp, opt); \

    init_lpf_mix2_func(1, 0, 1, v, 8, 4, bpp, opt); \

    init_lpf_mix2_func(1, 1, 1, v, 8, 8, bpp, opt)

#define init_itx_func(idxa, idxb, typea, typeb, size, bpp, opt) \

    dsp->itxfm_add[idxa][idxb] = \

        ff_vp9_##typea##_##typeb##_##size##x##size##_add_##bpp##_##opt;

#define init_itx_func_one(idx, typea, typeb, size, bpp, opt) \

    init_itx_func(idx, DCT_DCT,   typea, typeb, size, bpp, opt); \

    init_itx_func(idx, ADST_DCT,  typea, typeb, size, bpp, opt); \

    init_itx_func(idx, DCT_ADST,  typea, typeb, size, bpp, opt); \

    init_itx_func(idx, ADST_ADST, typea, typeb, size, bpp, opt)

#define init_itx_funcs(idx, size, bpp, opt) \

    init_itx_func(idx, DCT_DCT,   idct,  idct,  size, bpp, opt); \

    init_itx_func(idx, ADST_DCT,  idct,  iadst, size, bpp, opt); \

    init_itx_func(idx, DCT_ADST,  iadst, idct,  size, bpp, opt); \

    init_itx_func(idx, ADST_ADST, iadst, iadst, size, bpp, opt); \

    if (EXTERNAL_MMXEXT(cpu_flags)) {

        init_ipred_func(tm, TM_VP8, 4, BPC, mmxext);

        if (!bitexact) {

            init_itx_func_one(4 /* lossless */, iwht, iwht, 4, BPC, mmxext);

#if BPC == 10

            init_itx_func(TX_4X4, DCT_DCT, idct, idct, 4, 10, mmxext);

#endif

        }

    }

    if (EXTERNAL_SSE2(cpu_flags)) {

        init_subpel3(0, put, BPC, sse2);

        init_subpel3(1, avg, BPC, sse2);

        init_lpf_funcs(BPC, sse2);

        init_8_16_32_ipred_funcs(tm, TM_VP8, BPC, sse2);

#if BPC == 10

        if (!bitexact) {

            init_itx_func(TX_4X4, ADST_DCT,  idct,  iadst, 4, 10, sse2);

            init_itx_func(TX_4X4, DCT_ADST,  iadst, idct,  4, 10, sse2);

            init_itx_func(TX_4X4, ADST_ADST, iadst, iadst, 4, 10, sse2);

        }

#endif

    }

    if (EXTERNAL_SSSE3(cpu_flags)) {

        init_lpf_funcs(BPC, ssse3);

#if BPC == 10

        if (!bitexact) {

            init_itx_funcs(TX_4X4, 4, BPC, ssse3);

        }

#endif

    }

    if (EXTERNAL_AVX(cpu_flags)) {

        init_lpf_funcs(BPC, avx);

    }

    if (EXTERNAL_AVX2(cpu_flags)) {

#if HAVE_AVX2_EXTERNAL

        init_subpel3_32_64(0,  put, BPC, avx2);

        init_subpel3_32_64(1,  avg, BPC, avx2);

        init_subpel2(2, 0, 16, put, BPC, avx2);

        init_subpel2(2, 1, 16, avg, BPC, avx2);

#endif

    }

#endif /* HAVE_YASM */

    ff_vp9dsp_init_16bpp_x86(dsp);

}