build_dsdt(GArray *table_data, GArray *linker,
           AcpiPmInfo *pm, AcpiMiscInfo *misc,
           PcPciInfo *pci, MachineState *machine)
{
    CrsRangeEntry *entry;
    Aml *dsdt, *sb_scope, *scope, *dev, *method, *field, *pkg, *crs;
    GPtrArray *mem_ranges = g_ptr_array_new_with_free_func(crs_range_free);
    GPtrArray *io_ranges = g_ptr_array_new_with_free_func(crs_range_free);
    PCMachineState *pcms = PC_MACHINE(machine);
    uint32_t nr_mem = machine->ram_slots;
    int root_bus_limit = 0xFF;
    PCIBus *bus = NULL;
    int i;
    dsdt = init_aml_allocator();
    /* Reserve space for header */
    acpi_data_push(dsdt->buf, sizeof(AcpiTableHeader));
    build_dbg_aml(dsdt);
    if (misc->is_piix4) {
        sb_scope = aml_scope("_SB");
        dev = aml_device("PCI0");
        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));
        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));
        aml_append(dev, aml_name_decl("_UID", aml_int(1)));
        aml_append(sb_scope, dev);
        aml_append(dsdt, sb_scope);
        build_hpet_aml(dsdt);
        build_piix4_pm(dsdt);
        build_piix4_isa_bridge(dsdt);
        build_isa_devices_aml(dsdt);
        build_piix4_pci_hotplug(dsdt);
        build_piix4_pci0_int(dsdt);
    } else {
        sb_scope = aml_scope("_SB");
        aml_append(sb_scope,
            aml_operation_region("PCST", AML_SYSTEM_IO, aml_int(0xae00), 0x0c));
        aml_append(sb_scope,
            aml_operation_region("PCSB", AML_SYSTEM_IO, aml_int(0xae0c), 0x01));
        field = aml_field("PCSB", AML_ANY_ACC, AML_NOLOCK, AML_WRITE_AS_ZEROS);
        aml_append(field, aml_named_field("PCIB", 8));
        aml_append(sb_scope, field);
        aml_append(dsdt, sb_scope);
        sb_scope = aml_scope("_SB");
        dev = aml_device("PCI0");
        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A08")));
        aml_append(dev, aml_name_decl("_CID", aml_eisaid("PNP0A03")));
        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));
        aml_append(dev, aml_name_decl("_UID", aml_int(1)));
        aml_append(dev, aml_name_decl("SUPP", aml_int(0)));
        aml_append(dev, aml_name_decl("CTRL", aml_int(0)));
        aml_append(dev, build_q35_osc_method());
        aml_append(sb_scope, dev);
        aml_append(dsdt, sb_scope);
        build_hpet_aml(dsdt);
        build_q35_isa_bridge(dsdt);
        build_isa_devices_aml(dsdt);
        build_q35_pci0_int(dsdt);
    build_cpu_hotplug_aml(dsdt);
    build_memory_hotplug_aml(dsdt, nr_mem, pm->mem_hp_io_base,
                             pm->mem_hp_io_len);
    scope =  aml_scope("_GPE");
    {
        aml_append(scope, aml_name_decl("_HID", aml_string("ACPI0006")));
        aml_append(scope, aml_method("_L00", 0, AML_NOTSERIALIZED));
        if (misc->is_piix4) {
            method = aml_method("_E01", 0, AML_NOTSERIALIZED);
            aml_append(method,
                aml_acquire(aml_name("\\_SB.PCI0.BLCK"), 0xFFFF));
            aml_append(method, aml_call0("\\_SB.PCI0.PCNT"));
            aml_append(method, aml_release(aml_name("\\_SB.PCI0.BLCK")));
            aml_append(scope, method);
        } else {
            aml_append(scope, aml_method("_L01", 0, AML_NOTSERIALIZED));
        method = aml_method("_E02", 0, AML_NOTSERIALIZED);
        aml_append(method, aml_call0("\\_SB." CPU_SCAN_METHOD));
        aml_append(scope, method);
        method = aml_method("_E03", 0, AML_NOTSERIALIZED);
        aml_append(method, aml_call0(MEMORY_HOTPLUG_HANDLER_PATH));
        aml_append(scope, method);
        aml_append(scope, aml_method("_L04", 0, AML_NOTSERIALIZED));
        aml_append(scope, aml_method("_L05", 0, AML_NOTSERIALIZED));
        aml_append(scope, aml_method("_L06", 0, AML_NOTSERIALIZED));
        aml_append(scope, aml_method("_L07", 0, AML_NOTSERIALIZED));
        aml_append(scope, aml_method("_L08", 0, AML_NOTSERIALIZED));
        aml_append(scope, aml_method("_L09", 0, AML_NOTSERIALIZED));
        aml_append(scope, aml_method("_L0A", 0, AML_NOTSERIALIZED));
        aml_append(scope, aml_method("_L0B", 0, AML_NOTSERIALIZED));
        aml_append(scope, aml_method("_L0C", 0, AML_NOTSERIALIZED));
        aml_append(scope, aml_method("_L0D", 0, AML_NOTSERIALIZED));
        aml_append(scope, aml_method("_L0E", 0, AML_NOTSERIALIZED));
        aml_append(scope, aml_method("_L0F", 0, AML_NOTSERIALIZED));
    aml_append(dsdt, scope);
    bus = PC_MACHINE(machine)->bus;
    if (bus) {
        QLIST_FOREACH(bus, &bus->child, sibling) {
            uint8_t bus_num = pci_bus_num(bus);
            uint8_t numa_node = pci_bus_numa_node(bus);
            /* look only for expander root buses */
            if (!pci_bus_is_root(bus)) {
                continue;
            if (bus_num < root_bus_limit) {
                root_bus_limit = bus_num - 1;
            scope = aml_scope("\\_SB");
            dev = aml_device("PC%.02X", bus_num);
            aml_append(dev, aml_name_decl("_UID", aml_int(bus_num)));
            aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));
            aml_append(dev, aml_name_decl("_BBN", aml_int(bus_num)));
            if (numa_node != NUMA_NODE_UNASSIGNED) {
                aml_append(dev, aml_name_decl("_PXM", aml_int(numa_node)));
            aml_append(dev, build_prt(false));
            crs = build_crs(PCI_HOST_BRIDGE(BUS(bus)->parent),
                            io_ranges, mem_ranges);
            aml_append(dev, aml_name_decl("_CRS", crs));
            aml_append(scope, dev);
            aml_append(dsdt, scope);
    scope = aml_scope("\\_SB.PCI0");
    /* build PCI0._CRS */
    crs = aml_resource_template();
    aml_append(crs,
        aml_word_bus_number(AML_MIN_FIXED, AML_MAX_FIXED, AML_POS_DECODE,
                            0x0000, 0x0, root_bus_limit,
                            0x0000, root_bus_limit + 1));
    aml_append(crs, aml_io(AML_DECODE16, 0x0CF8, 0x0CF8, 0x01, 0x08));
    aml_append(crs,
        aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,
                    AML_POS_DECODE, AML_ENTIRE_RANGE,
                    0x0000, 0x0000, 0x0CF7, 0x0000, 0x0CF8));
    crs_replace_with_free_ranges(io_ranges, 0x0D00, 0xFFFF);
    for (i = 0; i < io_ranges->len; i++) {
        entry = g_ptr_array_index(io_ranges, i);
        aml_append(crs,
            aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,
                        AML_POS_DECODE, AML_ENTIRE_RANGE,
                        0x0000, entry->base, entry->limit,
                        0x0000, entry->limit - entry->base + 1));
    aml_append(crs,
        aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,
                         AML_CACHEABLE, AML_READ_WRITE,
                         0, 0x000A0000, 0x000BFFFF, 0, 0x00020000));
    crs_replace_with_free_ranges(mem_ranges, pci->w32.begin, pci->w32.end - 1);
    for (i = 0; i < mem_ranges->len; i++) {
        entry = g_ptr_array_index(mem_ranges, i);
        aml_append(crs,
            aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,
                             AML_NON_CACHEABLE, AML_READ_WRITE,
                             0, entry->base, entry->limit,
                             0, entry->limit - entry->base + 1));
    if (pci->w64.begin) {
        aml_append(crs,
            aml_qword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,
                             AML_CACHEABLE, AML_READ_WRITE,
                             0, pci->w64.begin, pci->w64.end - 1, 0,
                             pci->w64.end - pci->w64.begin));
    aml_append(scope, aml_name_decl("_CRS", crs));
    /* reserve GPE0 block resources */
    dev = aml_device("GPE0");
    aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));
    aml_append(dev, aml_name_decl("_UID", aml_string("GPE0 resources")));
    /* device present, functioning, decoding, not shown in UI */
    aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
    crs = aml_resource_template();
    aml_append(crs,
        aml_io(AML_DECODE16, pm->gpe0_blk, pm->gpe0_blk, 1, pm->gpe0_blk_len)
    );
    aml_append(dev, aml_name_decl("_CRS", crs));
    aml_append(scope, dev);
    g_ptr_array_free(io_ranges, true);
    g_ptr_array_free(mem_ranges, true);
    /* reserve PCIHP resources */
    if (pm->pcihp_io_len) {
        dev = aml_device("PHPR");
        aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));
        aml_append(dev,
            aml_name_decl("_UID", aml_string("PCI Hotplug resources")));
        /* device present, functioning, decoding, not shown in UI */
        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
        crs = aml_resource_template();
        aml_append(crs,
            aml_io(AML_DECODE16, pm->pcihp_io_base, pm->pcihp_io_base, 1,
                   pm->pcihp_io_len)
        );
        aml_append(dev, aml_name_decl("_CRS", crs));
        aml_append(scope, dev);
    aml_append(dsdt, scope);
    /*  create S3_ / S4_ / S5_ packages if necessary */
    scope = aml_scope("\\");
    if (!pm->s3_disabled) {
        pkg = aml_package(4);
        aml_append(pkg, aml_int(1)); /* PM1a_CNT.SLP_TYP */
        aml_append(pkg, aml_int(1)); /* PM1b_CNT.SLP_TYP, FIXME: not impl. */
        aml_append(pkg, aml_int(0)); /* reserved */
        aml_append(pkg, aml_int(0)); /* reserved */
        aml_append(scope, aml_name_decl("_S3", pkg));
    if (!pm->s4_disabled) {
        pkg = aml_package(4);
        aml_append(pkg, aml_int(pm->s4_val)); /* PM1a_CNT.SLP_TYP */
        /* PM1b_CNT.SLP_TYP, FIXME: not impl. */
        aml_append(pkg, aml_int(pm->s4_val));
        aml_append(pkg, aml_int(0)); /* reserved */
        aml_append(pkg, aml_int(0)); /* reserved */
        aml_append(scope, aml_name_decl("_S4", pkg));
    pkg = aml_package(4);
    aml_append(pkg, aml_int(0)); /* PM1a_CNT.SLP_TYP */
    aml_append(pkg, aml_int(0)); /* PM1b_CNT.SLP_TYP not impl. */
    aml_append(pkg, aml_int(0)); /* reserved */
    aml_append(pkg, aml_int(0)); /* reserved */
    aml_append(scope, aml_name_decl("_S5", pkg));
    aml_append(dsdt, scope);
    /* create fw_cfg node, unconditionally */
    {
        /* when using port i/o, the 8-bit data register *always* overlaps
         * with half of the 16-bit control register. Hence, the total size
         * of the i/o region used is FW_CFG_CTL_SIZE; when using DMA, the
         * DMA control register is located at FW_CFG_DMA_IO_BASE + 4 */
        uint8_t io_size = object_property_get_bool(OBJECT(pcms->fw_cfg),
                                                   "dma_enabled", NULL) ?
                          ROUND_UP(FW_CFG_CTL_SIZE, 4) + sizeof(dma_addr_t) :
                          FW_CFG_CTL_SIZE;
        scope = aml_scope("\\_SB.PCI0");
        dev = aml_device("FWCF");
        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0002")));
        /* device present, functioning, decoding, not shown in UI */
        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
        crs = aml_resource_template();
        aml_append(crs,
            aml_io(AML_DECODE16, FW_CFG_IO_BASE, FW_CFG_IO_BASE, 0x01, io_size)
        );
        aml_append(dev, aml_name_decl("_CRS", crs));
        aml_append(scope, dev);
        aml_append(dsdt, scope);
    if (misc->applesmc_io_base) {
        scope = aml_scope("\\_SB.PCI0.ISA");
        dev = aml_device("SMC");
        aml_append(dev, aml_name_decl("_HID", aml_eisaid("APP0001")));
        /* device present, functioning, decoding, not shown in UI */
        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
        crs = aml_resource_template();
        aml_append(crs,
            aml_io(AML_DECODE16, misc->applesmc_io_base, misc->applesmc_io_base,
                   0x01, APPLESMC_MAX_DATA_LENGTH)
        );
        aml_append(crs, aml_irq_no_flags(6));
        aml_append(dev, aml_name_decl("_CRS", crs));
        aml_append(scope, dev);
        aml_append(dsdt, scope);
    if (misc->pvpanic_port) {
        scope = aml_scope("\\_SB.PCI0.ISA");
        dev = aml_device("PEVT");
        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0001")));
        crs = aml_resource_template();
        aml_append(crs,
            aml_io(AML_DECODE16, misc->pvpanic_port, misc->pvpanic_port, 1, 1)
        );
        aml_append(dev, aml_name_decl("_CRS", crs));
        aml_append(dev, aml_operation_region("PEOR", AML_SYSTEM_IO,
                                              aml_int(misc->pvpanic_port), 1));
        field = aml_field("PEOR", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);
        aml_append(field, aml_named_field("PEPT", 8));
        aml_append(dev, field);
        /* device present, functioning, decoding, shown in UI */
        aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));
        method = aml_method("RDPT", 0, AML_NOTSERIALIZED);
        aml_append(method, aml_store(aml_name("PEPT"), aml_local(0)));
        aml_append(method, aml_return(aml_local(0)));
        aml_append(dev, method);
        method = aml_method("WRPT", 1, AML_NOTSERIALIZED);
        aml_append(method, aml_store(aml_arg(0), aml_name("PEPT")));
        aml_append(dev, method);
        aml_append(scope, dev);
        aml_append(dsdt, scope);
    sb_scope = aml_scope("\\_SB");
    {
        build_processor_devices(sb_scope, machine, pm);
        build_memory_devices(sb_scope, nr_mem, pm->mem_hp_io_base,
                             pm->mem_hp_io_len);
        {
            Object *pci_host;
            PCIBus *bus = NULL;
            pci_host = acpi_get_i386_pci_host();
            if (pci_host) {
                bus = PCI_HOST_BRIDGE(pci_host)->bus;
            if (bus) {
                Aml *scope = aml_scope("PCI0");
                /* Scan all PCI buses. Generate tables to support hotplug. */
                build_append_pci_bus_devices(scope, bus, pm->pcihp_bridge_en);
                    dev = aml_device("ISA.TPM");
                    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C31")));
                    aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));
                    crs = aml_resource_template();
                    aml_append(crs, aml_irq_no_flags(TPM_TIS_IRQ));
                    aml_append(dev, aml_name_decl("_CRS", crs));
                    aml_append(scope, dev);
                aml_append(sb_scope, scope);
        aml_append(dsdt, sb_scope);
    /* copy AML table into ACPI tables blob and patch header there */
    g_array_append_vals(table_data, dsdt->buf->data, dsdt->buf->len);
    build_header(linker, table_data,
        (void *)(table_data->data + table_data->len - dsdt->buf->len),
        "DSDT", dsdt->buf->len, 1, NULL, NULL);
    free_aml_allocator();


static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)

{

    AVDictionary **meta_in = NULL;

    AVDictionary **meta_out;

    int i, ret = 0;

    char type_in, type_out;

    const char *istream_spec = NULL, *ostream_spec = NULL;

    int idx_in = 0, idx_out = 0;

    parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);

    parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);

    if (type_in == 'g' || type_out == 'g')

        o->metadata_global_manual = 1;

    if (type_in == 's' || type_out == 's')

        o->metadata_streams_manual = 1;

    if (type_in == 'c' || type_out == 'c')

        o->metadata_chapters_manual = 1;

#define METADATA_CHECK_INDEX(index, nb_elems, desc)\

    if ((index) < 0 || (index) >= (nb_elems)) {\

        av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\

                (desc), (index));\

        exit_program(1);\

    }

#define SET_DICT(type, meta, context, index)\

        switch (type) {\

        case 'g':\

            meta = &context->metadata;\

            break;\

        case 'c':\

            METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\

            meta = &context->chapters[index]->metadata;\

            break;\

        case 'p':\

            METADATA_CHECK_INDEX(index, context->nb_programs, "program")\

            meta = &context->programs[index]->metadata;\

            break;\

        }\

    SET_DICT(type_in, meta_in, ic, idx_in);

    SET_DICT(type_out, meta_out, oc, idx_out);

    /* for input streams choose first matching stream */

    if (type_in == 's') {

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

            if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {

                meta_in = &ic->streams[i]->metadata;

                break;

            } else if (ret < 0)

                exit_program(1);

        }

        if (!meta_in) {

            av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match  any streams.\n", istream_spec);

            exit_program(1);

        }

    }

    if (type_out == 's') {

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

            if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {

                meta_out = &oc->streams[i]->metadata;

                av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);

            } else if (ret < 0)

                exit_program(1);

        }

    } else

        av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);

    return 0;

}


static uint32_t rtl8139_io_readw(void *opaque, uint8_t addr)

{

    RTL8139State *s = opaque;

    uint32_t ret;

    switch (addr)

    {

        case TxAddr0 ... TxAddr0+4*4-1:

            ret = rtl8139_TxStatus_read(s, addr, 2);

            break;

        case IntrMask:

            ret = rtl8139_IntrMask_read(s);

            break;

        case IntrStatus:

            ret = rtl8139_IntrStatus_read(s);

            break;

        case MultiIntr:

            ret = rtl8139_MultiIntr_read(s);

            break;

        case RxBufPtr:

            ret = rtl8139_RxBufPtr_read(s);

            break;

        case RxBufAddr:

            ret = rtl8139_RxBufAddr_read(s);

            break;

        case BasicModeCtrl:

            ret = rtl8139_BasicModeCtrl_read(s);

            break;

        case BasicModeStatus:

            ret = rtl8139_BasicModeStatus_read(s);

            break;

        case NWayAdvert:

            ret = s->NWayAdvert;

            DPRINTF("NWayAdvert read(w) val=0x%04x\n", ret);

            break;

        case NWayLPAR:

            ret = s->NWayLPAR;

            DPRINTF("NWayLPAR read(w) val=0x%04x\n", ret);

            break;

        case NWayExpansion:

            ret = s->NWayExpansion;

            DPRINTF("NWayExpansion read(w) val=0x%04x\n", ret);

            break;

        case CpCmd:

            ret = rtl8139_CpCmd_read(s);

            break;

        case IntrMitigate:

            ret = rtl8139_IntrMitigate_read(s);

            break;

        case TxSummary:

            ret = rtl8139_TSAD_read(s);

            break;

        case CSCR:

            ret = rtl8139_CSCR_read(s);

            break;

        default:

            DPRINTF("ioport read(w) addr=0x%x via read(b)\n", addr);

            ret  = rtl8139_io_readb(opaque, addr);

            ret |= rtl8139_io_readb(opaque, addr + 1) << 8;

            DPRINTF("ioport read(w) addr=0x%x val=0x%04x\n", addr, ret);

            break;

    }

    return ret;

}


static av_always_inline void paint_raw(uint8_t *dst, int w, int h,

                                       const uint8_t *src, int bpp,

                                       int be, int stride)

{

    int i, j, p;

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

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

            p = vmnc_get_pixel(src, bpp, be);

            src += bpp;

            switch (bpp) {

            case 1:

                dst[i] = p;

                break;

            case 2:

                ((uint16_t*)dst)[i] = p;

                break;

            case 4:

                ((uint32_t*)dst)[i] = p;

                break;

            }

        }

        dst += stride;

    }

}


static int decorrelate(TAKDecContext *s, int c1, int c2, int length)

{

    GetBitContext *gb = &s->gb;

    int32_t *p1       = s->decoded[c1] + 1;

    int32_t *p2       = s->decoded[c2] + 1;

    int i;

    int dshift, dfactor;

    switch (s->dmode) {

    case 1: /* left/side */

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

            int32_t a = p1[i];

            int32_t b = p2[i];

            p2[i]     = a + b;

        }

        break;

    case 2: /* side/right */

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

            int32_t a = p1[i];

            int32_t b = p2[i];

            p1[i]     = b - a;

        }

        break;

    case 3: /* side/mid */

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

            int32_t a = p1[i];

            int32_t b = p2[i];

            a        -= b >> 1;

            p1[i]     = a;

            p2[i]     = a + b;

        }

        break;

    case 4: /* side/left with scale factor */

        FFSWAP(int32_t*, p1, p2);

    case 5: /* side/right with scale factor */

        dshift  = get_bits_esc4(gb);

        dfactor = get_sbits(gb, 10);

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

            int32_t a = p1[i];

            int32_t b = p2[i];

            b         = dfactor * (b >> dshift) + 128 >> 8 << dshift;

            p1[i]     = b - a;

        }

        break;

    case 6:

        FFSWAP(int32_t*, p1, p2);

    case 7: {

        int length2, order_half, filter_order, dval1, dval2;

        int tmp, x, code_size;

        if (length < 256)

            return AVERROR_INVALIDDATA;

        dshift       = get_bits_esc4(gb);

        filter_order = 8 << get_bits1(gb);

        dval1        = get_bits1(gb);

        dval2        = get_bits1(gb);

        AV_ZERO128(s->filter + 8);

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

            if (!(i & 3))

                code_size = 14 - get_bits(gb, 3);

            s->filter[i] = get_sbits(gb, code_size);

        }

        order_half = filter_order / 2;

        length2    = length - (filter_order - 1);

        /* decorrelate beginning samples */

        if (dval1) {

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

                int32_t a = p1[i];

                int32_t b = p2[i];

                p1[i]     = a + b;

            }

        }

        /* decorrelate ending samples */

        if (dval2) {

            for (i = length2 + order_half; i < length; i++) {

                int32_t a = p1[i];

                int32_t b = p2[i];

                p1[i]     = a + b;

            }

        }

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

            s->residues[i] = *p2++ >> dshift;

        p1 += order_half;

        x = FF_ARRAY_ELEMS(s->residues) - filter_order;

        for (; length2 > 0; length2 -= tmp) {

            tmp = FFMIN(length2, x);

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

                s->residues[filter_order + i] = *p2++ >> dshift;

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

                int v = 1 << 9;

                v += s->adsp.scalarproduct_int16(&s->residues[i], s->filter, 16);

                v = (av_clip_intp2(v >> 10, 13) << dshift) - *p1;

                *p1++ = v;

            }

            memcpy(s->residues, &s->residues[tmp], 2 * filter_order);

        }

        emms_c();

        break;

    }

    }

    return 0;

}


static void *colo_compare_thread(void *opaque)

{

    GMainContext *worker_context;

    GMainLoop *compare_loop;

    CompareState *s = opaque;

    GSource *timeout_source;

    worker_context = g_main_context_new();

    qemu_chr_fe_set_handlers(&s->chr_pri_in, compare_chr_can_read,

                             compare_pri_chr_in, NULL, s, worker_context, true);

    qemu_chr_fe_set_handlers(&s->chr_sec_in, compare_chr_can_read,

                             compare_sec_chr_in, NULL, s, worker_context, true);

    compare_loop = g_main_loop_new(worker_context, FALSE);

    /* To kick any packets that the secondary doesn't match */

    timeout_source = g_timeout_source_new(REGULAR_PACKET_CHECK_MS);

    g_source_set_callback(timeout_source,

                          (GSourceFunc)check_old_packet_regular, s, NULL);

    g_source_attach(timeout_source, worker_context);

    g_main_loop_run(compare_loop);

    g_source_unref(timeout_source);

    g_main_loop_unref(compare_loop);

    g_main_context_unref(worker_context);

    return NULL;

}


static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)

{

    char val_str[128];

    int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;

    print_section_header("format");

    print_str("filename",         fmt_ctx->filename);

    print_int("nb_streams",       fmt_ctx->nb_streams);

    print_str("format_name",      fmt_ctx->iformat->name);

    print_str("format_long_name", fmt_ctx->iformat->long_name);

    print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);

    print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);

    if (size >= 0) print_val    ("size", size, unit_byte_str);

    else           print_str_opt("size", "N/A");

    if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);

    else                       print_str_opt("bit_rate", "N/A");

    show_tags(fmt_ctx->metadata);

    print_section_footer("format");

    fflush(stdout);

}


static SchroFrame *libschroedinger_frame_from_data(AVCodecContext *avctx,

                                                   const AVFrame *frame)

{

    SchroEncoderParams *p_schro_params = avctx->priv_data;

    SchroFrame *in_frame = ff_create_schro_frame(avctx,

                                                 p_schro_params->frame_format);

    if (in_frame) {

        /* Copy input data to SchroFrame buffers (they match the ones

         * referenced by the AVFrame stored in priv) */

        if (av_frame_copy(in_frame->priv, frame) < 0) {

            av_log(avctx, AV_LOG_ERROR, "Failed to copy input data\n");

            return NULL;

        }

    }

    return in_frame;

}


static void x86_cpu_reset(CPUState *s)
{
    X86CPU *cpu = X86_CPU(s);
    X86CPUClass *xcc = X86_CPU_GET_CLASS(cpu);
    CPUX86State *env = &cpu->env;
    int i;
    xcc->parent_reset(s);
    memset(env, 0, offsetof(CPUX86State, breakpoints));
    tlb_flush(env, 1);
    env->old_exception = -1;
    /* init to reset state */
#ifdef CONFIG_SOFTMMU
    env->hflags |= HF_SOFTMMU_MASK;
#endif
    env->hflags2 |= HF2_GIF_MASK;
    cpu_x86_update_cr0(env, 0x60000010);
    env->a20_mask = ~0x0;
    env->smbase = 0x30000;
    env->idt.limit = 0xffff;
    env->gdt.limit = 0xffff;
    env->ldt.limit = 0xffff;
    env->ldt.flags = DESC_P_MASK | (2 << DESC_TYPE_SHIFT);
    env->tr.limit = 0xffff;
    env->tr.flags = DESC_P_MASK | (11 << DESC_TYPE_SHIFT);
    cpu_x86_load_seg_cache(env, R_CS, 0xf000, 0xffff0000, 0xffff,
                           DESC_P_MASK | DESC_S_MASK | DESC_CS_MASK |
                           DESC_R_MASK | DESC_A_MASK);
    cpu_x86_load_seg_cache(env, R_DS, 0, 0, 0xffff,
                           DESC_P_MASK | DESC_S_MASK | DESC_W_MASK |
                           DESC_A_MASK);
    cpu_x86_load_seg_cache(env, R_ES, 0, 0, 0xffff,
                           DESC_P_MASK | DESC_S_MASK | DESC_W_MASK |
                           DESC_A_MASK);
    cpu_x86_load_seg_cache(env, R_SS, 0, 0, 0xffff,
                           DESC_P_MASK | DESC_S_MASK | DESC_W_MASK |
                           DESC_A_MASK);
    cpu_x86_load_seg_cache(env, R_FS, 0, 0, 0xffff,
                           DESC_P_MASK | DESC_S_MASK | DESC_W_MASK |
                           DESC_A_MASK);
    cpu_x86_load_seg_cache(env, R_GS, 0, 0, 0xffff,
                           DESC_P_MASK | DESC_S_MASK | DESC_W_MASK |
                           DESC_A_MASK);
    env->eip = 0xfff0;
    env->regs[R_EDX] = env->cpuid_version;
    env->eflags = 0x2;
    /* FPU init */
    for (i = 0; i < 8; i++) {
        env->fptags[i] = 1;
    }
    env->fpuc = 0x37f;
    env->mxcsr = 0x1f80;
    env->xstate_bv = XSTATE_FP | XSTATE_SSE;
    env->pat = 0x0007040600070406ULL;
    env->msr_ia32_misc_enable = MSR_IA32_MISC_ENABLE_DEFAULT;
    memset(env->dr, 0, sizeof(env->dr));
    env->dr[6] = DR6_FIXED_1;
    env->dr[7] = DR7_FIXED_1;
    cpu_breakpoint_remove_all(env, BP_CPU);
    cpu_watchpoint_remove_all(env, BP_CPU);
#if !defined(CONFIG_USER_ONLY)
    /* We hard-wire the BSP to the first CPU. */
    if (s->cpu_index == 0) {
        apic_designate_bsp(env->apic_state);
    }
    s->halted = !cpu_is_bsp(cpu);
#endif
}


DISAS_INSN(frestore)

{

    /* TODO: Implement frestore.  */

    qemu_assert(0, "FRESTORE not implemented");

}


int ff_h264_update_thread_context(AVCodecContext *dst,

                                  const AVCodecContext *src)

{

    H264Context *h = dst->priv_data, *h1 = src->priv_data;

    int inited = h->context_initialized, err = 0;

    int context_reinitialized = 0;

    int i, ret;

    if (dst == src)

        return 0;

    if (inited &&

        (h->width                 != h1->width                 ||

         h->height                != h1->height                ||

         h->mb_width              != h1->mb_width              ||

         h->mb_height             != h1->mb_height             ||

         h->sps.bit_depth_luma    != h1->sps.bit_depth_luma    ||

         h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||

         h->sps.colorspace        != h1->sps.colorspace)) {

        /* set bits_per_raw_sample to the previous value. the check for changed

         * bit depth in h264_set_parameter_from_sps() uses it and sets it to

         * the current value */

        h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;

        h->width     = h1->width;

        h->height    = h1->height;

        h->mb_height = h1->mb_height;

        h->mb_width  = h1->mb_width;

        h->mb_num    = h1->mb_num;

        h->mb_stride = h1->mb_stride;

        h->b_stride  = h1->b_stride;

        // SPS/PPS

        if ((ret = copy_parameter_set((void **)h->sps_buffers,

                                      (void **)h1->sps_buffers,

                                      MAX_SPS_COUNT, sizeof(SPS))) < 0)

            return ret;

        h->sps = h1->sps;

        if ((ret = copy_parameter_set((void **)h->pps_buffers,

                                      (void **)h1->pps_buffers,

                                      MAX_PPS_COUNT, sizeof(PPS))) < 0)

            return ret;

        h->pps = h1->pps;

        if ((err = h264_slice_header_init(h, 1)) < 0) {

            av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed\n");

            return err;

        }

        context_reinitialized = 1;

#if 0

        h264_set_parameter_from_sps(h);

        //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted

        h->cur_chroma_format_idc = h1->cur_chroma_format_idc;

#endif

    }

    /* copy block_offset since frame_start may not be called */

    memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));

    if (!inited) {

        H264SliceContext *orig_slice_ctx = h->slice_ctx;

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

            av_freep(h->sps_buffers + i);

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

            av_freep(h->pps_buffers + i);

        ff_h264_unref_picture(h, &h->last_pic_for_ec);

        memcpy(h, h1, sizeof(H264Context));

        memset(h->sps_buffers, 0, sizeof(h->sps_buffers));

        memset(h->pps_buffers, 0, sizeof(h->pps_buffers));

        memset(&h->cur_pic, 0, sizeof(h->cur_pic));

        memset(&h->last_pic_for_ec, 0, sizeof(h->last_pic_for_ec));

        h->slice_ctx = orig_slice_ctx;

        memset(&h->slice_ctx[0].er,         0, sizeof(h->slice_ctx[0].er));

        memset(&h->slice_ctx[0].mb,         0, sizeof(h->slice_ctx[0].mb));

        memset(&h->slice_ctx[0].mb_luma_dc, 0, sizeof(h->slice_ctx[0].mb_luma_dc));

        memset(&h->slice_ctx[0].mb_padding, 0, sizeof(h->slice_ctx[0].mb_padding));

        h->avctx             = dst;

        h->DPB               = NULL;

        h->qscale_table_pool = NULL;

        h->mb_type_pool      = NULL;

        h->ref_index_pool    = NULL;

        h->motion_val_pool   = NULL;

        h->intra4x4_pred_mode= NULL;

        h->non_zero_count    = NULL;

        h->slice_table_base  = NULL;

        h->slice_table       = NULL;

        h->cbp_table         = NULL;

        h->chroma_pred_mode_table = NULL;

        memset(h->mvd_table, 0, sizeof(h->mvd_table));

        h->direct_table      = NULL;

        h->list_counts       = NULL;

        h->mb2b_xy           = NULL;

        h->mb2br_xy          = NULL;

        if (h1->context_initialized) {

        h->context_initialized = 0;

        memset(&h->cur_pic, 0, sizeof(h->cur_pic));

        av_frame_unref(&h->cur_pic.f);

        h->cur_pic.tf.f = &h->cur_pic.f;

        ret = ff_h264_alloc_tables(h);

        if (ret < 0) {

            av_log(dst, AV_LOG_ERROR, "Could not allocate memory\n");

            return ret;

        }

        ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);

        if (ret < 0) {

            av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");

            return ret;

        }

        }

        h->context_initialized = h1->context_initialized;

    }

    h->avctx->coded_height  = h1->avctx->coded_height;

    h->avctx->coded_width   = h1->avctx->coded_width;

    h->avctx->width         = h1->avctx->width;

    h->avctx->height        = h1->avctx->height;

    h->coded_picture_number = h1->coded_picture_number;

    h->first_field          = h1->first_field;

    h->picture_structure    = h1->picture_structure;

    h->droppable            = h1->droppable;

    h->low_delay            = h1->low_delay;

    for (i = 0; h->DPB && i < H264_MAX_PICTURE_COUNT; i++) {

        ff_h264_unref_picture(h, &h->DPB[i]);

        if (h1->DPB && h1->DPB[i].f.buf[0] &&

            (ret = ff_h264_ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)

            return ret;

    }

    h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);

    ff_h264_unref_picture(h, &h->cur_pic);

    if (h1->cur_pic.f.buf[0]) {

        ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic);

        if (ret < 0)

            return ret;

    }

    h->workaround_bugs = h1->workaround_bugs;

    h->low_delay       = h1->low_delay;

    h->droppable       = h1->droppable;

    // extradata/NAL handling

    h->is_avc = h1->is_avc;

    // SPS/PPS

    if ((ret = copy_parameter_set((void **)h->sps_buffers,

                                  (void **)h1->sps_buffers,

                                  MAX_SPS_COUNT, sizeof(SPS))) < 0)

        return ret;

    h->sps = h1->sps;

    if ((ret = copy_parameter_set((void **)h->pps_buffers,

                                  (void **)h1->pps_buffers,

                                  MAX_PPS_COUNT, sizeof(PPS))) < 0)

        return ret;

    h->pps = h1->pps;

    // Dequantization matrices

    // FIXME these are big - can they be only copied when PPS changes?

    copy_fields(h, h1, dequant4_buffer, dequant4_coeff);

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

        h->dequant4_coeff[i] = h->dequant4_buffer[0] +

                               (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);

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

        h->dequant8_coeff[i] = h->dequant8_buffer[0] +

                               (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);

    h->dequant_coeff_pps = h1->dequant_coeff_pps;

    // POC timing

    copy_fields(h, h1, poc_lsb, default_ref_list);

    // reference lists

    copy_fields(h, h1, short_ref, current_slice);

    copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);

    copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);

    copy_picture_range(h->delayed_pic, h1->delayed_pic,

                       MAX_DELAYED_PIC_COUNT + 2, h, h1);

    h->frame_recovered       = h1->frame_recovered;

    if (context_reinitialized)

        ff_h264_set_parameter_from_sps(h);

    if (!h->cur_pic_ptr)

        return 0;

    if (!h->droppable) {

        err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);

        h->prev_poc_msb = h->poc_msb;

        h->prev_poc_lsb = h->poc_lsb;

    }

    h->prev_frame_num_offset = h->frame_num_offset;

    h->prev_frame_num        = h->frame_num;

    h->outputed_poc          = h->next_outputed_poc;

    h->recovery_frame        = h1->recovery_frame;

    return err;

}


static inline abi_long target_to_host_semarray(int semid, unsigned short **host_array,

                                               abi_ulong target_addr)

{

    int nsems;

    unsigned short *array;

    union semun semun;

    struct semid_ds semid_ds;

    int i, ret;

    semun.buf = &semid_ds;

    ret = semctl(semid, 0, IPC_STAT, semun);

    if (ret == -1)

        return get_errno(ret);

    nsems = semid_ds.sem_nsems;

    *host_array = malloc(nsems*sizeof(unsigned short));

    array = lock_user(VERIFY_READ, target_addr,

                      nsems*sizeof(unsigned short), 1);

    if (!array)

        return -TARGET_EFAULT;

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

        __get_user((*host_array)[i], &array[i]);

    }

    unlock_user(array, target_addr, 0);

    return 0;

}


static void vga_draw_text(VGAState *s, int full_update)

{

    int cx, cy, cheight, cw, ch, cattr, height, width, ch_attr;

    int cx_min, cx_max, linesize, x_incr;

    uint32_t offset, fgcol, bgcol, v, cursor_offset;

    uint8_t *d1, *d, *src, *s1, *dest, *cursor_ptr;

    const uint8_t *font_ptr, *font_base[2];

    int dup9, line_offset, depth_index;

    uint32_t *palette;

    uint32_t *ch_attr_ptr;

    vga_draw_glyph8_func *vga_draw_glyph8;

    vga_draw_glyph9_func *vga_draw_glyph9;

    vga_dirty_log_stop(s);

    /* compute font data address (in plane 2) */

    v = s->sr[3];

    offset = (((v >> 4) & 1) | ((v << 1) & 6)) * 8192 * 4 + 2;

    if (offset != s->font_offsets[0]) {

        s->font_offsets[0] = offset;

        full_update = 1;

    }

    font_base[0] = s->vram_ptr + offset;

    offset = (((v >> 5) & 1) | ((v >> 1) & 6)) * 8192 * 4 + 2;

    font_base[1] = s->vram_ptr + offset;

    if (offset != s->font_offsets[1]) {

        s->font_offsets[1] = offset;

        full_update = 1;

    }

    if (s->plane_updated & (1 << 2)) {

        /* if the plane 2 was modified since the last display, it

           indicates the font may have been modified */

        s->plane_updated = 0;

        full_update = 1;

    }

    full_update |= update_basic_params(s);

    line_offset = s->line_offset;

    s1 = s->vram_ptr + (s->start_addr * 4);

    vga_get_text_resolution(s, &width, &height, &cw, &cheight);

    x_incr = cw * ((ds_get_bits_per_pixel(s->ds) + 7) >> 3);

    if ((height * width) > CH_ATTR_SIZE) {

        /* better than nothing: exit if transient size is too big */

        return;

    }

    if (width != s->last_width || height != s->last_height ||

        cw != s->last_cw || cheight != s->last_ch || s->last_depth) {

        s->last_scr_width = width * cw;

        s->last_scr_height = height * cheight;

        qemu_console_resize(s->ds, s->last_scr_width, s->last_scr_height);

        s->last_depth = 0;

        s->last_width = width;

        s->last_height = height;

        s->last_ch = cheight;

        s->last_cw = cw;

        full_update = 1;

    }

    s->rgb_to_pixel =

        rgb_to_pixel_dup_table[get_depth_index(s->ds)];

    full_update |= update_palette16(s);

    palette = s->last_palette;

    x_incr = cw * ((ds_get_bits_per_pixel(s->ds) + 7) >> 3);

    cursor_offset = ((s->cr[0x0e] << 8) | s->cr[0x0f]) - s->start_addr;

    if (cursor_offset != s->cursor_offset ||

        s->cr[0xa] != s->cursor_start ||

        s->cr[0xb] != s->cursor_end) {

      /* if the cursor position changed, we update the old and new

         chars */

        if (s->cursor_offset < CH_ATTR_SIZE)

            s->last_ch_attr[s->cursor_offset] = -1;

        if (cursor_offset < CH_ATTR_SIZE)

            s->last_ch_attr[cursor_offset] = -1;

        s->cursor_offset = cursor_offset;

        s->cursor_start = s->cr[0xa];

        s->cursor_end = s->cr[0xb];

    }

    cursor_ptr = s->vram_ptr + (s->start_addr + cursor_offset) * 4;

    depth_index = get_depth_index(s->ds);

    if (cw == 16)

        vga_draw_glyph8 = vga_draw_glyph16_table[depth_index];

    else

        vga_draw_glyph8 = vga_draw_glyph8_table[depth_index];

    vga_draw_glyph9 = vga_draw_glyph9_table[depth_index];

    dest = ds_get_data(s->ds);

    linesize = ds_get_linesize(s->ds);

    ch_attr_ptr = s->last_ch_attr;

    for(cy = 0; cy < height; cy++) {

        d1 = dest;

        src = s1;

        cx_min = width;

        cx_max = -1;

        for(cx = 0; cx < width; cx++) {

            ch_attr = *(uint16_t *)src;

            if (full_update || ch_attr != *ch_attr_ptr) {

                if (cx < cx_min)

                    cx_min = cx;

                if (cx > cx_max)

                    cx_max = cx;

                *ch_attr_ptr = ch_attr;

#ifdef WORDS_BIGENDIAN

                ch = ch_attr >> 8;

                cattr = ch_attr & 0xff;

#else

                ch = ch_attr & 0xff;

                cattr = ch_attr >> 8;

#endif

                font_ptr = font_base[(cattr >> 3) & 1];

                font_ptr += 32 * 4 * ch;

                bgcol = palette[cattr >> 4];

                fgcol = palette[cattr & 0x0f];

                if (cw != 9) {

                    vga_draw_glyph8(d1, linesize,

                                    font_ptr, cheight, fgcol, bgcol);

                } else {

                    dup9 = 0;

                    if (ch >= 0xb0 && ch <= 0xdf && (s->ar[0x10] & 0x04))

                        dup9 = 1;

                    vga_draw_glyph9(d1, linesize,

                                    font_ptr, cheight, fgcol, bgcol, dup9);

                }

                if (src == cursor_ptr &&

                    !(s->cr[0x0a] & 0x20)) {

                    int line_start, line_last, h;

                    /* draw the cursor */

                    line_start = s->cr[0x0a] & 0x1f;

                    line_last = s->cr[0x0b] & 0x1f;

                    /* XXX: check that */

                    if (line_last > cheight - 1)

                        line_last = cheight - 1;

                    if (line_last >= line_start && line_start < cheight) {

                        h = line_last - line_start + 1;

                        d = d1 + linesize * line_start;

                        if (cw != 9) {

                            vga_draw_glyph8(d, linesize,

                                            cursor_glyph, h, fgcol, bgcol);

                        } else {

                            vga_draw_glyph9(d, linesize,

                                            cursor_glyph, h, fgcol, bgcol, 1);

                        }

                    }

                }

            }

            d1 += x_incr;

            src += 4;

            ch_attr_ptr++;

        }

        if (cx_max != -1) {

            dpy_update(s->ds, cx_min * cw, cy * cheight,

                       (cx_max - cx_min + 1) * cw, cheight);

        }

        dest += linesize * cheight;

        s1 += line_offset;

    }

}


static hwaddr ppc_hash64_pteg_search(PowerPCCPU *cpu, hwaddr hash,

                                     uint32_t slb_pshift, bool secondary,

                                     target_ulong ptem, ppc_hash_pte64_t *pte)

{

    CPUPPCState *env = &cpu->env;

    int i;

    uint64_t token;

    target_ulong pte0, pte1;

    target_ulong pte_index;

    pte_index = (hash & env->htab_mask) * HPTES_PER_GROUP;

    token = ppc_hash64_start_access(cpu, pte_index);

    if (!token) {

        return -1;

    }

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

        pte0 = ppc_hash64_load_hpte0(cpu, token, i);

        pte1 = ppc_hash64_load_hpte1(cpu, token, i);

        if ((pte0 & HPTE64_V_VALID)

            && (secondary == !!(pte0 & HPTE64_V_SECONDARY))

            && HPTE64_V_COMPARE(pte0, ptem)) {

            uint32_t pshift = ppc_hash64_pte_size_decode(pte1, slb_pshift);

            if (pshift == 0) {

                continue;

            }

            /* We don't do anything with pshift yet as qemu TLB only deals

             * with 4K pages anyway

             */

            pte->pte0 = pte0;

            pte->pte1 = pte1;

            ppc_hash64_stop_access(cpu, token);

            return (pte_index + i) * HASH_PTE_SIZE_64;

        }

    }

    ppc_hash64_stop_access(cpu, token);

    /*

     * We didn't find a valid entry.

     */

    return -1;

}


int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,

                        Error **errp)

{

    int ret = -1;

    Error *local_err = NULL;

    BlockDriver *drv;

    QemuOpts *opts;

    const char *value;

    bool read_only;

    assert(reopen_state != NULL);

    assert(reopen_state->bs->drv != NULL);

    drv = reopen_state->bs->drv;

    /* Process generic block layer options */

    opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto error;

    }

    update_flags_from_options(&reopen_state->flags, opts);

    /* node-name and driver must be unchanged. Put them back into the QDict, so

     * that they are checked at the end of this function. */

    value = qemu_opt_get(opts, "node-name");

    if (value) {

        qdict_put_str(reopen_state->options, "node-name", value);

    }

    value = qemu_opt_get(opts, "driver");

    if (value) {

        qdict_put_str(reopen_state->options, "driver", value);

    }

    /* If we are to stay read-only, do not allow permission change

     * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is

     * not set, or if the BDS still has copy_on_read enabled */

    read_only = !(reopen_state->flags & BDRV_O_RDWR);

    ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto error;

    }

    /* Calculate required permissions after reopening */

    bdrv_reopen_perm(queue, reopen_state->bs,

                     &reopen_state->perm, &reopen_state->shared_perm);

    ret = bdrv_flush(reopen_state->bs);

    if (ret) {

        error_setg_errno(errp, -ret, "Error flushing drive");

        goto error;

    }

    if (drv->bdrv_reopen_prepare) {

        ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);

        if (ret) {

            if (local_err != NULL) {

                error_propagate(errp, local_err);

            } else {

                error_setg(errp, "failed while preparing to reopen image '%s'",

                           reopen_state->bs->filename);

            }

            goto error;

        }

    } else {

        /* It is currently mandatory to have a bdrv_reopen_prepare()

         * handler for each supported drv. */

        error_setg(errp, "Block format '%s' used by node '%s' "

                   "does not support reopening files", drv->format_name,

                   bdrv_get_device_or_node_name(reopen_state->bs));

        ret = -1;

        goto error;

    }

    /* Options that are not handled are only okay if they are unchanged

     * compared to the old state. It is expected that some options are only

     * used for the initial open, but not reopen (e.g. filename) */

    if (qdict_size(reopen_state->options)) {

        const QDictEntry *entry = qdict_first(reopen_state->options);

        do {

            QString *new_obj = qobject_to_qstring(entry->value);

            const char *new = qstring_get_str(new_obj);

            /*

             * Caution: while qdict_get_try_str() is fine, getting

             * non-string types would require more care.  When

             * bs->options come from -blockdev or blockdev_add, its

             * members are typed according to the QAPI schema, but

             * when they come from -drive, they're all QString.

             */

            const char *old = qdict_get_try_str(reopen_state->bs->options,

                                                entry->key);

            if (!old || strcmp(new, old)) {

                error_setg(errp, "Cannot change the option '%s'", entry->key);

                ret = -EINVAL;

                goto error;

            }

        } while ((entry = qdict_next(reopen_state->options, entry)));

    }

    ret = bdrv_check_perm(reopen_state->bs, queue, reopen_state->perm,

                          reopen_state->shared_perm, NULL, errp);

    if (ret < 0) {

        goto error;

    }

    ret = 0;

error:

    qemu_opts_del(opts);

    return ret;

}


static av_cold int g722_encode_close(AVCodecContext *avctx)

{

    G722Context *c = avctx->priv_data;

    int i;

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

        av_freep(&c->paths[i]);

        av_freep(&c->node_buf[i]);

        av_freep(&c->nodep_buf[i]);

    }

    return 0;

}


static int asf_get_packet(AVFormatContext *s)

{

    ASFContext *asf = s->priv_data;

    ByteIOContext *pb = &s->pb;

    uint32_t packet_length, padsize;

    int rsize = 9;

    int c;

    c = get_byte(pb);

    if (c != 0x82) {

        if (!url_feof(pb))

            av_log(s, AV_LOG_ERROR, "ff asf bad header %x  at:%"PRId64"\n", c, url_ftell(pb));

    }

    if ((c & 0x0f) == 2) { // always true for now

        if (get_le16(pb) != 0) {

            if (!url_feof(pb))

                av_log(s, AV_LOG_ERROR, "ff asf bad non zero\n");

            return AVERROR_IO;

        }

        rsize+=2;

/*    }else{

        if (!url_feof(pb))

            printf("ff asf bad header %x  at:%"PRId64"\n", c, url_ftell(pb));

        return AVERROR_IO;*/

    }

    asf->packet_flags = get_byte(pb);

    asf->packet_property = get_byte(pb);

    DO_2BITS(asf->packet_flags >> 5, packet_length, asf->packet_size);

    DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored

    DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length

    //the following checks prevent overflows and infinite loops

    if(packet_length >= (1U<<29)){

        av_log(s, AV_LOG_ERROR, "invalid packet_length %d at:%"PRId64"\n", packet_length, url_ftell(pb));

        return -1;

    }

    if(padsize >= (1U<<29)){

        av_log(s, AV_LOG_ERROR, "invalid padsize %d at:%"PRId64"\n", padsize, url_ftell(pb));

        return -1;

    }

    asf->packet_timestamp = get_le32(pb);

    get_le16(pb); /* duration */

    // rsize has at least 11 bytes which have to be present

    if (asf->packet_flags & 0x01) {

        asf->packet_segsizetype = get_byte(pb); rsize++;

        asf->packet_segments = asf->packet_segsizetype & 0x3f;

    } else {

        asf->packet_segments = 1;

        asf->packet_segsizetype = 0x80;

    }

    asf->packet_size_left = packet_length - padsize - rsize;

    if (packet_length < asf->hdr.min_pktsize)

        padsize += asf->hdr.min_pktsize - packet_length;

    asf->packet_padsize = padsize;

#ifdef DEBUG

    printf("packet: size=%d padsize=%d  left=%d\n", asf->packet_size, asf->packet_padsize, asf->packet_size_left);

#endif

    return 0;

}


static void new_video_stream(AVFormatContext *oc, int file_idx)

{

    AVStream *st;

    OutputStream *ost;

    AVCodecContext *video_enc;

    enum CodecID codec_id = CODEC_ID_NONE;

    AVCodec *codec= NULL;

    if(!video_stream_copy){

        if (video_codec_name) {

            codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1,

                                         avcodec_opts[AVMEDIA_TYPE_VIDEO]->strict_std_compliance);

            codec = avcodec_find_encoder_by_name(video_codec_name);

        } else {

            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);

            codec = avcodec_find_encoder(codec_id);

        }

    }

    ost = new_output_stream(oc, file_idx, codec);

    st  = ost->st;

    if (!video_stream_copy) {

        ost->frame_aspect_ratio = frame_aspect_ratio;

        frame_aspect_ratio = 0;

#if CONFIG_AVFILTER

        ost->avfilter= vfilters;

        vfilters = NULL;

#endif

    }

    ost->bitstream_filters = video_bitstream_filters;

    video_bitstream_filters= NULL;

    st->codec->thread_count= thread_count;

    video_enc = st->codec;

    if(video_codec_tag)

        video_enc->codec_tag= video_codec_tag;

    if(oc->oformat->flags & AVFMT_GLOBALHEADER) {

        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;

    }

    if (video_stream_copy) {

        st->stream_copy = 1;

        video_enc->codec_type = AVMEDIA_TYPE_VIDEO;

        video_enc->sample_aspect_ratio =

        st->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);

    } else {

        const char *p;

        int i;

        if (frame_rate.num)

            ost->frame_rate = frame_rate;

        video_enc->codec_id = codec_id;

        set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);

        video_enc->width = frame_width;

        video_enc->height = frame_height;

        video_enc->pix_fmt = frame_pix_fmt;

        st->sample_aspect_ratio = video_enc->sample_aspect_ratio;

        if (intra_only)

            video_enc->gop_size = 0;

        if (video_qscale || same_quality) {

            video_enc->flags |= CODEC_FLAG_QSCALE;

            video_enc->global_quality = FF_QP2LAMBDA * video_qscale;

        }

        if(intra_matrix)

            video_enc->intra_matrix = intra_matrix;

        if(inter_matrix)

            video_enc->inter_matrix = inter_matrix;

        p= video_rc_override_string;

        for(i=0; p; i++){

            int start, end, q;

            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);

            if(e!=3){

                fprintf(stderr, "error parsing rc_override\n");

                ffmpeg_exit(1);

            }

            video_enc->rc_override=

                av_realloc(video_enc->rc_override,

                           sizeof(RcOverride)*(i+1));

            video_enc->rc_override[i].start_frame= start;

            video_enc->rc_override[i].end_frame  = end;

            if(q>0){

                video_enc->rc_override[i].qscale= q;

                video_enc->rc_override[i].quality_factor= 1.0;

            }

            else{

                video_enc->rc_override[i].qscale= 0;

                video_enc->rc_override[i].quality_factor= -q/100.0;

            }

            p= strchr(p, '/');

            if(p) p++;

        }

        video_enc->rc_override_count=i;

        if (!video_enc->rc_initial_buffer_occupancy)

            video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;

        video_enc->me_threshold= me_threshold;

        video_enc->intra_dc_precision= intra_dc_precision - 8;

        if (do_psnr)

            video_enc->flags|= CODEC_FLAG_PSNR;

        /* two pass mode */

        if (do_pass) {

            if (do_pass == 1) {

                video_enc->flags |= CODEC_FLAG_PASS1;

            } else {

                video_enc->flags |= CODEC_FLAG_PASS2;

            }

        }

        if (forced_key_frames)

            parse_forced_key_frames(forced_key_frames, ost, video_enc);

    }

    if (video_language) {

        av_dict_set(&st->metadata, "language", video_language, 0);

        av_freep(&video_language);

    }

    /* reset some key parameters */

    video_disable = 0;

    av_freep(&video_codec_name);

    av_freep(&forced_key_frames);

    video_stream_copy = 0;

    frame_pix_fmt = PIX_FMT_NONE;

}


static GSList *gd_vc_vte_init(GtkDisplayState *s, VirtualConsole *vc,

                              CharDriverState *chr, int idx,

                              GSList *group, GtkWidget *view_menu)

{

    char buffer[32];

    GtkWidget *box;

    GtkWidget *scrollbar;

    GtkAdjustment *vadjustment;

    VirtualConsole *tmp_vc = chr->opaque;

    vc->s = s;

    vc->vte.echo = tmp_vc->vte.echo;

    vc->vte.chr = chr;

    chr->opaque = vc;

    g_free(tmp_vc);

    snprintf(buffer, sizeof(buffer), "vc%d", idx);

    vc->label = g_strdup_printf("%s", vc->vte.chr->label

                                ? vc->vte.chr->label : buffer);

    group = gd_vc_menu_init(s, vc, idx, group, view_menu);

    vc->vte.terminal = vte_terminal_new();

    g_signal_connect(vc->vte.terminal, "commit", G_CALLBACK(gd_vc_in), vc);

    /* The documentation says that the default is UTF-8, but actually it is

     * 7-bit ASCII at least in VTE 0.38.

     */

#if VTE_CHECK_VERSION(0, 40, 0)

    vte_terminal_set_encoding(VTE_TERMINAL(vc->vte.terminal), "UTF-8", NULL);

#else

    vte_terminal_set_encoding(VTE_TERMINAL(vc->vte.terminal), "UTF-8");

#endif

    vte_terminal_set_scrollback_lines(VTE_TERMINAL(vc->vte.terminal), -1);

    vte_terminal_set_size(VTE_TERMINAL(vc->vte.terminal),

                          VC_TERM_X_MIN, VC_TERM_Y_MIN);

#if VTE_CHECK_VERSION(0, 28, 0) && GTK_CHECK_VERSION(3, 0, 0)

    vadjustment = gtk_scrollable_get_vadjustment

        (GTK_SCROLLABLE(vc->vte.terminal));

#else

    vadjustment = vte_terminal_get_adjustment(VTE_TERMINAL(vc->vte.terminal));

#endif

#if GTK_CHECK_VERSION(3, 0, 0)

    box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);

    scrollbar = gtk_scrollbar_new(GTK_ORIENTATION_VERTICAL, vadjustment);

#else

    box = gtk_hbox_new(false, 2);

    scrollbar = gtk_vscrollbar_new(vadjustment);

#endif

    gtk_box_pack_start(GTK_BOX(box), vc->vte.terminal, TRUE, TRUE, 0);

    gtk_box_pack_start(GTK_BOX(box), scrollbar, FALSE, FALSE, 0);

    vc->vte.box = box;

    vc->vte.scrollbar = scrollbar;

    g_signal_connect(vadjustment, "changed",

                     G_CALLBACK(gd_vc_adjustment_changed), vc);

    vc->type = GD_VC_VTE;

    vc->tab_item = box;

    vc->focus = vc->vte.terminal;

    gtk_notebook_append_page(GTK_NOTEBOOK(s->notebook), vc->tab_item,

                             gtk_label_new(vc->label));

    qemu_chr_be_generic_open(vc->vte.chr);

    if (vc->vte.chr->init) {

        vc->vte.chr->init(vc->vte.chr);

    }

    return group;

}


int qemu_opt_foreach(QemuOpts *opts, qemu_opt_loopfunc func, void *opaque,

                     int abort_on_failure)

{

    QemuOpt *opt;

    int rc = 0;

    TAILQ_FOREACH(opt, &opts->head, next) {

        rc = func(opt->name, opt->str, opaque);

        if (abort_on_failure  &&  rc != 0)

            break;

    }

    return rc;

}


static void build_fadt(GArray *table_data, BIOSLinker *linker,

                       VirtMachineState *vms, unsigned dsdt_tbl_offset)

{

    AcpiFadtDescriptorRev5_1 *fadt = acpi_data_push(table_data, sizeof(*fadt));

    unsigned dsdt_entry_offset = (char *)&fadt->dsdt - table_data->data;

    uint16_t bootflags;

    switch (vms->psci_conduit) {

    case QEMU_PSCI_CONDUIT_DISABLED:

        bootflags = 0;

        break;

    case QEMU_PSCI_CONDUIT_HVC:

        bootflags = ACPI_FADT_ARM_PSCI_COMPLIANT | ACPI_FADT_ARM_PSCI_USE_HVC;

        break;

    case QEMU_PSCI_CONDUIT_SMC:

        bootflags = ACPI_FADT_ARM_PSCI_COMPLIANT;

        break;

    default:

        g_assert_not_reached();

    }

    /* Hardware Reduced = 1 and use PSCI 0.2+ */

    fadt->flags = cpu_to_le32(1 << ACPI_FADT_F_HW_REDUCED_ACPI);

    fadt->arm_boot_flags = cpu_to_le16(bootflags);

    /* ACPI v5.1 (fadt->revision.fadt->minor_revision) */

    fadt->minor_revision = 0x1;

    /* DSDT address to be filled by Guest linker */

    bios_linker_loader_add_pointer(linker,

        ACPI_BUILD_TABLE_FILE, dsdt_entry_offset, sizeof(fadt->dsdt),

        ACPI_BUILD_TABLE_FILE, dsdt_tbl_offset);

    build_header(linker, table_data,

                 (void *)fadt, "FACP", sizeof(*fadt), 5, NULL, NULL);

}


static void vfio_pci_size_rom(VFIOPCIDevice *vdev)

{

    uint32_t orig, size = cpu_to_le32((uint32_t)PCI_ROM_ADDRESS_MASK);

    off_t offset = vdev->config_offset + PCI_ROM_ADDRESS;

    DeviceState *dev = DEVICE(vdev);

    char name[32];

    int fd = vdev->vbasedev.fd;

    if (vdev->pdev.romfile || !vdev->pdev.rom_bar) {

        /* Since pci handles romfile, just print a message and return */

        if (vfio_blacklist_opt_rom(vdev) && vdev->pdev.romfile) {

            error_printf("Warning : Device at %04x:%02x:%02x.%x "

                         "is known to cause system instability issues during "

                         "option rom execution. "

                         "Proceeding anyway since user specified romfile\n",

                         vdev->host.domain, vdev->host.bus, vdev->host.slot,

                         vdev->host.function);

        }

        return;

    }

    /*

     * Use the same size ROM BAR as the physical device.  The contents

     * will get filled in later when the guest tries to read it.

     */

    if (pread(fd, &orig, 4, offset) != 4 ||

        pwrite(fd, &size, 4, offset) != 4 ||

        pread(fd, &size, 4, offset) != 4 ||

        pwrite(fd, &orig, 4, offset) != 4) {

        error_report("%s(%04x:%02x:%02x.%x) failed: %m",

                     __func__, vdev->host.domain, vdev->host.bus,

                     vdev->host.slot, vdev->host.function);

        return;

    }

    size = ~(le32_to_cpu(size) & PCI_ROM_ADDRESS_MASK) + 1;

    if (!size) {

        return;

    }

    if (vfio_blacklist_opt_rom(vdev)) {

        if (dev->opts && qemu_opt_get(dev->opts, "rombar")) {

            error_printf("Warning : Device at %04x:%02x:%02x.%x "

                         "is known to cause system instability issues during "

                         "option rom execution. "

                         "Proceeding anyway since user specified non zero value for "

                         "rombar\n",

                         vdev->host.domain, vdev->host.bus, vdev->host.slot,

                         vdev->host.function);

        } else {

            error_printf("Warning : Rom loading for device at "

                         "%04x:%02x:%02x.%x has been disabled due to "

                         "system instability issues. "

                         "Specify rombar=1 or romfile to force\n",

                         vdev->host.domain, vdev->host.bus, vdev->host.slot,

                         vdev->host.function);

            return;

        }

    }

    trace_vfio_pci_size_rom(vdev->vbasedev.name, size);

    snprintf(name, sizeof(name), "vfio[%04x:%02x:%02x.%x].rom",

             vdev->host.domain, vdev->host.bus, vdev->host.slot,

             vdev->host.function);

    memory_region_init_io(&vdev->pdev.rom, OBJECT(vdev),

                          &vfio_rom_ops, vdev, name, size);

    pci_register_bar(&vdev->pdev, PCI_ROM_SLOT,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &vdev->pdev.rom);

    vdev->pdev.has_rom = true;

    vdev->rom_read_failed = false;

}


void ff_check_pixfmt_descriptors(void){

    int i, j;

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

        const AVPixFmtDescriptor *d = &av_pix_fmt_descriptors[i];

        if (!d->name && !d->nb_components && !d->log2_chroma_w && !d->log2_chroma_h && !d->flags)

            continue;

//         av_log(NULL, AV_LOG_DEBUG, "Checking: %s\n", d->name);

        av_assert0(d->log2_chroma_w <= 3);

        av_assert0(d->log2_chroma_h <= 3);

        av_assert0(d->nb_components <= 4);

        av_assert0(d->name && d->name[0]);

        av_assert0((d->nb_components==4 || d->nb_components==2) == !!(d->flags & PIX_FMT_ALPHA));

        av_assert2(av_get_pix_fmt(d->name) == i);

        for (j=0; j<FF_ARRAY_ELEMS(d->comp); j++) {

            const AVComponentDescriptor *c = &d->comp[j];

            if(j>=d->nb_components)

                av_assert0(!c->plane && !c->step_minus1 && !c->offset_plus1 && !c->shift && !c->depth_minus1);

        }

    }

}


static int vt82c686b_initfn(PCIDevice *d)

{

    uint8_t *pci_conf;

    uint8_t *wmask;

    int i;

    isa_bus_new(&d->qdev);

    pci_conf = d->config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_VIA);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_VIA_ISA_BRIDGE);

    pci_config_set_class(pci_conf, PCI_CLASS_BRIDGE_ISA);

    pci_config_set_prog_interface(pci_conf, 0x0);

    pci_config_set_revision(pci_conf,0x40); /* Revision 4.0 */

    wmask = d->wmask;

    for (i = 0x00; i < 0xff; i++) {

       if (i<=0x03 || (i>=0x08 && i<=0x3f)) {

           wmask[i] = 0x00;

       }

    }

    qemu_register_reset(vt82c686b_reset, d);

    return 0;

}


static int handle_diag(S390CPU *cpu, struct kvm_run *run, uint32_t ipb)

{

    int r = 0;

    uint16_t func_code;

    /*

     * For any diagnose call we support, bits 48-63 of the resulting

     * address specify the function code; the remainder is ignored.

     */

    func_code = decode_basedisp_rs(&cpu->env, ipb) & DIAG_KVM_CODE_MASK;

    switch (func_code) {

    case DIAG_IPL:

        kvm_handle_diag_308(cpu, run);

        break;

    case DIAG_KVM_HYPERCALL:

        r = handle_hypercall(cpu, run);

        break;

    case DIAG_KVM_BREAKPOINT:

        r = handle_sw_breakpoint(cpu, run);

        break;

    default:

        DPRINTF("KVM: unknown DIAG: 0x%x\n", func_code);

        r = -1;

        break;

    }

    return r;

}


static bool vring_notify(VirtIODevice *vdev, VirtQueue *vq)

{

    uint16_t old, new;

    bool v;

    /* We need to expose used array entries before checking used event. */

    smp_mb();

    /* Always notify when queue is empty (when feature acknowledge) */

    if (virtio_has_feature(vdev, VIRTIO_F_NOTIFY_ON_EMPTY) &&

        !vq->inuse && vring_avail_idx(vq) == vq->last_avail_idx) {

        return true;

    }

    if (!virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {

        return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT);

    }

    v = vq->signalled_used_valid;

    vq->signalled_used_valid = true;

    old = vq->signalled_used;

    new = vq->signalled_used = vring_used_idx(vq);

    return !v || vring_need_event(vring_get_used_event(vq), new, old);

}


static void kvm_do_inject_x86_mce(void *_data)

{

    struct kvm_x86_mce_data *data = _data;

    int r;

    /* If there is an MCE exception being processed, ignore this SRAO MCE */

    if ((data->env->mcg_cap & MCG_SER_P) &&

        !(data->mce->status & MCI_STATUS_AR)) {

        r = kvm_mce_in_exception(data->env);

        if (r == -1) {

            fprintf(stderr, "Failed to get MCE status\n");

        } else if (r) {

            return;

        }

    }

    r = kvm_set_mce(data->env, data->mce);

    if (r < 0) {

        perror("kvm_set_mce FAILED");

        if (data->abort_on_error) {

            abort();

        }

    }

}


void bareetraxfs_init (ram_addr_t ram_size, int vga_ram_size,

                       const char *boot_device, DisplayState *ds,

                       const char *kernel_filename, const char *kernel_cmdline,

                       const char *initrd_filename, const char *cpu_model)

{

    CPUState *env;

    struct etraxfs_pic *pic;

    void *etraxfs_dmac;

    struct etraxfs_dma_client *eth[2] = {NULL, NULL};

    int kernel_size;

    int i;

    ram_addr_t phys_ram;

    ram_addr_t phys_flash;

    ram_addr_t phys_intmem;

    /* init CPUs */

    if (cpu_model == NULL) {

        cpu_model = "crisv32";

    }

    env = cpu_init(cpu_model);

    qemu_register_reset(main_cpu_reset, env);

    /* allocate RAM */

    phys_ram = qemu_ram_alloc(ram_size);

    cpu_register_physical_memory(0x40000000, ram_size, phys_ram | IO_MEM_RAM);

    /* The ETRAX-FS has 128Kb on chip ram, the docs refer to it as the

       internal memory.  */

    phys_intmem = qemu_ram_alloc(INTMEM_SIZE);

    cpu_register_physical_memory(0x38000000, INTMEM_SIZE,

                                 phys_intmem | IO_MEM_RAM);

    phys_flash = qemu_ram_alloc(FLASH_SIZE);

    i = drive_get_index(IF_PFLASH, 0, 0);

    pflash_cfi02_register(0x0, phys_flash,

                          i != -1 ? drives_table[i].bdrv : NULL, (64 * 1024),

                          FLASH_SIZE >> 16,

                          1, 2, 0x0000, 0x0000, 0x0000, 0x0000,

                          0x555, 0x2aa);

    pic = etraxfs_pic_init(env, 0x3001c000);

    etraxfs_dmac = etraxfs_dmac_init(env, 0x30000000, 10);

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

        /* On ETRAX, odd numbered channels are inputs.  */

        etraxfs_dmac_connect(etraxfs_dmac, i, pic->irq + 7 + i, i & 1);

    }

    /* Add the two ethernet blocks.  */

    eth[0] = etraxfs_eth_init(&nd_table[0], env, pic->irq + 25, 0x30034000);

    if (nb_nics > 1)

        eth[1] = etraxfs_eth_init(&nd_table[1], env, pic->irq + 26, 0x30036000);

    /* The DMA Connector block is missing, hardwire things for now.  */

    etraxfs_dmac_connect_client(etraxfs_dmac, 0, eth[0]);

    etraxfs_dmac_connect_client(etraxfs_dmac, 1, eth[0] + 1);

    if (eth[1]) {

        etraxfs_dmac_connect_client(etraxfs_dmac, 6, eth[1]);

        etraxfs_dmac_connect_client(etraxfs_dmac, 7, eth[1] + 1);

    }

    /* 2 timers.  */

    etraxfs_timer_init(env, pic->irq + 0x1b, pic->nmi + 1, 0x3001e000);

    etraxfs_timer_init(env, pic->irq + 0x1b, pic->nmi + 1, 0x3005e000);

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

        if (serial_hds[i]) {

            etraxfs_ser_init(env, pic->irq + 0x14 + i,

                             serial_hds[i], 0x30026000 + i * 0x2000);

        }

    }

    if (kernel_filename) {

        uint64_t entry, high;

        int kcmdline_len;

        /* Boots a kernel elf binary, os/linux-2.6/vmlinux from the axis

           devboard SDK.  */

        kernel_size = load_elf(kernel_filename, -0x80000000LL,

                               &entry, NULL, &high);

        bootstrap_pc = entry;

        if (kernel_size < 0) {

            /* Takes a kimage from the axis devboard SDK.  */

            kernel_size = load_image(kernel_filename, phys_ram_base + 0x4000);

            bootstrap_pc = 0x40004000;

            env->regs[9] = 0x40004000 + kernel_size;

        }

        env->regs[8] = 0x56902387; /* RAM init magic.  */

        if (kernel_cmdline && (kcmdline_len = strlen(kernel_cmdline))) {

            if (kcmdline_len > 256) {

                fprintf(stderr, "Too long CRIS kernel cmdline (max 256)\n");

                exit(1);

            }

            pstrcpy_targphys(high, 256, kernel_cmdline);

            /* Let the kernel know we are modifying the cmdline.  */

            env->regs[10] = 0x87109563;

            env->regs[11] = high;

        }

    }

    env->pc = bootstrap_pc;

    printf ("pc =%x\n", env->pc);

    printf ("ram size =%ld\n", ram_size);

}


static void tcg_out_bpcc(TCGContext *s, int scond, int flags, int label)

{

    TCGLabel *l = &s->labels[label];

    int off19;

    if (l->has_value) {

        off19 = INSN_OFF19(tcg_pcrel_diff(s, l->u.value_ptr));

    } else {

        /* Make sure to preserve destinations during retranslation.  */

        off19 = *s->code_ptr & INSN_OFF19(-1);

        tcg_out_reloc(s, s->code_ptr, R_SPARC_WDISP19, label, 0);

    }

    tcg_out_bpcc0(s, scond, flags, off19);

}


void load_kernel (CPUState *env, int ram_size, const char *kernel_filename,

		  const char *kernel_cmdline,

		  const char *initrd_filename)

{

    int64_t entry = 0;

    long kernel_size, initrd_size;

    kernel_size = load_elf(kernel_filename, VIRT_TO_PHYS_ADDEND, &entry);

    if (kernel_size >= 0) {

        if ((entry & ~0x7fffffffULL) == 0x80000000)

            entry = (int32_t)entry;

        env->PC = entry;

    } else {

        kernel_size = load_image(kernel_filename,

                                 phys_ram_base + KERNEL_LOAD_ADDR + VIRT_TO_PHYS_ADDEND);

        if (kernel_size < 0) {

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

                    kernel_filename);

            exit(1);

        }

        env->PC = KERNEL_LOAD_ADDR;

    }

    /* load initrd */

    initrd_size = 0;

    if (initrd_filename) {

        initrd_size = load_image(initrd_filename,

                                 phys_ram_base + INITRD_LOAD_ADDR + VIRT_TO_PHYS_ADDEND);

        if (initrd_size == (target_ulong) -1) {

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

                    initrd_filename);

            exit(1);

        }

    }

    /* Store command line.  */

    if (initrd_size > 0) {

        int ret;

        ret = sprintf(phys_ram_base + (16 << 20) - 256,

                      "rd_start=0x" TLSZ " rd_size=%li ",

                      INITRD_LOAD_ADDR,

                      initrd_size);

        strcpy (phys_ram_base + (16 << 20) - 256 + ret, kernel_cmdline);

    }

    else {

        strcpy (phys_ram_base + (16 << 20) - 256, kernel_cmdline);

    }

    *(int *)(phys_ram_base + (16 << 20) - 260) = tswap32 (0x12345678);

    *(int *)(phys_ram_base + (16 << 20) - 264) = tswap32 (ram_size);

}


static int posix_aio_init(void)

{

    struct sigaction act;

    PosixAioState *s;

    int fds[2];

    struct qemu_paioinit ai;

    if (posix_aio_state)

        return 0;

    s = qemu_malloc(sizeof(PosixAioState));

    sigfillset(&act.sa_mask);

    act.sa_flags = 0; /* do not restart syscalls to interrupt select() */

    act.sa_handler = aio_signal_handler;

    sigaction(SIGUSR2, &act, NULL);

    s->first_aio = NULL;

    if (pipe(fds) == -1) {

        fprintf(stderr, "failed to create pipe\n");

        return -errno;

    }

    s->rfd = fds[0];

    s->wfd = fds[1];

    fcntl(s->rfd, F_SETFL, O_NONBLOCK);

    fcntl(s->wfd, F_SETFL, O_NONBLOCK);

    qemu_aio_set_fd_handler(s->rfd, posix_aio_read, NULL, posix_aio_flush, s);

    memset(&ai, 0, sizeof(ai));

    ai.aio_threads = 64;

    ai.aio_num = 64;

    qemu_paio_init(&ai);

    posix_aio_state = s;

    return 0;

}


e1000_receive(NetClientState *nc, const uint8_t *buf, size_t size)

{

    E1000State *s = DO_UPCAST(NICState, nc, nc)->opaque;

    struct e1000_rx_desc desc;

    dma_addr_t base;

    unsigned int n, rdt;

    uint32_t rdh_start;

    uint16_t vlan_special = 0;

    uint8_t vlan_status = 0, vlan_offset = 0;

    uint8_t min_buf[MIN_BUF_SIZE];

    size_t desc_offset;

    size_t desc_size;

    size_t total_size;

    if (!(s->mac_reg[RCTL] & E1000_RCTL_EN))

        return -1;

    /* Pad to minimum Ethernet frame length */

    if (size < sizeof(min_buf)) {

        memcpy(min_buf, buf, size);

        memset(&min_buf[size], 0, sizeof(min_buf) - size);

        buf = min_buf;

        size = sizeof(min_buf);

    }

    if (!receive_filter(s, buf, size))

        return size;

    if (vlan_enabled(s) && is_vlan_packet(s, buf)) {

        vlan_special = cpu_to_le16(be16_to_cpup((uint16_t *)(buf + 14)));

        memmove((uint8_t *)buf + 4, buf, 12);

        vlan_status = E1000_RXD_STAT_VP;

        vlan_offset = 4;

        size -= 4;

    }

    rdh_start = s->mac_reg[RDH];

    desc_offset = 0;

    total_size = size + fcs_len(s);

    if (!e1000_has_rxbufs(s, total_size)) {

            set_ics(s, 0, E1000_ICS_RXO);

            return -1;

    }

    do {

        desc_size = total_size - desc_offset;

        if (desc_size > s->rxbuf_size) {

            desc_size = s->rxbuf_size;

        }

        base = rx_desc_base(s) + sizeof(desc) * s->mac_reg[RDH];

        pci_dma_read(&s->dev, base, &desc, sizeof(desc));

        desc.special = vlan_special;

        desc.status |= (vlan_status | E1000_RXD_STAT_DD);

        if (desc.buffer_addr) {

            if (desc_offset < size) {

                size_t copy_size = size - desc_offset;

                if (copy_size > s->rxbuf_size) {

                    copy_size = s->rxbuf_size;

                }

                pci_dma_write(&s->dev, le64_to_cpu(desc.buffer_addr),

                              buf + desc_offset + vlan_offset, copy_size);

            }

            desc_offset += desc_size;

            desc.length = cpu_to_le16(desc_size);

            if (desc_offset >= total_size) {

                desc.status |= E1000_RXD_STAT_EOP | E1000_RXD_STAT_IXSM;

            } else {

                /* Guest zeroing out status is not a hardware requirement.

                   Clear EOP in case guest didn't do it. */

                desc.status &= ~E1000_RXD_STAT_EOP;

            }

        } else { // as per intel docs; skip descriptors with null buf addr

            DBGOUT(RX, "Null RX descriptor!!\n");

        }

        pci_dma_write(&s->dev, base, &desc, sizeof(desc));

        if (++s->mac_reg[RDH] * sizeof(desc) >= s->mac_reg[RDLEN])

            s->mac_reg[RDH] = 0;

        s->check_rxov = 1;

        /* see comment in start_xmit; same here */

        if (s->mac_reg[RDH] == rdh_start) {

            DBGOUT(RXERR, "RDH wraparound @%x, RDT %x, RDLEN %x\n",

                   rdh_start, s->mac_reg[RDT], s->mac_reg[RDLEN]);

            set_ics(s, 0, E1000_ICS_RXO);

            return -1;

        }

    } while (desc_offset < total_size);

    s->mac_reg[GPRC]++;

    s->mac_reg[TPR]++;

    /* TOR - Total Octets Received:

     * This register includes bytes received in a packet from the <Destination

     * Address> field through the <CRC> field, inclusively.

     */

    n = s->mac_reg[TORL] + size + /* Always include FCS length. */ 4;

    if (n < s->mac_reg[TORL])

        s->mac_reg[TORH]++;

    s->mac_reg[TORL] = n;

    n = E1000_ICS_RXT0;

    if ((rdt = s->mac_reg[RDT]) < s->mac_reg[RDH])

        rdt += s->mac_reg[RDLEN] / sizeof(desc);

    if (((rdt - s->mac_reg[RDH]) * sizeof(desc)) <= s->mac_reg[RDLEN] >>

        s->rxbuf_min_shift)

        n |= E1000_ICS_RXDMT0;

    set_ics(s, 0, n);

    return size;

}


void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes,

                               unsigned int *out_bytes,

                               unsigned max_in_bytes, unsigned max_out_bytes)

{

    unsigned int idx;

    unsigned int total_bufs, in_total, out_total;

    idx = vq->last_avail_idx;

    total_bufs = in_total = out_total = 0;

    while (virtqueue_num_heads(vq, idx)) {

        unsigned int max, num_bufs, indirect = 0;

        hwaddr desc_pa;

        int i;

        max = vq->vring.num;

        num_bufs = total_bufs;

        i = virtqueue_get_head(vq, idx++);

        desc_pa = vq->vring.desc;

        if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) {

            if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) {

                error_report("Invalid size for indirect buffer table");

                exit(1);

            }

            /* If we've got too many, that implies a descriptor loop. */

            if (num_bufs >= max) {

                error_report("Looped descriptor");

                exit(1);

            }

            /* loop over the indirect descriptor table */

            indirect = 1;

            max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc);

            num_bufs = i = 0;

            desc_pa = vring_desc_addr(desc_pa, i);

        }

        do {

            /* If we've got too many, that implies a descriptor loop. */

            if (++num_bufs > max) {

                error_report("Looped descriptor");

                exit(1);

            }

            if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) {

                in_total += vring_desc_len(desc_pa, i);

            } else {

                out_total += vring_desc_len(desc_pa, i);

            }

            if (in_total >= max_in_bytes && out_total >= max_out_bytes) {

                goto done;

            }

        } while ((i = virtqueue_next_desc(desc_pa, i, max)) != max);

        if (!indirect)

            total_bufs = num_bufs;

        else

            total_bufs++;

    }

done:

    if (in_bytes) {

        *in_bytes = in_total;

    }

    if (out_bytes) {

        *out_bytes = out_total;

    }

}


static void mxf_write_generic_desc(ByteIOContext *pb, const MXFDescriptorWriteTableEntry *desc_tbl, AVStream *st)

{

    const MXFCodecUL *codec_ul;

    put_buffer(pb, desc_tbl->key, 16);

    klv_encode_ber_length(pb, 108);

    mxf_write_local_tag(pb, 16, 0x3C0A);

    mxf_write_uuid(pb, SubDescriptor, st->index);

    mxf_write_local_tag(pb, 4, 0x3006);

    put_be32(pb, st->index);

    mxf_write_local_tag(pb, 8, 0x3001);

    put_be32(pb, st->time_base.den);

    put_be32(pb, st->time_base.num);

    codec_ul = mxf_get_essence_container_ul(st->codec->codec_id);

    mxf_write_local_tag(pb, 16, 0x3004);

    put_buffer(pb, codec_ul->uid, 16);

}


static void virtio_net_set_multiqueue(VirtIONet *n, int multiqueue, int ctrl)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(n);

    int i, max = multiqueue ? n->max_queues : 1;

    n->multiqueue = multiqueue;

    for (i = 2; i <= n->max_queues * 2 + 1; i++) {

        virtio_del_queue(vdev, i);

    }

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

        n->vqs[i].rx_vq = virtio_add_queue(vdev, 256, virtio_net_handle_rx);

        if (n->vqs[i].tx_timer) {

            n->vqs[i].tx_vq =

                virtio_add_queue(vdev, 256, virtio_net_handle_tx_timer);

            n->vqs[i].tx_timer = qemu_new_timer_ns(vm_clock,

                                                   virtio_net_tx_timer,

                                                   &n->vqs[i]);

        } else {

            n->vqs[i].tx_vq =

                virtio_add_queue(vdev, 256, virtio_net_handle_tx_bh);

            n->vqs[i].tx_bh = qemu_bh_new(virtio_net_tx_bh, &n->vqs[i]);

        }

        n->vqs[i].tx_waiting = 0;

        n->vqs[i].n = n;

    }

    if (ctrl) {

        n->ctrl_vq = virtio_add_queue(vdev, 64, virtio_net_handle_ctrl);

    }

    virtio_net_set_queues(n);

}


int register_savevm_live(const char *idstr,

                         int instance_id,

                         int version_id,

                         SaveLiveStateHandler *save_live_state,

                         SaveStateHandler *save_state,

                         LoadStateHandler *load_state,

                         void *opaque)

{

    SaveStateEntry *se;

    se = qemu_malloc(sizeof(SaveStateEntry));

    pstrcpy(se->idstr, sizeof(se->idstr), idstr);

    se->version_id = version_id;

    se->section_id = global_section_id++;

    se->save_live_state = save_live_state;

    se->save_state = save_state;

    se->load_state = load_state;

    se->opaque = opaque;

    se->vmsd = NULL;

    if (instance_id == -1) {

        se->instance_id = calculate_new_instance_id(idstr);

    } else {

        se->instance_id = instance_id;

    }

    /* add at the end of list */

    TAILQ_INSERT_TAIL(&savevm_handlers, se, entry);

    return 0;

}


static void sun4m_hw_init(const struct hwdef *hwdef, int ram_size,

                          DisplayState *ds, const char *cpu_model)

{

    CPUState *env, *envs[MAX_CPUS];

    unsigned int i;

    void *iommu, *espdma, *ledma, *main_esp;

    const sparc_def_t *def;

    qemu_irq *cpu_irqs[MAX_CPUS], *slavio_irq, *slavio_cpu_irq,

        *espdma_irq, *ledma_irq;

    /* init CPUs */

    sparc_find_by_name(cpu_model, &def);

    if (def == NULL) {

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

        exit(1);

    }

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

        env = cpu_init();

        cpu_sparc_register(env, def);

        envs[i] = env;

        if (i == 0) {

            qemu_register_reset(main_cpu_reset, env);

        } else {

            qemu_register_reset(secondary_cpu_reset, env);

            env->halted = 1;

        }

        register_savevm("cpu", i, 3, cpu_save, cpu_load, env);

        cpu_irqs[i] = qemu_allocate_irqs(cpu_set_irq, envs[i], MAX_PILS);

    }

    for (i = smp_cpus; i < MAX_CPUS; i++)

        cpu_irqs[i] = qemu_allocate_irqs(dummy_cpu_set_irq, NULL, MAX_PILS);

    /* allocate RAM */

    cpu_register_physical_memory(0, ram_size, 0);

    iommu = iommu_init(hwdef->iommu_base);

    slavio_intctl = slavio_intctl_init(hwdef->intctl_base,

                                       hwdef->intctl_base + 0x10000ULL,

                                       &hwdef->intbit_to_level[0],

                                       &slavio_irq, &slavio_cpu_irq,

                                       cpu_irqs,

                                       hwdef->clock_irq);

    espdma = sparc32_dma_init(hwdef->dma_base, slavio_irq[hwdef->esp_irq],

                              iommu, &espdma_irq);

    ledma = sparc32_dma_init(hwdef->dma_base + 16ULL,

                             slavio_irq[hwdef->le_irq], iommu, &ledma_irq);

    if (graphic_depth != 8 && graphic_depth != 24) {

        fprintf(stderr, "qemu: Unsupported depth: %d\n", graphic_depth);

        exit (1);

    }

    tcx_init(ds, hwdef->tcx_base, phys_ram_base + ram_size, ram_size,

             hwdef->vram_size, graphic_width, graphic_height, graphic_depth);

    if (nd_table[0].model == NULL

        || strcmp(nd_table[0].model, "lance") == 0) {

        lance_init(&nd_table[0], hwdef->le_base, ledma, *ledma_irq);

    } else if (strcmp(nd_table[0].model, "?") == 0) {

        fprintf(stderr, "qemu: Supported NICs: lance\n");

        exit (1);

    } else {

        fprintf(stderr, "qemu: Unsupported NIC: %s\n", nd_table[0].model);

        exit (1);

    }

    nvram = m48t59_init(slavio_irq[0], hwdef->nvram_base, 0,

                        hwdef->nvram_size, 8);

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

        slavio_timer_init(hwdef->counter_base +

                          (target_phys_addr_t)(i * TARGET_PAGE_SIZE),

                           slavio_cpu_irq[i], 0);

    }

    slavio_timer_init(hwdef->counter_base + 0x10000ULL,

                      slavio_irq[hwdef->clock1_irq], 2);

    slavio_serial_ms_kbd_init(hwdef->ms_kb_base, slavio_irq[hwdef->ms_kb_irq]);

    // Slavio TTYA (base+4, Linux ttyS0) is the first Qemu serial device

    // Slavio TTYB (base+0, Linux ttyS1) is the second Qemu serial device

    slavio_serial_init(hwdef->serial_base, slavio_irq[hwdef->ser_irq],

                       serial_hds[1], serial_hds[0]);

    fdctrl_init(slavio_irq[hwdef->fd_irq], 0, 1, hwdef->fd_base, fd_table);

    main_esp = esp_init(bs_table, hwdef->esp_base, espdma, *espdma_irq);

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

        if (bs_table[i]) {

            esp_scsi_attach(main_esp, bs_table[i], i);

        }

    }

    slavio_misc = slavio_misc_init(hwdef->slavio_base, hwdef->power_base,

                                   slavio_irq[hwdef->me_irq]);

    if (hwdef->cs_base != (target_phys_addr_t)-1)

        cs_init(hwdef->cs_base, hwdef->cs_irq, slavio_intctl);

}


static void init_demo(const char *filename)

{

    int i, j;

    int h;

    int radian;

    char line[3 * W];

    FILE *fichier;

    fichier = fopen(filename, "rb");

    if (!fichier) {

        perror(filename);

        exit(1);

    }

    fread(line, 1, 15, fichier);

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

        fread(line, 1, 3 * W, fichier);

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

            tab_r[W * i + j] = line[3 * j    ];

            tab_g[W * i + j] = line[3 * j + 1];

            tab_b[W * i + j] = line[3 * j + 2];

        }

    }

    fclose(fichier);

    /* tables sin/cos */

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

        radian = 2 * i * MY_PI / 360;

        h      = 2 * FIXP + int_sin (radian);

        h_cos[i] = h * int_sin(radian + MY_PI / 2) / 2 / FIXP;

        h_sin[i] = h * int_sin(radian)             / 2 / FIXP;

    }

}


static int qsv_get_buffer(AVCodecContext *s, AVFrame *frame, int flags)

{

    InputStream *ist = s->opaque;

    QSVContext  *qsv = ist->hwaccel_ctx;

    int i;

    for (i = 0; i < qsv->nb_surfaces; i++) {

        if (qsv->surface_used[i])

            continue;

        frame->buf[0] = av_buffer_create((uint8_t*)qsv->surface_ptrs[i], sizeof(*qsv->surface_ptrs[i]),

                                         buffer_release, &qsv->surface_used[i], 0);

        if (!frame->buf[0])

            return AVERROR(ENOMEM);

        frame->data[3]       = (uint8_t*)qsv->surface_ptrs[i];

        qsv->surface_used[i] = 1;

        return 0;

    }

    return AVERROR(ENOMEM);

}


static int vid_read_packet(AVFormatContext *s,

                           AVPacket *pkt)

{

    BVID_DemuxContext *vid = s->priv_data;

    AVIOContext *pb = s->pb;

    unsigned char block_type;

    int audio_length;

    int ret_value;

    if(vid->is_finished || pb->eof_reached)

        return AVERROR(EIO);

    block_type = avio_r8(pb);

    switch(block_type){

        case PALETTE_BLOCK:

            avio_seek(pb, -1, SEEK_CUR);     // include block type

            ret_value = av_get_packet(pb, pkt, 3 * 256 + 1);

            if(ret_value != 3 * 256 + 1){

                av_free_packet(pkt);

                return AVERROR(EIO);

            }

            pkt->stream_index = 0;

            return ret_value;

        case FIRST_AUDIO_BLOCK:

            avio_rl16(pb);

            // soundblaster DAC used for sample rate, as on specification page (link above)

            s->streams[1]->codec->sample_rate = 1000000 / (256 - avio_r8(pb));

            s->streams[1]->codec->bit_rate = s->streams[1]->codec->channels * s->streams[1]->codec->sample_rate * s->streams[1]->codec->bits_per_coded_sample;

        case AUDIO_BLOCK:

            audio_length = avio_rl16(pb);

            ret_value = av_get_packet(pb, pkt, audio_length);

            pkt->stream_index = 1;

            return ret_value != audio_length ? AVERROR(EIO) : ret_value;

        case VIDEO_P_FRAME:

        case VIDEO_YOFF_P_FRAME:

        case VIDEO_I_FRAME:

            return read_frame(vid, pb, pkt, block_type, s,

                              s->streams[0]->codec->width * s->streams[0]->codec->height);

        case EOF_BLOCK:

            if(vid->nframes != 0)

                av_log(s, AV_LOG_VERBOSE, "reached terminating character but not all frames read.\n");

            vid->is_finished = 1;

            return AVERROR(EIO);

        default:

            av_log(s, AV_LOG_ERROR, "unknown block (character = %c, decimal = %d, hex = %x)!!!\n",

                   block_type, block_type, block_type); return -1;

    }

}


void avpriv_solve_lls(LLSModel *m, double threshold, unsigned short min_order)

{

    int i, j, k;

    double (*factor)[MAX_VARS_ALIGN] = (void *) &m->covariance[1][0];

    double (*covar) [MAX_VARS_ALIGN] = (void *) &m->covariance[1][1];

    double *covar_y                = m->covariance[0];

    int count                      = m->indep_count;

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

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

            double sum = covar[i][j];

            for (k = i - 1; k >= 0; k--)

                sum -= factor[i][k] * factor[j][k];

            if (i == j) {

                if (sum < threshold)

                    sum = 1.0;

                factor[i][i] = sqrt(sum);

            } else {

                factor[j][i] = sum / factor[i][i];

            }

        }

    }

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

        double sum = covar_y[i + 1];

        for (k = i - 1; k >= 0; k--)

            sum -= factor[i][k] * m->coeff[0][k];

        m->coeff[0][i] = sum / factor[i][i];

    }

    for (j = count - 1; j >= min_order; j--) {

        for (i = j; i >= 0; i--) {

            double sum = m->coeff[0][i];

            for (k = i + 1; k <= j; k++)

                sum -= factor[k][i] * m->coeff[j][k];

            m->coeff[j][i] = sum / factor[i][i];

        }

        m->variance[j] = covar_y[0];

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

            double sum = m->coeff[j][i] * covar[i][i] - 2 * covar_y[i + 1];

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

                sum += 2 * m->coeff[j][k] * covar[k][i];

            m->variance[j] += m->coeff[j][i] * sum;

        }

    }

}


static int hap_encode(AVCodecContext *avctx, AVPacket *pkt,

                      const AVFrame *frame, int *got_packet)

{

    HapContext *ctx = avctx->priv_data;

    int header_length = hap_header_length(ctx);

    int final_data_size, ret;

    int pktsize = FFMAX(ctx->tex_size, ctx->max_snappy * ctx->chunk_count) + header_length;

    /* Allocate maximum size packet, shrink later. */

    ret = ff_alloc_packet2(avctx, pkt, pktsize, header_length);

    if (ret < 0)

        return ret;

    /* DXTC compression. */

    ret = compress_texture(avctx, ctx->tex_buf, ctx->tex_size, frame);

    if (ret < 0)

        return ret;

    /* Compress (using Snappy) the frame */

    final_data_size = hap_compress_frame(avctx, pkt->data + header_length);

    if (final_data_size < 0)

        return final_data_size;

    /* Write header at the start. */

    hap_write_frame_header(ctx, pkt->data, final_data_size + header_length);

    av_shrink_packet(pkt, final_data_size + header_length);

    pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

    return 0;

}


static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)

{

    int i;

    struct Program *p = NULL;

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

        if(ts->prg[i].id == programid) {

            p = &ts->prg[i];

            break;

        }

    }

    if(!p)

        return;

    if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)

        return;

    p->pids[p->nb_pids++] = pid;

}


void ff_h261_loop_filter(H261Context * h){

    MpegEncContext * const s = &h->s;

    int i;

    const int linesize  = s->linesize;

    const int uvlinesize= s->uvlinesize;

    uint8_t *dest_y = s->dest[0];

    uint8_t *dest_cb= s->dest[1];

    uint8_t *dest_cr= s->dest[2];

    uint8_t *src;

    CHECKED_ALLOCZ((src),sizeof(uint8_t) * 64 );

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

        memcpy(src+i*8,dest_y+i*linesize,sizeof(uint8_t) * 8 );

    s->dsp.h261_v_loop_filter(dest_y, src, linesize);

    s->dsp.h261_h_loop_filter(dest_y, src, linesize);

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

        memcpy(src+i*8,dest_y+i*linesize + 8,sizeof(uint8_t) * 8 );

    s->dsp.h261_v_loop_filter(dest_y + 8, src, linesize);

    s->dsp.h261_h_loop_filter(dest_y + 8, src, linesize);

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

        memcpy(src+i*8,dest_y+(i+8)*linesize,sizeof(uint8_t) * 8 );

    s->dsp.h261_v_loop_filter(dest_y + 8 * linesize, src, linesize);

    s->dsp.h261_h_loop_filter(dest_y + 8 * linesize, src, linesize);

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

        memcpy(src+i*8,dest_y+(i+8)*linesize + 8,sizeof(uint8_t) * 8 );

    s->dsp.h261_v_loop_filter(dest_y + 8 * linesize + 8, src, linesize);

    s->dsp.h261_h_loop_filter(dest_y + 8 * linesize + 8, src, linesize);

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

        memcpy(src+i*8,dest_cb+i*uvlinesize,sizeof(uint8_t) * 8 );

    s->dsp.h261_v_loop_filter(dest_cb, src, uvlinesize);

    s->dsp.h261_h_loop_filter(dest_cb, src, uvlinesize);

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

        memcpy(src+i*8,dest_cr+i*uvlinesize,sizeof(uint8_t) * 8 );

    s->dsp.h261_v_loop_filter(dest_cr, src, uvlinesize);

    s->dsp.h261_h_loop_filter(dest_cr, src, uvlinesize);

fail:

    av_free(src);

    return;

}


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

                                ptrdiff_t stride)

{

    avc_luma_midh_qrt_8w_msa(src - (2 * stride) - 2, stride, dst, stride, 8, 1);

}