static BlockDriverState *bdrv_open_inherit(const char *filename,

                                           const char *reference,

                                           QDict *options, int flags,

                                           BlockDriverState *parent,

                                           const BdrvChildRole *child_role,

                                           Error **errp)

{

    int ret;

    BdrvChild *file = NULL;

    BlockDriverState *bs;

    BlockDriver *drv = NULL;

    const char *drvname;

    const char *backing;

    Error *local_err = NULL;

    QDict *snapshot_options = NULL;

    int snapshot_flags = 0;

    assert(!child_role || !flags);

    assert(!child_role == !parent);

    if (reference) {

        bool options_non_empty = options ? qdict_size(options) : false;

        QDECREF(options);

        if (filename || options_non_empty) {

            error_setg(errp, "Cannot reference an existing block device with "

                       "additional options or a new filename");

            return NULL;

        }

        bs = bdrv_lookup_bs(reference, reference, errp);

        if (!bs) {

            return NULL;

        }

        bdrv_ref(bs);

        return bs;

    }

    bs = bdrv_new();

    /* NULL means an empty set of options */

    if (options == NULL) {

        options = qdict_new();

    }

    /* json: syntax counts as explicit options, as if in the QDict */

    parse_json_protocol(options, &filename, &local_err);

    if (local_err) {

        goto fail;

    }

    bs->explicit_options = qdict_clone_shallow(options);

    if (child_role) {

        bs->inherits_from = parent;

        child_role->inherit_options(&flags, options,

                                    parent->open_flags, parent->options);

    }

    ret = bdrv_fill_options(&options, filename, &flags, &local_err);

    if (local_err) {

        goto fail;

    }

    /* Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.

     * FIXME: we're parsing the QDict to avoid having to create a

     * QemuOpts just for this, but neither option is optimal. */

    if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&

        !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {

        flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);

    } else {

        flags &= ~BDRV_O_RDWR;

    }

    if (flags & BDRV_O_SNAPSHOT) {

        snapshot_options = qdict_new();

        bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,

                                   flags, options);

        /* Let bdrv_backing_options() override "read-only" */

        qdict_del(options, BDRV_OPT_READ_ONLY);

        bdrv_backing_options(&flags, options, flags, options);

    }

    bs->open_flags = flags;

    bs->options = options;

    options = qdict_clone_shallow(options);

    /* Find the right image format driver */

    drvname = qdict_get_try_str(options, "driver");

    if (drvname) {

        drv = bdrv_find_format(drvname);

        if (!drv) {

            error_setg(errp, "Unknown driver: '%s'", drvname);

            goto fail;

        }

    }

    assert(drvname || !(flags & BDRV_O_PROTOCOL));

    backing = qdict_get_try_str(options, "backing");

    if (backing && *backing == '\0') {

        flags |= BDRV_O_NO_BACKING;

        qdict_del(options, "backing");

    }

    /* Open image file without format layer */

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

        file = bdrv_open_child(filename, options, "file", bs,

                               &child_file, true, &local_err);

        if (local_err) {

            goto fail;

        }

    }

    /* Image format probing */

    bs->probed = !drv;

    if (!drv && file) {

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

        if (ret < 0) {

            goto fail;

        }

        /*

         * This option update would logically belong in bdrv_fill_options(),

         * but we first need to open bs->file for the probing to work, while

         * opening bs->file already requires the (mostly) final set of options

         * so that cache mode etc. can be inherited.

         *

         * Adding the driver later is somewhat ugly, but it's not an option

         * that would ever be inherited, so it's correct. We just need to make

         * sure to update both bs->options (which has the full effective

         * options for bs) and options (which has file.* already removed).

         */

        qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));

        qdict_put(options, "driver", qstring_from_str(drv->format_name));

    } else if (!drv) {

        error_setg(errp, "Must specify either driver or file");

        goto fail;

    }

    /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */

    assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);

    /* file must be NULL if a protocol BDS is about to be created

     * (the inverse results in an error message from bdrv_open_common()) */

    assert(!(flags & BDRV_O_PROTOCOL) || !file);

    /* Open the image */

    ret = bdrv_open_common(bs, file, options, &local_err);

    if (ret < 0) {

        goto fail;

    }

    if (file && (bs->file != file)) {

        bdrv_unref_child(bs, file);

        file = NULL;

    }

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

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

        ret = bdrv_open_backing_file(bs, options, "backing", &local_err);

        if (ret < 0) {

            goto close_and_fail;

        }

    }

    bdrv_refresh_filename(bs);

    /* Check if any unknown options were used */

    if (options && (qdict_size(options) != 0)) {

        const QDictEntry *entry = qdict_first(options);

        if (flags & BDRV_O_PROTOCOL) {

            error_setg(errp, "Block protocol '%s' doesn't support the option "

                       "'%s'", drv->format_name, entry->key);

        } else {

            error_setg(errp,

                       "Block format '%s' does not support the option '%s'",

                       drv->format_name, entry->key);

        }

        goto close_and_fail;

    }

    if (!bdrv_key_required(bs)) {

        bdrv_parent_cb_change_media(bs, true);

    } else if (!runstate_check(RUN_STATE_PRELAUNCH)

               && !runstate_check(RUN_STATE_INMIGRATE)

               && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */

        error_setg(errp,

                   "Guest must be stopped for opening of encrypted image");

        goto close_and_fail;

    }

    QDECREF(options);

    /* For snapshot=on, create a temporary qcow2 overlay. bs points to the

     * temporary snapshot afterwards. */

    if (snapshot_flags) {

        BlockDriverState *snapshot_bs;

        snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,

                                                snapshot_options, &local_err);

        snapshot_options = NULL;

        if (local_err) {

            goto close_and_fail;

        }

        /* We are not going to return bs but the overlay on top of it

         * (snapshot_bs); thus, we have to drop the strong reference to bs

         * (which we obtained by calling bdrv_new()). bs will not be deleted,

         * though, because the overlay still has a reference to it. */

        bdrv_unref(bs);

        bs = snapshot_bs;

    }

    return bs;

fail:

    if (file != NULL) {

        bdrv_unref_child(bs, file);

    }

    QDECREF(snapshot_options);

    QDECREF(bs->explicit_options);

    QDECREF(bs->options);

    QDECREF(options);

    bs->options = NULL;

    bdrv_unref(bs);

    error_propagate(errp, local_err);

    return NULL;

close_and_fail:

    bdrv_unref(bs);

    QDECREF(snapshot_options);

    QDECREF(options);

    error_propagate(errp, local_err);

    return NULL;

}


AlphaCPU *cpu_alpha_init(const char *cpu_model)

{

    AlphaCPU *cpu;

    ObjectClass *cpu_class;

    cpu_class = alpha_cpu_class_by_name(cpu_model);

    if (cpu_class == NULL) {

        /* Default to ev67; no reason not to emulate insns by default.  */

        cpu_class = object_class_by_name(TYPE("ev67"));

    }

    cpu = ALPHA_CPU(object_new(object_class_get_name(cpu_class)));

    object_property_set_bool(OBJECT(cpu), true, "realized", NULL);

    return cpu;

}


static void xen_pt_pci_write_config(PCIDevice *d, uint32_t addr,

                                    uint32_t val, int len)

{

    XenPCIPassthroughState *s = DO_UPCAST(XenPCIPassthroughState, dev, d);

    int index = 0;

    XenPTRegGroup *reg_grp_entry = NULL;

    int rc = 0;

    uint32_t read_val = 0, wb_mask;

    int emul_len = 0;

    XenPTReg *reg_entry = NULL;

    uint32_t find_addr = addr;

    XenPTRegInfo *reg = NULL;

    if (xen_pt_pci_config_access_check(d, addr, len)) {

        return;

    }

    XEN_PT_LOG_CONFIG(d, addr, val, len);

    /* check unused BAR register */

    index = xen_pt_bar_offset_to_index(addr);

    if ((index >= 0) && (val > 0 && val < XEN_PT_BAR_ALLF) &&

        (s->bases[index].bar_flag == XEN_PT_BAR_FLAG_UNUSED)) {

        XEN_PT_WARN(d, "Guest attempt to set address to unused Base Address "

                    "Register. (addr: 0x%02x, len: %d)\n", addr, len);

    }

    /* find register group entry */

    reg_grp_entry = xen_pt_find_reg_grp(s, addr);

    if (reg_grp_entry) {

        /* check 0-Hardwired register group */

        if (reg_grp_entry->reg_grp->grp_type == XEN_PT_GRP_TYPE_HARDWIRED) {

            /* ignore silently */

            XEN_PT_WARN(d, "Access to 0-Hardwired register. "

                        "(addr: 0x%02x, len: %d)\n", addr, len);

            return;

        }

    }

    rc = xen_host_pci_get_block(&s->real_device, addr,

                                (uint8_t *)&read_val, len);

    if (rc < 0) {

        XEN_PT_ERR(d, "pci_read_block failed. return value: %d.\n", rc);

        memset(&read_val, 0xff, len);

        wb_mask = 0;

    } else {

        wb_mask = 0xFFFFFFFF >> ((4 - len) << 3);

    }

    /* pass directly to the real device for passthrough type register group */

    if (reg_grp_entry == NULL) {

        goto out;

    }

    memory_region_transaction_begin();

    pci_default_write_config(d, addr, val, len);

    /* adjust the read and write value to appropriate CFC-CFF window */

    read_val <<= (addr & 3) << 3;

    val <<= (addr & 3) << 3;

    emul_len = len;

    /* loop around the guest requested size */

    while (emul_len > 0) {

        /* find register entry to be emulated */

        reg_entry = xen_pt_find_reg(reg_grp_entry, find_addr);

        if (reg_entry) {

            reg = reg_entry->reg;

            uint32_t real_offset = reg_grp_entry->base_offset + reg->offset;

            uint32_t valid_mask = 0xFFFFFFFF >> ((4 - emul_len) << 3);

            uint8_t *ptr_val = NULL;

            valid_mask <<= (find_addr - real_offset) << 3;

            ptr_val = (uint8_t *)&val + (real_offset & 3);

            if (reg->emu_mask == (0xFFFFFFFF >> ((4 - reg->size) << 3))) {

                wb_mask &= ~((reg->emu_mask

                              >> ((find_addr - real_offset) << 3))

                             << ((len - emul_len) << 3));

            }

            /* do emulation based on register size */

            switch (reg->size) {

            case 1:

                if (reg->u.b.write) {

                    rc = reg->u.b.write(s, reg_entry, ptr_val,

                                        read_val >> ((real_offset & 3) << 3),

                                        valid_mask);

                }

                break;

            case 2:

                if (reg->u.w.write) {

                    rc = reg->u.w.write(s, reg_entry, (uint16_t *)ptr_val,

                                        (read_val >> ((real_offset & 3) << 3)),

                                        valid_mask);

                }

                break;

            case 4:

                if (reg->u.dw.write) {

                    rc = reg->u.dw.write(s, reg_entry, (uint32_t *)ptr_val,

                                         (read_val >> ((real_offset & 3) << 3)),

                                         valid_mask);

                }

                break;

            }

            if (rc < 0) {

                xen_shutdown_fatal_error("Internal error: Invalid write"

                                         " emulation. (%s, rc: %d)\n",

                                         __func__, rc);

                return;

            }

            /* calculate next address to find */

            emul_len -= reg->size;

            if (emul_len > 0) {

                find_addr = real_offset + reg->size;

            }

        } else {

            /* nothing to do with passthrough type register,

             * continue to find next byte */

            emul_len--;

            find_addr++;

        }

    }

    /* need to shift back before passing them to xen_host_pci_device */

    val >>= (addr & 3) << 3;

    memory_region_transaction_commit();

out:

    for (index = 0; wb_mask; index += len) {

        /* unknown regs are passed through */

        while (!(wb_mask & 0xff)) {

            index++;

            wb_mask >>= 8;

        }

        len = 0;

        do {

            len++;

            wb_mask >>= 8;

        } while (wb_mask & 0xff);

        rc = xen_host_pci_set_block(&s->real_device, addr + index,

                                    (uint8_t *)&val + index, len);

        if (rc < 0) {

            XEN_PT_ERR(d, "pci_write_block failed. return value: %d.\n", rc);

        }

    }

}


static void test_hash_base64(void)

{

    size_t i;

    g_assert(qcrypto_init(NULL) == 0);

    for (i = 0; i < G_N_ELEMENTS(expected_outputs) ; i++) {

        int ret;

        char *digest;

        ret = qcrypto_hash_base64(i,

                                  INPUT_TEXT,

                                  strlen(INPUT_TEXT),

                                  &digest,

                                  NULL);

        g_assert(ret == 0);

        g_assert(g_str_equal(digest, expected_outputs_b64[i]));

        g_free(digest);

    }

}


static void virtio_ccw_serial_realize(VirtioCcwDevice *ccw_dev, Error **errp)

{

    VirtioSerialCcw *dev = VIRTIO_SERIAL_CCW(ccw_dev);

    DeviceState *vdev = DEVICE(&dev->vdev);

    DeviceState *proxy = DEVICE(ccw_dev);

    Error *err = NULL;

    char *bus_name;

    /*

     * For command line compatibility, this sets the virtio-serial-device bus

     * name as before.

     */

    if (proxy->id) {

        bus_name = g_strdup_printf("%s.0", proxy->id);

        virtio_device_set_child_bus_name(VIRTIO_DEVICE(vdev), bus_name);

        g_free(bus_name);

    }

    qdev_set_parent_bus(vdev, BUS(&ccw_dev->bus));

    object_property_set_bool(OBJECT(vdev), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

    }

}


uint32_t kvmppc_get_vmx(void)

{

    return kvmppc_read_int_cpu_dt("ibm,vmx");

}


static void check_reserved_space (target_phys_addr_t *start,

                                  target_phys_addr_t *length)

{

    target_phys_addr_t begin = *start;

    target_phys_addr_t end = *start + *length;

    if (end >= 0x1e000000LL && end < 0x1f100000LL)

        end = 0x1e000000LL;

    if (begin >= 0x1e000000LL && begin < 0x1f100000LL)

        begin = 0x1f100000LL;

    if (end >= 0x1fc00000LL && end < 0x1fd00000LL)

        end = 0x1fc00000LL;

    if (begin >= 0x1fc00000LL && begin < 0x1fd00000LL)

        begin = 0x1fd00000LL;

    /* XXX: This is broken when a reserved range splits the requested range */

    if (end >= 0x1f100000LL && begin < 0x1e000000LL)

        end = 0x1e000000LL;

    if (end >= 0x1fd00000LL && begin < 0x1fc00000LL)

        end = 0x1fc00000LL;

    *start = begin;

    *length = end - begin;

}


CharDriverState *qemu_chr_open_msmouse(void)

{

    CharDriverState *chr;

    chr = g_malloc0(sizeof(CharDriverState));

    chr->chr_write = msmouse_chr_write;

    chr->chr_close = msmouse_chr_close;

    chr->explicit_be_open = true;

    qemu_add_mouse_event_handler(msmouse_event, chr, 0, "QEMU Microsoft Mouse");

    return chr;

}


void vfio_pci_write_config(PCIDevice *pdev,

                           uint32_t addr, uint32_t val, int len)

{

    VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);

    uint32_t val_le = cpu_to_le32(val);

    trace_vfio_pci_write_config(vdev->vbasedev.name, addr, val, len);

    /* Write everything to VFIO, let it filter out what we can't write */

    if (pwrite(vdev->vbasedev.fd, &val_le, len, vdev->config_offset + addr)

                != len) {

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

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

                     vdev->host.slot, vdev->host.function, addr, val, len);

    }

    /* MSI/MSI-X Enabling/Disabling */

    if (pdev->cap_present & QEMU_PCI_CAP_MSI &&

        ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {

        int is_enabled, was_enabled = msi_enabled(pdev);

        pci_default_write_config(pdev, addr, val, len);

        is_enabled = msi_enabled(pdev);

        if (!was_enabled) {

            if (is_enabled) {

                vfio_msi_enable(vdev);

            }

        } else {

            if (!is_enabled) {

                vfio_msi_disable(vdev);

            } else {

                vfio_update_msi(vdev);

            }

        }

    } else if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&

        ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {

        int is_enabled, was_enabled = msix_enabled(pdev);

        pci_default_write_config(pdev, addr, val, len);

        is_enabled = msix_enabled(pdev);

        if (!was_enabled && is_enabled) {

            vfio_msix_enable(vdev);

        } else if (was_enabled && !is_enabled) {

            vfio_msix_disable(vdev);

        }

    } else {

        /* Write everything to QEMU to keep emulated bits correct */

        pci_default_write_config(pdev, addr, val, len);

    }

}


static int sap_fetch_packet(AVFormatContext *s, AVPacket *pkt)

{

    struct SAPState *sap = s->priv_data;

    int fd = url_get_file_handle(sap->ann_fd);

    int n, ret;

    fd_set rfds;

    struct timeval tv;

    uint8_t recvbuf[1500];

    if (sap->eof)

        return AVERROR_EOF;

    while (1) {

        FD_ZERO(&rfds);

        FD_SET(fd, &rfds);

        tv.tv_sec = tv.tv_usec = 0;

        n = select(fd + 1, &rfds, NULL, NULL, &tv);

        if (n <= 0 || !FD_ISSET(fd, &rfds))

            break;

        ret = url_read(sap->ann_fd, recvbuf, sizeof(recvbuf));

        if (ret >= 8) {

            uint16_t hash = AV_RB16(&recvbuf[2]);

            /* Should ideally check the source IP address, too */

            if (recvbuf[0] & 0x04 && hash == sap->hash) {

                /* Stream deletion */

                sap->eof = 1;

                return AVERROR_EOF;

            }

        }

    }

    ret = av_read_frame(sap->sdp_ctx, pkt);

    if (ret < 0)

        return ret;

    if (s->ctx_flags & AVFMTCTX_NOHEADER) {

        while (sap->sdp_ctx->nb_streams > s->nb_streams) {

            int i = s->nb_streams;

            AVStream *st = av_new_stream(s, i);

            if (!st) {

                av_free_packet(pkt);

                return AVERROR(ENOMEM);

            }

            avcodec_copy_context(st->codec, sap->sdp_ctx->streams[i]->codec);

            st->time_base = sap->sdp_ctx->streams[i]->time_base;

        }

    }

    return ret;

}


static void run_dependent_requests(BDRVQcowState *s, QCowL2Meta *m)

{

    /* Take the request off the list of running requests */

    if (m->nb_clusters != 0) {

        QLIST_REMOVE(m, next_in_flight);

    }

    /* Restart all dependent requests */

    if (!qemu_co_queue_empty(&m->dependent_requests)) {

        qemu_co_mutex_unlock(&s->lock);

        while(qemu_co_queue_next(&m->dependent_requests));

        qemu_co_mutex_lock(&s->lock);

    }

}


uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,

                                      uint32_t index, int reg)

{

    struct kvm_cpuid2 *cpuid;

    int max;

    uint32_t ret = 0;

    uint32_t cpuid_1_edx;

    bool found = false;

    max = 1;

    while ((cpuid = try_get_cpuid(s, max)) == NULL) {

        max *= 2;

    }

    struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);

    if (entry) {

        found = true;

        ret = cpuid_entry_get_reg(entry, reg);

    }

    /* Fixups for the data returned by KVM, below */

    if (reg == R_EDX) {

        switch (function) {

        case 1:

            /* KVM before 2.6.30 misreports the following features */

            ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;

            break;

        case 0x80000001:

            /* On Intel, kvm returns cpuid according to the Intel spec,

             * so add missing bits according to the AMD spec:

             */

            cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);

            ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;

            break;

        }

    }

    g_free(cpuid);

    /* fallback for older kernels */

    if ((function == KVM_CPUID_FEATURES) && !found) {

        ret = get_para_features(s);

    }

    return ret;

}


static abi_long do_socketcall(int num, abi_ulong vptr)

{

    abi_long ret;

    const int n = sizeof(abi_ulong);

    switch(num) {

    case SOCKOP_socket:

	{

            abi_ulong domain, type, protocol;

            if (get_user_ual(domain, vptr)

                || get_user_ual(type, vptr + n)

                || get_user_ual(protocol, vptr + 2 * n))

                return -TARGET_EFAULT;

            ret = do_socket(domain, type, protocol);

	}

        break;

    case SOCKOP_bind:

	{

            abi_ulong sockfd;

            abi_ulong target_addr;

            socklen_t addrlen;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(target_addr, vptr + n)

                || get_user_ual(addrlen, vptr + 2 * n))

                return -TARGET_EFAULT;

            ret = do_bind(sockfd, target_addr, addrlen);

        }

        break;

    case SOCKOP_connect:

        {

            abi_ulong sockfd;

            abi_ulong target_addr;

            socklen_t addrlen;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(target_addr, vptr + n)

                || get_user_ual(addrlen, vptr + 2 * n))

                return -TARGET_EFAULT;

            ret = do_connect(sockfd, target_addr, addrlen);

        }

        break;

    case SOCKOP_listen:

        {

            abi_ulong sockfd, backlog;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(backlog, vptr + n))

                return -TARGET_EFAULT;

            ret = get_errno(listen(sockfd, backlog));

        }

        break;

    case SOCKOP_accept:

        {

            abi_ulong sockfd;

            abi_ulong target_addr, target_addrlen;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(target_addr, vptr + n)

                || get_user_ual(target_addrlen, vptr + 2 * n))

                return -TARGET_EFAULT;

            ret = do_accept4(sockfd, target_addr, target_addrlen, 0);

        }

        break;

    case SOCKOP_accept4:

        {

            abi_ulong sockfd;

            abi_ulong target_addr, target_addrlen;

            abi_ulong flags;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(target_addr, vptr + n)

                || get_user_ual(target_addrlen, vptr + 2 * n)

                || get_user_ual(flags, vptr + 3 * n)) {

                return -TARGET_EFAULT;

            }

            ret = do_accept4(sockfd, target_addr, target_addrlen, flags);

        }

        break;

    case SOCKOP_getsockname:

        {

            abi_ulong sockfd;

            abi_ulong target_addr, target_addrlen;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(target_addr, vptr + n)

                || get_user_ual(target_addrlen, vptr + 2 * n))

                return -TARGET_EFAULT;

            ret = do_getsockname(sockfd, target_addr, target_addrlen);

        }

        break;

    case SOCKOP_getpeername:

        {

            abi_ulong sockfd;

            abi_ulong target_addr, target_addrlen;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(target_addr, vptr + n)

                || get_user_ual(target_addrlen, vptr + 2 * n))

                return -TARGET_EFAULT;

            ret = do_getpeername(sockfd, target_addr, target_addrlen);

        }

        break;

    case SOCKOP_socketpair:

        {

            abi_ulong domain, type, protocol;

            abi_ulong tab;

            if (get_user_ual(domain, vptr)

                || get_user_ual(type, vptr + n)

                || get_user_ual(protocol, vptr + 2 * n)

                || get_user_ual(tab, vptr + 3 * n))

                return -TARGET_EFAULT;

            ret = do_socketpair(domain, type, protocol, tab);

        }

        break;

    case SOCKOP_send:

        {

            abi_ulong sockfd;

            abi_ulong msg;

            size_t len;

            abi_ulong flags;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(msg, vptr + n)

                || get_user_ual(len, vptr + 2 * n)

                || get_user_ual(flags, vptr + 3 * n))

                return -TARGET_EFAULT;

            ret = do_sendto(sockfd, msg, len, flags, 0, 0);

        }

        break;

    case SOCKOP_recv:

        {

            abi_ulong sockfd;

            abi_ulong msg;

            size_t len;

            abi_ulong flags;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(msg, vptr + n)

                || get_user_ual(len, vptr + 2 * n)

                || get_user_ual(flags, vptr + 3 * n))

                return -TARGET_EFAULT;

            ret = do_recvfrom(sockfd, msg, len, flags, 0, 0);

        }

        break;

    case SOCKOP_sendto:

        {

            abi_ulong sockfd;

            abi_ulong msg;

            size_t len;

            abi_ulong flags;

            abi_ulong addr;

            abi_ulong addrlen;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(msg, vptr + n)

                || get_user_ual(len, vptr + 2 * n)

                || get_user_ual(flags, vptr + 3 * n)

                || get_user_ual(addr, vptr + 4 * n)

                || get_user_ual(addrlen, vptr + 5 * n))

                return -TARGET_EFAULT;

            ret = do_sendto(sockfd, msg, len, flags, addr, addrlen);

        }

        break;

    case SOCKOP_recvfrom:

        {

            abi_ulong sockfd;

            abi_ulong msg;

            size_t len;

            abi_ulong flags;

            abi_ulong addr;

            socklen_t addrlen;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(msg, vptr + n)

                || get_user_ual(len, vptr + 2 * n)

                || get_user_ual(flags, vptr + 3 * n)

                || get_user_ual(addr, vptr + 4 * n)

                || get_user_ual(addrlen, vptr + 5 * n))

                return -TARGET_EFAULT;

            ret = do_recvfrom(sockfd, msg, len, flags, addr, addrlen);

        }

        break;

    case SOCKOP_shutdown:

        {

            abi_ulong sockfd, how;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(how, vptr + n))

                return -TARGET_EFAULT;

            ret = get_errno(shutdown(sockfd, how));

        }

        break;

    case SOCKOP_sendmsg:

    case SOCKOP_recvmsg:

        {

            abi_ulong fd;

            abi_ulong target_msg;

            abi_ulong flags;

            if (get_user_ual(fd, vptr)

                || get_user_ual(target_msg, vptr + n)

                || get_user_ual(flags, vptr + 2 * n))

                return -TARGET_EFAULT;

            ret = do_sendrecvmsg(fd, target_msg, flags,

                                 (num == SOCKOP_sendmsg));

        }

        break;

    case SOCKOP_setsockopt:

        {

            abi_ulong sockfd;

            abi_ulong level;

            abi_ulong optname;

            abi_ulong optval;

            abi_ulong optlen;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(level, vptr + n)

                || get_user_ual(optname, vptr + 2 * n)

                || get_user_ual(optval, vptr + 3 * n)

                || get_user_ual(optlen, vptr + 4 * n))

                return -TARGET_EFAULT;

            ret = do_setsockopt(sockfd, level, optname, optval, optlen);

        }

        break;

    case SOCKOP_getsockopt:

        {

            abi_ulong sockfd;

            abi_ulong level;

            abi_ulong optname;

            abi_ulong optval;

            socklen_t optlen;

            if (get_user_ual(sockfd, vptr)

                || get_user_ual(level, vptr + n)

                || get_user_ual(optname, vptr + 2 * n)

                || get_user_ual(optval, vptr + 3 * n)

                || get_user_ual(optlen, vptr + 4 * n))

                return -TARGET_EFAULT;

            ret = do_getsockopt(sockfd, level, optname, optval, optlen);

        }

        break;

    default:

        gemu_log("Unsupported socketcall: %d\n", num);

        ret = -TARGET_ENOSYS;

        break;

    }

    return ret;

}


static int nbd_send_rep_list(int csock, NBDExport *exp)

{

    uint64_t magic, name_len;

    uint32_t opt, type, len;

    name_len = strlen(exp->name);

    magic = cpu_to_be64(NBD_REP_MAGIC);

    if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {

        LOG("write failed (magic)");

        return -EINVAL;

     }

    opt = cpu_to_be32(NBD_OPT_LIST);

    if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {

        LOG("write failed (opt)");

        return -EINVAL;

    }

    type = cpu_to_be32(NBD_REP_SERVER);

    if (write_sync(csock, &type, sizeof(type)) != sizeof(type)) {

        LOG("write failed (reply type)");

        return -EINVAL;

    }

    len = cpu_to_be32(name_len + sizeof(len));

    if (write_sync(csock, &len, sizeof(len)) != sizeof(len)) {

        LOG("write failed (length)");

        return -EINVAL;

    }

    len = cpu_to_be32(name_len);

    if (write_sync(csock, &len, sizeof(len)) != sizeof(len)) {

        LOG("write failed (length)");

        return -EINVAL;

    }

    if (write_sync(csock, exp->name, name_len) != name_len) {

        LOG("write failed (buffer)");

        return -EINVAL;

    }

    return 0;

}


static int nic_init(PCIDevice *pci_dev, uint32_t device)

{

    PCIEEPRO100State *d = DO_UPCAST(PCIEEPRO100State, dev, pci_dev);

    EEPRO100State *s;

    logout("\n");

    d->dev.unregister = pci_nic_uninit;

    s = &d->eepro100;

    s->device = device;

    s->pci_dev = &d->dev;

    pci_reset(s);

    /* Add 64 * 2 EEPROM. i82557 and i82558 support a 64 word EEPROM,

     * i82559 and later support 64 or 256 word EEPROM. */

    s->eeprom = eeprom93xx_new(EEPROM_SIZE);

    /* Handler for memory-mapped I/O */

    d->eepro100.mmio_index =

        cpu_register_io_memory(pci_mmio_read, pci_mmio_write, s);

    pci_register_bar(&d->dev, 0, PCI_MEM_SIZE,

                           PCI_ADDRESS_SPACE_MEM |

                           PCI_ADDRESS_SPACE_MEM_PREFETCH, pci_mmio_map);

    pci_register_bar(&d->dev, 1, PCI_IO_SIZE, PCI_ADDRESS_SPACE_IO,

                           pci_map);

    pci_register_bar(&d->dev, 2, PCI_FLASH_SIZE, PCI_ADDRESS_SPACE_MEM,

                           pci_mmio_map);

    qdev_get_macaddr(&d->dev.qdev, s->macaddr);

    logout("macaddr: %s\n", nic_dump(&s->macaddr[0], 6));

    assert(s->region[1] == 0);

    nic_reset(s);

    s->vc = qdev_get_vlan_client(&d->dev.qdev,

                                 nic_can_receive, nic_receive, NULL,

                                 nic_cleanup, s);

    qemu_format_nic_info_str(s->vc, s->macaddr);

    qemu_register_reset(nic_reset, s);

    register_savevm(s->vc->model, -1, 3, nic_save, nic_load, s);

    return 0;

}


static uint64_t pchip_read(void *opaque, target_phys_addr_t addr, unsigned size)

{

    TyphoonState *s = opaque;

    uint64_t ret = 0;

    if (addr & 4) {

        return s->latch_tmp;

    }

    switch (addr) {

    case 0x0000:

        /* WSBA0: Window Space Base Address Register.  */

        ret = s->pchip.win[0].base_addr;

        break;

    case 0x0040:

        /* WSBA1 */

        ret = s->pchip.win[1].base_addr;

        break;

    case 0x0080:

        /* WSBA2 */

        ret = s->pchip.win[2].base_addr;

        break;

    case 0x00c0:

        /* WSBA3 */

        ret = s->pchip.win[3].base_addr;

        break;

    case 0x0100:

        /* WSM0: Window Space Mask Register.  */

        ret = s->pchip.win[0].mask;

        break;

    case 0x0140:

        /* WSM1 */

        ret = s->pchip.win[1].mask;

        break;

    case 0x0180:

        /* WSM2 */

        ret = s->pchip.win[2].mask;

        break;

    case 0x01c0:

        /* WSM3 */

        ret = s->pchip.win[3].mask;

        break;

    case 0x0200:

        /* TBA0: Translated Base Address Register.  */

        ret = (uint64_t)s->pchip.win[0].translated_base_pfn << 10;

        break;

    case 0x0240:

        /* TBA1 */

        ret = (uint64_t)s->pchip.win[1].translated_base_pfn << 10;

        break;

    case 0x0280:

        /* TBA2 */

        ret = (uint64_t)s->pchip.win[2].translated_base_pfn << 10;

        break;

    case 0x02c0:

        /* TBA3 */

        ret = (uint64_t)s->pchip.win[3].translated_base_pfn << 10;

        break;

    case 0x0300:

        /* PCTL: Pchip Control Register.  */

        ret = s->pchip.ctl;

        break;

    case 0x0340:

        /* PLAT: Pchip Master Latency Register.  */

        break;

    case 0x03c0:

        /* PERROR: Pchip Error Register.  */

        break;

    case 0x0400:

        /* PERRMASK: Pchip Error Mask Register.  */

        break;

    case 0x0440:

        /* PERRSET: Pchip Error Set Register.  */

        break;

    case 0x0480:

        /* TLBIV: Translation Buffer Invalidate Virtual Register (WO).  */

        break;

    case 0x04c0:

        /* TLBIA: Translation Buffer Invalidate All Register (WO).  */

        break;

    case 0x0500: /* PMONCTL */

    case 0x0540: /* PMONCNT */

    case 0x0800: /* SPRST */

        break;

    default:

        cpu_unassigned_access(cpu_single_env, addr, 0, 0, 0, size);

        return -1;

    }

    s->latch_tmp = ret >> 32;

    return ret;

}


static void curl_close(BlockDriverState *bs)

{

    BDRVCURLState *s = bs->opaque;

    DPRINTF("CURL: Close\n");

    curl_detach_aio_context(bs);

    qemu_mutex_destroy(&s->mutex);

    g_free(s->cookie);

    g_free(s->url);

}


int get_partial_buffer(ByteIOContext *s, unsigned char *buf, int size)
{
    int len;
    len = s->buf_end - s->buf_ptr;
    if (len == 0) {
        fill_buffer(s);
        len = s->buf_end - s->buf_ptr;
    }
    if (len > size)
        len = size;
    memcpy(buf, s->buf_ptr, len);
    s->buf_ptr += len;
    return len;
}


static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)

{

    int num_gain = 0;

    int c, g, sfb, ret;

    int sign;

    INTFLOAT scale;

    SingleChannelElement *sce = &che->ch[0];

    ChannelCoupling     *coup = &che->coup;

    coup->coupling_point = 2 * get_bits1(gb);

    coup->num_coupled = get_bits(gb, 3);

    for (c = 0; c <= coup->num_coupled; c++) {

        num_gain++;

        coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;

        coup->id_select[c] = get_bits(gb, 4);

        if (coup->type[c] == TYPE_CPE) {

            coup->ch_select[c] = get_bits(gb, 2);

            if (coup->ch_select[c] == 3)

                num_gain++;

        } else

            coup->ch_select[c] = 2;

    }

    coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);

    sign  = get_bits(gb, 1);

    scale = AAC_RENAME(cce_scale)[get_bits(gb, 2)];

    if ((ret = decode_ics(ac, sce, gb, 0, 0)))

        return ret;

    for (c = 0; c < num_gain; c++) {

        int idx  = 0;

        int cge  = 1;

        int gain = 0;

        INTFLOAT gain_cache = FIXR10(1.);

        if (c) {

            cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);

            gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;

            gain_cache = GET_GAIN(scale, gain);

        }

        if (coup->coupling_point == AFTER_IMDCT) {

            coup->gain[c][0] = gain_cache;

        } else {

            for (g = 0; g < sce->ics.num_window_groups; g++) {

                for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {

                    if (sce->band_type[idx] != ZERO_BT) {

                        if (!cge) {

                            int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;

                            if (t) {

                                int s = 1;

                                t = gain += t;

                                if (sign) {

                                    s  -= 2 * (t & 0x1);

                                    t >>= 1;

                                }

                                gain_cache = GET_GAIN(scale, t) * s;

                            }

                        }

                        coup->gain[c][idx] = gain_cache;

                    }

                }

            }

        }

    }

    return 0;

}


static gboolean gd_key_event(GtkWidget *widget, GdkEventKey *key, void *opaque)
{
    VirtualConsole *vc = opaque;
    GtkDisplayState *s = vc->s;
    int gdk_keycode = key->hardware_keycode;
    int qemu_keycode;
    int i;
    if (key->keyval == GDK_KEY_Pause) {
        qemu_input_event_send_key_qcode(vc->gfx.dcl.con, Q_KEY_CODE_PAUSE,
                                        key->type == GDK_KEY_PRESS);
    qemu_keycode = gd_map_keycode(s, gtk_widget_get_display(widget),
                                  gdk_keycode);
    trace_gd_key_event(vc->label, gdk_keycode, qemu_keycode,
                       (key->type == GDK_KEY_PRESS) ? "down" : "up");
    for (i = 0; i < ARRAY_SIZE(modifier_keycode); i++) {
        if (qemu_keycode == modifier_keycode[i]) {
            s->modifier_pressed[i] = (key->type == GDK_KEY_PRESS);
    qemu_input_event_send_key_number(vc->gfx.dcl.con, qemu_keycode,
                                     key->type == GDK_KEY_PRESS);


void *pl110_init(DisplayState *ds, uint32_t base, qemu_irq irq,

                 int versatile)

{

    pl110_state *s;

    int iomemtype;

    s = (pl110_state *)qemu_mallocz(sizeof(pl110_state));

    iomemtype = cpu_register_io_memory(0, pl110_readfn,

                                       pl110_writefn, s);

    cpu_register_physical_memory(base, 0x00000fff, iomemtype);

    s->base = base;

    s->ds = ds;

    s->versatile = versatile;

    s->irq = irq;

    graphic_console_init(ds, pl110_update_display, pl110_invalidate_display,

                         NULL, s);

    /* ??? Save/restore.  */

    return s;

}


void rgb16tobgr15(const uint8_t *src, uint8_t *dst, long src_size)

{

	long i;

	long num_pixels = src_size >> 1;

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

	{

	    unsigned b,g,r;

	    register uint16_t rgb;

	    rgb = src[2*i];

	    r = rgb&0x1F;

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

	    b = (rgb&0xF800)>>11;

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

	}

}


static void replication_start(ReplicationState *rs, ReplicationMode mode,

                              Error **errp)

{

    BlockDriverState *bs = rs->opaque;

    BDRVReplicationState *s;

    BlockDriverState *top_bs;

    int64_t active_length, hidden_length, disk_length;

    AioContext *aio_context;

    Error *local_err = NULL;

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    s = bs->opaque;

    if (s->replication_state != BLOCK_REPLICATION_NONE) {

        error_setg(errp, "Block replication is running or done");

        aio_context_release(aio_context);

        return;

    }

    if (s->mode != mode) {

        error_setg(errp, "The parameter mode's value is invalid, needs %d,"

                   " but got %d", s->mode, mode);

        aio_context_release(aio_context);

        return;

    }

    switch (s->mode) {

    case REPLICATION_MODE_PRIMARY:

        break;

    case REPLICATION_MODE_SECONDARY:

        s->active_disk = bs->file;

        if (!s->active_disk || !s->active_disk->bs ||

                                    !s->active_disk->bs->backing) {

            error_setg(errp, "Active disk doesn't have backing file");

            aio_context_release(aio_context);

            return;

        }

        s->hidden_disk = s->active_disk->bs->backing;

        if (!s->hidden_disk->bs || !s->hidden_disk->bs->backing) {

            error_setg(errp, "Hidden disk doesn't have backing file");

            aio_context_release(aio_context);

            return;

        }

        s->secondary_disk = s->hidden_disk->bs->backing;

        if (!s->secondary_disk->bs || !bdrv_has_blk(s->secondary_disk->bs)) {

            error_setg(errp, "The secondary disk doesn't have block backend");

            aio_context_release(aio_context);

            return;

        }

        /* verify the length */

        active_length = bdrv_getlength(s->active_disk->bs);

        hidden_length = bdrv_getlength(s->hidden_disk->bs);

        disk_length = bdrv_getlength(s->secondary_disk->bs);

        if (active_length < 0 || hidden_length < 0 || disk_length < 0 ||

            active_length != hidden_length || hidden_length != disk_length) {

            error_setg(errp, "Active disk, hidden disk, secondary disk's length"

                       " are not the same");

            aio_context_release(aio_context);

            return;

        }

        if (!s->active_disk->bs->drv->bdrv_make_empty ||

            !s->hidden_disk->bs->drv->bdrv_make_empty) {

            error_setg(errp,

                       "Active disk or hidden disk doesn't support make_empty");

            aio_context_release(aio_context);

            return;

        }

        /* reopen the backing file in r/w mode */

        reopen_backing_file(bs, true, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            aio_context_release(aio_context);

            return;

        }

        /* start backup job now */

        error_setg(&s->blocker,

                   "Block device is in use by internal backup job");

        top_bs = bdrv_lookup_bs(s->top_id, s->top_id, NULL);

        if (!top_bs || !bdrv_is_root_node(top_bs) ||

            !check_top_bs(top_bs, bs)) {

            error_setg(errp, "No top_bs or it is invalid");

            reopen_backing_file(bs, false, NULL);

            aio_context_release(aio_context);

            return;

        }

        bdrv_op_block_all(top_bs, s->blocker);

        bdrv_op_unblock(top_bs, BLOCK_OP_TYPE_DATAPLANE, s->blocker);

        backup_start(NULL, s->secondary_disk->bs, s->hidden_disk->bs, 0,

                     MIRROR_SYNC_MODE_NONE, NULL, false,

                     BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,

                     BLOCK_JOB_INTERNAL, backup_job_completed, bs,

                     NULL, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            backup_job_cleanup(bs);

            aio_context_release(aio_context);

            return;

        }

        break;

    default:

        aio_context_release(aio_context);

        abort();

    }

    s->replication_state = BLOCK_REPLICATION_RUNNING;

    if (s->mode == REPLICATION_MODE_SECONDARY) {

        secondary_do_checkpoint(s, errp);

    }

    s->error = 0;

    aio_context_release(aio_context);

}


static inline void RENAME(uyvyToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, int 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"

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

        "pand                %%mm4, %%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 + 0];

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

    }

#endif

    assert(src1 == src2);

}


uint32_t vga_mem_readb(VGACommonState *s, hwaddr addr)

{

    int memory_map_mode, plane;

    uint32_t ret;

    /* convert to VGA memory offset */

    memory_map_mode = (s->gr[VGA_GFX_MISC] >> 2) & 3;

    addr &= 0x1ffff;

    switch(memory_map_mode) {

    case 0:

        break;

    case 1:

        if (addr >= 0x10000)

            return 0xff;

        addr += s->bank_offset;

        break;

    case 2:

        addr -= 0x10000;

        if (addr >= 0x8000)

            return 0xff;

        break;

    default:

    case 3:

        addr -= 0x18000;

        if (addr >= 0x8000)

            return 0xff;

        break;

    }

    if (s->sr[VGA_SEQ_MEMORY_MODE] & VGA_SR04_CHN_4M) {

        /* chain 4 mode : simplest access */

        ret = s->vram_ptr[addr];

    } else if (s->gr[VGA_GFX_MODE] & 0x10) {

        /* odd/even mode (aka text mode mapping) */

        plane = (s->gr[VGA_GFX_PLANE_READ] & 2) | (addr & 1);

        ret = s->vram_ptr[((addr & ~1) << 1) | plane];

    } else {

        /* standard VGA latched access */

        s->latch = ((uint32_t *)s->vram_ptr)[addr];

        if (!(s->gr[VGA_GFX_MODE] & 0x08)) {

            /* read mode 0 */

            plane = s->gr[VGA_GFX_PLANE_READ];

            ret = GET_PLANE(s->latch, plane);

        } else {

            /* read mode 1 */

            ret = (s->latch ^ mask16[s->gr[VGA_GFX_COMPARE_VALUE]]) &

                mask16[s->gr[VGA_GFX_COMPARE_MASK]];

            ret |= ret >> 16;

            ret |= ret >> 8;

            ret = (~ret) & 0xff;

        }

    }

    return ret;

}


static av_cold int libx265_encode_close(AVCodecContext *avctx)

{

    libx265Context *ctx = avctx->priv_data;

    av_frame_free(&avctx->coded_frame);

    ctx->api->param_free(ctx->params);

    if (ctx->encoder)

        ctx->api->encoder_close(ctx->encoder);

    return 0;

}


static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDisplay *display,

                                          const uint8_t *buf, int buf_size, int top_bottom, int non_mod)

{

    DVBSubContext *ctx = avctx->priv_data;

    DVBSubRegion *region = get_region(ctx, display->region_id);

    const uint8_t *buf_end = buf + buf_size;

    uint8_t *pbuf;

    int x_pos, y_pos;

    int i;

    uint8_t map2to4[] = { 0x0,  0x7,  0x8,  0xf};

    uint8_t map2to8[] = {0x00, 0x77, 0x88, 0xff};

    uint8_t map4to8[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,

                         0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};

    uint8_t *map_table;

#if 0

    av_dlog(avctx, "DVB pixel block size %d, %s field:\n", buf_size,

            top_bottom ? "bottom" : "top");

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

        if (i % 16 == 0)

            av_dlog(avctx, "0x%8p: ", buf+i);

        av_dlog(avctx, "%02x ", buf[i]);

        if (i % 16 == 15)

            av_dlog(avctx, "\n");

    }

    if (i % 16)

        av_dlog(avctx, "\n");

#endif

    if (region == 0)

        return;

    pbuf = region->pbuf;

    region->dirty = 1;

    x_pos = display->x_pos;

    y_pos = display->y_pos;

    if ((y_pos & 1) != top_bottom)

        y_pos++;

    while (buf < buf_end) {

        if (x_pos > region->width || y_pos > region->height) {

            av_log(avctx, AV_LOG_ERROR, "Invalid object location!\n");

            return;

        }

        switch (*buf++) {

        case 0x10:

            if (region->depth == 8)

                map_table = map2to8;

            else if (region->depth == 4)

                map_table = map2to4;

            else

                map_table = NULL;

            x_pos += dvbsub_read_2bit_string(pbuf + (y_pos * region->width) + x_pos,

                                                region->width - x_pos, &buf, buf_end - buf,

                                                non_mod, map_table);

            break;

        case 0x11:

            if (region->depth < 4) {

                av_log(avctx, AV_LOG_ERROR, "4-bit pixel string in %d-bit region!\n", region->depth);

                return;

            }

            if (region->depth == 8)

                map_table = map4to8;

            else

                map_table = NULL;

            x_pos += dvbsub_read_4bit_string(pbuf + (y_pos * region->width) + x_pos,

                                                region->width - x_pos, &buf, buf_end - buf,

                                                non_mod, map_table);

            break;

        case 0x12:

            if (region->depth < 8) {

                av_log(avctx, AV_LOG_ERROR, "8-bit pixel string in %d-bit region!\n", region->depth);

                return;

            }

            x_pos += dvbsub_read_8bit_string(pbuf + (y_pos * region->width) + x_pos,

                                                region->width - x_pos, &buf, buf_end - buf,

                                                non_mod, NULL);

            break;

        case 0x20:

            map2to4[0] = (*buf) >> 4;

            map2to4[1] = (*buf++) & 0xf;

            map2to4[2] = (*buf) >> 4;

            map2to4[3] = (*buf++) & 0xf;

            break;

        case 0x21:

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

                map2to8[i] = *buf++;

            break;

        case 0x22:

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

                map4to8[i] = *buf++;

            break;

        case 0xf0:

            x_pos = display->x_pos;

            y_pos += 2;

            break;

        default:

            av_log(avctx, AV_LOG_INFO, "Unknown/unsupported pixel block 0x%x\n", *(buf-1));

        }

    }

}


static void assert_file_overwrite(const char *filename)

{

    if (file_overwrite && file_skip) {

        fprintf(stderr, "Error, both -y and -n supplied. Exiting.\n");

        exit_program(1);

    }

    if (!file_overwrite &&

        (strchr(filename, ':') == NULL || filename[1] == ':' ||

         av_strstart(filename, "file:", NULL))) {

        if (avio_check(filename, 0) == 0) {

            if (!using_stdin && !file_skip) {

                fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);

                fflush(stderr);

                if (!read_yesno()) {

                    fprintf(stderr, "Not overwriting - exiting\n");

                    exit_program(1);

                }

            }

            else {

                fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);

                exit_program(1);

            }

        }

    }

}


static void tlb_info(Monitor *mon)

{

    CPUState *env;

    int l1, l2;

    uint32_t pgd, pde, pte;

    env = mon_get_cpu();

    if (!(env->cr[0] & CR0_PG_MASK)) {

        monitor_printf(mon, "PG disabled\n");

        return;

    }

    pgd = env->cr[3] & ~0xfff;

    for(l1 = 0; l1 < 1024; l1++) {

        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);

        pde = le32_to_cpu(pde);

        if (pde & PG_PRESENT_MASK) {

            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {

                print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));

            } else {

                for(l2 = 0; l2 < 1024; l2++) {

                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,

                                             (uint8_t *)&pte, 4);

                    pte = le32_to_cpu(pte);

                    if (pte & PG_PRESENT_MASK) {

                        print_pte(mon, (l1 << 22) + (l2 << 12),

                                  pte & ~PG_PSE_MASK,

                                  ~0xfff);

                    }

                }

            }

        }

    }

}


static void parse_option_number(const char *name, const char *value,

                                uint64_t *ret, Error **errp)

{

    char *postfix;

    uint64_t number;

    number = strtoull(value, &postfix, 0);

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

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");

        return;

    }

    *ret = number;

}


static int decode_vol_header(MpegEncContext *s, GetBitContext *gb){

    int width, height, vo_ver_id;

    /* vol header */

    skip_bits(gb, 1); /* random access */

    s->vo_type= get_bits(gb, 8);

    if (get_bits1(gb) != 0) { /* is_ol_id */

        vo_ver_id = get_bits(gb, 4); /* vo_ver_id */

        skip_bits(gb, 3); /* vo_priority */

    } else {

        vo_ver_id = 1;

//printf("vo type:%d\n",s->vo_type);

    s->aspect_ratio_info= get_bits(gb, 4);

    if(s->aspect_ratio_info == FF_ASPECT_EXTENDED){

        s->avctx->sample_aspect_ratio.num= get_bits(gb, 8); // par_width

        s->avctx->sample_aspect_ratio.den= get_bits(gb, 8); // par_height

    }else{

        s->avctx->sample_aspect_ratio= pixel_aspect[s->aspect_ratio_info];

    if ((s->vol_control_parameters=get_bits1(gb))) { /* vol control parameter */

        int chroma_format= get_bits(gb, 2);

        if(chroma_format!=1){

            av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");

        s->low_delay= get_bits1(gb);

        if(get_bits1(gb)){ /* vbv parameters */

            get_bits(gb, 15);   /* first_half_bitrate */

            skip_bits1(gb);     /* marker */

            get_bits(gb, 15);   /* latter_half_bitrate */

            skip_bits1(gb);     /* marker */

            get_bits(gb, 15);   /* first_half_vbv_buffer_size */

            skip_bits1(gb);     /* marker */

            get_bits(gb, 3);    /* latter_half_vbv_buffer_size */

            get_bits(gb, 11);   /* first_half_vbv_occupancy */

            skip_bits1(gb);     /* marker */

            get_bits(gb, 15);   /* latter_half_vbv_occupancy */

            skip_bits1(gb);     /* marker */

    }else{

        // set low delay flag only once the smartest? low delay detection won't be overriden

        if(s->picture_number==0)

            s->low_delay=0;

    s->shape = get_bits(gb, 2); /* vol shape */

    if(s->shape != RECT_SHAPE) av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");

    if(s->shape == GRAY_SHAPE && vo_ver_id != 1){

        av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");

        skip_bits(gb, 4);  //video_object_layer_shape_extension

    check_marker(gb, "before time_increment_resolution");

    s->avctx->time_base.den = get_bits(gb, 16);

    if(!s->avctx->time_base.den){

        av_log(s->avctx, AV_LOG_ERROR, "time_base.den==0\n");

    s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;

    if (s->time_increment_bits < 1)

        s->time_increment_bits = 1;

    check_marker(gb, "before fixed_vop_rate");

    if (get_bits1(gb) != 0) {   /* fixed_vop_rate  */

        s->avctx->time_base.num = get_bits(gb, s->time_increment_bits);

    }else

        s->avctx->time_base.num = 1;

    s->t_frame=0;

    if (s->shape != BIN_ONLY_SHAPE) {

        if (s->shape == RECT_SHAPE) {

            skip_bits1(gb);   /* marker */

            width = get_bits(gb, 13);

            skip_bits1(gb);   /* marker */

            height = get_bits(gb, 13);

            skip_bits1(gb);   /* marker */

            if(width && height && !(s->width && s->codec_tag == ff_get_fourcc("MP4S"))){ /* they should be non zero but who knows ... */

                s->width = width;

                s->height = height;

//                printf("width/height: %d %d\n", width, height);

        s->progressive_sequence=

        s->progressive_frame= get_bits1(gb)^1;

        s->interlaced_dct=0;

        if(!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))

            av_log(s->avctx, AV_LOG_INFO, "MPEG4 OBMC not supported (very likely buggy encoder)\n");   /* OBMC Disable */

        if (vo_ver_id == 1) {

            s->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */

        } else {

            s->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */

        if(s->vol_sprite_usage==STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");

        if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){

            if(s->vol_sprite_usage==STATIC_SPRITE){

                s->sprite_width = get_bits(gb, 13);

                skip_bits1(gb); /* marker */

                s->sprite_height= get_bits(gb, 13);

                skip_bits1(gb); /* marker */

                s->sprite_left  = get_bits(gb, 13);

                skip_bits1(gb); /* marker */

                s->sprite_top   = get_bits(gb, 13);

                skip_bits1(gb); /* marker */

            s->num_sprite_warping_points= get_bits(gb, 6);

            s->sprite_warping_accuracy = get_bits(gb, 2);

            s->sprite_brightness_change= get_bits1(gb);

            if(s->vol_sprite_usage==STATIC_SPRITE)

                s->low_latency_sprite= get_bits1(gb);

        // FIXME sadct disable bit if verid!=1 && shape not rect

        if (get_bits1(gb) == 1) {   /* not_8_bit */

            s->quant_precision = get_bits(gb, 4); /* quant_precision */

            if(get_bits(gb, 4)!=8) av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n"); /* bits_per_pixel */

            if(s->quant_precision!=5) av_log(s->avctx, AV_LOG_ERROR, "quant precision %d\n", s->quant_precision);

        } else {

            s->quant_precision = 5;

        // FIXME a bunch of grayscale shape things

        if((s->mpeg_quant=get_bits1(gb))){ /* vol_quant_type */

            int i, v;

            /* load default matrixes */

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

                int j= s->dsp.idct_permutation[i];

                v= ff_mpeg4_default_intra_matrix[i];

                s->intra_matrix[j]= v;

                s->chroma_intra_matrix[j]= v;

                v= ff_mpeg4_default_non_intra_matrix[i];

                s->inter_matrix[j]= v;

                s->chroma_inter_matrix[j]= v;

            /* load custom intra matrix */

            if(get_bits1(gb)){

                int last=0;

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

                    int j;

                    v= get_bits(gb, 8);

                    if(v==0) break;

                    last= v;

                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];

                    s->intra_matrix[j]= v;

                    s->chroma_intra_matrix[j]= v;

                /* replicate last value */

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

                    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];

                    s->intra_matrix[j]= last;

                    s->chroma_intra_matrix[j]= last;

            /* load custom non intra matrix */

            if(get_bits1(gb)){

                int last=0;

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

                    int j;

                    v= get_bits(gb, 8);

                    if(v==0) break;

                    last= v;

                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];

                    s->inter_matrix[j]= v;

                    s->chroma_inter_matrix[j]= v;

                /* replicate last value */

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

                    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];

                    s->inter_matrix[j]= last;

                    s->chroma_inter_matrix[j]= last;

            // FIXME a bunch of grayscale shape things

        if(vo_ver_id != 1)

             s->quarter_sample= get_bits1(gb);

        else s->quarter_sample=0;

        if(!get_bits1(gb)) av_log(s->avctx, AV_LOG_ERROR, "Complexity estimation not supported\n");

        s->resync_marker= !get_bits1(gb); /* resync_marker_disabled */

        s->data_partitioning= get_bits1(gb);

        if(s->data_partitioning){

            s->rvlc= get_bits1(gb);

        if(vo_ver_id != 1) {

            s->new_pred= get_bits1(gb);

            if(s->new_pred){

                av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");

                skip_bits(gb, 2); /* requested upstream message type */

                skip_bits1(gb); /* newpred segment type */

            s->reduced_res_vop= get_bits1(gb);

            if(s->reduced_res_vop) av_log(s->avctx, AV_LOG_ERROR, "reduced resolution VOP not supported\n");

        else{

            s->new_pred=0;

            s->reduced_res_vop= 0;

        s->scalability= get_bits1(gb);

        if (s->scalability) {

            GetBitContext bak= *gb;

            int ref_layer_id;

            int ref_layer_sampling_dir;

            int h_sampling_factor_n;

            int h_sampling_factor_m;

            int v_sampling_factor_n;

            int v_sampling_factor_m;

            s->hierachy_type= get_bits1(gb);

            ref_layer_id= get_bits(gb, 4);

            ref_layer_sampling_dir= get_bits1(gb);

            h_sampling_factor_n= get_bits(gb, 5);

            h_sampling_factor_m= get_bits(gb, 5);

            v_sampling_factor_n= get_bits(gb, 5);

            v_sampling_factor_m= get_bits(gb, 5);

            s->enhancement_type= get_bits1(gb);

            if(   h_sampling_factor_n==0 || h_sampling_factor_m==0

               || v_sampling_factor_n==0 || v_sampling_factor_m==0){

//                fprintf(stderr, "illegal scalability header (VERY broken encoder), trying to workaround\n");

                s->scalability=0;

                *gb= bak;

            }else

                av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");

            // bin shape stuff FIXME

    return 0;


static int scsi_disk_initfn(SCSIDevice *dev)
{
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
    int is_cd;
    DriveInfo *dinfo;
    if (!s->qdev.conf.bs) {
        error_report("scsi-disk: drive property not set");
    s->bs = s->qdev.conf.bs;
    is_cd = bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM;
    if (bdrv_get_on_error(s->bs, 1) != BLOCK_ERR_REPORT) {
        error_report("Device doesn't support drive option rerror");
    if (!s->serial) {
        /* try to fall back to value set with legacy -drive serial=... */
        dinfo = drive_get_by_blockdev(s->bs);
        s->serial = qemu_strdup(*dinfo->serial ? dinfo->serial : "0");
    if (!s->version) {
        s->version = qemu_strdup(QEMU_VERSION);
    if (bdrv_is_sg(s->bs)) {
        error_report("scsi-disk: unwanted /dev/sg*");
    if (is_cd) {
        s->qdev.blocksize = 2048;
    } else {
        s->qdev.blocksize = s->qdev.conf.logical_block_size;
    s->cluster_size = s->qdev.blocksize / 512;
    s->qdev.type = TYPE_DISK;
    qemu_add_vm_change_state_handler(scsi_dma_restart_cb, s);
    bdrv_set_removable(s->bs, is_cd);
    return 0;


static av_cold int dvdsub_init(AVCodecContext *avctx)

{

    DVDSubContext *ctx = avctx->priv_data;

    char *data, *cur;

    if (!avctx->extradata || !avctx->extradata_size)

        return 0;

    data = av_malloc(avctx->extradata_size + 1);

    if (!data)

        return AVERROR(ENOMEM);

    memcpy(data, avctx->extradata, avctx->extradata_size);

    data[avctx->extradata_size] = '\0';

    cur = data;

    while (*cur) {

        if (strncmp("palette:", cur, 8) == 0) {

            int i;

            char *p = cur + 8;

            ctx->has_palette = 1;

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

                ctx->palette[i] = strtoul(p, &p, 16);

                while (*p == ',' || av_isspace(*p))

                    p++;

            }

        } else if (!strncmp("size:", cur, 5)) {

            int w, h;

            if (sscanf(cur + 5, "%dx%d", &w, &h) == 2) {

               int ret = ff_set_dimensions(avctx, w, h);

               if (ret < 0)

                   return ret;

            }

        }

        cur += strcspn(cur, "\n\r");

        cur += strspn(cur, "\n\r");

    }

    av_free(data);

    return 0;

}


static void mxf_write_random_index_pack(AVFormatContext *s)

{

    MXFContext *mxf = s->priv_data;

    AVIOContext *pb = s->pb;

    uint64_t pos = avio_tell(pb);

    int i;

    avio_write(pb, random_index_pack_key, 16);

    klv_encode_ber_length(pb, 28 + 12*mxf->body_partitions_count);

    if (mxf->edit_unit_byte_count)

        avio_wb32(pb, 1); // BodySID of header partition

    else

        avio_wb32(pb, 0);

    avio_wb64(pb, 0); // offset of header partition

    for (i = 0; i < mxf->body_partitions_count; i++) {

        avio_wb32(pb, 1); // BodySID

        avio_wb64(pb, mxf->body_partition_offset[i]);

    }

    avio_wb32(pb, 0); // BodySID of footer partition

    avio_wb64(pb, mxf->footer_partition_offset);

    avio_wb32(pb, avio_tell(pb) - pos + 4);

}


static int qcow2_mark_clean(BlockDriverState *bs)

{

    BDRVQcowState *s = bs->opaque;

    if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {

        int ret = bdrv_flush(bs);

        if (ret < 0) {

            return ret;

        }

        s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;

        return qcow2_update_header(bs);

    }

    return 0;

}


static int config_props(AVFilterLink *link)

{

    YADIFContext *yadif = link->src->priv;

    link->time_base.num = link->src->inputs[0]->time_base.num;

    link->time_base.den = link->src->inputs[0]->time_base.den * 2;

    link->w             = link->src->inputs[0]->w;

    link->h             = link->src->inputs[0]->h;

    if(yadif->mode&1)

        link->frame_rate = av_mul_q(link->src->inputs[0]->frame_rate, (AVRational){2,1});

    return 0;

}


void qemu_system_powerdown(void)

{

    if(pm_state->pmen & PWRBTN_EN) {

        pm_state->pmsts |= PWRBTN_EN;

	pm_update_sci(pm_state);

    }

}


static int alloc_table(VLC *vlc, int size)

{

    int index;

    index = vlc->table_size;

    vlc->table_size += size;

    if (vlc->table_size > vlc->table_allocated) {

        vlc->table_allocated += (1 << vlc->bits);

        vlc->table = av_realloc(vlc->table,

                                sizeof(VLC_TYPE) * 2 * vlc->table_allocated);

        if (!vlc->table)

            return -1;

    }

    return index;

}


int net_slirp_smb(const char *exported_dir)

{

    struct in_addr vserver_addr = { .s_addr = 0 };

    if (legacy_smb_export) {

        fprintf(stderr, "-smb given twice\n");

        return -1;

    }

    legacy_smb_export = exported_dir;

    if (!QTAILQ_EMPTY(&slirp_stacks)) {

        return slirp_smb(QTAILQ_FIRST(&slirp_stacks), exported_dir,

                         vserver_addr);

    }

    return 0;

}


static void set_int32(Object *obj, Visitor *v, void *opaque,

                      const char *name, Error **errp)

{

    DeviceState *dev = DEVICE(obj);

    Property *prop = opaque;

    int32_t *ptr = qdev_get_prop_ptr(dev, prop);

    Error *local_err = NULL;

    int64_t value;

    if (dev->state != DEV_STATE_CREATED) {

        error_set(errp, QERR_PERMISSION_DENIED);

        return;

    }

    visit_type_int(v, &value, name, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    if (value > prop->info->min && value <= prop->info->max) {

        *ptr = value;

    } else {

        error_set(errp, QERR_PROPERTY_VALUE_OUT_OF_RANGE,

                  dev->id?:"", name, value, prop->info->min,

                  prop->info->max);

    }

}


static av_cold int smvjpeg_decode_init(AVCodecContext *avctx)

{

    SMVJpegDecodeContext *s = avctx->priv_data;

    AVCodec *codec;

    AVDictionary *thread_opt = NULL;

    int ret = 0;

    s->frames_per_jpeg = 0;

    s->picture[0] = av_frame_alloc();

    if (!s->picture[0])

        return AVERROR(ENOMEM);

    s->picture[1] = av_frame_alloc();

    if (!s->picture[1])

        return AVERROR(ENOMEM);

    s->jpg.picture_ptr      = s->picture[0];

    if (avctx->extradata_size >= 4)

        s->frames_per_jpeg = AV_RL32(avctx->extradata);

    if (s->frames_per_jpeg <= 0) {

        av_log(avctx, AV_LOG_ERROR, "Invalid number of frames per jpeg.\n");

        ret = -1;

    }

    codec = avcodec_find_decoder(AV_CODEC_ID_MJPEG);

    if (!codec) {

        av_log(avctx, AV_LOG_ERROR, "MJPEG codec not found\n");

        ret = -1;

    }

    s->avctx = avcodec_alloc_context3(codec);

    av_dict_set(&thread_opt, "threads", "1", 0);

    s->avctx->refcounted_frames = 1;

    s->avctx->flags = avctx->flags;

    s->avctx->idct_algo = avctx->idct_algo;

    if (ff_codec_open2_recursive(s->avctx, codec, &thread_opt) < 0) {

        av_log(avctx, AV_LOG_ERROR, "MJPEG codec failed to open\n");

        ret = -1;

    }

    av_dict_free(&thread_opt);

    return ret;

}


static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const char *vfilters)

{

    static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };

    char sws_flags_str[128];

    char buffersrc_args[256];

    int ret;

    AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();

    AVFilterContext *filt_src = NULL, *filt_out = NULL, *filt_format, *filt_crop;

    AVCodecContext *codec = is->video_st->codec;

    snprintf(sws_flags_str, sizeof(sws_flags_str), "flags=%d", sws_flags);

    graph->scale_sws_opts = av_strdup(sws_flags_str);

    snprintf(buffersrc_args, sizeof(buffersrc_args),

             "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",

             codec->width, codec->height, codec->pix_fmt,

             is->video_st->time_base.num, is->video_st->time_base.den,

             codec->sample_aspect_ratio.num, codec->sample_aspect_ratio.den);

    if ((ret = avfilter_graph_create_filter(&filt_src,

                                            avfilter_get_by_name("buffer"),

                                            "ffplay_buffer", buffersrc_args, NULL,

                                            graph)) < 0)

        return ret;

    buffersink_params->pixel_fmts = pix_fmts;

    ret = avfilter_graph_create_filter(&filt_out,

                                       avfilter_get_by_name("ffbuffersink"),

                                       "ffplay_buffersink", NULL, buffersink_params, graph);

    av_freep(&buffersink_params);

    if (ret < 0)

        return ret;

    /* SDL YUV code is not handling odd width/height for some driver

     * combinations, therefore we crop the picture to an even width/height. */

    if ((ret = avfilter_graph_create_filter(&filt_crop,

                                            avfilter_get_by_name("crop"),

                                            "ffplay_crop", "floor(in_w/2)*2:floor(in_h/2)*2", NULL, graph)) < 0)

        return ret;

    if ((ret = avfilter_graph_create_filter(&filt_format,

                                            avfilter_get_by_name("format"),

                                            "format", "yuv420p", NULL, graph)) < 0)

        return ret;

    if ((ret = avfilter_link(filt_crop, 0, filt_format, 0)) < 0)

        return ret;

    if ((ret = avfilter_link(filt_format, 0, filt_out, 0)) < 0)

        return ret;

    if ((ret = configure_filtergraph(graph, vfilters, filt_src, filt_crop)) < 0)

        return ret;

    is->in_video_filter  = filt_src;

    is->out_video_filter = filt_out;

    return ret;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    dc->realize = pxa2xx_pcmcia_realize;

}


static void cuvid_flush(AVCodecContext *avctx)

{

    CuvidContext *ctx = avctx->priv_data;

    AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;

    AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;

    CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;

    CUVIDSOURCEDATAPACKET seq_pkt = { 0 };

    int ret;

    ctx->ever_flushed = 1;

    ret = CHECK_CU(cuCtxPushCurrent(cuda_ctx));

    if (ret < 0)

        goto error;

    av_fifo_freep(&ctx->frame_queue);

    ctx->frame_queue = av_fifo_alloc(MAX_FRAME_COUNT * sizeof(CuvidParsedFrame));

    if (!ctx->frame_queue) {

        av_log(avctx, AV_LOG_ERROR, "Failed to recreate frame queue on flush\n");

        return;

    }

    if (ctx->cudecoder) {

        cuvidDestroyDecoder(ctx->cudecoder);

        ctx->cudecoder = NULL;

    }

    if (ctx->cuparser) {

        cuvidDestroyVideoParser(ctx->cuparser);

        ctx->cuparser = NULL;

    }

    ret = CHECK_CU(cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));

    if (ret < 0)

        goto error;

    seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;

    seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;

    if (seq_pkt.payload && seq_pkt.payload_size) {

        ret = CHECK_CU(cuvidParseVideoData(ctx->cuparser, &seq_pkt));

        if (ret < 0)

            goto error;

    }

    ret = CHECK_CU(cuCtxPopCurrent(&dummy));

    if (ret < 0)

        goto error;

    ctx->prev_pts = INT64_MIN;

    ctx->decoder_flushing = 0;

    return;

 error:

    av_log(avctx, AV_LOG_ERROR, "CUDA reinit on flush failed\n");

}


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

                                ptrdiff_t stride)

{

    avg_width8_msa(src, stride, dst, stride, 8);

}


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

                        const AVFrame *pict, int *got_packet)

{

    TiffEncoderContext *s = avctx->priv_data;

    const AVFrame *const p = pict;

    int i;

    uint8_t *ptr;

    uint8_t *offset;

    uint32_t strips;

    uint32_t *strip_sizes   = NULL;

    uint32_t *strip_offsets = NULL;

    int bytes_per_row;

    uint32_t res[2]    = { 72, 1 };     // image resolution (72/1)

    uint16_t bpp_tab[] = { 8, 8, 8, 8 };

    int ret;

    int is_yuv = 0;

    uint8_t *yuv_line = NULL;

    int shift_h, shift_v;

    int packet_size;

    const AVPixFmtDescriptor *pfd;

    s->avctx = avctx;

    s->width          = avctx->width;

    s->height         = avctx->height;

    s->subsampling[0] = 1;

    s->subsampling[1] = 1;

    switch (avctx->pix_fmt) {

    case AV_PIX_FMT_RGB48LE:

    case AV_PIX_FMT_GRAY16LE:

    case AV_PIX_FMT_RGBA:

    case AV_PIX_FMT_RGB24:

    case AV_PIX_FMT_GRAY8:

    case AV_PIX_FMT_PAL8:

        pfd    = av_pix_fmt_desc_get(avctx->pix_fmt);

        s->bpp = av_get_bits_per_pixel(pfd);

        if (pfd->flags & AV_PIX_FMT_FLAG_PAL)

            s->photometric_interpretation = TIFF_PHOTOMETRIC_PALETTE;

        else if (pfd->flags & AV_PIX_FMT_FLAG_RGB)

            s->photometric_interpretation = TIFF_PHOTOMETRIC_RGB;

        else

            s->photometric_interpretation = TIFF_PHOTOMETRIC_BLACK_IS_ZERO;

        s->bpp_tab_size = pfd->nb_components;

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

            bpp_tab[i] = s->bpp / s->bpp_tab_size;

        break;

    case AV_PIX_FMT_MONOBLACK:

        s->bpp                        = 1;

        s->photometric_interpretation = TIFF_PHOTOMETRIC_BLACK_IS_ZERO;

        s->bpp_tab_size               = 0;

        break;

    case AV_PIX_FMT_MONOWHITE:

        s->bpp                        = 1;

        s->photometric_interpretation = TIFF_PHOTOMETRIC_WHITE_IS_ZERO;

        s->bpp_tab_size               = 0;

        break;

    case AV_PIX_FMT_YUV420P:

    case AV_PIX_FMT_YUV422P:

    case AV_PIX_FMT_YUV444P:

    case AV_PIX_FMT_YUV410P:

    case AV_PIX_FMT_YUV411P:

        av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &shift_h, &shift_v);

        s->photometric_interpretation = TIFF_PHOTOMETRIC_YCBCR;

        s->bpp                        = 8 + (16 >> (shift_h + shift_v));

        s->subsampling[0]             = 1 << shift_h;

        s->subsampling[1]             = 1 << shift_v;

        s->bpp_tab_size               = 3;

        is_yuv                        = 1;

        break;

    default:

        av_log(s->avctx, AV_LOG_ERROR,

               "This colors format is not supported\n");

        return -1;

    }

    if (s->compr == TIFF_DEFLATE       ||

        s->compr == TIFF_ADOBE_DEFLATE ||

        s->compr == TIFF_LZW)

        // best choice for DEFLATE

        s->rps = s->height;

    else

        // suggest size of strip

        s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1);

    // round rps up

    s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1];

    strips = (s->height - 1) / s->rps + 1;

    packet_size = avctx->height * ((avctx->width * s->bpp + 7) >> 3) * 2 +

                  avctx->height * 4 + FF_MIN_BUFFER_SIZE;

    if (!pkt->data &&

        (ret = av_new_packet(pkt, packet_size)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");

        return ret;

    }

    ptr          = pkt->data;

    s->buf_start = pkt->data;

    s->buf       = &ptr;

    s->buf_size  = pkt->size;

    if (check_size(s, 8))

        goto fail;

    // write header

    bytestream_put_le16(&ptr, 0x4949);

    bytestream_put_le16(&ptr, 42);

    offset = ptr;

    bytestream_put_le32(&ptr, 0);

    strip_sizes   = av_mallocz_array(strips, sizeof(*strip_sizes));

    strip_offsets = av_mallocz_array(strips, sizeof(*strip_offsets));

    if (!strip_sizes || !strip_offsets) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    bytes_per_row = (((s->width - 1) / s->subsampling[0] + 1) * s->bpp *

                     s->subsampling[0] * s->subsampling[1] + 7) >> 3;

    if (is_yuv) {

        yuv_line = av_malloc(bytes_per_row);

        if (!yuv_line) {

            av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");

            ret = AVERROR(ENOMEM);

            goto fail;

        }

    }

#if CONFIG_ZLIB

    if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {

        uint8_t *zbuf;

        int zlen, zn;

        int j;

        zlen = bytes_per_row * s->rps;

        zbuf = av_malloc(zlen);

        if (!zbuf) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        strip_offsets[0] = ptr - pkt->data;

        zn               = 0;

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

            if (is_yuv) {

                pack_yuv(s, p, yuv_line, j);

                memcpy(zbuf + zn, yuv_line, bytes_per_row);

                j += s->subsampling[1] - 1;

            } else

                memcpy(zbuf + j * bytes_per_row,

                       p->data[0] + j * p->linesize[0], bytes_per_row);

            zn += bytes_per_row;

        }

        ret = encode_strip(s, zbuf, ptr, zn, s->compr);

        av_free(zbuf);

        if (ret < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");

            goto fail;

        }

        ptr           += ret;

        strip_sizes[0] = ptr - pkt->data - strip_offsets[0];

    } else

#endif

    if (s->compr == TIFF_LZW) {

        s->lzws = av_malloc(ff_lzw_encode_state_size);

        if (!s->lzws) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

    }

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

        if (strip_sizes[i / s->rps] == 0) {

            if (s->compr == TIFF_LZW) {

                ff_lzw_encode_init(s->lzws, ptr,

                                   s->buf_size - (*s->buf - s->buf_start),

                                   12, FF_LZW_TIFF, put_bits);

            }

            strip_offsets[i / s->rps] = ptr - pkt->data;

        }

        if (is_yuv) {

            pack_yuv(s, p, yuv_line, i);

            ret = encode_strip(s, yuv_line, ptr, bytes_per_row, s->compr);

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

        } else

            ret = encode_strip(s, p->data[0] + i * p->linesize[0],

                               ptr, bytes_per_row, s->compr);

        if (ret < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");

            goto fail;

        }

        strip_sizes[i / s->rps] += ret;

        ptr                     += ret;

        if (s->compr == TIFF_LZW &&

            (i == s->height - 1 || i % s->rps == s->rps - 1)) {

            ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);

            strip_sizes[(i / s->rps)] += ret;

            ptr                       += ret;

        }

    }

    if (s->compr == TIFF_LZW)

        av_free(s->lzws);

    s->num_entries = 0;

    add_entry1(s, TIFF_SUBFILE, TIFF_LONG, 0);

    add_entry1(s, TIFF_WIDTH,   TIFF_LONG, s->width);

    add_entry1(s, TIFF_HEIGHT,  TIFF_LONG, s->height);

    if (s->bpp_tab_size)

        add_entry(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab);

    add_entry1(s, TIFF_COMPR,       TIFF_SHORT, s->compr);

    add_entry1(s, TIFF_PHOTOMETRIC, TIFF_SHORT, s->photometric_interpretation);

    add_entry(s,  TIFF_STRIP_OFFS,  TIFF_LONG,  strips, strip_offsets);

    if (s->bpp_tab_size)

        add_entry1(s, TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT, s->bpp_tab_size);

    add_entry1(s, TIFF_ROWSPERSTRIP, TIFF_LONG,     s->rps);

    add_entry(s,  TIFF_STRIP_SIZE,   TIFF_LONG,     strips, strip_sizes);

    add_entry(s,  TIFF_XRES,         TIFF_RATIONAL, 1,      res);

    add_entry(s,  TIFF_YRES,         TIFF_RATIONAL, 1,      res);

    add_entry1(s, TIFF_RES_UNIT,     TIFF_SHORT,    2);

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

        add_entry(s, TIFF_SOFTWARE_NAME, TIFF_STRING,

                  strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);

    if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {

        uint16_t pal[256 * 3];

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

            uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);

            pal[i]       = ((rgb >> 16) & 0xff) * 257;

            pal[i + 256] = ((rgb >>  8) & 0xff) * 257;

            pal[i + 512] =  (rgb        & 0xff) * 257;

        }

        add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);

    }

    if (is_yuv) {

        /** according to CCIR Recommendation 601.1 */

        uint32_t refbw[12] = { 15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1 };

        add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT,    2, s->subsampling);

        add_entry(s, TIFF_REFERENCE_BW,      TIFF_RATIONAL, 6, refbw);

    }

    // write offset to dir

    bytestream_put_le32(&offset, ptr - pkt->data);

    if (check_size(s, 6 + s->num_entries * 12)) {

        ret = AVERROR(EINVAL);

        goto fail;

    }

    bytestream_put_le16(&ptr, s->num_entries);  // write tag count

    bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);

    bytestream_put_le32(&ptr, 0);

    pkt->size   = ptr - pkt->data;

    pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

fail:

    av_free(strip_sizes);

    av_free(strip_offsets);

    av_free(yuv_line);

    return ret;

}


static int parse_key(DBEContext *s)

{

    int key = 0;

    if (s->key_present && s->input_size > 0)

        key = AV_RB24(s->input) >> 24 - s->word_bits;

    skip_input(s, s->key_present);

    return key;

}


static int vaapi_encode_issue(AVCodecContext *avctx,

                              VAAPIEncodePicture *pic)

{

    VAAPIEncodeContext *ctx = avctx->priv_data;

    VAAPIEncodeSlice *slice;

    VAStatus vas;

    int err, i;

    char data[MAX_PARAM_BUFFER_SIZE];

    size_t bit_len;

    av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "

           "as type %s.\n", pic->display_order, pic->encode_order,

           picture_type_name[pic->type]);

    if (pic->nb_refs == 0) {

        av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");

    } else {

        av_log(avctx, AV_LOG_DEBUG, "Refers to:");

        for (i = 0; i < pic->nb_refs; i++) {

            av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,

                   pic->refs[i]->display_order, pic->refs[i]->encode_order);

        }

        av_log(avctx, AV_LOG_DEBUG, ".\n");

    }

    av_assert0(pic->input_available && !pic->encode_issued);

    for (i = 0; i < pic->nb_refs; i++) {

        av_assert0(pic->refs[i]);

        // If we are serialised then the references must have already

        // completed.  If not, they must have been issued but need not

        // have completed yet.

        if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)

            av_assert0(pic->refs[i]->encode_complete);

        else

            av_assert0(pic->refs[i]->encode_issued);

    }

    av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);

    pic->recon_image = av_frame_alloc();

    if (!pic->recon_image) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);

    if (err < 0) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];

    av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);

    pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);

    if (!pic->output_buffer_ref) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;

    av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",

           pic->output_buffer);

    if (ctx->codec->picture_params_size > 0) {

        pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);

        if (!pic->codec_picture_params)

            goto fail;

        memcpy(pic->codec_picture_params, ctx->codec_picture_params,

               ctx->codec->picture_params_size);

    } else {

        av_assert0(!ctx->codec_picture_params);

    }

    pic->nb_param_buffers = 0;

    if (pic->encode_order == 0) {

        // Global parameter buffers are set on the first picture only.

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

            err = vaapi_encode_make_param_buffer(avctx, pic,

                                                 VAEncMiscParameterBufferType,

                                                 (char*)ctx->global_params[i],

                                                 ctx->global_params_size[i]);

            if (err < 0)

                goto fail;

        }

    }

    if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {

        err = vaapi_encode_make_param_buffer(avctx, pic,

                                             VAEncSequenceParameterBufferType,

                                             ctx->codec_sequence_params,

                                             ctx->codec->sequence_params_size);

        if (err < 0)

            goto fail;

    }

    if (ctx->codec->init_picture_params) {

        err = ctx->codec->init_picture_params(avctx, pic);

        if (err < 0) {

            av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "

                   "parameters: %d.\n", err);

            goto fail;

        }

        err = vaapi_encode_make_param_buffer(avctx, pic,

                                             VAEncPictureParameterBufferType,

                                             pic->codec_picture_params,

                                             ctx->codec->picture_params_size);

        if (err < 0)

            goto fail;

    }

    if (pic->type == PICTURE_TYPE_IDR) {

        if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&

            ctx->codec->write_sequence_header) {

            bit_len = 8 * sizeof(data);

            err = ctx->codec->write_sequence_header(avctx, data, &bit_len);

            if (err < 0) {

                av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "

                       "header: %d.\n", err);

                goto fail;

            }

            err = vaapi_encode_make_packed_header(avctx, pic,

                                                  ctx->codec->sequence_header_type,

                                                  data, bit_len);

            if (err < 0)

                goto fail;

        }

    }

    if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&

        ctx->codec->write_picture_header) {

        bit_len = 8 * sizeof(data);

        err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);

        if (err < 0) {

            av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "

                   "header: %d.\n", err);

            goto fail;

        }

        err = vaapi_encode_make_packed_header(avctx, pic,

                                              ctx->codec->picture_header_type,

                                              data, bit_len);

        if (err < 0)

            goto fail;

    }

    if (ctx->codec->write_extra_buffer) {

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

            size_t len = sizeof(data);

            int type;

            err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,

                                                 data, &len);

            if (err == AVERROR_EOF)

                break;

            if (err < 0) {

                av_log(avctx, AV_LOG_ERROR, "Failed to write extra "

                       "buffer %d: %d.\n", i, err);

                goto fail;

            }

            err = vaapi_encode_make_param_buffer(avctx, pic, type,

                                                 data, len);

            if (err < 0)

                goto fail;

        }

    }

    if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&

        ctx->codec->write_extra_header) {

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

            int type;

            bit_len = 8 * sizeof(data);

            err = ctx->codec->write_extra_header(avctx, pic, i, &type,

                                                 data, &bit_len);

            if (err == AVERROR_EOF)

                break;

            if (err < 0) {

                av_log(avctx, AV_LOG_ERROR, "Failed to write extra "

                       "header %d: %d.\n", i, err);

                goto fail;

            }

            err = vaapi_encode_make_packed_header(avctx, pic, type,

                                                  data, bit_len);

            if (err < 0)

                goto fail;

        }

    }

    av_assert0(pic->nb_slices <= MAX_PICTURE_SLICES);

    for (i = 0; i < pic->nb_slices; i++) {

        slice = av_mallocz(sizeof(*slice));

        if (!slice) {

            err = AVERROR(ENOMEM);

            goto fail;

        }

        slice->index = i;

        pic->slices[i] = slice;

        if (ctx->codec->slice_params_size > 0) {

            slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);

            if (!slice->codec_slice_params) {

                err = AVERROR(ENOMEM);

                goto fail;

            }

        }

        if (ctx->codec->init_slice_params) {

            err = ctx->codec->init_slice_params(avctx, pic, slice);

            if (err < 0) {

                av_log(avctx, AV_LOG_ERROR, "Failed to initalise slice "

                       "parameters: %d.\n", err);

                goto fail;

            }

        }

        if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&

            ctx->codec->write_slice_header) {

            bit_len = 8 * sizeof(data);

            err = ctx->codec->write_slice_header(avctx, pic, slice,

                                                 data, &bit_len);

            if (err < 0) {

                av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "

                       "header: %d.\n", err);

                goto fail;

            }

            err = vaapi_encode_make_packed_header(avctx, pic,

                                                  ctx->codec->slice_header_type,

                                                  data, bit_len);

            if (err < 0)

                goto fail;

        }

        if (ctx->codec->init_slice_params) {

            err = vaapi_encode_make_param_buffer(avctx, pic,

                                                 VAEncSliceParameterBufferType,

                                                 slice->codec_slice_params,

                                                 ctx->codec->slice_params_size);

            if (err < 0)

                goto fail;

        }

    }

    vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,

                         pic->input_surface);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "

               "%d (%s).\n", vas, vaErrorStr(vas));

        err = AVERROR(EIO);

        goto fail_with_picture;

    }

    vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,

                          pic->param_buffers, pic->nb_param_buffers);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "

               "%d (%s).\n", vas, vaErrorStr(vas));

        err = AVERROR(EIO);

        goto fail_with_picture;

    }

    vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "

               "%d (%s).\n", vas, vaErrorStr(vas));

        err = AVERROR(EIO);

        // vaRenderPicture() has been called here, so we should not destroy

        // the parameter buffers unless separate destruction is required.

        if (ctx->hwctx->driver_quirks &

            AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)

            goto fail;

        else

            goto fail_at_end;

    }

    if (ctx->hwctx->driver_quirks &

        AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {

        for (i = 0; i < pic->nb_param_buffers; i++) {

            vas = vaDestroyBuffer(ctx->hwctx->display,

                                  pic->param_buffers[i]);

            if (vas != VA_STATUS_SUCCESS) {

                av_log(avctx, AV_LOG_ERROR, "Failed to destroy "

                       "param buffer %#x: %d (%s).\n",

                       pic->param_buffers[i], vas, vaErrorStr(vas));

                // And ignore.

            }

        }

    }

    pic->encode_issued = 1;

    if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)

        return vaapi_encode_wait(avctx, pic);

    else

        return 0;

fail_with_picture:

    vaEndPicture(ctx->hwctx->display, ctx->va_context);

fail:

    for(i = 0; i < pic->nb_param_buffers; i++)

        vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);

fail_at_end:

    av_freep(&pic->codec_picture_params);

    av_frame_free(&pic->recon_image);

    return err;

}


static void pc_q35_machine_options(MachineClass *m)

{

    m->family = "pc_q35";

    m->desc = "Standard PC (Q35 + ICH9, 2009)";

    m->hot_add_cpu = pc_hot_add_cpu;

    m->units_per_default_bus = 1;

    m->default_machine_opts = "firmware=bios-256k.bin";

    m->default_display = "std";

    m->no_floppy = 1;

}


static int check_protocol_support(bool *has_ipv4, bool *has_ipv6)

{

    struct sockaddr_in sin = {

        .sin_family = AF_INET,

        .sin_addr = { .s_addr = htonl(INADDR_LOOPBACK) },

    };

    struct sockaddr_in6 sin6 = {

        .sin6_family = AF_INET6,

        .sin6_addr = IN6ADDR_LOOPBACK_INIT,

    };

    if (check_bind((struct sockaddr *)&sin, sizeof(sin), has_ipv4) < 0) {

        return -1;

    }

    if (check_bind((struct sockaddr *)&sin6, sizeof(sin6), has_ipv6) < 0) {

        return -1;

    }

    return 0;

}


static inline void RENAME(rgb24to32)(const uint8_t *src,uint8_t *dst,unsigned src_size)

{

  uint8_t *dest = dst;

  const uint8_t *s = src;

  const uint8_t *end;

#ifdef HAVE_MMX

  const uint8_t *mm_end;

#endif

  end = s + src_size;

#ifdef HAVE_MMX

  __asm __volatile(PREFETCH"	%0"::"m"(*s):"memory");

  mm_end = end - 23;

  __asm __volatile("movq	%0, %%mm7"::"m"(mask32):"memory");

  while(s < mm_end)

  {

    __asm __volatile(

	PREFETCH"	32%1\n\t"

	"movd	%1, %%mm0\n\t"

	"punpckldq 3%1, %%mm0\n\t"

	"movd	6%1, %%mm1\n\t"

	"punpckldq 9%1, %%mm1\n\t"

	"movd	12%1, %%mm2\n\t"

	"punpckldq 15%1, %%mm2\n\t"

	"movd	18%1, %%mm3\n\t"

	"punpckldq 21%1, %%mm3\n\t"

	"pand	%%mm7, %%mm0\n\t"

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

	"pand	%%mm7, %%mm2\n\t"

	"pand	%%mm7, %%mm3\n\t"

	MOVNTQ"	%%mm0, %0\n\t"

	MOVNTQ"	%%mm1, 8%0\n\t"

	MOVNTQ"	%%mm2, 16%0\n\t"

	MOVNTQ"	%%mm3, 24%0"

	:"=m"(*dest)

	:"m"(*s)

	:"memory");

    dest += 32;

    s += 24;

  }

  __asm __volatile(SFENCE:::"memory");

  __asm __volatile(EMMS:::"memory");

#endif

  while(s < end)

  {

#ifdef WORDS_BIGENDIAN

    *dest++ = 0;

    *dest++ = *s++;

    *dest++ = *s++;

    *dest++ = *s++;

#else

    *dest++ = *s++;

    *dest++ = *s++;

    *dest++ = *s++;

    *dest++ = 0;

#endif

  }

}