int usb_desc_get_descriptor(USBDevice *dev, int value, uint8_t *dest, size_t len)

{

    const USBDesc *desc = dev->info->usb_desc;

    uint8_t buf[256];

    uint8_t type = value >> 8;

    uint8_t index = value & 0xff;

    int ret = -1;

    switch(type) {

    case USB_DT_DEVICE:

        ret = usb_desc_device(&desc->id, desc->full, buf, sizeof(buf));

        trace_usb_desc_device(dev->addr, len, ret);

        break;

    case USB_DT_CONFIG:

        if (index < desc->full->bNumConfigurations) {

            ret = usb_desc_config(desc->full->confs + index, buf, sizeof(buf));

        }

        trace_usb_desc_config(dev->addr, index, len, ret);

        break;

    case USB_DT_STRING:

        ret = usb_desc_string(dev, index, buf, sizeof(buf));

        trace_usb_desc_string(dev->addr, index, len, ret);

        break;

    default:

        fprintf(stderr, "%s: %d unknown type %d (len %zd)\n", __FUNCTION__,

                dev->addr, type, len);

        break;

    }

    if (ret > 0) {

        if (ret > len) {

            ret = len;

        }

        memcpy(dest, buf, ret);

    }

    return ret;

}


static void connex_init(MachineState *machine)

{

    PXA2xxState *cpu;

    DriveInfo *dinfo;

    int be;

    MemoryRegion *address_space_mem = get_system_memory();

    uint32_t connex_rom = 0x01000000;

    uint32_t connex_ram = 0x04000000;

    cpu = pxa255_init(address_space_mem, connex_ram);

    dinfo = drive_get(IF_PFLASH, 0, 0);

    if (!dinfo && !qtest_enabled()) {

        fprintf(stderr, "A flash image must be given with the "

                "'pflash' parameter\n");

        exit(1);

    }

#ifdef TARGET_WORDS_BIGENDIAN

    be = 1;

#else

    be = 0;

#endif

    if (!pflash_cfi01_register(0x00000000, NULL, "connext.rom", connex_rom,

                               dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,

                               sector_len, connex_rom / sector_len,

                               2, 0, 0, 0, 0, be)) {

        fprintf(stderr, "qemu: Error registering flash memory.\n");

        exit(1);

    }

    /* Interrupt line of NIC is connected to GPIO line 36 */

    smc91c111_init(&nd_table[0], 0x04000300,

                    qdev_get_gpio_in(cpu->gpio, 36));

}


void aio_set_event_notifier(AioContext *ctx,

                            EventNotifier *notifier,

                            bool is_external,

                            EventNotifierHandler *io_read,

                            AioPollFn *io_poll)

{

    aio_set_fd_handler(ctx, event_notifier_get_fd(notifier), is_external,

                       (IOHandler *)io_read, NULL, io_poll, notifier);

}


void av_xtea_crypt(AVXTEA *ctx, uint8_t *dst, const uint8_t *src, int count,

                   uint8_t *iv, int decrypt)

{

    int i;

    while (count > 0) {

        if (decrypt) {

            xtea_crypt_ecb(ctx, dst, src, decrypt);

            if (iv) {

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

                    dst[i] = dst[i] ^ iv[i];

                memcpy(iv, src, 8);

            }

        } else {

            if (iv) {

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

                    dst[i] = src[i] ^ iv[i];

                xtea_crypt_ecb(ctx, dst, dst, decrypt);

                memcpy(iv, dst, 8);

            } else {

                xtea_crypt_ecb(ctx, dst, src, decrypt);

            }

        }

        src   += 8;

        dst   += 8;

        count -= 8;

    }

}


static void read_chapter(AVFormatContext *s, AVIOContext *pb, int len, char *ttag, ID3v2ExtraMeta **extra_meta)

{

    AVRational time_base = {1, 1000};

    uint32_t start, end;

    AVChapter *chapter;

    uint8_t *dst = NULL;

    int taglen;

    char tag[5];

    decode_str(s, pb, 0, &dst, &len);

    if (len < 16)

        return;

    start = avio_rb32(pb);

    end   = avio_rb32(pb);

    avio_skip(pb, 8);

    chapter = avpriv_new_chapter(s, s->nb_chapters + 1, time_base, start, end, dst);

    if (!chapter) {

        av_free(dst);

        return;

    }

    len -= 16;

    while (len > 10) {

        avio_read(pb, tag, 4);

        tag[4] = 0;

        taglen = avio_rb32(pb);

        avio_skip(pb, 2);

        len -= 10;

        if (taglen < 0 || taglen > len) {

            av_free(dst);

            return;

        }

        if (tag[0] == 'T')

            read_ttag(s, pb, taglen, &chapter->metadata, tag);

        else

            avio_skip(pb, taglen);

        len -= taglen;

    }

    ff_metadata_conv(&chapter->metadata, NULL, ff_id3v2_34_metadata_conv);

    ff_metadata_conv(&chapter->metadata, NULL, ff_id3v2_4_metadata_conv);

    av_free(dst);

}


void kqemu_modify_page(CPUState *env, ram_addr_t ram_addr)

{

    unsigned long page_index;

    int ret;

#ifdef _WIN32

    DWORD temp;

#endif

    page_index = ram_addr >> TARGET_PAGE_BITS;

    if (!modified_ram_pages_table[page_index]) {

#if 0

        printf("%d: modify_page=%08lx\n", nb_modified_ram_pages, ram_addr);

#endif

        modified_ram_pages_table[page_index] = 1;

        modified_ram_pages[nb_modified_ram_pages++] = ram_addr;

        if (nb_modified_ram_pages >= KQEMU_MAX_MODIFIED_RAM_PAGES) {

            /* flush */

#ifdef _WIN32

            ret = DeviceIoControl(kqemu_fd, KQEMU_MODIFY_RAM_PAGES,

                                  &nb_modified_ram_pages,

                                  sizeof(nb_modified_ram_pages),

                                  NULL, 0, &temp, NULL);

#else

            ret = ioctl(kqemu_fd, KQEMU_MODIFY_RAM_PAGES,

                        &nb_modified_ram_pages);

#endif

            kqemu_reset_modified_ram_pages();

        }

    }

}


static bool aio_epoll_check_poll(AioContext *ctx, GPollFD *pfds,

                                 unsigned npfd, int64_t timeout)

{

    if (!ctx->epoll_available) {

        return false;

    }

    if (aio_epoll_enabled(ctx)) {

        return true;

    }

    if (npfd >= EPOLL_ENABLE_THRESHOLD) {

        if (aio_epoll_try_enable(ctx)) {

            return true;

        } else {

            aio_epoll_disable(ctx);

        }

    }

    return false;

}


static void aarch64_cpu_register_types(void)

{

    int i;

    type_register_static(&aarch64_cpu_type_info);

    for (i = 0; i < ARRAY_SIZE(aarch64_cpus); i++) {

        aarch64_cpu_register(&aarch64_cpus[i]);

    }

}


static void musicpal_lcd_write(void *opaque, target_phys_addr_t offset,

                               uint64_t value, unsigned size)

{

    musicpal_lcd_state *s = opaque;

    switch (offset) {

    case MP_LCD_IRQCTRL:

        s->irqctrl = value;

        break;

    case MP_LCD_SPICTRL:

        if (value == MP_LCD_SPI_DATA || value == MP_LCD_SPI_CMD) {

            s->mode = value;

        } else {

            s->mode = MP_LCD_SPI_INVALID;

        }

        break;

    case MP_LCD_INST:

        if (value >= MP_LCD_INST_SETPAGE0 && value <= MP_LCD_INST_SETPAGE7) {

            s->page = value - MP_LCD_INST_SETPAGE0;

            s->page_off = 0;

        }

        break;

    case MP_LCD_DATA:

        if (s->mode == MP_LCD_SPI_CMD) {

            if (value >= MP_LCD_INST_SETPAGE0 &&

                value <= MP_LCD_INST_SETPAGE7) {

                s->page = value - MP_LCD_INST_SETPAGE0;

                s->page_off = 0;

            }

        } else if (s->mode == MP_LCD_SPI_DATA) {

            s->video_ram[s->page*128 + s->page_off] = value;

            s->page_off = (s->page_off + 1) & 127;

        }

        break;

    }

}


static inline uint32_t nvic_gprio_mask(NVICState *s)

{

    return ~0U << (s->prigroup + 1);

}


int qemu_eventfd(int fds[2])

{

#ifdef CONFIG_EVENTFD

    int ret;

    ret = eventfd(0, 0);

    if (ret >= 0) {

        fds[0] = ret;

        qemu_set_cloexec(ret);

        if ((fds[1] = dup(ret)) == -1) {

            close(ret);

            return -1;

        }

        qemu_set_cloexec(fds[1]);

        return 0;

    }

    if (errno != ENOSYS) {

        return -1;

    }

#endif

    return qemu_pipe(fds);

}


static int bdrv_qed_truncate(BlockDriverState *bs, int64_t offset)

{

    return -ENOTSUP;

}


void HELPER(wsr_ibreakenable)(uint32_t v)

{

    uint32_t change = v ^ env->sregs[IBREAKENABLE];

    unsigned i;

    for (i = 0; i < env->config->nibreak; ++i) {

        if (change & (1 << i)) {

            tb_invalidate_phys_page_range(

                    env->sregs[IBREAKA + i], env->sregs[IBREAKA + i] + 1, 0);

        }

    }

    env->sregs[IBREAKENABLE] = v & ((1 << env->config->nibreak) - 1);

}


static void openrisc_cpu_class_init(ObjectClass *oc, void *data)

{

    OpenRISCCPUClass *occ = OPENRISC_CPU_CLASS(oc);

    CPUClass *cc = CPU_CLASS(occ);

    DeviceClass *dc = DEVICE_CLASS(oc);

    occ->parent_realize = dc->realize;

    dc->realize = openrisc_cpu_realizefn;

    occ->parent_reset = cc->reset;

    cc->reset = openrisc_cpu_reset;

    cc->class_by_name = openrisc_cpu_class_by_name;

    cc->has_work = openrisc_cpu_has_work;

    cc->do_interrupt = openrisc_cpu_do_interrupt;

    cc->cpu_exec_interrupt = openrisc_cpu_exec_interrupt;

    cc->dump_state = openrisc_cpu_dump_state;

    cc->set_pc = openrisc_cpu_set_pc;

    cc->gdb_read_register = openrisc_cpu_gdb_read_register;

    cc->gdb_write_register = openrisc_cpu_gdb_write_register;

#ifdef CONFIG_USER_ONLY

    cc->handle_mmu_fault = openrisc_cpu_handle_mmu_fault;

#else

    cc->get_phys_page_debug = openrisc_cpu_get_phys_page_debug;

    dc->vmsd = &vmstate_openrisc_cpu;

#endif

    cc->gdb_num_core_regs = 32 + 3;

    /*

     * Reason: openrisc_cpu_initfn() calls cpu_exec_init(), which saves

     * the object in cpus -> dangling pointer after final

     * object_unref().

     */

    dc->cannot_destroy_with_object_finalize_yet = true;

}


static void tcp_accept_incoming_migration(void *opaque)

{

    struct sockaddr_in addr;

    socklen_t addrlen = sizeof(addr);

    int s = (intptr_t)opaque;

    QEMUFile *f;

    int c;

    do {

        c = qemu_accept(s, (struct sockaddr *)&addr, &addrlen);

    } while (c == -1 && socket_error() == EINTR);

    qemu_set_fd_handler2(s, NULL, NULL, NULL, NULL);

    closesocket(s);

    DPRINTF("accepted migration\n");

    if (c == -1) {

        fprintf(stderr, "could not accept migration connection\n");

        goto out;

    }

    f = qemu_fopen_socket(c, "rb");

    if (f == NULL) {

        fprintf(stderr, "could not qemu_fopen socket\n");

        goto out;

    }

    process_incoming_migration(f);

    return;

out:

    closesocket(c);

}


static void quorum_copy_qiov(QEMUIOVector *dest, QEMUIOVector *source)

{

    int i;

    assert(dest->niov == source->niov);

    assert(dest->size == source->size);

    for (i = 0; i < source->niov; i++) {

        assert(dest->iov[i].iov_len == source->iov[i].iov_len);

        memcpy(dest->iov[i].iov_base,

               source->iov[i].iov_base,

               source->iov[i].iov_len);

    }

}


static int decode_sgirle8(AVCodecContext *avctx, uint8_t *dst, const uint8_t *src, int src_size, int width, int height, int linesize)

{

    const uint8_t *src_end = src + src_size;

    int x = 0, y = 0;

#define INC_XY(n) \

    x += n; \

    if (x >= width) { \

        y++; \

        if (y >= height) \

            return 0; \

        x = 0; \

    }

    while (src_end - src >= 2) {

        uint8_t v = *src++;

        if (v > 0 && v < 0xC0) {

            do {

                int length = FFMIN(v, width - x);

                memset(dst + y*linesize + x, RGB332_TO_BGR8(*src), length);

                INC_XY(length);

                v   -= length;

            } while (v > 0);

            src++;

        } else if (v >= 0xC1) {

            v -= 0xC0;

            do {

                int length = FFMIN3(v, width - x, src_end - src);

                if (src_end - src < length)

                    break;

                memcpy_rgb332_to_bgr8(dst + y*linesize + x, src, length);

                INC_XY(length);

                src += length;

                v   -= length;

            } while (v > 0);

        } else {

            avpriv_request_sample(avctx, "opcode %d", v);

            return AVERROR_PATCHWELCOME;

        }

    }

    return 0;

}


static int hls_read_seek(AVFormatContext *s, int stream_index,

                               int64_t timestamp, int flags)

{

    HLSContext *c = s->priv_data;

    int i;

    int64_t seek_timestamp;

    int valid_for = -1;

    if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->playlists[0]->finished)

        return AVERROR(ENOSYS);

    seek_timestamp = stream_index < 0 ? timestamp :

                     av_rescale_rnd(timestamp, AV_TIME_BASE,

                                    s->streams[stream_index]->time_base.den,

                                    flags & AVSEEK_FLAG_BACKWARD ?

                                    AV_ROUND_DOWN : AV_ROUND_UP);

    if (s->duration < seek_timestamp)

        return AVERROR(EIO);

    for (i = 0; i < c->n_playlists; i++) {

        /* check first that the timestamp is valid for some playlist */

        struct playlist *pls = c->playlists[i];

        int seq_no;

        if (find_timestamp_in_playlist(c, pls, seek_timestamp, &seq_no)) {

            /* set segment now so we do not need to search again below */

            pls->cur_seq_no = seq_no;

            valid_for = i;

            break;

        }

    }

    if (valid_for < 0)

        return AVERROR(EIO);

    for (i = 0; i < c->n_playlists; i++) {

        /* Reset reading */

        struct playlist *pls = c->playlists[i];

        if (pls->input) {

            ffurl_close(pls->input);

            pls->input = NULL;

        }

        av_free_packet(&pls->pkt);

        reset_packet(&pls->pkt);

        pls->pb.eof_reached = 0;

        /* Clear any buffered data */

        pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;

        /* Reset the pos, to let the mpegts demuxer know we've seeked. */

        pls->pb.pos = 0;

        pls->seek_timestamp = seek_timestamp;

        pls->seek_flags = flags;

        /* set closest segment seq_no for playlists not handled above */

        if (valid_for != i)

            find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no);

    }

    c->cur_timestamp = seek_timestamp;

    return 0;

}


static int assigned_initfn(struct PCIDevice *pci_dev)

{

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

    uint8_t e_intx;

    int r;

    Error *local_err = NULL;

    if (!kvm_enabled()) {

        error_report("pci-assign: error: requires KVM support");

        return -1;

    }

    if (!dev->host.domain && !dev->host.bus && !dev->host.slot &&

        !dev->host.function) {

        error_report("pci-assign: error: no host device specified");

        return -1;

    }

    /*

     * Set up basic config space access control. Will be further refined during

     * device initialization.

     */

    assigned_dev_emulate_config_read(dev, 0, PCI_CONFIG_SPACE_SIZE);

    assigned_dev_direct_config_read(dev, PCI_STATUS, 2);

    assigned_dev_direct_config_read(dev, PCI_REVISION_ID, 1);

    assigned_dev_direct_config_read(dev, PCI_CLASS_PROG, 3);

    assigned_dev_direct_config_read(dev, PCI_CACHE_LINE_SIZE, 1);

    assigned_dev_direct_config_read(dev, PCI_LATENCY_TIMER, 1);

    assigned_dev_direct_config_read(dev, PCI_BIST, 1);

    assigned_dev_direct_config_read(dev, PCI_CARDBUS_CIS, 4);

    assigned_dev_direct_config_read(dev, PCI_SUBSYSTEM_VENDOR_ID, 2);

    assigned_dev_direct_config_read(dev, PCI_SUBSYSTEM_ID, 2);

    assigned_dev_direct_config_read(dev, PCI_CAPABILITY_LIST + 1, 7);

    assigned_dev_direct_config_read(dev, PCI_MIN_GNT, 1);

    assigned_dev_direct_config_read(dev, PCI_MAX_LAT, 1);

    memcpy(dev->emulate_config_write, dev->emulate_config_read,

           sizeof(dev->emulate_config_read));

    get_real_device(dev, &local_err);

    if (local_err) {

        qerror_report_err(local_err);

        error_free(local_err);

        goto out;

    }

    if (assigned_device_pci_cap_init(pci_dev, &local_err) < 0) {

        qerror_report_err(local_err);

        error_free(local_err);

        goto out;

    }

    /* intercept MSI-X entry page in the MMIO */

    if (dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {

        assigned_dev_register_msix_mmio(dev, &local_err);

        if (local_err) {

            qerror_report_err(local_err);

            error_free(local_err);

            goto out;

        }

    }

    /* handle real device's MMIO/PIO BARs */

    assigned_dev_register_regions(dev->real_device.regions,

                                  dev->real_device.region_number, dev,

                                  &local_err);

    if (local_err) {

        qerror_report_err(local_err);

        error_free(local_err);

        goto out;

    }

    /* handle interrupt routing */

    e_intx = dev->dev.config[PCI_INTERRUPT_PIN] - 1;

    dev->intpin = e_intx;

    dev->intx_route.mode = PCI_INTX_DISABLED;

    dev->intx_route.irq = -1;

    /* assign device to guest */

    r = assign_device(dev);

    if (r < 0) {

        goto out;

    }

    /* assign legacy INTx to the device */

    r = assign_intx(dev);

    if (r < 0) {

        goto assigned_out;

    }

    assigned_dev_load_option_rom(dev);

    add_boot_device_path(dev->bootindex, &pci_dev->qdev, NULL);

    return 0;

assigned_out:

    deassign_device(dev);

out:

    free_assigned_device(dev);

    return -1;

}


int xen_be_send_notify(struct XenDevice *xendev)

{

    return xc_evtchn_notify(xendev->evtchndev, xendev->local_port);

}


static int64_t wrap_timestamp(AVStream *st, int64_t timestamp)

{

    if (st->pts_wrap_behavior != AV_PTS_WRAP_IGNORE && st->pts_wrap_bits < 64 &&

        st->pts_wrap_reference != AV_NOPTS_VALUE && timestamp != AV_NOPTS_VALUE) {

        if (st->pts_wrap_behavior == AV_PTS_WRAP_ADD_OFFSET &&

            timestamp < st->pts_wrap_reference)

            return timestamp + (1ULL<<st->pts_wrap_bits);

        else if (st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET &&

            timestamp >= st->pts_wrap_reference)

            return timestamp - (1ULL<<st->pts_wrap_bits);

    }

    return timestamp;

}


static void ide_atapi_cmd_reply_end(IDEState *s)

{

    int byte_count_limit, size, ret;

#ifdef DEBUG_IDE_ATAPI

    printf("reply: tx_size=%d elem_tx_size=%d index=%d\n",

           s->packet_transfer_size,

           s->elementary_transfer_size,

           s->io_buffer_index);

#endif

    if (s->packet_transfer_size <= 0) {

        /* end of transfer */

        ide_transfer_stop(s);

        s->status = READY_STAT;

        s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;

        ide_set_irq(s);

#ifdef DEBUG_IDE_ATAPI

        printf("status=0x%x\n", s->status);

#endif

    } else {

        /* see if a new sector must be read */

        if (s->lba != -1 && s->io_buffer_index >= s->cd_sector_size) {

            ret = cd_read_sector(s->bs, s->lba, s->io_buffer, s->cd_sector_size);

            if (ret < 0) {

                ide_transfer_stop(s);

                ide_atapi_io_error(s, ret);

                return;

            }

            s->lba++;

            s->io_buffer_index = 0;

        }

        if (s->elementary_transfer_size > 0) {

            /* there are some data left to transmit in this elementary

               transfer */

            size = s->cd_sector_size - s->io_buffer_index;

            if (size > s->elementary_transfer_size)

                size = s->elementary_transfer_size;

            ide_transfer_start(s, s->io_buffer + s->io_buffer_index,

                               size, ide_atapi_cmd_reply_end);

            s->packet_transfer_size -= size;

            s->elementary_transfer_size -= size;

            s->io_buffer_index += size;

        } else {

            /* a new transfer is needed */

            s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO;

            byte_count_limit = s->lcyl | (s->hcyl << 8);

#ifdef DEBUG_IDE_ATAPI

            printf("byte_count_limit=%d\n", byte_count_limit);

#endif

            if (byte_count_limit == 0xffff)

                byte_count_limit--;

            size = s->packet_transfer_size;

            if (size > byte_count_limit) {

                /* byte count limit must be even if this case */

                if (byte_count_limit & 1)

                    byte_count_limit--;

                size = byte_count_limit;

            }

            s->lcyl = size;

            s->hcyl = size >> 8;

            s->elementary_transfer_size = size;

            /* we cannot transmit more than one sector at a time */

            if (s->lba != -1) {

                if (size > (s->cd_sector_size - s->io_buffer_index))

                    size = (s->cd_sector_size - s->io_buffer_index);

            }

            ide_transfer_start(s, s->io_buffer + s->io_buffer_index,

                               size, ide_atapi_cmd_reply_end);

            s->packet_transfer_size -= size;

            s->elementary_transfer_size -= size;

            s->io_buffer_index += size;

            ide_set_irq(s);

#ifdef DEBUG_IDE_ATAPI

            printf("status=0x%x\n", s->status);

#endif

        }

    }

}


static void slavio_led_mem_writes(void *opaque, target_phys_addr_t addr,

                                  uint32_t val)

{

    MiscState *s = opaque;

    uint32_t saddr;

    saddr = addr & LED_MAXADDR;

    MISC_DPRINTF("Write diagnostic LED reg 0x" TARGET_FMT_plx " =  %x\n", addr,

                 val);

    switch (saddr) {

    case 0:

        s->leds = val;

        break;

    default:

        break;

    }

}


int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,

                                 int nb_sectors)

{

    int max_discard;

    if (!bs->drv) {

        return -ENOMEDIUM;

    } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {

        return -EIO;

    } else if (bs->read_only) {

        return -EROFS;

    }

    bdrv_reset_dirty(bs, sector_num, nb_sectors);

    /* Do nothing if disabled.  */

    if (!(bs->open_flags & BDRV_O_UNMAP)) {

        return 0;

    }

    if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {

        return 0;

    }

    max_discard = bs->bl.max_discard ?  bs->bl.max_discard : MAX_DISCARD_DEFAULT;

    while (nb_sectors > 0) {

        int ret;

        int num = nb_sectors;

        /* align request */

        if (bs->bl.discard_alignment &&

            num >= bs->bl.discard_alignment &&

            sector_num % bs->bl.discard_alignment) {

            if (num > bs->bl.discard_alignment) {

                num = bs->bl.discard_alignment;

            }

            num -= sector_num % bs->bl.discard_alignment;

        }

        /* limit request size */

        if (num > max_discard) {

            num = max_discard;

        }

        if (bs->drv->bdrv_co_discard) {

            ret = bs->drv->bdrv_co_discard(bs, sector_num, num);

        } else {

            BlockDriverAIOCB *acb;

            CoroutineIOCompletion co = {

                .coroutine = qemu_coroutine_self(),

            };

            acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,

                                            bdrv_co_io_em_complete, &co);

            if (acb == NULL) {

                return -EIO;

            } else {

                qemu_coroutine_yield();

                ret = co.ret;

            }

        }

        if (ret) {

            return ret;

        }

        sector_num += num;

        nb_sectors -= num;

    }

    return 0;

}


static void xlnx_ep108_machine_init(MachineClass *mc)

{

    mc->desc = "Xilinx ZynqMP EP108 board";

    mc->init = xlnx_ep108_init;

    mc->block_default_type = IF_IDE;

    mc->units_per_default_bus = 1;

    mc->ignore_memory_transaction_failures = true;

}


static void tcg_out_logicali(TCGContext *s, AArch64Insn insn, TCGType ext,

                             TCGReg rd, TCGReg rn, uint64_t limm)

{

    unsigned h, l, r, c;

    assert(is_limm(limm));

    h = clz64(limm);

    l = ctz64(limm);

    if (l == 0) {

        r = 0;                  /* form 0....01....1 */

        c = ctz64(~limm) - 1;

        if (h == 0) {

            r = clz64(~limm);   /* form 1..10..01..1 */

            c += r;

        }

    } else {

        r = 64 - l;             /* form 1....10....0 or 0..01..10..0 */

        c = r - h - 1;

    }

    if (ext == TCG_TYPE_I32) {

        r &= 31;

        c &= 31;

    }

    tcg_out_insn_3404(s, insn, ext, rd, rn, ext, r, c);

}


void ich9_pm_init(PCIDevice *lpc_pci, ICH9LPCPMRegs *pm,

                  bool smm_enabled,

                  qemu_irq sci_irq)

{

    memory_region_init(&pm->io, OBJECT(lpc_pci), "ich9-pm", ICH9_PMIO_SIZE);

    memory_region_set_enabled(&pm->io, false);

    memory_region_add_subregion(pci_address_space_io(lpc_pci),

                                0, &pm->io);

    acpi_pm_tmr_init(&pm->acpi_regs, ich9_pm_update_sci_fn, &pm->io);

    acpi_pm1_evt_init(&pm->acpi_regs, ich9_pm_update_sci_fn, &pm->io);

    acpi_pm1_cnt_init(&pm->acpi_regs, &pm->io, pm->disable_s3, pm->disable_s4,

                      pm->s4_val);

    acpi_gpe_init(&pm->acpi_regs, ICH9_PMIO_GPE0_LEN);

    memory_region_init_io(&pm->io_gpe, OBJECT(lpc_pci), &ich9_gpe_ops, pm,

                          "acpi-gpe0", ICH9_PMIO_GPE0_LEN);

    memory_region_add_subregion(&pm->io, ICH9_PMIO_GPE0_STS, &pm->io_gpe);

    memory_region_init_io(&pm->io_smi, OBJECT(lpc_pci), &ich9_smi_ops, pm,

                          "acpi-smi", 8);

    memory_region_add_subregion(&pm->io, ICH9_PMIO_SMI_EN, &pm->io_smi);

    pm->smm_enabled = smm_enabled;

    pm->enable_tco = true;

    acpi_pm_tco_init(&pm->tco_regs, &pm->io);

    pm->irq = sci_irq;

    qemu_register_reset(pm_reset, pm);

    pm->powerdown_notifier.notify = pm_powerdown_req;

    qemu_register_powerdown_notifier(&pm->powerdown_notifier);

    legacy_acpi_cpu_hotplug_init(pci_address_space_io(lpc_pci),

        OBJECT(lpc_pci), &pm->gpe_cpu, ICH9_CPU_HOTPLUG_IO_BASE);

    if (pm->acpi_memory_hotplug.is_enabled) {

        acpi_memory_hotplug_init(pci_address_space_io(lpc_pci), OBJECT(lpc_pci),

                                 &pm->acpi_memory_hotplug);

    }

}


static void handle_sys(DisasContext *s, uint32_t insn, bool isread,

                       unsigned int op0, unsigned int op1, unsigned int op2,

                       unsigned int crn, unsigned int crm, unsigned int rt)

{

    const ARMCPRegInfo *ri;

    TCGv_i64 tcg_rt;

    ri = get_arm_cp_reginfo(s->cp_regs,

                            ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP,

                                               crn, crm, op0, op1, op2));

    if (!ri) {

        /* Unknown register; this might be a guest error or a QEMU

         * unimplemented feature.

         */

        qemu_log_mask(LOG_UNIMP, "%s access to unsupported AArch64 "

                      "system register op0:%d op1:%d crn:%d crm:%d op2:%d\n",

                      isread ? "read" : "write", op0, op1, crn, crm, op2);

        unallocated_encoding(s);

        return;

    }

    /* Check access permissions */

    if (!cp_access_ok(s->current_el, ri, isread)) {

        unallocated_encoding(s);

        return;

    }

    if (ri->accessfn) {

        /* Emit code to perform further access permissions checks at

         * runtime; this may result in an exception.

         */

        TCGv_ptr tmpptr;

        TCGv_i32 tcg_syn;

        uint32_t syndrome;

        gen_a64_set_pc_im(s->pc - 4);

        tmpptr = tcg_const_ptr(ri);

        syndrome = syn_aa64_sysregtrap(op0, op1, op2, crn, crm, rt, isread);

        tcg_syn = tcg_const_i32(syndrome);

        gen_helper_access_check_cp_reg(cpu_env, tmpptr, tcg_syn);

        tcg_temp_free_ptr(tmpptr);

        tcg_temp_free_i32(tcg_syn);

    }

    /* Handle special cases first */

    switch (ri->type & ~(ARM_CP_FLAG_MASK & ~ARM_CP_SPECIAL)) {

    case ARM_CP_NOP:

        return;

    case ARM_CP_NZCV:

        tcg_rt = cpu_reg(s, rt);

        if (isread) {

            gen_get_nzcv(tcg_rt);

        } else {

            gen_set_nzcv(tcg_rt);

        }

        return;

    case ARM_CP_CURRENTEL:

        /* Reads as current EL value from pstate, which is

         * guaranteed to be constant by the tb flags.

         */

        tcg_rt = cpu_reg(s, rt);

        tcg_gen_movi_i64(tcg_rt, s->current_el << 2);

        return;

    case ARM_CP_DC_ZVA:

        /* Writes clear the aligned block of memory which rt points into. */

        tcg_rt = cpu_reg(s, rt);

        gen_helper_dc_zva(cpu_env, tcg_rt);

        return;

    default:

        break;

    }

    if (use_icount && (ri->type & ARM_CP_IO)) {

        gen_io_start();

    }

    tcg_rt = cpu_reg(s, rt);

    if (isread) {

        if (ri->type & ARM_CP_CONST) {

            tcg_gen_movi_i64(tcg_rt, ri->resetvalue);

        } else if (ri->readfn) {

            TCGv_ptr tmpptr;

            tmpptr = tcg_const_ptr(ri);

            gen_helper_get_cp_reg64(tcg_rt, cpu_env, tmpptr);

            tcg_temp_free_ptr(tmpptr);

        } else {

            tcg_gen_ld_i64(tcg_rt, cpu_env, ri->fieldoffset);

        }

    } else {

        if (ri->type & ARM_CP_CONST) {

            /* If not forbidden by access permissions, treat as WI */

            return;

        } else if (ri->writefn) {

            TCGv_ptr tmpptr;

            tmpptr = tcg_const_ptr(ri);

            gen_helper_set_cp_reg64(cpu_env, tmpptr, tcg_rt);

            tcg_temp_free_ptr(tmpptr);

        } else {

            tcg_gen_st_i64(tcg_rt, cpu_env, ri->fieldoffset);

        }

    }

    if (use_icount && (ri->type & ARM_CP_IO)) {

        /* I/O operations must end the TB here (whether read or write) */

        gen_io_end();

        s->is_jmp = DISAS_UPDATE;

    } else if (!isread && !(ri->type & ARM_CP_SUPPRESS_TB_END)) {

        /* We default to ending the TB on a coprocessor register write,

         * but allow this to be suppressed by the register definition

         * (usually only necessary to work around guest bugs).

         */

        s->is_jmp = DISAS_UPDATE;

    }

}


static Visitor *visitor_input_test_init_raw(TestInputVisitorData *data,

                                            const char *json_string)

{

    return visitor_input_test_init_internal(data, json_string, NULL);

}


static void do_info_version(Monitor *mon)

{

    monitor_printf(mon, "%s\n", QEMU_VERSION);

}


static int qcrypto_ivgen_essiv_init(QCryptoIVGen *ivgen,

                                    const uint8_t *key, size_t nkey,

                                    Error **errp)

{

    uint8_t *salt;

    size_t nhash;

    size_t nsalt;

    QCryptoIVGenESSIV *essiv = g_new0(QCryptoIVGenESSIV, 1);

    /* Not necessarily the same as nkey */

    nsalt = qcrypto_cipher_get_key_len(ivgen->cipher);

    nhash = qcrypto_hash_digest_len(ivgen->hash);

    /* Salt must be larger of hash size or key size */

    salt = g_new0(uint8_t, MAX(nhash, nsalt));

    if (qcrypto_hash_bytes(ivgen->hash, (const gchar *)key, nkey,

                           &salt, &nhash,

                           errp) < 0) {

        g_free(essiv);

        return -1;

    }

    /* Now potentially truncate salt to match cipher key len */

    essiv->cipher = qcrypto_cipher_new(ivgen->cipher,

                                       QCRYPTO_CIPHER_MODE_ECB,

                                       salt, MIN(nhash, nsalt),

                                       errp);

    if (!essiv->cipher) {

        g_free(essiv);

        return -1;

    }

    ivgen->private = essiv;

    return 0;

}


static void mpeg1_encode_sequence_header(MpegEncContext *s)

{

        unsigned int vbv_buffer_size;

        unsigned int fps, v;

        int n;

        UINT64 time_code;

        if ((s->picture_number % s->gop_size) == 0) {

            /* mpeg1 header repeated every gop */

            put_header(s, SEQ_START_CODE);

            /* search closest frame rate */

            {

                int i, dmin, d;

                s->frame_rate_index = 0;

                dmin = 0x7fffffff;

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

                    d = abs(s->frame_rate - frame_rate_tab[i]);

                    if (d < dmin) {

                        dmin = d;

                        s->frame_rate_index = i;

                    }

                }

            }

            put_bits(&s->pb, 12, s->width);

            put_bits(&s->pb, 12, s->height);

            put_bits(&s->pb, 4, 1); /* 1/1 aspect ratio */

            put_bits(&s->pb, 4, s->frame_rate_index);

            v = s->bit_rate / 400;

            if (v > 0x3ffff)

                v = 0x3ffff;

            put_bits(&s->pb, 18, v);

            put_bits(&s->pb, 1, 1); /* marker */

            /* vbv buffer size: slightly greater than an I frame. We add

               some margin just in case */

            vbv_buffer_size = (3 * s->I_frame_bits) / (2 * 8);

            put_bits(&s->pb, 10, (vbv_buffer_size + 16383) / 16384);

            put_bits(&s->pb, 1, 1); /* constrained parameter flag */

            put_bits(&s->pb, 1, 0); /* no custom intra matrix */

            put_bits(&s->pb, 1, 0); /* no custom non intra matrix */

            put_header(s, GOP_START_CODE);

            put_bits(&s->pb, 1, 0); /* do drop frame */

            /* time code : we must convert from the real frame rate to a

               fake mpeg frame rate in case of low frame rate */

            fps = frame_rate_tab[s->frame_rate_index];

            time_code = s->fake_picture_number * FRAME_RATE_BASE;

            s->gop_picture_number = s->fake_picture_number;

            put_bits(&s->pb, 5, (UINT32)((time_code / (fps * 3600)) % 24));

            put_bits(&s->pb, 6, (UINT32)((time_code / (fps * 60)) % 60));

            put_bits(&s->pb, 1, 1);

            put_bits(&s->pb, 6, (UINT32)((time_code / fps) % 60));

            put_bits(&s->pb, 6, (UINT32)((time_code % fps) / FRAME_RATE_BASE));

            put_bits(&s->pb, 1, 1); /* closed gop */

            put_bits(&s->pb, 1, 0); /* broken link */

        }

        if (s->frame_rate < (24 * FRAME_RATE_BASE) && s->picture_number > 0) {

            /* insert empty P pictures to slow down to the desired

               frame rate. Each fake pictures takes about 20 bytes */

            fps = frame_rate_tab[s->frame_rate_index];

            n = ((s->picture_number * fps) / s->frame_rate) - 1;

            while (s->fake_picture_number < n) {

                mpeg1_skip_picture(s, s->fake_picture_number -

                                   s->gop_picture_number);

                s->fake_picture_number++;

            }

        }

        s->fake_picture_number++;

}


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

                                ptrdiff_t stride)

{

    avc_luma_hv_qrt_4w_msa(src + stride - 2,

                           src - (stride * 2) +

                           sizeof(uint8_t), stride, dst, stride, 4);

}


static av_cold int mpeg_mux_init(AVFormatContext *ctx)

{

    MpegMuxContext *s = ctx->priv_data;

    int bitrate, i, mpa_id, mpv_id, h264_id, mps_id, ac3_id, dts_id, lpcm_id, j;

    AVStream *st;

    StreamInfo *stream;

    int audio_bitrate;

    int video_bitrate;

    s->packet_number = 0;

    s->is_vcd   =  (CONFIG_MPEG1VCD_MUXER  && ctx->oformat == &ff_mpeg1vcd_muxer);

    s->is_svcd  =  (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer);

    s->is_mpeg2 = ((CONFIG_MPEG2VOB_MUXER  && ctx->oformat == &ff_mpeg2vob_muxer) ||

                   (CONFIG_MPEG2DVD_MUXER  && ctx->oformat == &ff_mpeg2dvd_muxer) ||

                   (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer));

    s->is_dvd   =  (CONFIG_MPEG2DVD_MUXER  && ctx->oformat == &ff_mpeg2dvd_muxer);

    if (ctx->packet_size) {

        if (ctx->packet_size < 20 || ctx->packet_size > (1 << 23) + 10) {

            av_log(ctx, AV_LOG_ERROR, "Invalid packet size %d\n",

                   ctx->packet_size);

            goto fail;

        }

        s->packet_size = ctx->packet_size;

    } else

        s->packet_size = 2048;

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

        ctx->max_delay = AV_TIME_BASE*7/10;

    s->vcd_padding_bytes_written = 0;

    s->vcd_padding_bitrate_num   = 0;

    s->audio_bound = 0;

    s->video_bound = 0;

    mpa_id  = AUDIO_ID;

    ac3_id  = AC3_ID;

    dts_id  = DTS_ID;

    mpv_id  = VIDEO_ID;

    h264_id = H264_ID;

    mps_id  = SUB_ID;

    lpcm_id = LPCM_ID;

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

        st     = ctx->streams[i];

        stream = av_mallocz(sizeof(StreamInfo));

        if (!stream)

            goto fail;

        st->priv_data = stream;

        avpriv_set_pts_info(st, 64, 1, 90000);

        switch (st->codec->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            if (!s->is_mpeg2 &&

                (st->codec->codec_id == AV_CODEC_ID_AC3 ||

                 st->codec->codec_id == AV_CODEC_ID_DTS ||

                 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE))

                 av_log(ctx, AV_LOG_WARNING,

                        "%s in MPEG-1 system streams is not widely supported, "

                        "consider using the vob or the dvd muxer "

                        "to force a MPEG-2 program stream.\n",

                        avcodec_get_name(st->codec->codec_id));

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

                stream->id = ac3_id++;

            } else if (st->codec->codec_id == AV_CODEC_ID_DTS) {

                stream->id = dts_id++;

            } else if (st->codec->codec_id == AV_CODEC_ID_PCM_S16BE) {

                stream->id = lpcm_id++;

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

                    if (lpcm_freq_tab[j] == st->codec->sample_rate)

                        break;

                }

                if (j == 4)

                    goto fail;

                if (st->codec->channels > 8)

                    return -1;

                stream->lpcm_header[0] = 0x0c;

                stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);

                stream->lpcm_header[2] = 0x80;

                stream->lpcm_align     = st->codec->channels * 2;

            } else {

                stream->id = mpa_id++;

            }

            /* This value HAS to be used for VCD (see VCD standard, p. IV-7).

             * Right now it is also used for everything else. */

            stream->max_buffer_size = 4 * 1024;

            s->audio_bound++;

            break;

        case AVMEDIA_TYPE_VIDEO:

            if (st->codec->codec_id == AV_CODEC_ID_H264)

                stream->id = h264_id++;

            else

                stream->id = mpv_id++;

            if (st->codec->rc_buffer_size)

                stream->max_buffer_size = 6 * 1024 + st->codec->rc_buffer_size / 8;

            else {

                av_log(ctx, AV_LOG_WARNING,

                       "VBV buffer size not set, using default size of 130KB\n"

                       "If you want the mpeg file to be compliant to some specification\n"

                       "Like DVD, VCD or others, make sure you set the correct buffer size\n");

                // FIXME: this is probably too small as default

                stream->max_buffer_size = 230 * 1024;

            }

            if (stream->max_buffer_size > 1024 * 8191) {

                av_log(ctx, AV_LOG_WARNING, "buffer size %d, too large\n", stream->max_buffer_size);

                stream->max_buffer_size = 1024 * 8191;

            }

            s->video_bound++;

            break;

        case AVMEDIA_TYPE_SUBTITLE:

            stream->id              = mps_id++;

            stream->max_buffer_size = 16 * 1024;

            break;

        default:

            return -1;

        }

        stream->fifo = av_fifo_alloc(16);

        if (!stream->fifo)

            goto fail;

    }

    bitrate       = 0;

    audio_bitrate = 0;

    video_bitrate = 0;

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

        int codec_rate;

        st     = ctx->streams[i];

        stream = (StreamInfo *)st->priv_data;

        if (st->codec->rc_max_rate ||

            st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

            codec_rate = st->codec->rc_max_rate;

        else

            codec_rate = st->codec->bit_rate;

        if (!codec_rate)

            codec_rate = (1 << 21) * 8 * 50 / ctx->nb_streams;

        bitrate += codec_rate;

        if ((stream->id & 0xe0) == AUDIO_ID)

            audio_bitrate += codec_rate;

        else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

            video_bitrate += codec_rate;

    }

    if (s->user_mux_rate) {

        s->mux_rate = (s->user_mux_rate + (8 * 50) - 1) / (8 * 50);

    } else {

        /* we increase slightly the bitrate to take into account the

         * headers. XXX: compute it exactly */

        bitrate    += bitrate / 20;

        bitrate    += 10000;

        s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);

        if (s->mux_rate >= (1<<22)) {

            av_log(ctx, AV_LOG_WARNING, "mux rate %d is too large\n", s->mux_rate);

            s->mux_rate = (1<<22) - 1;

        }

    }

    if (s->is_vcd) {

        int64_t overhead_rate;

        /* The VCD standard mandates that the mux_rate field is 3528

         * (see standard p. IV-6).

         * The value is actually "wrong", i.e. if you calculate

         * it using the normal formula and the 75 sectors per second transfer

         * rate you get a different value because the real pack size is 2324,

         * not 2352. But the standard explicitly specifies that the mux_rate

         * field in the header must have this value. */

        // s->mux_rate = 2352 * 75 / 50;    /* = 3528 */

        /* The VCD standard states that the muxed stream must be

         * exactly 75 packs / second (the data rate of a single speed cdrom).

         * Since the video bitrate (probably 1150000 bits/sec) will be below

         * the theoretical maximum we have to add some padding packets

         * to make up for the lower data rate.

         * (cf. VCD standard p. IV-6 ) */

        /* Add the header overhead to the data rate.

         * 2279 data bytes per audio pack, 2294 data bytes per video pack */

        overhead_rate  = audio_bitrate * 2294LL * (2324 - 2279);

        overhead_rate += video_bitrate * 2279LL * (2324 - 2294);

        /* Add padding so that the full bitrate is 2324*75 bytes/sec */

        s->vcd_padding_bitrate_num = (2324LL * 75 * 8 - bitrate) * 2279 * 2294 - overhead_rate;

#define VCD_PADDING_BITRATE_DEN (2279 * 2294)

    }

    if (s->is_vcd || s->is_mpeg2)

        /* every packet */

        s->pack_header_freq = 1;

    else

        /* every 2 seconds */

        s->pack_header_freq = 2 * bitrate / s->packet_size / 8;

    /* the above seems to make pack_header_freq zero sometimes */

    if (s->pack_header_freq == 0)

        s->pack_header_freq = 1;

    if (s->is_mpeg2)

        /* every 200 packets. Need to look at the spec.  */

        s->system_header_freq = s->pack_header_freq * 40;

    else if (s->is_vcd)

        /* the standard mandates that there are only two system headers

         * in the whole file: one in the first packet of each stream.

         * (see standard p. IV-7 and IV-8) */

        s->system_header_freq = 0x7fffffff;

    else

        s->system_header_freq = s->pack_header_freq * 5;

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

        stream                = ctx->streams[i]->priv_data;

        stream->packet_number = 0;

    }

    s->system_header_size = get_system_header_size(ctx);

    s->last_scr           = AV_NOPTS_VALUE;

    return 0;

fail:

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

        av_freep(&ctx->streams[i]->priv_data);

    return AVERROR(ENOMEM);

}


static void dsputil_init_mmx2(DSPContext *c, AVCodecContext *avctx,

                              int mm_flags)

{

    const int bit_depth      = avctx->bits_per_raw_sample;

    const int high_bit_depth = bit_depth > 8;

    c->prefetch = prefetch_mmx2;

    if (!high_bit_depth) {

        c->put_pixels_tab[0][1] = put_pixels16_x2_mmx2;

        c->put_pixels_tab[0][2] = put_pixels16_y2_mmx2;

        c->avg_pixels_tab[0][0] = avg_pixels16_mmx2;

        c->avg_pixels_tab[0][1] = avg_pixels16_x2_mmx2;

        c->avg_pixels_tab[0][2] = avg_pixels16_y2_mmx2;

        c->put_pixels_tab[1][1] = put_pixels8_x2_mmx2;

        c->put_pixels_tab[1][2] = put_pixels8_y2_mmx2;

        c->avg_pixels_tab[1][0] = avg_pixels8_mmx2;

        c->avg_pixels_tab[1][1] = avg_pixels8_x2_mmx2;

        c->avg_pixels_tab[1][2] = avg_pixels8_y2_mmx2;

    }

    if (!(avctx->flags & CODEC_FLAG_BITEXACT)) {

        if (!high_bit_depth) {

            c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_mmx2;

            c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_mmx2;

            c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_mmx2;

            c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_mmx2;

            c->avg_pixels_tab[0][3] = avg_pixels16_xy2_mmx2;

            c->avg_pixels_tab[1][3] = avg_pixels8_xy2_mmx2;

        }

        if (CONFIG_VP3_DECODER && HAVE_YASM) {

            c->vp3_v_loop_filter = ff_vp3_v_loop_filter_mmx2;

            c->vp3_h_loop_filter = ff_vp3_h_loop_filter_mmx2;

        }

    }

    if (CONFIG_VP3_DECODER && HAVE_YASM)

        c->vp3_idct_dc_add = ff_vp3_idct_dc_add_mmx2;

    if (CONFIG_VP3_DECODER && (avctx->codec_id == CODEC_ID_VP3 ||

                               avctx->codec_id == CODEC_ID_THEORA)) {

        c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_exact_mmx2;

        c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_mmx2;

    }

    if (CONFIG_H264QPEL) {

        SET_QPEL_FUNCS(put_qpel,        0, 16, mmx2, );

        SET_QPEL_FUNCS(put_qpel,        1,  8, mmx2, );

        SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, mmx2, );

        SET_QPEL_FUNCS(put_no_rnd_qpel, 1,  8, mmx2, );

        SET_QPEL_FUNCS(avg_qpel,        0, 16, mmx2, );

        SET_QPEL_FUNCS(avg_qpel,        1,  8, mmx2, );

        if (!high_bit_depth) {

            SET_QPEL_FUNCS(put_h264_qpel, 0, 16, mmx2, );

            SET_QPEL_FUNCS(put_h264_qpel, 1,  8, mmx2, );

            SET_QPEL_FUNCS(put_h264_qpel, 2,  4, mmx2, );

            SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, mmx2, );

            SET_QPEL_FUNCS(avg_h264_qpel, 1,  8, mmx2, );

            SET_QPEL_FUNCS(avg_h264_qpel, 2,  4, mmx2, );

        } else if (bit_depth == 10) {

#if HAVE_YASM

#if !ARCH_X86_64

            SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, 10_mmxext, ff_);

            SET_QPEL_FUNCS(put_h264_qpel, 0, 16, 10_mmxext, ff_);

            SET_QPEL_FUNCS(put_h264_qpel, 1,  8, 10_mmxext, ff_);

            SET_QPEL_FUNCS(avg_h264_qpel, 1,  8, 10_mmxext, ff_);

#endif

            SET_QPEL_FUNCS(put_h264_qpel, 2, 4,  10_mmxext, ff_);

            SET_QPEL_FUNCS(avg_h264_qpel, 2, 4,  10_mmxext, ff_);

#endif

        }

        SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, mmx2, );

        SET_QPEL_FUNCS(put_2tap_qpel, 1,  8, mmx2, );

        SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, mmx2, );

        SET_QPEL_FUNCS(avg_2tap_qpel, 1,  8, mmx2, );

    }

#if HAVE_YASM

    if (!high_bit_depth && CONFIG_H264CHROMA) {

        c->avg_h264_chroma_pixels_tab[0] = ff_avg_h264_chroma_mc8_mmx2_rnd;

        c->avg_h264_chroma_pixels_tab[1] = ff_avg_h264_chroma_mc4_mmx2;

        c->avg_h264_chroma_pixels_tab[2] = ff_avg_h264_chroma_mc2_mmx2;

        c->put_h264_chroma_pixels_tab[2] = ff_put_h264_chroma_mc2_mmx2;

    }

    if (bit_depth == 10 && CONFIG_H264CHROMA) {

        c->put_h264_chroma_pixels_tab[2] = ff_put_h264_chroma_mc2_10_mmxext;

        c->avg_h264_chroma_pixels_tab[2] = ff_avg_h264_chroma_mc2_10_mmxext;

        c->put_h264_chroma_pixels_tab[1] = ff_put_h264_chroma_mc4_10_mmxext;

        c->avg_h264_chroma_pixels_tab[1] = ff_avg_h264_chroma_mc4_10_mmxext;

    }

    c->add_hfyu_median_prediction   = ff_add_hfyu_median_prediction_mmx2;

    c->scalarproduct_int16          = ff_scalarproduct_int16_mmx2;

    c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_mmx2;

    if (avctx->flags & CODEC_FLAG_BITEXACT) {

        c->apply_window_int16 = ff_apply_window_int16_mmxext_ba;

    } else {

        c->apply_window_int16 = ff_apply_window_int16_mmxext;

    }

#endif

}


static int vaapi_encode_h264_init_sequence_params(AVCodecContext *avctx)

{

    VAAPIEncodeContext                 *ctx = avctx->priv_data;

    VAEncSequenceParameterBufferH264  *vseq = ctx->codec_sequence_params;

    VAEncPictureParameterBufferH264   *vpic = ctx->codec_picture_params;

    VAAPIEncodeH264Context            *priv = ctx->priv_data;

    VAAPIEncodeH264MiscSequenceParams *mseq = &priv->misc_sequence_params;

    int i;

    {

        vseq->seq_parameter_set_id = 0;

        vseq->level_idc = avctx->level;

        vseq->max_num_ref_frames = 2;

        vseq->picture_width_in_mbs  = priv->mb_width;

        vseq->picture_height_in_mbs = priv->mb_height;

        vseq->seq_fields.bits.chroma_format_idc = 1;

        vseq->seq_fields.bits.frame_mbs_only_flag = 1;

        vseq->seq_fields.bits.direct_8x8_inference_flag = 1;

        vseq->seq_fields.bits.log2_max_frame_num_minus4 = 4;

        vseq->seq_fields.bits.pic_order_cnt_type = 0;

        if (ctx->input_width  != ctx->aligned_width ||

            ctx->input_height != ctx->aligned_height) {

            vseq->frame_cropping_flag = 1;

            vseq->frame_crop_left_offset   = 0;

            vseq->frame_crop_right_offset  =

                (ctx->aligned_width - ctx->input_width) / 2;

            vseq->frame_crop_top_offset    = 0;

            vseq->frame_crop_bottom_offset =

                (ctx->aligned_height - ctx->input_height) / 2;

        } else {

            vseq->frame_cropping_flag = 0;

        }

        vseq->vui_parameters_present_flag = 1;

        if (avctx->sample_aspect_ratio.num != 0) {

            vseq->vui_fields.bits.aspect_ratio_info_present_flag = 1;

            // There is a large enum of these which we could support

            // individually rather than using the generic X/Y form?

            if (avctx->sample_aspect_ratio.num ==

                avctx->sample_aspect_ratio.den) {

                vseq->aspect_ratio_idc = 1;

            } else {

                vseq->aspect_ratio_idc = 255; // Extended SAR.

                vseq->sar_width  = avctx->sample_aspect_ratio.num;

                vseq->sar_height = avctx->sample_aspect_ratio.den;

            }

        }

        if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||

            avctx->color_trc       != AVCOL_TRC_UNSPECIFIED ||

            avctx->colorspace      != AVCOL_SPC_UNSPECIFIED) {

            mseq->video_signal_type_present_flag = 1;

            mseq->video_format             = 5; // Unspecified.

            mseq->video_full_range_flag    = 0;

            mseq->colour_description_present_flag = 1;

            // These enums are derived from the standard and hence

            // we can just use the values directly.

            mseq->colour_primaries         = avctx->color_primaries;

            mseq->transfer_characteristics = avctx->color_trc;

            mseq->matrix_coefficients      = avctx->colorspace;

        }

        vseq->bits_per_second = avctx->bit_rate;

        vseq->vui_fields.bits.timing_info_present_flag = 1;

        if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {

            vseq->num_units_in_tick = avctx->framerate.num;

            vseq->time_scale        = 2 * avctx->framerate.den;

            mseq->fixed_frame_rate_flag = 1;

        } else {

            vseq->num_units_in_tick = avctx->time_base.num;

            vseq->time_scale        = 2 * avctx->time_base.den;

            mseq->fixed_frame_rate_flag = 0;

        }

        if (ctx->va_rc_mode == VA_RC_CBR) {

            priv->send_timing_sei = 1;

            mseq->nal_hrd_parameters_present_flag = 1;

            mseq->cpb_cnt_minus1 = 0;

            // Try to scale these to a sensible range so that the

            // golomb encode of the value is not overlong.

            mseq->bit_rate_scale =

                av_clip_uintp2(av_log2(avctx->bit_rate) - 15 - 6, 4);

            mseq->bit_rate_value_minus1[0] =

                (avctx->bit_rate >> mseq->bit_rate_scale + 6) - 1;

            mseq->cpb_size_scale =

                av_clip_uintp2(av_log2(priv->hrd_params.hrd.buffer_size) - 15 - 4, 4);

            mseq->cpb_size_value_minus1[0] =

                (priv->hrd_params.hrd.buffer_size >> mseq->cpb_size_scale + 4) - 1;

            // CBR mode isn't actually available here, despite naming.

            mseq->cbr_flag[0] = 0;

            mseq->initial_cpb_removal_delay_length_minus1 = 23;

            mseq->cpb_removal_delay_length_minus1         = 23;

            mseq->dpb_output_delay_length_minus1          = 7;

            mseq->time_offset_length = 0;

            // This calculation can easily overflow 32 bits.

            mseq->initial_cpb_removal_delay = 90000 *

                (uint64_t)priv->hrd_params.hrd.initial_buffer_fullness /

                priv->hrd_params.hrd.buffer_size;

            mseq->initial_cpb_removal_delay_offset = 0;

        } else {

            priv->send_timing_sei = 0;

            mseq->nal_hrd_parameters_present_flag = 0;

        }

        vseq->intra_period     = ctx->p_per_i * (ctx->b_per_p + 1);

        vseq->intra_idr_period = vseq->intra_period;

        vseq->ip_period        = ctx->b_per_p + 1;

    }

    {

        vpic->CurrPic.picture_id = VA_INVALID_ID;

        vpic->CurrPic.flags      = VA_PICTURE_H264_INVALID;

        for (i = 0; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {

            vpic->ReferenceFrames[i].picture_id = VA_INVALID_ID;

            vpic->ReferenceFrames[i].flags      = VA_PICTURE_H264_INVALID;

        }

        vpic->coded_buf = VA_INVALID_ID;

        vpic->pic_parameter_set_id = 0;

        vpic->seq_parameter_set_id = 0;

        vpic->num_ref_idx_l0_active_minus1 = 0;

        vpic->num_ref_idx_l1_active_minus1 = 0;

        vpic->pic_fields.bits.entropy_coding_mode_flag =

            ((avctx->profile & 0xff) != 66);

        vpic->pic_fields.bits.weighted_pred_flag = 0;

        vpic->pic_fields.bits.weighted_bipred_idc = 0;

        vpic->pic_fields.bits.transform_8x8_mode_flag =

            ((avctx->profile & 0xff) >= 100);

        vpic->pic_init_qp = priv->fixed_qp_idr;

    }

    {

        mseq->profile_idc = avctx->profile & 0xff;

        if (avctx->profile & FF_PROFILE_H264_CONSTRAINED)

            mseq->constraint_set1_flag = 1;

        if (avctx->profile & FF_PROFILE_H264_INTRA)

            mseq->constraint_set3_flag = 1;

    }

    return 0;

}


void if_start(Slirp *slirp)

{

    uint64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);

    bool from_batchq, next_from_batchq;

    struct mbuf *ifm, *ifm_next, *ifqt;

    DEBUG_CALL("if_start");

    if (slirp->if_start_busy) {

        return;

    }

    slirp->if_start_busy = true;

    if (slirp->if_fastq.ifq_next != &slirp->if_fastq) {

        ifm_next = slirp->if_fastq.ifq_next;

        next_from_batchq = false;

    } else if (slirp->next_m != &slirp->if_batchq) {

        /* Nothing on fastq, pick up from batchq via next_m */

        ifm_next = slirp->next_m;

        next_from_batchq = true;

    } else {

        ifm_next = NULL;

    }

    while (ifm_next) {

        ifm = ifm_next;

        from_batchq = next_from_batchq;

        ifm_next = ifm->ifq_next;

        if (ifm_next == &slirp->if_fastq) {

            /* No more packets in fastq, switch to batchq */

            ifm_next = slirp->next_m;

            next_from_batchq = true;

        }

        if (ifm_next == &slirp->if_batchq) {

            /* end of batchq */

            ifm_next = NULL;

        }

        /* Try to send packet unless it already expired */

        if (ifm->expiration_date >= now && !if_encap(slirp, ifm)) {

            /* Packet is delayed due to pending ARP resolution */

            continue;

        }

        if (ifm == slirp->next_m) {

            /* Set which packet to send on next iteration */

            slirp->next_m = ifm->ifq_next;

        }

        /* Remove it from the queue */

        ifqt = ifm->ifq_prev;

        remque(ifm);

        /* If there are more packets for this session, re-queue them */

        if (ifm->ifs_next != ifm) {

            struct mbuf *next = ifm->ifs_next;

            insque(next, ifqt);

            ifs_remque(ifm);

            if (!from_batchq) {

                /* Next packet in fastq is from the same session */

                ifm_next = next;

                next_from_batchq = false;

            } else if (slirp->next_m == &slirp->if_batchq) {

                /* Set next_m and ifm_next if the session packet is now the

                 * only one on batchq */

                slirp->next_m = ifm_next = next;

            }

        }

        /* Update so_queued */

        if (ifm->ifq_so && --ifm->ifq_so->so_queued == 0) {

            /* If there's no more queued, reset nqueued */

            ifm->ifq_so->so_nqueued = 0;

        }

        m_free(ifm);

    }

    slirp->if_start_busy = false;

}


static void handle_ti(ESPState *s)

{

    uint32_t dmalen, minlen;

    if (s->dma && !s->dma_enabled) {

        s->dma_cb = handle_ti;

        return;

    }

    dmalen = s->rregs[ESP_TCLO];

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

    dmalen |= s->rregs[ESP_TCHI] << 16;

    if (dmalen==0) {

      dmalen=0x10000;

    }

    s->dma_counter = dmalen;

    if (s->do_cmd)

        minlen = (dmalen < 32) ? dmalen : 32;

    else if (s->ti_size < 0)

        minlen = (dmalen < -s->ti_size) ? dmalen : -s->ti_size;

    else

        minlen = (dmalen < s->ti_size) ? dmalen : s->ti_size;

    trace_esp_handle_ti(minlen);

    if (s->dma) {

        s->dma_left = minlen;

        s->rregs[ESP_RSTAT] &= ~STAT_TC;

        esp_do_dma(s);

    }

    if (s->do_cmd) {

        trace_esp_handle_ti_cmd(s->cmdlen);

        s->ti_size = 0;

        s->cmdlen = 0;

        s->do_cmd = 0;

        do_cmd(s, s->cmdbuf);

    }

}


static void lsi53c895a_register_devices(void)

{

    type_register_static(&lsi_info);

    type_register_static_alias(&lsi_info, "lsi");

}


static void receive_from_chr_layer(SCLPConsole *scon, const uint8_t *buf,

                                   int size)

{

    /* read data must fit into current buffer */

    assert(size <= SIZE_BUFFER_VT220 - scon->iov_data_len);

    /* put byte-stream from character layer into buffer */

    memcpy(&scon->iov[scon->iov_bs], buf, size);

    scon->iov_data_len += size;

    scon->iov_sclp_rest += size;

    scon->iov_bs += size;

    scon->event.event_pending = true;

}


static void usbredir_do_attach(void *opaque)

{

    USBRedirDevice *dev = opaque;

    /* In order to work properly with XHCI controllers we need these caps */

    if ((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER) && !(

                                    usb_redir_cap_ep_info_max_packet_size) &&

                                    usb_redir_cap_64bits_ids))) {

        ERROR("usb-redir-host lacks capabilities needed for use with XHCI\n");

        usbredir_reject_device(dev);

        return;

    }

    if (usb_device_attach(&dev->dev) != 0) {

        WARNING("rejecting device due to speed mismatch\n");

        usbredir_reject_device(dev);

    }

}


static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)

{

    int ch, bw_code;

    if (cutoff) {

        /* calculate bandwidth based on user-specified cutoff frequency */

        int fbw_coeffs;

        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);

        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;

        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);

    } else {

        /* use default bandwidth setting */

        /* XXX: should compute the bandwidth according to the frame

           size, so that we avoid annoying high frequency artifacts */

        bw_code = 50;

    }

    /* set number of coefficients for each channel */

    for (ch = 0; ch < s->fbw_channels; ch++) {

        s->bandwidth_code[ch] = bw_code;

        s->nb_coefs[ch]       = bw_code * 3 + 73;

    }

    if (s->lfe_on)

        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */

}


static inline void RENAME(yuy2ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(

        "movq "MANGLE(bm01010101)", %%mm4           \n\t"

        "mov                    %0, %%"REG_a"       \n\t"

        "1:                                         \n\t"

        "movq    (%1, %%"REG_a",4), %%mm0           \n\t"

        "movq   8(%1, %%"REG_a",4), %%mm1           \n\t"

        "psrlw                  $8, %%mm0           \n\t"

        "psrlw                  $8, %%mm1           \n\t"

        "packuswb            %%mm1, %%mm0           \n\t"

        "movq                %%mm0, %%mm1           \n\t"

        "psrlw                  $8, %%mm0           \n\t"

        "pand                %%mm4, %%mm1           \n\t"

        "packuswb            %%mm0, %%mm0           \n\t"

        "packuswb            %%mm1, %%mm1           \n\t"

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

        "movd                %%mm1, (%2, %%"REG_a") \n\t"

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

        " js                    1b                  \n\t"

        : : "g" ((x86_reg)-width), "r" (src1+width*4), "r" (dstU+width), "r" (dstV+width)

        : "%"REG_a

    );

#else

    int i;

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

        dstU[i]= src1[4*i + 1];

        dstV[i]= src1[4*i + 3];

    }

#endif

    assert(src1 == src2);

}


static void xtensa_kc705_init(MachineState *machine)

{

    static const LxBoardDesc kc705_board = {

        .flash_base = 0xf0000000,

        .flash_size = 0x08000000,

        .flash_boot_base = 0x06000000,

        .flash_sector_size = 0x20000,

        .sram_size = 0x2000000,

    };

    lx_init(&kc705_board, machine);

}


static void virtqueue_unmap_sg(VirtQueue *vq, const VirtQueueElement *elem,

                               unsigned int len)

{

    unsigned int offset;

    int i;

    offset = 0;

    for (i = 0; i < elem->in_num; i++) {

        size_t size = MIN(len - offset, elem->in_sg[i].iov_len);

        cpu_physical_memory_unmap(elem->in_sg[i].iov_base,

                                  elem->in_sg[i].iov_len,

                                  1, size);

        offset += size;

    }

    for (i = 0; i < elem->out_num; i++)

        cpu_physical_memory_unmap(elem->out_sg[i].iov_base,

                                  elem->out_sg[i].iov_len,

                                  0, elem->out_sg[i].iov_len);

}


static int vmdk_reopen_prepare(BDRVReopenState *state,

                               BlockReopenQueue *queue, Error **errp)

{

    BDRVVmdkState *s;

    int ret = -1;

    int i;

    VmdkExtent *e;

    assert(state != NULL);

    assert(state->bs != NULL);

    if (queue == NULL) {

        error_setg(errp, "No reopen queue for VMDK extents");

        goto exit;

    }

    s = state->bs->opaque;

    assert(s != NULL);

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

        e = &s->extents[i];

        if (e->file != state->bs->file) {

            bdrv_reopen_queue(queue, e->file, state->flags);

        }

    }

    ret = 0;

exit:

    return ret;

}


static inline void tcg_out_goto_label(TCGContext *s, int label_index)

{

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

    if (!l->has_value) {

        tcg_out_reloc(s, s->code_ptr, R_AARCH64_JUMP26, label_index, 0);

        tcg_out_goto_noaddr(s);

    } else {

        tcg_out_goto(s, l->u.value_ptr);

    }

}


static void ac97_map (PCIDevice *pci_dev, int region_num,

                      uint32_t addr, uint32_t size, int type)

{

    PCIAC97LinkState *d = (PCIAC97LinkState *) pci_dev;

    AC97LinkState *s = &d->ac97;

    if (!region_num) {

        s->base[0] = addr;

        register_ioport_read (addr, 256 * 1, 1, nam_readb, d);

        register_ioport_read (addr, 256 * 2, 2, nam_readw, d);

        register_ioport_read (addr, 256 * 4, 4, nam_readl, d);

        register_ioport_write (addr, 256 * 1, 1, nam_writeb, d);

        register_ioport_write (addr, 256 * 2, 2, nam_writew, d);

        register_ioport_write (addr, 256 * 4, 4, nam_writel, d);

    }

    else {

        s->base[1] = addr;

        register_ioport_read (addr, 64 * 1, 1, nabm_readb, d);

        register_ioport_read (addr, 64 * 2, 2, nabm_readw, d);

        register_ioport_read (addr, 64 * 4, 4, nabm_readl, d);

        register_ioport_write (addr, 64 * 1, 1, nabm_writeb, d);

        register_ioport_write (addr, 64 * 2, 2, nabm_writew, d);

        register_ioport_write (addr, 64 * 4, 4, nabm_writel, d);

    }

}


void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,

                        void *opaque)

{

    SaveStateEntry *se, *new_se;

    QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {

        if (se->vmsd == vmsd && se->opaque == opaque) {

            QTAILQ_REMOVE(&savevm_state.handlers, se, entry);

            if (se->compat) {

                g_free(se->compat);

            }

            g_free(se);

        }

    }

}


static int xenfb_send_motion(struct XenInput *xenfb,

			     int rel_x, int rel_y, int rel_z)

{

    union xenkbd_in_event event;

    memset(&event, 0, XENKBD_IN_EVENT_SIZE);

    event.type = XENKBD_TYPE_MOTION;

    event.motion.rel_x = rel_x;

    event.motion.rel_y = rel_y;

#if __XEN_LATEST_INTERFACE_VERSION__ >= 0x00030207

    event.motion.rel_z = rel_z;

#endif

    return xenfb_kbd_event(xenfb, &event);

}


static int read_header(AVFormatContext *s,

                       AVFormatParameters *ap)

{

    JVDemuxContext *jv = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *vst, *ast;

    int64_t audio_pts = 0;

    int64_t offset;

    int i;

    avio_skip(pb, 80);

    ast = av_new_stream(s, 0);

    vst = av_new_stream(s, 1);

    if (!ast || !vst)

        return AVERROR(ENOMEM);

    vst->codec->codec_type  = CODEC_TYPE_VIDEO;

    vst->codec->codec_id    = CODEC_ID_JV;

    vst->codec->codec_tag   = 0; /* no fourcc */

    vst->codec->width       = avio_rl16(pb);

    vst->codec->height      = avio_rl16(pb);

    vst->nb_frames          =

    ast->nb_index_entries   = avio_rl16(pb);

    av_set_pts_info(vst, 64, avio_rl16(pb), 1000);

    avio_skip(pb, 4);

    ast->codec->codec_type  = CODEC_TYPE_AUDIO;

    ast->codec->codec_id    = CODEC_ID_PCM_U8;

    ast->codec->codec_tag   = 0; /* no fourcc */

    ast->codec->sample_rate = avio_rl16(pb);

    ast->codec->channels    = 1;

    av_set_pts_info(ast, 64, 1, ast->codec->sample_rate);

    avio_skip(pb, 10);

    ast->index_entries = av_malloc(ast->nb_index_entries * sizeof(*ast->index_entries));

    if (!ast->index_entries)

        return AVERROR(ENOMEM);

    jv->frames = av_malloc(ast->nb_index_entries * sizeof(JVFrame));

    if (!jv->frames)

        return AVERROR(ENOMEM);

    offset = 0x68 + ast->nb_index_entries * 16;

    for(i = 0; i < ast->nb_index_entries; i++) {

        AVIndexEntry *e   = ast->index_entries + i;

        JVFrame      *jvf = jv->frames + i;

        /* total frame size including audio, video, palette data and padding */

        e->size         = avio_rl32(pb);

        e->timestamp    = i;

        e->pos          = offset;

        offset         += e->size;

        jvf->audio_size = avio_rl32(pb);

        jvf->video_size = avio_rl32(pb);

        jvf->palette_size = avio_r8(pb) ? 768 : 0;

        if (avio_r8(pb))

             av_log(s, AV_LOG_WARNING, "unsupported audio codec\n");

        jvf->video_type = avio_r8(pb);

        avio_skip(pb, 1);

        e->timestamp = jvf->audio_size ? audio_pts : AV_NOPTS_VALUE;

        audio_pts += jvf->audio_size;

        e->flags = jvf->video_type != 1 ? AVINDEX_KEYFRAME : 0;

    }

    jv->state = JV_AUDIO;

    return 0;

}


static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)

{

    // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9

    // Ref (MP4): ISO/IEC 14496-12:2012

    if (track->enc->color_primaries == AVCOL_PRI_UNSPECIFIED &&

        track->enc->color_trc == AVCOL_TRC_UNSPECIFIED &&

        track->enc->colorspace == AVCOL_SPC_UNSPECIFIED) {

        if ((track->enc->width >= 1920 && track->enc->height >= 1080)

          || (track->enc->width == 1280 && track->enc->height == 720)) {

            av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");

            track->enc->color_primaries = AVCOL_PRI_BT709;

        } else if (track->enc->width == 720 && track->height == 576) {

            av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");

            track->enc->color_primaries = AVCOL_PRI_BT470BG;

        } else if (track->enc->width == 720 &&

                   (track->height == 486 || track->height == 480)) {

            av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");

            track->enc->color_primaries = AVCOL_PRI_SMPTE170M;

        } else {

            av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");

        }

        switch (track->enc->color_primaries) {

        case AVCOL_PRI_BT709:

            track->enc->color_trc = AVCOL_TRC_BT709;

            track->enc->colorspace = AVCOL_SPC_BT709;

            break;

        case AVCOL_PRI_SMPTE170M:

        case AVCOL_PRI_BT470BG:

            track->enc->color_trc = AVCOL_TRC_BT709;

            track->enc->colorspace = AVCOL_SPC_SMPTE170M;

            break;

        }

    }

    /* We should only ever be called by MOV or MP4. */

    av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);

    avio_wb32(pb, 18 + (track->mode == MODE_MP4));

    ffio_wfourcc(pb, "colr");

    if (track->mode == MODE_MP4)

        ffio_wfourcc(pb, "nclx");

    else

        ffio_wfourcc(pb, "nclc");

    switch (track->enc->color_primaries) {

    case AVCOL_PRI_BT709:     avio_wb16(pb, 1); break;

    case AVCOL_PRI_SMPTE170M:

    case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;

    case AVCOL_PRI_BT470BG:   avio_wb16(pb, 5); break;

    default:                  avio_wb16(pb, 2);

    }

    switch (track->enc->color_trc) {

    case AVCOL_TRC_BT709:     avio_wb16(pb, 1); break;

    case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped

    case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;

    default:                  avio_wb16(pb, 2);

    }

    switch (track->enc->colorspace) {

    case AVCOL_TRC_BT709:     avio_wb16(pb, 1); break;

    case AVCOL_SPC_BT470BG:

    case AVCOL_PRI_SMPTE170M: avio_wb16(pb, 6); break;

    case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 7); break;

    default:                  avio_wb16(pb, 2);

    }

    if (track->mode == MODE_MP4) {

        int full_range = track->enc->color_range == AVCOL_RANGE_JPEG;

        avio_w8(pb, full_range << 7);

        return 19;

    } else {

        return 18;

    }

}


static int slirp_socket_load(QEMUFile *f, struct socket *so)

{

    if (tcp_attach(so) < 0)

        return -ENOMEM;

    so->so_urgc = qemu_get_be32(f);

    so->so_ffamily = qemu_get_be16(f);

    switch (so->so_ffamily) {

    case AF_INET:

        so->so_faddr.s_addr = qemu_get_be32(f);

        so->so_fport = qemu_get_be16(f);

        break;

    default:

        error_report(

                "so_ffamily unknown, unable to restore so_faddr and so_lport\n");

    }

    so->so_lfamily = qemu_get_be16(f);

    switch (so->so_lfamily) {

    case AF_INET:

        so->so_laddr.s_addr = qemu_get_be32(f);

        so->so_lport = qemu_get_be16(f);

        break;

    default:

        error_report(

                "so_ffamily unknown, unable to restore so_laddr and so_lport\n");

    }

    so->so_iptos = qemu_get_byte(f);

    so->so_emu = qemu_get_byte(f);

    so->so_type = qemu_get_byte(f);

    so->so_state = qemu_get_be32(f);

    if (slirp_sbuf_load(f, &so->so_rcv) < 0)

        return -ENOMEM;

    if (slirp_sbuf_load(f, &so->so_snd) < 0)

        return -ENOMEM;

    slirp_tcp_load(f, so->so_tcpcb);

    return 0;

}


static int qdev_print_devinfo(DeviceInfo *info, char *dest, int len)

{

    int pos = 0;

    pos += snprintf(dest+pos, len-pos, "name \"%s\", bus %s",

                    info->name, info->bus_info->name);

    if (info->alias)

        pos += snprintf(dest+pos, len-pos, ", alias \"%s\"", info->alias);

    if (info->desc)

        pos += snprintf(dest+pos, len-pos, ", desc \"%s\"", info->desc);

    if (info->no_user)

        pos += snprintf(dest+pos, len-pos, ", no-user");

    return pos;

}


static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)

{

    int next_avc    = h->is_avc ? 0 : buf_size;

    int nal_index   = 0;

    int buf_index   = 0;

    int nals_needed = 0;

    while(1) {

        int nalsize = 0;

        int dst_length, bit_length, consumed;

        const uint8_t *ptr;

        if (buf_index >= next_avc) {

            nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);

            if (nalsize < 0)

                break;

            next_avc = buf_index + nalsize;

        } else {

            buf_index = find_start_code(buf, buf_size, buf_index, next_avc);

            if (buf_index >= buf_size)

                break;

        }

        ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,

                                 next_avc - buf_index);

        if (ptr == NULL || dst_length < 0)

            return AVERROR_INVALIDDATA;

        buf_index += consumed;

        bit_length = get_bit_length(h, buf, ptr, dst_length,

                                    buf_index, next_avc);

        nal_index++;

        /* packets can sometimes contain multiple PPS/SPS,

         * e.g. two PAFF field pictures in one packet, or a demuxer

         * which splits NALs strangely if so, when frame threading we

         * can't start the next thread until we've read all of them */

        switch (h->nal_unit_type) {

        case NAL_SPS:

        case NAL_PPS:

            nals_needed = nal_index;

            break;

        case NAL_DPA:

        case NAL_IDR_SLICE:

        case NAL_SLICE:

            init_get_bits(&h->gb, ptr, bit_length);

            if (!get_ue_golomb(&h->gb))

                nals_needed = nal_index;

        }

    }

    return nals_needed;

}


e1000e_write_packet_to_guest(E1000ECore *core, struct NetRxPkt *pkt,

                             const E1000E_RxRing *rxr,

                             const E1000E_RSSInfo *rss_info)

{

    PCIDevice *d = core->owner;

    dma_addr_t base;

    uint8_t desc[E1000_MAX_RX_DESC_LEN];

    size_t desc_size;

    size_t desc_offset = 0;

    size_t iov_ofs = 0;

    struct iovec *iov = net_rx_pkt_get_iovec(pkt);

    size_t size = net_rx_pkt_get_total_len(pkt);

    size_t total_size = size + e1000x_fcs_len(core->mac);

    const E1000E_RingInfo *rxi;

    size_t ps_hdr_len = 0;

    bool do_ps = e1000e_do_ps(core, pkt, &ps_hdr_len);

    rxi = rxr->i;

    do {

        hwaddr ba[MAX_PS_BUFFERS];

        e1000e_ba_state bastate = { { 0 } };

        bool is_last = false;

        bool is_first = true;

        desc_size = total_size - desc_offset;

        if (desc_size > core->rx_desc_buf_size) {

            desc_size = core->rx_desc_buf_size;

        }

        base = e1000e_ring_head_descr(core, rxi);

        pci_dma_read(d, base, &desc, core->rx_desc_len);

        trace_e1000e_rx_descr(rxi->idx, base, core->rx_desc_len);

        e1000e_read_rx_descr(core, desc, &ba);

        if (ba[0]) {

            if (desc_offset < size) {

                static const uint32_t fcs_pad;

                size_t iov_copy;

                size_t copy_size = size - desc_offset;

                if (copy_size > core->rx_desc_buf_size) {

                    copy_size = core->rx_desc_buf_size;

                }

                /* For PS mode copy the packet header first */

                if (do_ps) {

                    if (is_first) {

                        size_t ps_hdr_copied = 0;

                        do {

                            iov_copy = MIN(ps_hdr_len - ps_hdr_copied,

                                           iov->iov_len - iov_ofs);

                            e1000e_write_hdr_to_rx_buffers(core, &ba, &bastate,

                                                      iov->iov_base, iov_copy);

                            copy_size -= iov_copy;

                            ps_hdr_copied += iov_copy;

                            iov_ofs += iov_copy;

                            if (iov_ofs == iov->iov_len) {

                                iov++;

                                iov_ofs = 0;

                            }

                        } while (ps_hdr_copied < ps_hdr_len);

                        is_first = false;

                    } else {

                        /* Leave buffer 0 of each descriptor except first */

                        /* empty as per spec 7.1.5.1                      */

                        e1000e_write_hdr_to_rx_buffers(core, &ba, &bastate,

                                                       NULL, 0);

                    }

                }

                /* Copy packet payload */

                while (copy_size) {

                    iov_copy = MIN(copy_size, iov->iov_len - iov_ofs);

                    e1000e_write_to_rx_buffers(core, &ba, &bastate,

                                            iov->iov_base + iov_ofs, iov_copy);

                    copy_size -= iov_copy;

                    iov_ofs += iov_copy;

                    if (iov_ofs == iov->iov_len) {

                        iov++;

                        iov_ofs = 0;

                    }

                }

                if (desc_offset + desc_size >= total_size) {

                    /* Simulate FCS checksum presence in the last descriptor */

                    e1000e_write_to_rx_buffers(core, &ba, &bastate,

                          (const char *) &fcs_pad, e1000x_fcs_len(core->mac));

                }

            }

            desc_offset += desc_size;

            if (desc_offset >= total_size) {

                is_last = true;

            }

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

            trace_e1000e_rx_null_descriptor();

        }

        e1000e_write_rx_descr(core, desc, is_last ? core->rx_pkt : NULL,

                           rss_info, do_ps ? ps_hdr_len : 0, &bastate.written);

        pci_dma_write(d, base, &desc, core->rx_desc_len);

        e1000e_ring_advance(core, rxi,

                            core->rx_desc_len / E1000_MIN_RX_DESC_LEN);

    } while (desc_offset < total_size);

    e1000e_update_rx_stats(core, size, total_size);

}


static int cirrus_do_copy(CirrusVGAState *s, int dst, int src, int w, int h)

{

    int sx = 0, sy = 0;

    int dx = 0, dy = 0;

    int depth = 0;

    int notify = 0;

    /* make sure to only copy if it's a plain copy ROP */

    if (*s->cirrus_rop == cirrus_bitblt_rop_fwd_src ||

        *s->cirrus_rop == cirrus_bitblt_rop_bkwd_src) {

        int width, height;

        depth = s->vga.get_bpp(&s->vga) / 8;

        if (!depth) {

            return 0;

        }

        s->vga.get_resolution(&s->vga, &width, &height);

        /* extra x, y */

        sx = (src % ABS(s->cirrus_blt_srcpitch)) / depth;

        sy = (src / ABS(s->cirrus_blt_srcpitch));

        dx = (dst % ABS(s->cirrus_blt_dstpitch)) / depth;

        dy = (dst / ABS(s->cirrus_blt_dstpitch));

        /* normalize width */

        w /= depth;

        /* if we're doing a backward copy, we have to adjust

           our x/y to be the upper left corner (instead of the lower

           right corner) */

        if (s->cirrus_blt_dstpitch < 0) {

            sx -= (s->cirrus_blt_width / depth) - 1;

            dx -= (s->cirrus_blt_width / depth) - 1;

            sy -= s->cirrus_blt_height - 1;

            dy -= s->cirrus_blt_height - 1;

        }

        /* are we in the visible portion of memory? */

        if (sx >= 0 && sy >= 0 && dx >= 0 && dy >= 0 &&

            (sx + w) <= width && (sy + h) <= height &&

            (dx + w) <= width && (dy + h) <= height) {

            notify = 1;

        }

    }

    (*s->cirrus_rop) (s, s->vga.vram_ptr + s->cirrus_blt_dstaddr,

                      s->vga.vram_ptr + s->cirrus_blt_srcaddr,

		      s->cirrus_blt_dstpitch, s->cirrus_blt_srcpitch,

		      s->cirrus_blt_width, s->cirrus_blt_height);

    if (notify) {

        dpy_gfx_update(s->vga.con, dx, dy,

                       s->cirrus_blt_width / depth,

                       s->cirrus_blt_height);

    }

    /* we don't have to notify the display that this portion has

       changed since qemu_console_copy implies this */

    cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,

				s->cirrus_blt_dstpitch, s->cirrus_blt_width,

				s->cirrus_blt_height);

    return 1;

}


static int write_l1_entry(BlockDriverState *bs, int l1_index)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t buf[L1_ENTRIES_PER_SECTOR];

    int l1_start_index;

    int i, ret;

    l1_start_index = l1_index & ~(L1_ENTRIES_PER_SECTOR - 1);

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

        buf[i] = cpu_to_be64(s->l1_table[l1_start_index + i]);

    }

    BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);

    ret = bdrv_pwrite(bs->file, s->l1_table_offset + 8 * l1_start_index,

        buf, sizeof(buf));

    if (ret < 0) {

        return ret;

    }

    return 0;

}


int vhost_dev_init(struct vhost_dev *hdev, void *opaque,
                   VhostBackendType backend_type)
{
    uint64_t features;
    int i, r;
    if (vhost_set_backend_type(hdev, backend_type) < 0) {
        close((uintptr_t)opaque);
        return -1;
    }
    if (hdev->vhost_ops->vhost_backend_init(hdev, opaque) < 0) {
        close((uintptr_t)opaque);
        return -errno;
    }
    r = hdev->vhost_ops->vhost_call(hdev, VHOST_SET_OWNER, NULL);
    if (r < 0) {
        goto fail;
    }
    r = hdev->vhost_ops->vhost_call(hdev, VHOST_GET_FEATURES, &features);
    if (r < 0) {
        goto fail;
    }
    for (i = 0; i < hdev->nvqs; ++i) {
        r = vhost_virtqueue_init(hdev, hdev->vqs + i, hdev->vq_index + i);
        if (r < 0) {
            goto fail_vq;
        }
    }
    hdev->features = features;
    hdev->memory_listener = (MemoryListener) {
        .begin = vhost_begin,
        .commit = vhost_commit,
        .region_add = vhost_region_add,
        .region_del = vhost_region_del,
        .region_nop = vhost_region_nop,
        .log_start = vhost_log_start,
        .log_stop = vhost_log_stop,
        .log_sync = vhost_log_sync,
        .log_global_start = vhost_log_global_start,
        .log_global_stop = vhost_log_global_stop,
        .eventfd_add = vhost_eventfd_add,
        .eventfd_del = vhost_eventfd_del,
        .priority = 10
    };
    hdev->migration_blocker = NULL;
    if (!(hdev->features & (0x1ULL << VHOST_F_LOG_ALL))) {
        error_setg(&hdev->migration_blocker,
                   "Migration disabled: vhost lacks VHOST_F_LOG_ALL feature.");
        migrate_add_blocker(hdev->migration_blocker);
    }
    hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions));
    hdev->n_mem_sections = 0;
    hdev->mem_sections = NULL;
    hdev->log = NULL;
    hdev->log_size = 0;
    hdev->log_enabled = false;
    hdev->started = false;
    hdev->memory_changed = false;
    memory_listener_register(&hdev->memory_listener, &address_space_memory);
    return 0;
fail_vq:
    while (--i >= 0) {
        vhost_virtqueue_cleanup(hdev->vqs + i);
    }
fail:
    r = -errno;
    hdev->vhost_ops->vhost_backend_cleanup(hdev);
    QLIST_REMOVE(hdev, entry);
    return r;
}


int bdrv_read(BlockDriverState *bs, int64_t sector_num,

              uint8_t *buf, int nb_sectors)

{

    BlockDriver *drv = bs->drv;

    if (!drv)

        return -ENOMEDIUM;

    if (drv->bdrv_pread) {

        int ret, len;

        len = nb_sectors * 512;

        ret = drv->bdrv_pread(bs, sector_num * 512, buf, len);

        if (ret < 0)

            return ret;

        else if (ret != len)

            return -EINVAL;

        else {

	    bs->rd_bytes += (unsigned) len;

	    bs->rd_ops ++;

            return 0;

	}

    } else {

        return drv->bdrv_read(bs, sector_num, buf, nb_sectors);

    }

}


static int make_cdt24_entry(int p1, int p2, int16_t *cdt)

{

    int r, b;

    b = cdt[p2];

    r = cdt[p1]<<16;

    return (b+r) << 1;

}


static AVFrame *do_psnr(AVFilterContext *ctx, AVFrame *main,

                        const AVFrame *ref)

{

    PSNRContext *s = ctx->priv;

    double comp_mse[4], mse = 0;

    int j, c;

    AVDictionary **metadata = avpriv_frame_get_metadatap(main);

    s->compute_mse(s, (const uint8_t **)main->data, main->linesize,

                      (const uint8_t **)ref->data, ref->linesize,

                       main->width, main->height, comp_mse);

    for (j = 0; j < s->nb_components; j++)

        mse += comp_mse[j] * s->planeweight[j];

    s->min_mse = FFMIN(s->min_mse, mse);

    s->max_mse = FFMAX(s->max_mse, mse);

    s->mse += mse;

    for (j = 0; j < s->nb_components; j++)

        s->mse_comp[j] += comp_mse[j];

    s->nb_frames++;

    for (j = 0; j < s->nb_components; j++) {

        c = s->is_rgb ? s->rgba_map[j] : j;

        set_meta(metadata, "lavfi.psnr.mse.", s->comps[j], comp_mse[c]);

        set_meta(metadata, "lavfi.psnr.psnr.", s->comps[j], get_psnr(comp_mse[c], 1, s->max[c]));

    }

    set_meta(metadata, "lavfi.psnr.mse_avg", 0, mse);

    set_meta(metadata, "lavfi.psnr.psnr_avg", 0, get_psnr(mse, 1, s->average_max));

    if (s->stats_file) {

        fprintf(s->stats_file, "n:%"PRId64" mse_avg:%0.2f ", s->nb_frames, mse);

        for (j = 0; j < s->nb_components; j++) {

            c = s->is_rgb ? s->rgba_map[j] : j;

            fprintf(s->stats_file, "mse_%c:%0.2f ", s->comps[j], comp_mse[c]);

        }

        for (j = 0; j < s->nb_components; j++) {

            c = s->is_rgb ? s->rgba_map[j] : j;

            fprintf(s->stats_file, "psnr_%c:%0.2f ", s->comps[j],

                    get_psnr(comp_mse[c], 1, s->max[c]));

        }

        fprintf(s->stats_file, "\n");

    }

    return main;

}


static void matroska_add_index_entries(MatroskaDemuxContext *matroska)

{

    EbmlList *index_list;

    MatroskaIndex *index;

    int index_scale = 1;

    int i, j;

    if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)

        return;

    index_list = &matroska->index;

    index      = index_list->elem;

    if (index_list->nb_elem &&

        index[0].time > 1E14 / matroska->time_scale) {

        av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");

        index_scale = matroska->time_scale;

    }

    for (i = 0; i < index_list->nb_elem; i++) {

        EbmlList *pos_list    = &index[i].pos;

        MatroskaIndexPos *pos = pos_list->elem;

        for (j = 0; j < pos_list->nb_elem; j++) {

            MatroskaTrack *track = matroska_find_track_by_num(matroska,

                                                              pos[j].track);

            if (track && track->stream)

                av_add_index_entry(track->stream,

                                   pos[j].pos + matroska->segment_start,

                                   index[i].time / index_scale, 0, 0,

                                   AVINDEX_KEYFRAME);

        }

    }

}


static inline void downmix_3f_2r_to_mono(float *samples)

{

    int i;

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

        samples[i] += (samples[i + 256] + samples[i + 512] + samples[i + 768] + samples[i + 1024]);

        samples[i + 256] = samples[i + 512] = samples[i + 768] = samples[i + 1024] = 0;

    }

}


static bool vtd_decide_config(IntelIOMMUState *s, Error **errp)

{

    X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);

    /* Currently Intel IOMMU IR only support "kernel-irqchip={off|split}" */

    if (x86_iommu->intr_supported && kvm_irqchip_in_kernel() &&

        !kvm_irqchip_is_split()) {

        error_setg(errp, "Intel Interrupt Remapping cannot work with "

                         "kernel-irqchip=on, please use 'split|off'.");

        return false;

    }

    if (s->intr_eim == ON_OFF_AUTO_ON && !x86_iommu->intr_supported) {

        error_setg(errp, "eim=on cannot be selected without intremap=on");

        return false;

    }

    if (s->intr_eim == ON_OFF_AUTO_AUTO) {

        s->intr_eim = x86_iommu->intr_supported ?

                                              ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;

    }

    return true;

}


static int no_init_in (HWVoiceIn *hw, struct audsettings *as)

{

    audio_pcm_init_info (&hw->info, as);

    hw->samples = 1024;

    return 0;

}


static int nsv_read_chunk(AVFormatContext *s, int fill_header)

{

    NSVContext *nsv = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *st[2] = {NULL, NULL};

    NSVStream *nst;

    AVPacket *pkt;

    int i, err = 0;

    uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */

    uint32_t vsize;

    uint16_t asize;

    uint16_t auxsize;

    if (nsv->ahead[0].data || nsv->ahead[1].data)

        return 0; //-1; /* hey! eat what you've in your plate first! */

null_chunk_retry:

    if (pb->eof_reached)

        return -1;

    for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++)

        err = nsv_resync(s);

    if (err < 0)

        return err;

    if (nsv->state == NSV_FOUND_NSVS)

        err = nsv_parse_NSVs_header(s);

    if (err < 0)

        return err;

    if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF)

        return -1;

    auxcount = avio_r8(pb);

    vsize = avio_rl16(pb);

    asize = avio_rl16(pb);

    vsize = (vsize << 4) | (auxcount >> 4);

    auxcount &= 0x0f;

    av_log(s, AV_LOG_TRACE, "NSV CHUNK %"PRIu8" aux, %"PRIu32" bytes video, %"PRIu16" bytes audio\n",

           auxcount, vsize, asize);

    /* skip aux stuff */

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

        uint32_t av_unused auxtag;

        auxsize = avio_rl16(pb);

        auxtag = avio_rl32(pb);

        avio_skip(pb, auxsize);

        vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */

    }

    if (pb->eof_reached)

        return -1;

    if (!vsize && !asize) {

        nsv->state = NSV_UNSYNC;

        goto null_chunk_retry;

    }

    /* map back streams to v,a */

    if (s->nb_streams > 0)

        st[s->streams[0]->id] = s->streams[0];

    if (s->nb_streams > 1)

        st[s->streams[1]->id] = s->streams[1];

    if (vsize && st[NSV_ST_VIDEO]) {

        nst = st[NSV_ST_VIDEO]->priv_data;

        pkt = &nsv->ahead[NSV_ST_VIDEO];

        av_get_packet(pb, pkt, vsize);

        pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO;

        pkt->dts = nst->frame_offset;

        pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */

        for (i = 0; i < FFMIN(8, vsize); i++)

            av_log(s, AV_LOG_TRACE, "NSV video: [%d] = %02"PRIx8"\n",

                   i, pkt->data[i]);

    }

    if(st[NSV_ST_VIDEO])

        ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;

    if (asize && st[NSV_ST_AUDIO]) {

        nst = st[NSV_ST_AUDIO]->priv_data;

        pkt = &nsv->ahead[NSV_ST_AUDIO];

        /* read raw audio specific header on the first audio chunk... */

        /* on ALL audio chunks ?? seems so! */

        if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) {

            uint8_t bps;

            uint8_t channels;

            uint16_t samplerate;

            bps = avio_r8(pb);

            channels = avio_r8(pb);

            samplerate = avio_rl16(pb);

            if (!channels || !samplerate)

                return AVERROR_INVALIDDATA;

            asize-=4;

            av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n",

                   bps, channels, samplerate);

            if (fill_header) {

                st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */

                if (bps != 16) {

                    av_log(s, AV_LOG_TRACE, "NSV AUDIO bit/sample != 16 (%"PRIu8")!!!\n", bps);

                }

                bps /= channels; // ???

                if (bps == 8)

                    st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8;

                samplerate /= 4;/* UGH ??? XXX */

                channels = 1;

                st[NSV_ST_AUDIO]->codecpar->channels = channels;

                st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate;

                av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n",

                       bps, channels, samplerate);

            }

        }

        av_get_packet(pb, pkt, asize);

        pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO;

        pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */

        if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) {

            /* on a nsvs frame we have new information on a/v sync */

            pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1);

            pkt->dts *= (int64_t)1000        * nsv->framerate.den;

            pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num;

            av_log(s, AV_LOG_TRACE, "NSV AUDIO: sync:%"PRId16", dts:%"PRId64,

                   nsv->avsync, pkt->dts);

        }

        nst->frame_offset++;

    }

    nsv->state = NSV_UNSYNC;

    return 0;

}


static int block_save_complete(QEMUFile *f, void *opaque)

{

    int ret;

    DPRINTF("Enter save live complete submitted %d transferred %d\n",

            block_mig_state.submitted, block_mig_state.transferred);

    ret = flush_blks(f);

    if (ret) {

        return ret;

    }

    blk_mig_reset_dirty_cursor();

    /* we know for sure that save bulk is completed and

       all async read completed */

    blk_mig_lock();

    assert(block_mig_state.submitted == 0);

    blk_mig_unlock();

    do {

        ret = blk_mig_save_dirty_block(f, 0);

        if (ret < 0) {

            return ret;

        }

    } while (ret == 0);

    /* report completion */

    qemu_put_be64(f, (100 << BDRV_SECTOR_BITS) | BLK_MIG_FLAG_PROGRESS);

    DPRINTF("Block migration completed\n");

    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

    blk_mig_cleanup();

    return 0;

}