static void vararg_number(void)

{

    QObject *obj;

    QInt *qint;

    QFloat *qfloat;

    int value = 0x2342;

    int64_t value64 = 0x2342342343LL;

    double valuef = 2.323423423;

    obj = qobject_from_jsonf("%d", value);

    g_assert(obj != NULL);

    g_assert(qobject_type(obj) == QTYPE_QINT);

    qint = qobject_to_qint(obj);

    g_assert(qint_get_int(qint) == value);

    QDECREF(qint);

    obj = qobject_from_jsonf("%" PRId64, value64);

    g_assert(obj != NULL);

    g_assert(qobject_type(obj) == QTYPE_QINT);

    qint = qobject_to_qint(obj);

    g_assert(qint_get_int(qint) == value64);

    QDECREF(qint);

    obj = qobject_from_jsonf("%f", valuef);

    g_assert(obj != NULL);

    g_assert(qobject_type(obj) == QTYPE_QFLOAT);

    qfloat = qobject_to_qfloat(obj);

    g_assert(qfloat_get_double(qfloat) == valuef);

    QDECREF(qfloat);

}


static int ohci_service_ed_list(OHCIState *ohci, uint32_t head, int completion)

{

    struct ohci_ed ed;

    uint32_t next_ed;

    uint32_t cur;

    int active;

    active = 0;

    if (head == 0)

        return 0;

    for (cur = head; cur; cur = next_ed) {

        if (ohci_read_ed(ohci, cur, &ed)) {

            trace_usb_ohci_ed_read_error(cur);

            ohci_die(ohci);

            return 0;

        }

        next_ed = ed.next & OHCI_DPTR_MASK;

        if ((ed.head & OHCI_ED_H) || (ed.flags & OHCI_ED_K)) {

            uint32_t addr;

            /* Cancel pending packets for ED that have been paused.  */

            addr = ed.head & OHCI_DPTR_MASK;

            if (ohci->async_td && addr == ohci->async_td) {

                usb_cancel_packet(&ohci->usb_packet);

                ohci->async_td = 0;

                usb_device_ep_stopped(ohci->usb_packet.ep->dev,

                                      ohci->usb_packet.ep);

            }

            continue;

        }

        while ((ed.head & OHCI_DPTR_MASK) != ed.tail) {

            trace_usb_ohci_ed_pkt(cur, (ed.head & OHCI_ED_H) != 0,

                    (ed.head & OHCI_ED_C) != 0, ed.head & OHCI_DPTR_MASK,

                    ed.tail & OHCI_DPTR_MASK, ed.next & OHCI_DPTR_MASK);

            trace_usb_ohci_ed_pkt_flags(

                    OHCI_BM(ed.flags, ED_FA), OHCI_BM(ed.flags, ED_EN),

                    OHCI_BM(ed.flags, ED_D), (ed.flags & OHCI_ED_S)!= 0,

                    (ed.flags & OHCI_ED_K) != 0, (ed.flags & OHCI_ED_F) != 0,

                    OHCI_BM(ed.flags, ED_MPS));

            active = 1;

            if ((ed.flags & OHCI_ED_F) == 0) {

                if (ohci_service_td(ohci, &ed))

                    break;

            } else {

                /* Handle isochronous endpoints */

                if (ohci_service_iso_td(ohci, &ed, completion))

                    break;

            }

        }

        if (ohci_put_ed(ohci, cur, &ed)) {

            ohci_die(ohci);

            return 0;

        }

    }

    return active;

}


void s390_pci_iommu_disable(S390PCIBusDevice *pbdev)

{

    memory_region_del_subregion(&pbdev->mr, &pbdev->iommu_mr);

    object_unparent(OBJECT(&pbdev->iommu_mr));

    pbdev->iommu_enabled = false;

}


int ffurl_connect(URLContext *uc, AVDictionary **options)

{

    int err =

        uc->prot->url_open2 ? uc->prot->url_open2(uc,

                                                  uc->filename,

                                                  uc->flags,

                                                  options) :

        uc->prot->url_open(uc, uc->filename, uc->flags);

    if (err)

        return err;

    uc->is_connected = 1;

    /* We must be careful here as ffurl_seek() could be slow,

     * for example for http */

    if ((uc->flags & AVIO_FLAG_WRITE) || !strcmp(uc->prot->name, "file"))

        if (!uc->is_streamed && ffurl_seek(uc, 0, SEEK_SET) < 0)

            uc->is_streamed = 1;

    return 0;

}


uint8_t sd_read_data(SDState *sd)

{

    /* TODO: Append CRCs */

    uint8_t ret;

    int io_len;

    if (!sd->bdrv || !bdrv_is_inserted(sd->bdrv) || !sd->enable)

        return 0x00;

    if (sd->state != sd_sendingdata_state) {

        fprintf(stderr, "sd_read_data: not in Sending-Data state\n");

        return 0x00;

    }

    if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))

        return 0x00;

    io_len = (sd->ocr & (1 << 30)) ? 512 : sd->blk_len;

    switch (sd->current_cmd) {

    case 6:	/* CMD6:   SWITCH_FUNCTION */

        ret = sd->data[sd->data_offset ++];

        if (sd->data_offset >= 64)

            sd->state = sd_transfer_state;

        break;

    case 9:	/* CMD9:   SEND_CSD */

    case 10:	/* CMD10:  SEND_CID */

        ret = sd->data[sd->data_offset ++];

        if (sd->data_offset >= 16)

            sd->state = sd_transfer_state;

        break;

    case 11:	/* CMD11:  READ_DAT_UNTIL_STOP */

        if (sd->data_offset == 0)

            BLK_READ_BLOCK(sd->data_start, io_len);

        ret = sd->data[sd->data_offset ++];

        if (sd->data_offset >= io_len) {

            sd->data_start += io_len;

            sd->data_offset = 0;

            if (sd->data_start + io_len > sd->size) {

                sd->card_status |= ADDRESS_ERROR;

                break;

            }

        }

        break;

    case 13:	/* ACMD13: SD_STATUS */

        ret = sd->sd_status[sd->data_offset ++];

        if (sd->data_offset >= sizeof(sd->sd_status))

            sd->state = sd_transfer_state;

        break;

    case 17:	/* CMD17:  READ_SINGLE_BLOCK */

        if (sd->data_offset == 0)

            BLK_READ_BLOCK(sd->data_start, io_len);

        ret = sd->data[sd->data_offset ++];

        if (sd->data_offset >= io_len)

            sd->state = sd_transfer_state;

        break;

    case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */

        if (sd->data_offset == 0)

            BLK_READ_BLOCK(sd->data_start, io_len);

        ret = sd->data[sd->data_offset ++];

        if (sd->data_offset >= io_len) {

            sd->data_start += io_len;

            sd->data_offset = 0;

            if (sd->data_start + io_len > sd->size) {

                sd->card_status |= ADDRESS_ERROR;

                break;

            }

        }

        break;

    case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */

        ret = sd->data[sd->data_offset ++];

        if (sd->data_offset >= 4)

            sd->state = sd_transfer_state;

        break;

    case 30:	/* CMD30:  SEND_WRITE_PROT */

        ret = sd->data[sd->data_offset ++];

        if (sd->data_offset >= 4)

            sd->state = sd_transfer_state;

        break;

    case 51:	/* ACMD51: SEND_SCR */

        ret = sd->scr[sd->data_offset ++];

        if (sd->data_offset >= sizeof(sd->scr))

            sd->state = sd_transfer_state;

        break;

    case 56:	/* CMD56:  GEN_CMD */

        if (sd->data_offset == 0)

            APP_READ_BLOCK(sd->data_start, sd->blk_len);

        ret = sd->data[sd->data_offset ++];

        if (sd->data_offset >= sd->blk_len)

            sd->state = sd_transfer_state;

        break;

    default:

        fprintf(stderr, "sd_read_data: unknown command\n");

        return 0x00;

    }

    return ret;

}


static void test_visitor_out_int(TestOutputVisitorData *data,

                                 const void *unused)

{

    int64_t value = -42;

    QObject *obj;

    visit_type_int(data->ov, NULL, &value, &error_abort);

    obj = visitor_get(data);

    g_assert(qobject_type(obj) == QTYPE_QINT);

    g_assert_cmpint(qint_get_int(qobject_to_qint(obj)), ==, value);

}


void net_slirp_hostfwd_remove(Monitor *mon, const char *src_str)

{

    struct in_addr host_addr = { .s_addr = INADDR_ANY };

    int host_port;

    char buf[256] = "";

    const char *p = src_str;

    int is_udp = 0;

    int n;

    if (!slirp_inited) {

        monitor_printf(mon, "user mode network stack not in use\n");

        return;

    }

    if (!src_str || !src_str[0])

        goto fail_syntax;

    get_str_sep(buf, sizeof(buf), &p, ':');

    if (!strcmp(buf, "tcp") || buf[0] == '\0') {

        is_udp = 0;

    } else if (!strcmp(buf, "udp")) {

        is_udp = 1;

    } else {

        goto fail_syntax;

    }

    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

        goto fail_syntax;

    }

    if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {

        goto fail_syntax;

    }

    host_port = atoi(p);

    n = slirp_remove_hostfwd(is_udp, host_addr, host_port);

    monitor_printf(mon, "removed %d host forwarding rules for %s\n", n,

                   src_str);

    return;

 fail_syntax:

    monitor_printf(mon, "invalid format\n");

}


static int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,

                          int remaining_sectors, QEMUIOVector *qiov)

{

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster, n1;

    int ret;

    int cur_nr_sectors; /* number of sectors in current iteration */

    uint64_t cluster_offset = 0;

    uint64_t bytes_done = 0;

    QEMUIOVector hd_qiov;

    uint8_t *cluster_data = NULL;

    qemu_iovec_init(&hd_qiov, qiov->niov);

    qemu_co_mutex_lock(&s->lock);

    while (remaining_sectors != 0) {

        /* prepare next request */

        cur_nr_sectors = remaining_sectors;

        if (s->crypt_method) {

            cur_nr_sectors = MIN(cur_nr_sectors,

                QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);

        }

        ret = qcow2_get_cluster_offset(bs, sector_num << 9,

            &cur_nr_sectors, &cluster_offset);

        if (ret < 0) {

            goto fail;

        }

        index_in_cluster = sector_num & (s->cluster_sectors - 1);

        qemu_iovec_reset(&hd_qiov);

        qemu_iovec_copy(&hd_qiov, qiov, bytes_done,

            cur_nr_sectors * 512);

        if (!cluster_offset) {

            if (bs->backing_hd) {

                /* read from the base image */

                n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,

                    sector_num, cur_nr_sectors);

                if (n1 > 0) {

                    BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);

                    qemu_co_mutex_unlock(&s->lock);

                    ret = bdrv_co_readv(bs->backing_hd, sector_num,

                                        n1, &hd_qiov);

                    qemu_co_mutex_lock(&s->lock);

                    if (ret < 0) {

                        goto fail;

                    }

                }

            } else {

                /* Note: in this case, no need to wait */

                qemu_iovec_memset(&hd_qiov, 0, 512 * cur_nr_sectors);

            }

        } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {

            /* add AIO support for compressed blocks ? */

            ret = qcow2_decompress_cluster(bs, cluster_offset);

            if (ret < 0) {

                goto fail;

            }

            qemu_iovec_from_buffer(&hd_qiov,

                s->cluster_cache + index_in_cluster * 512,

                512 * cur_nr_sectors);

        } else {

            if ((cluster_offset & 511) != 0) {

                ret = -EIO;

                goto fail;

            }

            if (s->crypt_method) {

                /*

                 * For encrypted images, read everything into a temporary

                 * contiguous buffer on which the AES functions can work.

                 */

                if (!cluster_data) {

                    cluster_data =

                        g_malloc0(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);

                }

                assert(cur_nr_sectors <=

                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);

                qemu_iovec_reset(&hd_qiov);

                qemu_iovec_add(&hd_qiov, cluster_data,

                    512 * cur_nr_sectors);

            }

            BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);

            qemu_co_mutex_unlock(&s->lock);

            ret = bdrv_co_readv(bs->file,

                                (cluster_offset >> 9) + index_in_cluster,

                                cur_nr_sectors, &hd_qiov);

            qemu_co_mutex_lock(&s->lock);

            if (ret < 0) {

                goto fail;

            }

            if (s->crypt_method) {

                qcow2_encrypt_sectors(s, sector_num,  cluster_data,

                    cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);

                qemu_iovec_reset(&hd_qiov);

                qemu_iovec_copy(&hd_qiov, qiov, bytes_done,

                    cur_nr_sectors * 512);

                qemu_iovec_from_buffer(&hd_qiov, cluster_data,

                    512 * cur_nr_sectors);

            }

        }

        remaining_sectors -= cur_nr_sectors;

        sector_num += cur_nr_sectors;

        bytes_done += cur_nr_sectors * 512;

    }

    ret = 0;

fail:

    qemu_co_mutex_unlock(&s->lock);

    qemu_iovec_destroy(&hd_qiov);

    return ret;

}


static int read_kuki_chunk(AVFormatContext *s, int64_t size)

{

    AVIOContext *pb = s->pb;

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

    if (size < 0 || size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)

        return -1;

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

        /* The magic cookie format for AAC is an mp4 esds atom.

           The lavc AAC decoder requires the data from the codec specific

           description as extradata input. */

        int strt, skip;

        MOVAtom atom;

        strt = avio_tell(pb);

        ff_mov_read_esds(s, pb, atom);

        skip = size - (avio_tell(pb) - strt);

        if (skip < 0 || !st->codec->extradata ||

            st->codec->codec_id != AV_CODEC_ID_AAC) {

            av_log(s, AV_LOG_ERROR, "invalid AAC magic cookie\n");

            return AVERROR_INVALIDDATA;

        }

        avio_skip(pb, skip);

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

#define ALAC_PREAMBLE 12

#define ALAC_HEADER   36

#define ALAC_NEW_KUKI 24

        uint8_t preamble[12];

        if (size < ALAC_NEW_KUKI) {

            av_log(s, AV_LOG_ERROR, "invalid ALAC magic cookie\n");

            avio_skip(pb, size);

            return AVERROR_INVALIDDATA;

        }

        avio_read(pb, preamble, ALAC_PREAMBLE);

        st->codec->extradata = av_mallocz(ALAC_HEADER + FF_INPUT_BUFFER_PADDING_SIZE);

        if (!st->codec->extradata)

            return AVERROR(ENOMEM);

        /* For the old style cookie, we skip 12 bytes, then read 36 bytes.

         * The new style cookie only contains the last 24 bytes of what was

         * 36 bytes in the old style cookie, so we fabricate the first 12 bytes

         * in that case to maintain compatibility. */

        if (!memcmp(&preamble[4], "frmaalac", 8)) {

            if (size < ALAC_PREAMBLE + ALAC_HEADER) {

                av_log(s, AV_LOG_ERROR, "invalid ALAC magic cookie\n");

                av_freep(&st->codec->extradata);

                return AVERROR_INVALIDDATA;

            }

            avio_read(pb, st->codec->extradata, ALAC_HEADER);

            avio_skip(pb, size - ALAC_PREAMBLE - ALAC_HEADER);

        } else {

            AV_WB32(st->codec->extradata, 36);

            memcpy(&st->codec->extradata[4], "alac", 4);

            AV_WB32(&st->codec->extradata[8], 0);

            memcpy(&st->codec->extradata[12], preamble, 12);

            avio_read(pb, &st->codec->extradata[24], ALAC_NEW_KUKI - 12);

            avio_skip(pb, size - ALAC_NEW_KUKI);

        }

        st->codec->extradata_size = ALAC_HEADER;

    } else {

        st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);

        if (!st->codec->extradata)

            return AVERROR(ENOMEM);

        avio_read(pb, st->codec->extradata, size);

        st->codec->extradata_size = size;

    }

    return 0;

}


static void *qemu_fopen_rdma(RDMAContext *rdma, const char *mode)

{

    QEMUFileRDMA *r = g_malloc0(sizeof(QEMUFileRDMA));

    if (qemu_file_mode_is_not_valid(mode)) {

        return NULL;

    }

    r->rdma = rdma;

    if (mode[0] == 'w') {

        r->file = qemu_fopen_ops(r, &rdma_write_ops);

    } else {

        r->file = qemu_fopen_ops(r, &rdma_read_ops);

    }

    return r->file;

}


static int decode_codestream(J2kDecoderContext *s)

{

    J2kCodingStyle *codsty = s->codsty;

    J2kQuantStyle  *qntsty = s->qntsty;

    uint8_t *properties = s->properties;

    for (;;){

        int marker, len, ret = 0;

        const uint8_t *oldbuf;

        if (s->buf_end - s->buf < 2){

            av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");

            break;

        }

        marker = bytestream_get_be16(&s->buf);

        if(s->avctx->debug & FF_DEBUG_STARTCODE)

            av_log(s->avctx, AV_LOG_DEBUG, "marker 0x%.4X at pos 0x%tx\n", marker, s->buf - s->buf_start - 4);

        oldbuf = s->buf;

        if (marker == J2K_SOD){

            J2kTile *tile = s->tile + s->curtileno;

            if (ret = init_tile(s, s->curtileno))

                return ret;

            if (ret = decode_packets(s, tile))

                return ret;

            continue;

        }

        if (marker == J2K_EOC)

            break;

        if (s->buf_end - s->buf < 2)

            return AVERROR(EINVAL);

        len = bytestream_get_be16(&s->buf);

        switch(marker){

            case J2K_SIZ:

                ret = get_siz(s); break;

            case J2K_COC:

                ret = get_coc(s, codsty, properties); break;

            case J2K_COD:

                ret = get_cod(s, codsty, properties); break;

            case J2K_QCC:

                ret = get_qcc(s, len, qntsty, properties); break;

            case J2K_QCD:

                ret = get_qcd(s, len, qntsty, properties); break;

            case J2K_SOT:

                if (!(ret = get_sot(s))){

                    codsty = s->tile[s->curtileno].codsty;

                    qntsty = s->tile[s->curtileno].qntsty;

                    properties = s->tile[s->curtileno].properties;

                }

                break;

            case J2K_COM:

                // the comment is ignored

                s->buf += len - 2; break;

            default:

                av_log(s->avctx, AV_LOG_ERROR, "unsupported marker 0x%.4X at pos 0x%tx\n", marker, s->buf - s->buf_start - 4);

                s->buf += len - 2; break;

        }

        if (s->buf - oldbuf != len || ret){

            av_log(s->avctx, AV_LOG_ERROR, "error during processing marker segment %.4x\n", marker);

            return ret ? ret : -1;

        }

    }

    return 0;

}


static av_cold int ass_decode_init(AVCodecContext *avctx)

{

    avctx->subtitle_header = av_malloc(avctx->extradata_size);

    if (!avctx->extradata)

        return AVERROR(ENOMEM);

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

    avctx->subtitle_header_size = avctx->extradata_size;

    return 0;

}


int v9fs_device_realize_common(V9fsState *s, Error **errp)

{

    int i, len;

    struct stat stat;

    FsDriverEntry *fse;

    V9fsPath path;

    int rc = 1;

    /* initialize pdu allocator */

    QLIST_INIT(&s->free_list);

    QLIST_INIT(&s->active_list);

    for (i = 0; i < (MAX_REQ - 1); i++) {

        QLIST_INSERT_HEAD(&s->free_list, &s->pdus[i], next);

        s->pdus[i].s = s;

        s->pdus[i].idx = i;

    }

    v9fs_path_init(&path);

    fse = get_fsdev_fsentry(s->fsconf.fsdev_id);

    if (!fse) {

        /* We don't have a fsdev identified by fsdev_id */

        error_setg(errp, "9pfs device couldn't find fsdev with the "

                   "id = %s",

                   s->fsconf.fsdev_id ? s->fsconf.fsdev_id : "NULL");

        goto out;

    }

    if (!s->fsconf.tag) {

        /* we haven't specified a mount_tag */

        error_setg(errp, "fsdev with id %s needs mount_tag arguments",

                   s->fsconf.fsdev_id);

        goto out;

    }

    s->ctx.export_flags = fse->export_flags;

    s->ctx.fs_root = g_strdup(fse->path);

    s->ctx.exops.get_st_gen = NULL;

    len = strlen(s->fsconf.tag);

    if (len > MAX_TAG_LEN - 1) {

        error_setg(errp, "mount tag '%s' (%d bytes) is longer than "

                   "maximum (%d bytes)", s->fsconf.tag, len, MAX_TAG_LEN - 1);

        goto out;

    }

    s->tag = g_strdup(s->fsconf.tag);

    s->ctx.uid = -1;

    s->ops = fse->ops;

    s->fid_list = NULL;

    qemu_co_rwlock_init(&s->rename_lock);

    if (s->ops->init(&s->ctx) < 0) {

        error_setg(errp, "9pfs Failed to initialize fs-driver with id:%s"

                   " and export path:%s", s->fsconf.fsdev_id, s->ctx.fs_root);

        goto out;

    }

    /*

     * Check details of export path, We need to use fs driver

     * call back to do that. Since we are in the init path, we don't

     * use co-routines here.

     */

    if (s->ops->name_to_path(&s->ctx, NULL, "/", &path) < 0) {

        error_setg(errp,

                   "error in converting name to path %s", strerror(errno));

        goto out;

    }

    if (s->ops->lstat(&s->ctx, &path, &stat)) {

        error_setg(errp, "share path %s does not exist", fse->path);

        goto out;

    } else if (!S_ISDIR(stat.st_mode)) {

        error_setg(errp, "share path %s is not a directory", fse->path);

        goto out;

    }

    v9fs_path_free(&path);

    rc = 0;

out:

    if (rc) {

        if (s->ops->cleanup && s->ctx.private) {

            s->ops->cleanup(&s->ctx);

        }

        g_free(s->tag);

        g_free(s->ctx.fs_root);

        v9fs_path_free(&path);

    }

    return rc;

}


static int wsd_read_header(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    AVStream *st;

    int version;

    uint32_t text_offset, data_offset, channel_assign;

    char playback_time[AV_TIMECODE_STR_SIZE];

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    avio_skip(pb, 8);

    version = avio_r8(pb);

    av_log(s, AV_LOG_DEBUG, "version: %i.%i\n", version >> 4, version & 0xF);

    avio_skip(pb, 11);

    if (version < 0x10) {

        text_offset = 0x80;

        data_offset = 0x800;

        avio_skip(pb, 8);

    } else {

        text_offset = avio_rb32(pb);

        data_offset = avio_rb32(pb);

    }

    avio_skip(pb, 4);

    av_timecode_make_smpte_tc_string(playback_time, avio_rb32(pb), 0);

    av_dict_set(&s->metadata, "playback_time", playback_time, 0);

    st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;

    st->codecpar->codec_id    = s->iformat->raw_codec_id;

    st->codecpar->sample_rate = avio_rb32(pb) / 8;

    avio_skip(pb, 4);

    st->codecpar->channels    = avio_r8(pb) & 0xF;

    st->codecpar->bit_rate    = st->codecpar->channels * st->codecpar->sample_rate * 8LL;

    if (!st->codecpar->channels)

        return AVERROR_INVALIDDATA;

    avio_skip(pb, 3);

    channel_assign         = avio_rb32(pb);

    if (!(channel_assign & 1)) {

        int i;

        for (i = 1; i < 32; i++)

            if (channel_assign & (1 << i))

                st->codecpar->channel_layout |= wsd_to_av_channel_layoyt(s, i);

    }

    avio_skip(pb, 16);

    if (avio_rb32(pb))

       avpriv_request_sample(s, "emphasis");

    if (avio_seek(pb, text_offset, SEEK_SET) >= 0) {

        get_metadata(s, "title",       128);

        get_metadata(s, "composer",    128);

        get_metadata(s, "song_writer", 128);

        get_metadata(s, "artist",      128);

        get_metadata(s, "album",       128);

        get_metadata(s, "genre",        32);

        get_metadata(s, "date",         32);

        get_metadata(s, "location",     32);

        get_metadata(s, "comment",     512);

        get_metadata(s, "user",        512);

    }

    return avio_seek(pb, data_offset, SEEK_SET);

}


x11grab_read_header(AVFormatContext *s1)

{

    struct x11grab *x11grab = s1->priv_data;

    Display *dpy;

    AVStream *st = NULL;

    enum AVPixelFormat input_pixfmt;

    XImage *image;

    int x_off = 0;

    int y_off = 0;

    int screen;

    int use_shm;

    char *dpyname, *offset;

    int ret = 0;

    Colormap color_map;

    XColor color[256];

    int i;

    dpyname = av_strdup(s1->filename);

    if (!dpyname)

        goto out;

    offset = strchr(dpyname, '+');

    if (offset) {

        sscanf(offset, "%d,%d", &x_off, &y_off);

        if (strstr(offset, "nomouse")) {

            av_log(s1, AV_LOG_WARNING,

                   "'nomouse' specification in argument is deprecated: "

                   "use 'draw_mouse' option with value 0 instead\n");

            x11grab->draw_mouse = 0;

        }

        *offset= 0;

    }

    av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",

           s1->filename, dpyname, x_off, y_off, x11grab->width, x11grab->height);

    dpy = XOpenDisplay(dpyname);

    av_freep(&dpyname);

    if(!dpy) {

        av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");

        ret = AVERROR(EIO);

        goto out;

    }

    st = avformat_new_stream(s1, NULL);

    if (!st) {

        ret = AVERROR(ENOMEM);

        goto out;

    }

    avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */

    screen = DefaultScreen(dpy);

    if (x11grab->follow_mouse) {

        int screen_w, screen_h;

        Window w;

        screen_w = DisplayWidth(dpy, screen);

        screen_h = DisplayHeight(dpy, screen);

        XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off, &ret, &ret, &ret);

        x_off -= x11grab->width / 2;

        y_off -= x11grab->height / 2;

        x_off = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width);

        y_off = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height);

        av_log(s1, AV_LOG_INFO, "followmouse is enabled, resetting grabbing region to x: %d y: %d\n", x_off, y_off);

    }

    use_shm = XShmQueryExtension(dpy);

    av_log(s1, AV_LOG_INFO, "shared memory extension%s found\n", use_shm ? "" : " not");

    if(use_shm) {

        int scr = XDefaultScreen(dpy);

        image = XShmCreateImage(dpy,

                                DefaultVisual(dpy, scr),

                                DefaultDepth(dpy, scr),

                                ZPixmap,

                                NULL,

                                &x11grab->shminfo,

                                x11grab->width, x11grab->height);

        x11grab->shminfo.shmid = shmget(IPC_PRIVATE,

                                        image->bytes_per_line * image->height,

                                        IPC_CREAT|0777);

        if (x11grab->shminfo.shmid == -1) {

            av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");

            ret = AVERROR(ENOMEM);

            goto out;

        }

        x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);

        x11grab->shminfo.readOnly = False;

        if (!XShmAttach(dpy, &x11grab->shminfo)) {

            av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");

            /* needs some better error subroutine :) */

            ret = AVERROR(EIO);

            goto out;

        }

    } else {

        image = XGetImage(dpy, RootWindow(dpy, screen),

                          x_off,y_off,

                          x11grab->width, x11grab->height,

                          AllPlanes, ZPixmap);

    }

    switch (image->bits_per_pixel) {

    case 8:

        av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");

        input_pixfmt = AV_PIX_FMT_PAL8;

        color_map = DefaultColormap(dpy, screen);

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

            color[i].pixel = i;

        XQueryColors(dpy, color_map, color, 256);

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

            x11grab->palette[i] = (color[i].red   & 0xFF00) << 8 |

                                  (color[i].green & 0xFF00)      |

                                  (color[i].blue  & 0xFF00) >> 8;

        x11grab->palette_changed = 1;

        break;

    case 16:

        if (       image->red_mask   == 0xf800 &&

                   image->green_mask == 0x07e0 &&

                   image->blue_mask  == 0x001f ) {

            av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");

            input_pixfmt = AV_PIX_FMT_RGB565;

        } else if (image->red_mask   == 0x7c00 &&

                   image->green_mask == 0x03e0 &&

                   image->blue_mask  == 0x001f ) {

            av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");

            input_pixfmt = AV_PIX_FMT_RGB555;

        } else {

            av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);

            av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask);

            ret = AVERROR_PATCHWELCOME;

            goto out;

        }

        break;

    case 24:

        if (        image->red_mask   == 0xff0000 &&

                    image->green_mask == 0x00ff00 &&

                    image->blue_mask  == 0x0000ff ) {

            input_pixfmt = AV_PIX_FMT_BGR24;

        } else if ( image->red_mask   == 0x0000ff &&

                    image->green_mask == 0x00ff00 &&

                    image->blue_mask  == 0xff0000 ) {

            input_pixfmt = AV_PIX_FMT_RGB24;

        } else {

            av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);

            av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask);

            ret = AVERROR_PATCHWELCOME;

            goto out;

        }

        break;

    case 32:

        input_pixfmt = AV_PIX_FMT_0RGB32;

        break;

    default:

        av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);

        ret = AVERROR_PATCHWELCOME;

        goto out;

    }

    x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;

    x11grab->dpy = dpy;

    x11grab->time_base  = av_inv_q(x11grab->framerate);

    x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);

    x11grab->x_off = x_off;

    x11grab->y_off = y_off;

    x11grab->image = image;

    x11grab->use_shm = use_shm;

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;

    st->codec->width  = x11grab->width;

    st->codec->height = x11grab->height;

    st->codec->pix_fmt = input_pixfmt;

    st->codec->time_base = x11grab->time_base;

    st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8;

out:

    av_free(dpyname);

    return ret;

}


static void vp8_h_loop_filter_simple_c(uint8_t *dst, ptrdiff_t stride, int flim)

{

    int i;

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

        if (simple_limit(dst+i*stride, 1, flim))

            filter_common(dst+i*stride, 1, 1);

}


void bdrv_drain(BlockDriverState *bs)

{

    bool busy = true;

    bdrv_drain_recurse(bs);

    while (busy) {

        /* Keep iterating */

         bdrv_flush_io_queue(bs);

         busy = bdrv_requests_pending(bs);

         busy |= aio_poll(bdrv_get_aio_context(bs), busy);


static void main_loop(void)

{

    bool nonblocking;

    int last_io __attribute__ ((unused)) = 0;

#ifdef CONFIG_PROFILER

    int64_t ti;

#endif

    int r;

    qemu_main_loop_start();

    for (;;) {

#ifdef CONFIG_IOTHREAD

        nonblocking = !kvm_enabled() && last_io > 0;

#else

        nonblocking = cpu_exec_all();

        if (vm_request_pending()) {

            nonblocking = true;

        }

#endif

#ifdef CONFIG_PROFILER

        ti = profile_getclock();

#endif

        last_io = main_loop_wait(nonblocking);

#ifdef CONFIG_PROFILER

        dev_time += profile_getclock() - ti;

#endif

        if (qemu_debug_requested()) {

            vm_stop(VMSTOP_DEBUG);

        }

        if (qemu_shutdown_requested()) {

            qemu_kill_report();

            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);

            if (no_shutdown) {

                vm_stop(VMSTOP_SHUTDOWN);

            } else

                break;

        }

        if (qemu_reset_requested()) {

            pause_all_vcpus();

            cpu_synchronize_all_states();

            qemu_system_reset(VMRESET_REPORT);

            resume_all_vcpus();

        }

        if (qemu_powerdown_requested()) {

            monitor_protocol_event(QEVENT_POWERDOWN, NULL);

            qemu_irq_raise(qemu_system_powerdown);

        }

        if ((r = qemu_vmstop_requested())) {

            vm_stop(r);

        }

    }

    bdrv_close_all();

    pause_all_vcpus();

}


static void bootp_reply(const struct bootp_t *bp)

{

    BOOTPClient *bc = NULL;

    struct mbuf *m;

    struct bootp_t *rbp;

    struct sockaddr_in saddr, daddr;

    struct in_addr dns_addr;

    const struct in_addr *preq_addr;

    int dhcp_msg_type, val;

    uint8_t *q;

    /* extract exact DHCP msg type */

    dhcp_decode(bp, &dhcp_msg_type, &preq_addr);

    dprintf("bootp packet op=%d msgtype=%d", bp->bp_op, dhcp_msg_type);

    if (preq_addr)

        dprintf(" req_addr=%08x\n", ntohl(preq_addr->s_addr));

    else

        dprintf("\n");

    if (dhcp_msg_type == 0)

        dhcp_msg_type = DHCPREQUEST; /* Force reply for old BOOTP clients */

    if (dhcp_msg_type != DHCPDISCOVER &&

        dhcp_msg_type != DHCPREQUEST)

        return;

    /* XXX: this is a hack to get the client mac address */

    memcpy(client_ethaddr, bp->bp_hwaddr, 6);

    if ((m = m_get()) == NULL)

        return;

    m->m_data += IF_MAXLINKHDR;

    rbp = (struct bootp_t *)m->m_data;

    m->m_data += sizeof(struct udpiphdr);

    memset(rbp, 0, sizeof(struct bootp_t));

    if (dhcp_msg_type == DHCPDISCOVER) {

        if (preq_addr) {

            bc = request_addr(preq_addr, client_ethaddr);

            if (bc) {

                daddr.sin_addr = *preq_addr;

            }

        }

        if (!bc) {

         new_addr:

            bc = get_new_addr(&daddr.sin_addr);

            if (!bc) {

                dprintf("no address left\n");

                return;

            }

        }

        memcpy(bc->macaddr, client_ethaddr, 6);

    } else if (preq_addr) {

        bc = request_addr(preq_addr, client_ethaddr);

        if (bc) {

            daddr.sin_addr = *preq_addr;

            memcpy(bc->macaddr, client_ethaddr, 6);

        } else {

            daddr.sin_addr.s_addr = 0;

        }

    } else {

        bc = find_addr(&daddr.sin_addr, bp->bp_hwaddr);

        if (!bc) {

            /* if never assigned, behaves as if it was already

               assigned (windows fix because it remembers its address) */

            goto new_addr;

        }

    }

    saddr.sin_addr.s_addr = htonl(ntohl(special_addr.s_addr) | CTL_ALIAS);

    saddr.sin_port = htons(BOOTP_SERVER);

    daddr.sin_port = htons(BOOTP_CLIENT);

    rbp->bp_op = BOOTP_REPLY;

    rbp->bp_xid = bp->bp_xid;

    rbp->bp_htype = 1;

    rbp->bp_hlen = 6;

    memcpy(rbp->bp_hwaddr, bp->bp_hwaddr, 6);

    rbp->bp_yiaddr = daddr.sin_addr; /* Client IP address */

    rbp->bp_siaddr = saddr.sin_addr; /* Server IP address */

    q = rbp->bp_vend;

    memcpy(q, rfc1533_cookie, 4);

    q += 4;

    if (bc) {

        dprintf("%s addr=%08x\n",

                (dhcp_msg_type == DHCPDISCOVER) ? "offered" : "ack'ed",

                ntohl(daddr.sin_addr.s_addr));

        if (dhcp_msg_type == DHCPDISCOVER) {

            *q++ = RFC2132_MSG_TYPE;

            *q++ = 1;

            *q++ = DHCPOFFER;

        } else /* DHCPREQUEST */ {

            *q++ = RFC2132_MSG_TYPE;

            *q++ = 1;

            *q++ = DHCPACK;

        }

        if (bootp_filename)

            snprintf((char *)rbp->bp_file, sizeof(rbp->bp_file), "%s",

                     bootp_filename);

        *q++ = RFC2132_SRV_ID;

        *q++ = 4;

        memcpy(q, &saddr.sin_addr, 4);

        q += 4;

        *q++ = RFC1533_NETMASK;

        *q++ = 4;

        *q++ = 0xff;

        *q++ = 0xff;

        *q++ = 0xff;

        *q++ = 0x00;

        if (!slirp_restrict) {

            *q++ = RFC1533_GATEWAY;

            *q++ = 4;

            memcpy(q, &saddr.sin_addr, 4);

            q += 4;

            *q++ = RFC1533_DNS;

            *q++ = 4;

            dns_addr.s_addr = htonl(ntohl(special_addr.s_addr) | CTL_DNS);

            memcpy(q, &dns_addr, 4);

            q += 4;

        }

        *q++ = RFC2132_LEASE_TIME;

        *q++ = 4;

        val = htonl(LEASE_TIME);

        memcpy(q, &val, 4);

        q += 4;

        if (*slirp_hostname) {

            val = strlen(slirp_hostname);

            *q++ = RFC1533_HOSTNAME;

            *q++ = val;

            memcpy(q, slirp_hostname, val);

            q += val;

        }

    } else {

        static const char nak_msg[] = "requested address not available";

        dprintf("nak'ed addr=%08x\n", ntohl(preq_addr->s_addr));

        *q++ = RFC2132_MSG_TYPE;

        *q++ = 1;

        *q++ = DHCPNAK;

        *q++ = RFC2132_MESSAGE;

        *q++ = sizeof(nak_msg) - 1;

        memcpy(q, nak_msg, sizeof(nak_msg) - 1);

        q += sizeof(nak_msg) - 1;

    }

    *q++ = RFC1533_END;

    daddr.sin_addr.s_addr = 0xffffffffu;

    m->m_len = sizeof(struct bootp_t) -

        sizeof(struct ip) - sizeof(struct udphdr);

    udp_output2(NULL, m, &saddr, &daddr, IPTOS_LOWDELAY);

}


static void print_features(FILE *f,

                           int (*cpu_fprintf)(FILE *f, const char *fmt, ...),

                           uint32_t features, const char *prefix)

{

    unsigned int i;

    for (i = 0; i < ARRAY_SIZE(feature_name); i++)

        if (feature_name[i] && (features & (1 << i))) {

            if (prefix)

                (*cpu_fprintf)(f, "%s", prefix);

            (*cpu_fprintf)(f, "%s ", feature_name[i]);

        }

}


int cpu_x86_gen_code(uint8_t *gen_code_buf, int max_code_size,

                     int *gen_code_size_ptr, uint8_t *pc_start,

                     int flags)

{

    DisasContext dc1, *dc = &dc1;

    uint8_t *gen_code_end, *pc_ptr;

    long ret;

#ifdef DEBUG_DISAS

    struct disassemble_info disasm_info;

#endif

    dc->code32 = (flags >> GEN_FLAG_CODE32_SHIFT) & 1;

    dc->addseg = (flags >> GEN_FLAG_ADDSEG_SHIFT) & 1;

    dc->f_st = (flags >> GEN_FLAG_ST_SHIFT) & 7;

    dc->cc_op = CC_OP_DYNAMIC;

    gen_code_ptr = gen_code_buf;

    gen_code_end = gen_code_buf + max_code_size - 4096;

    gen_start();

    dc->is_jmp = 0;

    pc_ptr = pc_start;

    do {

        ret = disas_insn(dc, pc_ptr);

        if (ret == -1)

            error("unknown instruction at PC=0x%x B=%02x %02x",

                  pc_ptr, pc_ptr[0], pc_ptr[1]);

        pc_ptr = (void *)ret;

    } while (!dc->is_jmp && gen_code_ptr < gen_code_end);

    /* we must store the eflags state if it is not already done */

    if (dc->cc_op != CC_OP_DYNAMIC)

        gen_op_set_cc_op(dc->cc_op);

    if (dc->is_jmp != 1) {

        /* we add an additionnal jmp to update the simulated PC */

        gen_op_jmp_im(ret);

    }

    gen_end();

    *gen_code_size_ptr = gen_code_ptr - gen_code_buf;

#ifdef DEBUG_DISAS

    if (loglevel) {

        uint8_t *pc;

        int count;

        INIT_DISASSEMBLE_INFO(disasm_info, logfile, fprintf);

#if 0

        disasm_info.flavour = bfd_get_flavour (abfd);

        disasm_info.arch = bfd_get_arch (abfd);

        disasm_info.mach = bfd_get_mach (abfd);

#endif

#ifdef WORDS_BIGENDIAN

        disasm_info.endian = BFD_ENDIAN_BIG;

#else

        disasm_info.endian = BFD_ENDIAN_LITTLE;

#endif

        fprintf(logfile, "IN:\n");

        disasm_info.buffer = pc_start;

        disasm_info.buffer_vma = (unsigned long)pc_start;

        disasm_info.buffer_length = pc_ptr - pc_start;

        pc = pc_start;

        while (pc < pc_ptr) {

            fprintf(logfile, "0x%08lx:  ", (long)pc);

            count = print_insn_i386((unsigned long)pc, &disasm_info);

            fprintf(logfile, "\n");

            pc += count;

        }

        fprintf(logfile, "\n");

        pc = gen_code_buf;

        disasm_info.buffer = pc;

        disasm_info.buffer_vma = (unsigned long)pc;

        disasm_info.buffer_length = *gen_code_size_ptr;

        fprintf(logfile, "OUT: [size=%d]\n", *gen_code_size_ptr);

        while (pc < gen_code_ptr) {

            fprintf(logfile, "0x%08lx:  ", (long)pc);

            count = print_insn_i386((unsigned long)pc, &disasm_info);

            fprintf(logfile, "\n");

            pc += count;

        }

        fprintf(logfile, "\n");

    }

#endif

    return 0;

}


static const char *qobject_input_get_keyval(QObjectInputVisitor *qiv,

                                            const char *name,

                                            Error **errp)

{

    QObject *qobj;

    QString *qstr;

    qobj = qobject_input_get_object(qiv, name, true, errp);

    if (!qobj) {

        return NULL;

    }

    qstr = qobject_to_qstring(qobj);

    if (!qstr) {

        error_setg(errp, QERR_INVALID_PARAMETER_TYPE,

                   full_name(qiv, name), "string");

        return NULL;

    }

    return qstring_get_str(qstr);

}


static void qio_channel_socket_finalize(Object *obj)
{
    QIOChannelSocket *ioc = QIO_CHANNEL_SOCKET(obj);
    if (ioc->fd != -1) {
#ifdef WIN32
        WSAEventSelect(ioc->fd, NULL, 0);
#endif
        closesocket(ioc->fd);
        ioc->fd = -1;


bool ftrace_init(void)

{

    char mount_point[PATH_MAX];

    char path[PATH_MAX];

    int debugfs_found;

    int trace_fd = -1;

    debugfs_found = find_mount(mount_point, "debugfs");

    if (debugfs_found) {

        snprintf(path, PATH_MAX, "%s/tracing/tracing_on", mount_point);

        trace_fd = open(path, O_WRONLY);

        if (trace_fd < 0) {

            if (errno == EACCES) {

                trace_marker_fd = open("/dev/null", O_WRONLY);

                if (trace_marker_fd != -1) {

                    return true;

                }

            }

            perror("Could not open ftrace 'tracing_on' file");

            return false;

        } else {

            if (write(trace_fd, "1", 1) < 0) {

                perror("Could not write to 'tracing_on' file");

                close(trace_fd);

                return false;

            }

            close(trace_fd);

        }

        snprintf(path, PATH_MAX, "%s/tracing/trace_marker", mount_point);

        trace_marker_fd = open(path, O_WRONLY);

        if (trace_marker_fd < 0) {

            perror("Could not open ftrace 'trace_marker' file");

            return false;

        }

    } else {

        fprintf(stderr, "debugfs is not mounted\n");

        return false;

    }

    return true;

}


yuv2rgba64_1_c_template(SwsContext *c, const int32_t *buf0,

                       const int32_t *ubuf[2], const int32_t *vbuf[2],

                       const int32_t *abuf0, uint16_t *dest, int dstW,

                       int uvalpha, int y, enum AVPixelFormat target, int hasAlpha, int eightbytes)

{

    const int32_t *ubuf0 = ubuf[0], *vbuf0 = vbuf[0];

    int i;

    int A1 = 0xffff<<14, A2= 0xffff<<14;

    if (uvalpha < 2048) {

        for (i = 0; i < ((dstW + 1) >> 1); i++) {

            int Y1 = (buf0[i * 2]    ) >> 2;

            int Y2 = (buf0[i * 2 + 1]) >> 2;

            int U  = (ubuf0[i] + (-128 << 11)) >> 2;

            int V  = (vbuf0[i] + (-128 << 11)) >> 2;

            int R, G, B;

            Y1 -= c->yuv2rgb_y_offset;

            Y2 -= c->yuv2rgb_y_offset;

            Y1 *= c->yuv2rgb_y_coeff;

            Y2 *= c->yuv2rgb_y_coeff;

            Y1 += 1 << 13;

            Y2 += 1 << 13;

            if (hasAlpha) {

                A1 = abuf0[i * 2    ] << 11;

                A2 = abuf0[i * 2 + 1] << 11;

                A1 += 1 << 13;

                A2 += 1 << 13;

            }

            R = V * c->yuv2rgb_v2r_coeff;

            G = V * c->yuv2rgb_v2g_coeff + U * c->yuv2rgb_u2g_coeff;

            B =                            U * c->yuv2rgb_u2b_coeff;

            output_pixel(&dest[0], av_clip_uintp2(R_B + Y1, 30) >> 14);

            output_pixel(&dest[1], av_clip_uintp2(  G + Y1, 30) >> 14);

            output_pixel(&dest[2], av_clip_uintp2(B_R + Y1, 30) >> 14);

            if (eightbytes) {

                output_pixel(&dest[3], av_clip_uintp2(A1      , 30) >> 14);

                output_pixel(&dest[4], av_clip_uintp2(R_B + Y2, 30) >> 14);

                output_pixel(&dest[5], av_clip_uintp2(  G + Y2, 30) >> 14);

                output_pixel(&dest[6], av_clip_uintp2(B_R + Y2, 30) >> 14);

                output_pixel(&dest[7], av_clip_uintp2(A2      , 30) >> 14);

                dest += 8;

            } else {

                output_pixel(&dest[3], av_clip_uintp2(R_B + Y2, 30) >> 14);

                output_pixel(&dest[4], av_clip_uintp2(  G + Y2, 30) >> 14);

                output_pixel(&dest[5], av_clip_uintp2(B_R + Y2, 30) >> 14);

                dest += 6;

            }

        }

    } else {

        const int32_t *ubuf1 = ubuf[1], *vbuf1 = vbuf[1];

        int A1 = 0xffff<<14, A2 = 0xffff<<14;

        for (i = 0; i < ((dstW + 1) >> 1); i++) {

            int Y1 = (buf0[i * 2]    ) >> 2;

            int Y2 = (buf0[i * 2 + 1]) >> 2;

            int U  = (ubuf0[i] + ubuf1[i] + (-128 << 12)) >> 3;

            int V  = (vbuf0[i] + vbuf1[i] + (-128 << 12)) >> 3;

            int R, G, B;

            Y1 -= c->yuv2rgb_y_offset;

            Y2 -= c->yuv2rgb_y_offset;

            Y1 *= c->yuv2rgb_y_coeff;

            Y2 *= c->yuv2rgb_y_coeff;

            Y1 += 1 << 13;

            Y2 += 1 << 13;

            if (hasAlpha) {

                A1 = abuf0[i * 2    ] << 11;

                A2 = abuf0[i * 2 + 1] << 11;

                A1 += 1 << 13;

                A2 += 1 << 13;

            }

            R = V * c->yuv2rgb_v2r_coeff;

            G = V * c->yuv2rgb_v2g_coeff + U * c->yuv2rgb_u2g_coeff;

            B =                            U * c->yuv2rgb_u2b_coeff;

            output_pixel(&dest[0], av_clip_uintp2(R_B + Y1, 30) >> 14);

            output_pixel(&dest[1], av_clip_uintp2(  G + Y1, 30) >> 14);

            output_pixel(&dest[2], av_clip_uintp2(B_R + Y1, 30) >> 14);

            if (eightbytes) {

                output_pixel(&dest[3], av_clip_uintp2(A1      , 30) >> 14);

                output_pixel(&dest[4], av_clip_uintp2(R_B + Y2, 30) >> 14);

                output_pixel(&dest[5], av_clip_uintp2(  G + Y2, 30) >> 14);

                output_pixel(&dest[6], av_clip_uintp2(B_R + Y2, 30) >> 14);

                output_pixel(&dest[7], av_clip_uintp2(A2      , 30) >> 14);

                dest += 8;

            } else {

                output_pixel(&dest[3], av_clip_uintp2(R_B + Y2, 30) >> 14);

                output_pixel(&dest[4], av_clip_uintp2(  G + Y2, 30) >> 14);

                output_pixel(&dest[5], av_clip_uintp2(B_R + Y2, 30) >> 14);

                dest += 6;

            }

        }

    }

}


void visit_type_int(Visitor *v, int64_t *obj, const char *name, Error **errp)

{

    if (!error_is_set(errp)) {

        v->type_int(v, obj, name, errp);

    }

}


static void avc_luma_mid_8w_msa(const uint8_t *src, int32_t src_stride,

                                uint8_t *dst, int32_t dst_stride,

                                int32_t height)

{

    uint32_t loop_cnt;

    v16i8 src0, src1, src2, src3, src4;

    v16i8 mask0, mask1, mask2;

    v8i16 hz_out0, hz_out1, hz_out2, hz_out3;

    v8i16 hz_out4, hz_out5, hz_out6, hz_out7, hz_out8;

    v8i16 dst0, dst1, dst2, dst3;

    v16u8 out0, out1;

    LD_SB3(&luma_mask_arr[0], 16, mask0, mask1, mask2);

    LD_SB5(src, src_stride, src0, src1, src2, src3, src4);

    XORI_B5_128_SB(src0, src1, src2, src3, src4);

    src += (5 * src_stride);

    hz_out0 = AVC_HORZ_FILTER_SH(src0, src0, mask0, mask1, mask2);

    hz_out1 = AVC_HORZ_FILTER_SH(src1, src1, mask0, mask1, mask2);

    hz_out2 = AVC_HORZ_FILTER_SH(src2, src2, mask0, mask1, mask2);

    hz_out3 = AVC_HORZ_FILTER_SH(src3, src3, mask0, mask1, mask2);

    hz_out4 = AVC_HORZ_FILTER_SH(src4, src4, mask0, mask1, mask2);

    for (loop_cnt = (height >> 2); loop_cnt--;) {

        LD_SB4(src, src_stride, src0, src1, src2, src3);

        XORI_B4_128_SB(src0, src1, src2, src3);

        src += (4 * src_stride);

        hz_out5 = AVC_HORZ_FILTER_SH(src0, src0, mask0, mask1, mask2);

        hz_out6 = AVC_HORZ_FILTER_SH(src1, src1, mask0, mask1, mask2);

        hz_out7 = AVC_HORZ_FILTER_SH(src2, src2, mask0, mask1, mask2);

        hz_out8 = AVC_HORZ_FILTER_SH(src3, src3, mask0, mask1, mask2);

        dst0 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out0, hz_out1, hz_out2,

                                               hz_out3, hz_out4, hz_out5);

        dst1 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out1, hz_out2, hz_out3,

                                               hz_out4, hz_out5, hz_out6);

        dst2 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out2, hz_out3, hz_out4,

                                               hz_out5, hz_out6, hz_out7);

        dst3 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out3, hz_out4, hz_out5,

                                               hz_out6, hz_out7, hz_out8);

        out0 = PCKEV_XORI128_UB(dst0, dst1);

        out1 = PCKEV_XORI128_UB(dst2, dst3);

        ST8x4_UB(out0, out1, dst, dst_stride);

        dst += (4 * dst_stride);

        hz_out3 = hz_out7;

        hz_out1 = hz_out5;

        hz_out5 = hz_out4;

        hz_out4 = hz_out8;

        hz_out2 = hz_out6;

        hz_out0 = hz_out5;

    }

}


static av_cold int pam_encode_close(AVCodecContext *avctx)

{

    av_frame_free(&avctx->coded_frame);

    return 0;

}


static av_cold int oggvorbis_init_encoder(vorbis_info *vi, AVCodecContext *avccontext)

{

    OggVorbisContext *context = avccontext->priv_data;

    double cfreq;

    if (avccontext->flags & CODEC_FLAG_QSCALE) {

        /* variable bitrate */

        if (vorbis_encode_setup_vbr(vi, avccontext->channels,

                                    avccontext->sample_rate,

                                    avccontext->global_quality / (float)FF_QP2LAMBDA / 10.0))

            return -1;

    } else {

        int minrate = avccontext->rc_min_rate > 0 ? avccontext->rc_min_rate : -1;

        int maxrate = avccontext->rc_min_rate > 0 ? avccontext->rc_max_rate : -1;

        /* constant bitrate */

        if (vorbis_encode_setup_managed(vi, avccontext->channels,

                                        avccontext->sample_rate, minrate,

                                        avccontext->bit_rate, maxrate))

            return -1;

        /* variable bitrate by estimate, disable slow rate management */

        if (minrate == -1 && maxrate == -1)

            if (vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE2_SET, NULL))

                return -1;

    }

    /* cutoff frequency */

    if (avccontext->cutoff > 0) {

        cfreq = avccontext->cutoff / 1000.0;

        if (vorbis_encode_ctl(vi, OV_ECTL_LOWPASS_SET, &cfreq))

            return -1;

    }

    if (context->iblock) {

        vorbis_encode_ctl(vi, OV_ECTL_IBLOCK_SET, &context->iblock);

    }

    return vorbis_encode_setup_init(vi);

}


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

                        const AVFrame *frame, int *got_packet_ptr)

{

    NellyMoserEncodeContext *s = avctx->priv_data;

    int ret;

    if (s->last_frame)

        return 0;

    memcpy(s->buf, s->buf + NELLY_SAMPLES, NELLY_BUF_LEN * sizeof(*s->buf));

    if (frame) {

        memcpy(s->buf + NELLY_BUF_LEN, frame->data[0],

               frame->nb_samples * sizeof(*s->buf));

        if (frame->nb_samples < NELLY_SAMPLES) {

            memset(s->buf + NELLY_BUF_LEN + avctx->frame_size, 0,

                   (NELLY_SAMPLES - frame->nb_samples) * sizeof(*s->buf));

            if (frame->nb_samples >= NELLY_BUF_LEN)

                s->last_frame = 1;

        }

        if ((ret = ff_af_queue_add(&s->afq, frame) < 0))

            return ret;

    } else {

        memset(s->buf + NELLY_BUF_LEN, 0, NELLY_SAMPLES * sizeof(*s->buf));

        s->last_frame = 1;

    }

    if ((ret = ff_alloc_packet(avpkt, NELLY_BLOCK_LEN))) {

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

        return ret;

    }

    encode_block(s, avpkt->data, avpkt->size);

    /* Get the next frame pts/duration */

    ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,

                       &avpkt->duration);

    *got_packet_ptr = 1;

    return 0;

}


static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce, float bias)

{

    IndividualChannelStream *ics = &sce->ics;

    float *in    = sce->coeffs;

    float *out   = sce->ret;

    float *saved = sce->saved;

    const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;

    const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;

    const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;

    float *buf  = ac->buf_mdct;

    float *temp = ac->temp;

    int i;

    // imdct

    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {

        if (ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE)

            av_log(ac->avctx, AV_LOG_WARNING,

                   "Transition from an ONLY_LONG or LONG_STOP to an EIGHT_SHORT sequence detected. "

                   "If you heard an audible artifact, please submit the sample to the FFmpeg developers.\n");

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

            ff_imdct_half(&ac->mdct_small, buf + i, in + i);

    } else

        ff_imdct_half(&ac->mdct, buf, in);

    /* window overlapping

     * NOTE: To simplify the overlapping code, all 'meaningless' short to long

     * and long to short transitions are considered to be short to short

     * transitions. This leaves just two cases (long to long and short to short)

     * with a little special sauce for EIGHT_SHORT_SEQUENCE.

     */

    if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&

            (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {

        ac->dsp.vector_fmul_window(    out,               saved,            buf,         lwindow_prev, bias, 512);

    } else {

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

            out[i] = saved[i] + bias;

        if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {

            ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, bias, 64);

            ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      bias, 64);

            ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      bias, 64);

            ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      bias, 64);

            ac->dsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      bias, 64);

            memcpy(                    out + 448 + 4*128, temp, 64 * sizeof(float));

        } else {

            ac->dsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, bias, 64);

            for (i = 576; i < 1024; i++)

                out[i] = buf[i-512] + bias;

        }

    }

    // buffer update

    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {

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

            saved[i] = temp[64 + i] - bias;

        ac->dsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);

        ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);

        ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);

        memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));

    } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {

        memcpy(                    saved,       buf + 512,        448 * sizeof(float));

        memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));

    } else { // LONG_STOP or ONLY_LONG

        memcpy(                    saved,       buf + 512,        512 * sizeof(float));

    }

}


void ff_dsputil_init_alpha(DSPContext* c, AVCodecContext *avctx)

{

    const int high_bit_depth = avctx->bits_per_raw_sample > 8;

    if (!high_bit_depth) {

    c->put_pixels_tab[0][0] = put_pixels16_axp_asm;

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

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

    c->put_pixels_tab[0][3] = put_pixels16_xy2_axp;

    c->put_no_rnd_pixels_tab[0][0] = put_pixels16_axp_asm;

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

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

    c->put_no_rnd_pixels_tab[0][3] = put_no_rnd_pixels16_xy2_axp;

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

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

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

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

    c->avg_no_rnd_pixels_tab[0][0] = avg_no_rnd_pixels16_axp;

    c->avg_no_rnd_pixels_tab[0][1] = avg_no_rnd_pixels16_x2_axp;

    c->avg_no_rnd_pixels_tab[0][2] = avg_no_rnd_pixels16_y2_axp;

    c->avg_no_rnd_pixels_tab[0][3] = avg_no_rnd_pixels16_xy2_axp;

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

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

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

    c->put_pixels_tab[1][3] = put_pixels_xy2_axp;

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

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

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

    c->put_no_rnd_pixels_tab[1][3] = put_no_rnd_pixels_xy2_axp;

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

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

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

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

    c->avg_no_rnd_pixels_tab[1][0] = avg_no_rnd_pixels_axp;

    c->avg_no_rnd_pixels_tab[1][1] = avg_no_rnd_pixels_x2_axp;

    c->avg_no_rnd_pixels_tab[1][2] = avg_no_rnd_pixels_y2_axp;

    c->avg_no_rnd_pixels_tab[1][3] = avg_no_rnd_pixels_xy2_axp;

    c->clear_blocks = clear_blocks_axp;

    }

    /* amask clears all bits that correspond to present features.  */

    if (amask(AMASK_MVI) == 0) {

        c->put_pixels_clamped = put_pixels_clamped_mvi_asm;

        c->add_pixels_clamped = add_pixels_clamped_mvi_asm;

        if (!high_bit_depth)

            c->get_pixels   = get_pixels_mvi;

        c->diff_pixels      = diff_pixels_mvi;

        c->sad[0]           = pix_abs16x16_mvi_asm;

        c->sad[1]           = pix_abs8x8_mvi;

        c->pix_abs[0][0]    = pix_abs16x16_mvi_asm;

        c->pix_abs[1][0]    = pix_abs8x8_mvi;

        c->pix_abs[0][1]    = pix_abs16x16_x2_mvi;

        c->pix_abs[0][2]    = pix_abs16x16_y2_mvi;

        c->pix_abs[0][3]    = pix_abs16x16_xy2_mvi;

    }

    put_pixels_clamped_axp_p = c->put_pixels_clamped;

    add_pixels_clamped_axp_p = c->add_pixels_clamped;

    if (avctx->bits_per_raw_sample <= 8 &&

        (avctx->idct_algo == FF_IDCT_AUTO ||

         avctx->idct_algo == FF_IDCT_SIMPLEALPHA)) {

        c->idct_put = ff_simple_idct_put_axp;

        c->idct_add = ff_simple_idct_add_axp;

        c->idct =     ff_simple_idct_axp;

    }

}


static void diff_bytes_c(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w){

    long i;

#if !HAVE_FAST_UNALIGNED

    if((long)src2 & (sizeof(long)-1)){

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

            dst[i+0] = src1[i+0]-src2[i+0];

            dst[i+1] = src1[i+1]-src2[i+1];

            dst[i+2] = src1[i+2]-src2[i+2];

            dst[i+3] = src1[i+3]-src2[i+3];

            dst[i+4] = src1[i+4]-src2[i+4];

            dst[i+5] = src1[i+5]-src2[i+5];

            dst[i+6] = src1[i+6]-src2[i+6];

            dst[i+7] = src1[i+7]-src2[i+7];

        }

    }else

#endif

    for(i=0; i<=w-sizeof(long); i+=sizeof(long)){

        long a = *(long*)(src1+i);

        long b = *(long*)(src2+i);

        *(long*)(dst+i) = ((a|pb_80) - (b&pb_7f)) ^ ((a^b^pb_80)&pb_80);

    }

    for(; i<w; i++)

        dst[i+0] = src1[i+0]-src2[i+0];

}


static int decode_frame(AVCodecContext *avctx,

                        void *data,

                        int *got_frame,

                        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    DPXContext *const s = avctx->priv_data;

    AVFrame *picture  = data;

    AVFrame *const p = &s->picture;

    uint8_t *ptr[AV_NUM_DATA_POINTERS];

    unsigned int offset;

    int magic_num, endian;

    int x, y, i, ret;

    int w, h, bits_per_color, descriptor, elements, packing, total_size;

    unsigned int rgbBuffer = 0;

    int n_datum = 0;

    if (avpkt->size <= 1634) {

        av_log(avctx, AV_LOG_ERROR, "Packet too small for DPX header\n");

        return AVERROR_INVALIDDATA;

    }

    magic_num = AV_RB32(buf);

    buf += 4;

    /* Check if the files "magic number" is "SDPX" which means it uses

     * big-endian or XPDS which is for little-endian files */

    if (magic_num == AV_RL32("SDPX")) {

        endian = 0;

    } else if (magic_num == AV_RB32("SDPX")) {

        endian = 1;

    } else {

        av_log(avctx, AV_LOG_ERROR, "DPX marker not found\n");

        return AVERROR_INVALIDDATA;

    }

    offset = read32(&buf, endian);

    if (avpkt->size <= offset) {

        av_log(avctx, AV_LOG_ERROR, "Invalid data start offset\n");

        return AVERROR_INVALIDDATA;

    }

    // Need to end in 0x304 offset from start of file

    buf = avpkt->data + 0x304;

    w = read32(&buf, endian);

    h = read32(&buf, endian);

    if ((ret = av_image_check_size(w, h, 0, avctx)) < 0)

        return ret;

    if (w != avctx->width || h != avctx->height)

        avcodec_set_dimensions(avctx, w, h);

    // Need to end in 0x320 to read the descriptor

    buf += 20;

    descriptor = buf[0];

    // Need to end in 0x323 to read the bits per color

    buf += 3;

    avctx->bits_per_raw_sample =

    bits_per_color = buf[0];

    buf++;

    packing = *((uint16_t*)buf);

    buf += 824;

    avctx->sample_aspect_ratio.num = read32(&buf, endian);

    avctx->sample_aspect_ratio.den = read32(&buf, endian);

    if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0)

        av_reduce(&avctx->sample_aspect_ratio.num, &avctx->sample_aspect_ratio.den,

                   avctx->sample_aspect_ratio.num,  avctx->sample_aspect_ratio.den,

                  0x10000);

    else

        avctx->sample_aspect_ratio = (AVRational){ 0, 1 };

    switch (descriptor) {

        case 51: // RGBA

            elements = 4;

            break;

        case 50: // RGB

            elements = 3;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unsupported descriptor %d\n", descriptor);

            return AVERROR_INVALIDDATA;

    }

    switch (bits_per_color) {

        case 8:

            if (elements == 4) {

                avctx->pix_fmt = AV_PIX_FMT_RGBA;

            } else {

                avctx->pix_fmt = AV_PIX_FMT_RGB24;

            }

            total_size = avctx->width * avctx->height * elements;

            break;

        case 10:

            if (!packing) {

                av_log(avctx, AV_LOG_ERROR, "Packing to 32bit required\n");

                return -1;

            }

            avctx->pix_fmt = AV_PIX_FMT_GBRP10;

            total_size = (avctx->width * avctx->height * elements + 2) / 3 * 4;

            break;

        case 12:

            if (!packing) {

                av_log(avctx, AV_LOG_ERROR, "Packing to 16bit required\n");

                return -1;

            }

            if (endian) {

                avctx->pix_fmt = AV_PIX_FMT_GBRP12BE;

            } else {

                avctx->pix_fmt = AV_PIX_FMT_GBRP12LE;

            }

            total_size = 2 * avctx->width * avctx->height * elements;

            break;

        case 16:

            if (endian) {

                avctx->pix_fmt = elements == 4 ? AV_PIX_FMT_RGBA64BE : AV_PIX_FMT_RGB48BE;

            } else {

                avctx->pix_fmt = elements == 4 ? AV_PIX_FMT_RGBA64LE : AV_PIX_FMT_RGB48LE;

            }

            total_size = 2 * avctx->width * avctx->height * elements;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unsupported color depth : %d\n", bits_per_color);

            return AVERROR_INVALIDDATA;

    }

    if (s->picture.data[0])

        avctx->release_buffer(avctx, &s->picture);

    if ((ret = ff_get_buffer(avctx, p)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return ret;

    }

    // Move pointer to offset from start of file

    buf =  avpkt->data + offset;

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

        ptr[i] = p->data[i];

    if (total_size > avpkt->size) {

        av_log(avctx, AV_LOG_ERROR, "Overread buffer. Invalid header?\n");

        return AVERROR_INVALIDDATA;

    }

    switch (bits_per_color) {

    case 10:

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

            uint16_t *dst[3] = {(uint16_t*)ptr[0],

                                (uint16_t*)ptr[1],

                                (uint16_t*)ptr[2]};

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

                *dst[2]++ = read10in32(&buf, &rgbBuffer,

                                       &n_datum, endian);

                *dst[0]++ = read10in32(&buf, &rgbBuffer,

                                       &n_datum, endian);

                *dst[1]++ = read10in32(&buf, &rgbBuffer,

                                       &n_datum, endian);

                // For 10 bit, ignore alpha

                if (elements == 4)

                    read10in32(&buf, &rgbBuffer,

                               &n_datum, endian);

            }

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

                ptr[i] += p->linesize[i];

        }

        break;

    case 12:

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

            uint16_t *dst[3] = {(uint16_t*)ptr[0],

                                (uint16_t*)ptr[1],

                                (uint16_t*)ptr[2]};

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

                *dst[2] = *((uint16_t*)buf);

                *dst[2] = (*dst[2] >> 4) | (*dst[2] << 12);

                dst[2]++;

                buf += 2;

                *dst[0] = *((uint16_t*)buf);

                *dst[0] = (*dst[0] >> 4) | (*dst[0] << 12);

                dst[0]++;

                buf += 2;

                *dst[1] = *((uint16_t*)buf);

                *dst[1] = (*dst[1] >> 4) | (*dst[1] << 12);

                dst[1]++;

                buf += 2;

                // For 12 bit, ignore alpha

                if (elements == 4)

                    buf += 2;

            }

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

                ptr[i] += p->linesize[i];

        }

        break;

    case 16:

        elements *= 2;

    case 8:

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

            memcpy(ptr[0], buf, elements*avctx->width);

            ptr[0] += p->linesize[0];

            buf += elements*avctx->width;

        }

        break;

    }

    *picture   = s->picture;

    *got_frame = 1;

    return buf_size;

}


static void gen_pool16c_insn(DisasContext *ctx, int *is_branch)

{

    int rd = mmreg((ctx->opcode >> 3) & 0x7);

    int rs = mmreg(ctx->opcode & 0x7);

    int opc;

    switch (((ctx->opcode) >> 4) & 0x3f) {

    case NOT16 + 0:

    case NOT16 + 1:

    case NOT16 + 2:

    case NOT16 + 3:

        gen_logic(ctx, OPC_NOR, rd, rs, 0);

        break;

    case XOR16 + 0:

    case XOR16 + 1:

    case XOR16 + 2:

    case XOR16 + 3:

        gen_logic(ctx, OPC_XOR, rd, rd, rs);

        break;

    case AND16 + 0:

    case AND16 + 1:

    case AND16 + 2:

    case AND16 + 3:

        gen_logic(ctx, OPC_AND, rd, rd, rs);

        break;

    case OR16 + 0:

    case OR16 + 1:

    case OR16 + 2:

    case OR16 + 3:

        gen_logic(ctx, OPC_OR, rd, rd, rs);

        break;

    case LWM16 + 0:

    case LWM16 + 1:

    case LWM16 + 2:

    case LWM16 + 3:

        {

            static const int lwm_convert[] = { 0x11, 0x12, 0x13, 0x14 };

            int offset = ZIMM(ctx->opcode, 0, 4);

            gen_ldst_multiple(ctx, LWM32, lwm_convert[(ctx->opcode >> 4) & 0x3],

                              29, offset << 2);

        }

        break;

    case SWM16 + 0:

    case SWM16 + 1:

    case SWM16 + 2:

    case SWM16 + 3:

        {

            static const int swm_convert[] = { 0x11, 0x12, 0x13, 0x14 };

            int offset = ZIMM(ctx->opcode, 0, 4);

            gen_ldst_multiple(ctx, SWM32, swm_convert[(ctx->opcode >> 4) & 0x3],

                              29, offset << 2);

        }

        break;

    case JR16 + 0:

    case JR16 + 1:

        {

            int reg = ctx->opcode & 0x1f;

            gen_compute_branch(ctx, OPC_JR, 2, reg, 0, 0);

        }

        *is_branch = 1;

        break;

    case JRC16 + 0:

    case JRC16 + 1:

        {

            int reg = ctx->opcode & 0x1f;

            gen_compute_branch(ctx, OPC_JR, 2, reg, 0, 0);

            /* Let normal delay slot handling in our caller take us

               to the branch target.  */

        }

        break;

    case JALR16 + 0:

    case JALR16 + 1:

        opc = OPC_JALR;

        goto do_jalr;

    case JALR16S + 0:

    case JALR16S + 1:

        opc = OPC_JALRS;

    do_jalr:

        {

            int reg = ctx->opcode & 0x1f;

            gen_compute_branch(ctx, opc, 2, reg, 31, 0);

        }

        *is_branch = 1;

        break;

    case MFHI16 + 0:

    case MFHI16 + 1:

        gen_HILO(ctx, OPC_MFHI, 0, uMIPS_RS5(ctx->opcode));

        break;

    case MFLO16 + 0:

    case MFLO16 + 1:

        gen_HILO(ctx, OPC_MFLO, 0, uMIPS_RS5(ctx->opcode));

        break;

    case BREAK16:

        generate_exception(ctx, EXCP_BREAK);

        break;

    case SDBBP16:

        /* XXX: not clear which exception should be raised

         *      when in debug mode...

         */

        check_insn(ctx, ISA_MIPS32);

        if (!(ctx->hflags & MIPS_HFLAG_DM)) {

            generate_exception(ctx, EXCP_DBp);

        } else {

            generate_exception(ctx, EXCP_DBp);

        }

        break;

    case JRADDIUSP + 0:

    case JRADDIUSP + 1:

        {

            int imm = ZIMM(ctx->opcode, 0, 5);

            gen_compute_branch(ctx, OPC_JR, 2, 31, 0, 0);

            gen_arith_imm(ctx, OPC_ADDIU, 29, 29, imm << 2);

            /* Let normal delay slot handling in our caller take us

               to the branch target.  */

        }

        break;

    default:

        generate_exception(ctx, EXCP_RI);

        break;

    }

}


int ff_filter_frame(AVFilterLink *link, AVFrame *frame)

{

    int (*filter_frame)(AVFilterLink *, AVFrame *);

    AVFilterPad *dst = link->dstpad;

    AVFrame *out;

    FF_DPRINTF_START(NULL, filter_frame);

    ff_dlog_link(NULL, link, 1);

    if (!(filter_frame = dst->filter_frame))

        filter_frame = default_filter_frame;

    /* copy the frame if needed */

    if (dst->needs_writable && !av_frame_is_writable(frame)) {

        av_log(link->dst, AV_LOG_DEBUG, "Copying data in avfilter.\n");

        switch (link->type) {

        case AVMEDIA_TYPE_VIDEO:

            out = ff_get_video_buffer(link, link->w, link->h);

            break;

        case AVMEDIA_TYPE_AUDIO:

            out = ff_get_audio_buffer(link, frame->nb_samples);

            break;

        default: return AVERROR(EINVAL);

        }

        if (!out) {

            av_frame_free(&frame);

            return AVERROR(ENOMEM);

        }

        av_frame_copy_props(out, frame);

        switch (link->type) {

        case AVMEDIA_TYPE_VIDEO:

            av_image_copy(out->data, out->linesize, frame->data, frame->linesize,

                          frame->format, frame->width, frame->height);

            break;

        case AVMEDIA_TYPE_AUDIO:

            av_samples_copy(out->extended_data, frame->extended_data,

                            0, 0, frame->nb_samples,

                            av_get_channel_layout_nb_channels(frame->channel_layout),

                            frame->format);

            break;

        default: return AVERROR(EINVAL);

        }

        av_frame_free(&frame);

    } else

        out = frame;

    return filter_frame(link, out);

}


static ssize_t vnc_tls_push(gnutls_transport_ptr_t transport,

                            const void *data,

                            size_t len) {

    VncState *vs = (VncState *)transport;

    int ret;

 retry:

    ret = send(vs->csock, data, len, 0);

    if (ret < 0) {

        if (errno == EINTR)

            goto retry;

        return -1;

    }

    return ret;

}


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

                              const char *name, Error **errp)

{

    EnumProperty *prop = opaque;

    int value;

    visit_type_enum(v, &value, prop->strings, NULL, name, errp);

    prop->set(obj, value, errp);

}


void ff_h264_filter_mb_fast(const H264Context *h, H264SliceContext *sl,

                            int mb_x, int mb_y, uint8_t *img_y,

                            uint8_t *img_cb, uint8_t *img_cr,

                            unsigned int linesize, unsigned int uvlinesize)

{

    assert(!FRAME_MBAFF(h));

    if(!h->h264dsp.h264_loop_filter_strength || h->pps.chroma_qp_diff) {

        ff_h264_filter_mb(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize);

        return;

    }

#if CONFIG_SMALL

    h264_filter_mb_fast_internal(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, h->pixel_shift);

#else

    if(h->pixel_shift){

        h264_filter_mb_fast_internal(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, 1);

    }else{

        h264_filter_mb_fast_internal(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, 0);

    }

#endif

}


void qmp_eject(const char *device, bool has_force, bool force, Error **errp)

{

    Error *local_err = NULL;

    int rc;

    if (!has_force) {

        force = false;

    }

    rc = do_open_tray(device, force, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    if (rc == EINPROGRESS) {

        error_setg(errp, "Device '%s' is locked and force was not specified, "

                   "wait for tray to open and try again", device);

        return;

    }

    qmp_x_blockdev_remove_medium(device, errp);

}


int check_prot(int prot, int rw, int access_type)

{

    int ret;

    if (access_type == ACCESS_CODE) {

        if (prot & PAGE_EXEC) {

            ret = 0;

        } else {

            ret = -2;

        }

    } else if (rw) {

        if (prot & PAGE_WRITE) {

            ret = 0;

        } else {

            ret = -2;

        }

    } else {

        if (prot & PAGE_READ) {

            ret = 0;

        } else {

            ret = -2;

        }

    }

    return ret;

}


static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,

                            int64_t offset_in_cluster, QEMUIOVector *qiov,

                            uint64_t qiov_offset, uint64_t n_bytes,

                            uint64_t offset)

{

    int ret;

    VmdkGrainMarker *data = NULL;

    uLongf buf_len;

    QEMUIOVector local_qiov;

    struct iovec iov;

    int64_t write_offset;

    int64_t write_end_sector;

    if (extent->compressed) {

        void *compressed_data;

        if (!extent->has_marker) {

            ret = -EINVAL;

            goto out;

        }

        buf_len = (extent->cluster_sectors << 9) * 2;

        data = g_malloc(buf_len + sizeof(VmdkGrainMarker));

        compressed_data = g_malloc(n_bytes);

        qemu_iovec_to_buf(qiov, qiov_offset, compressed_data, n_bytes);

        ret = compress(data->data, &buf_len, compressed_data, n_bytes);

        g_free(compressed_data);

        if (ret != Z_OK || buf_len == 0) {

            ret = -EINVAL;

            goto out;

        }

        data->lba = offset >> BDRV_SECTOR_BITS;

        data->size = buf_len;

        n_bytes = buf_len + sizeof(VmdkGrainMarker);

        iov = (struct iovec) {

            .iov_base   = data,

            .iov_len    = n_bytes,

        };

        qemu_iovec_init_external(&local_qiov, &iov, 1);

    } else {

        qemu_iovec_init(&local_qiov, qiov->niov);

        qemu_iovec_concat(&local_qiov, qiov, qiov_offset, n_bytes);

    }

    write_offset = cluster_offset + offset_in_cluster,

    ret = bdrv_co_pwritev(extent->file, write_offset, n_bytes,

                          &local_qiov, 0);

    write_end_sector = DIV_ROUND_UP(write_offset + n_bytes, BDRV_SECTOR_SIZE);

    if (extent->compressed) {

        extent->next_cluster_sector = write_end_sector;

    } else {

        extent->next_cluster_sector = MAX(extent->next_cluster_sector,

                                          write_end_sector);

    }

    if (ret < 0) {

        goto out;

    }

    ret = 0;

 out:

    g_free(data);

    if (!extent->compressed) {

        qemu_iovec_destroy(&local_qiov);

    }

    return ret;

}


static int http_server(void)

{

    int server_fd, ret, rtsp_server_fd, delay, delay1;

    struct pollfd poll_table[HTTP_MAX_CONNECTIONS + 2], *poll_entry;

    HTTPContext *c, *c_next;

    server_fd = socket_open_listen(&my_http_addr);

    if (server_fd < 0)

        return -1;

    rtsp_server_fd = socket_open_listen(&my_rtsp_addr);

    if (rtsp_server_fd < 0)

        return -1;

    http_log("ffserver started.\n");

    start_children(first_feed);

    first_http_ctx = NULL;

    nb_connections = 0;

    first_http_ctx = NULL;

    start_multicast();

    for(;;) {

        poll_entry = poll_table;

        poll_entry->fd = server_fd;

        poll_entry->events = POLLIN;

        poll_entry++;

        poll_entry->fd = rtsp_server_fd;

        poll_entry->events = POLLIN;

        poll_entry++;

        /* wait for events on each HTTP handle */

        c = first_http_ctx;

        delay = 1000;

        while (c != NULL) {

            int fd;

            fd = c->fd;

            switch(c->state) {

            case HTTPSTATE_SEND_HEADER:

            case RTSPSTATE_SEND_REPLY:

            case RTSPSTATE_SEND_PACKET:

                c->poll_entry = poll_entry;

                poll_entry->fd = fd;

                poll_entry->events = POLLOUT;

                poll_entry++;

                break;

            case HTTPSTATE_SEND_DATA_HEADER:

            case HTTPSTATE_SEND_DATA:

            case HTTPSTATE_SEND_DATA_TRAILER:

                if (!c->is_packetized) {

                    /* for TCP, we output as much as we can (may need to put a limit) */

                    c->poll_entry = poll_entry;

                    poll_entry->fd = fd;

                    poll_entry->events = POLLOUT;

                    poll_entry++;

                } else {

                    /* not strictly correct, but currently cannot add

                       more than one fd in poll entry */

                    delay = 0;

                }

                break;

            case HTTPSTATE_WAIT_REQUEST:

            case HTTPSTATE_RECEIVE_DATA:

            case HTTPSTATE_WAIT_FEED:

            case RTSPSTATE_WAIT_REQUEST:

                /* need to catch errors */

                c->poll_entry = poll_entry;

                poll_entry->fd = fd;

                poll_entry->events = POLLIN;/* Maybe this will work */

                poll_entry++;

                break;

            case HTTPSTATE_WAIT:

                c->poll_entry = NULL;

                delay1 = compute_send_delay(c);

                if (delay1 < delay)

                    delay = delay1;

                break;

            case HTTPSTATE_WAIT_SHORT:

                c->poll_entry = NULL;

                delay1 = 10; /* one tick wait XXX: 10 ms assumed */

                if (delay1 < delay)

                    delay = delay1;

                break;

            default:

                c->poll_entry = NULL;

                break;

            }

            c = c->next;

        }

        /* wait for an event on one connection. We poll at least every

           second to handle timeouts */

        do {

            ret = poll(poll_table, poll_entry - poll_table, delay);

        } while (ret == -1);

        cur_time = gettime_ms();

        if (need_to_start_children) {

            need_to_start_children = 0;

            start_children(first_feed);

        }

        /* now handle the events */

        for(c = first_http_ctx; c != NULL; c = c_next) {

            c_next = c->next;

            if (handle_connection(c) < 0) {

                /* close and free the connection */

                log_connection(c);

                close_connection(c);

            }

        }

        poll_entry = poll_table;

        /* new HTTP connection request ? */

        if (poll_entry->revents & POLLIN) {

            new_connection(server_fd, 0);

        }

        poll_entry++;

        /* new RTSP connection request ? */

        if (poll_entry->revents & POLLIN) {

            new_connection(rtsp_server_fd, 1);

        }

    }

}


static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,

                               const uint8_t *buf, int buf_size,

                               int first_field)

{

    static const uint8_t header_prefix[]    = { 0x00, 0x00, 0x02, 0x80, 0x01 };

    static const uint8_t header_prefix444[] = { 0x00, 0x00, 0x02, 0x80, 0x02 };

    int i, cid, ret;

    if (buf_size < 0x280)

        return AVERROR_INVALIDDATA;

    if (memcmp(buf, header_prefix, 5) && memcmp(buf, header_prefix444, 5)) {

        av_log(ctx->avctx, AV_LOG_ERROR, "error in header\n");

        return AVERROR_INVALIDDATA;

    }

    if (buf[5] & 2) { /* interlaced */

        ctx->cur_field = buf[5] & 1;

        frame->interlaced_frame = 1;

        frame->top_field_first  = first_field ^ ctx->cur_field;

        av_log(ctx->avctx, AV_LOG_DEBUG,

               "interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field);

    }

    ctx->height = AV_RB16(buf + 0x18);

    ctx->width  = AV_RB16(buf + 0x1a);

    av_dlog(ctx->avctx, "width %d, height %d\n", ctx->width, ctx->height);

    ctx->is_444 = 0;

    if (buf[0x4] == 0x2) {

        ctx->avctx->pix_fmt = AV_PIX_FMT_YUV444P10;

        ctx->avctx->bits_per_raw_sample = 10;

        if (ctx->bit_depth != 10) {

            ff_blockdsp_init(&ctx->bdsp, ctx->avctx);

            ff_idctdsp_init(&ctx->idsp, ctx->avctx);

            ctx->bit_depth = 10;

            ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;

        }

        ctx->is_444 = 1;

    } else if (buf[0x21] & 0x40) {

        ctx->avctx->pix_fmt = AV_PIX_FMT_YUV422P10;

        ctx->avctx->bits_per_raw_sample = 10;

        if (ctx->bit_depth != 10) {

            ff_blockdsp_init(&ctx->bdsp, ctx->avctx);

            ff_idctdsp_init(&ctx->idsp, ctx->avctx);

            ctx->bit_depth = 10;

            ctx->decode_dct_block = dnxhd_decode_dct_block_10;

        }

    } else {

        ctx->avctx->pix_fmt = AV_PIX_FMT_YUV422P;

        ctx->avctx->bits_per_raw_sample = 8;

        if (ctx->bit_depth != 8) {

            ff_blockdsp_init(&ctx->bdsp, ctx->avctx);

            ff_idctdsp_init(&ctx->idsp, ctx->avctx);

            ctx->bit_depth = 8;

            ctx->decode_dct_block = dnxhd_decode_dct_block_8;

        }

    }

    cid = AV_RB32(buf + 0x28);

    av_dlog(ctx->avctx, "compression id %d\n", cid);

    if ((ret = dnxhd_init_vlc(ctx, cid)) < 0)

        return ret;

    if (buf_size < ctx->cid_table->coding_unit_size) {

        av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size\n");

        return AVERROR_INVALIDDATA;

    }

    ctx->mb_width  = ctx->width >> 4;

    ctx->mb_height = buf[0x16d];

    av_dlog(ctx->avctx,

            "mb width %d, mb height %d\n", ctx->mb_width, ctx->mb_height);

    if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame)

        ctx->height <<= 1;

    if (ctx->mb_height > 68 ||

        (ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {

        av_log(ctx->avctx, AV_LOG_ERROR,

               "mb height too big: %d\n", ctx->mb_height);

        return AVERROR_INVALIDDATA;

    }

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

        ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2));

        av_dlog(ctx->avctx, "mb scan index %d\n", ctx->mb_scan_index[i]);

        if (buf_size < ctx->mb_scan_index[i] + 0x280LL) {

            av_log(ctx->avctx, AV_LOG_ERROR, "invalid mb scan index\n");

            return AVERROR_INVALIDDATA;

        }

    }

    return 0;

}


static int get_monitor_def(target_long *pval, const char *name)

{

    const MonitorDef *md;

    void *ptr;

    for(md = monitor_defs; md->name != NULL; md++) {

        if (compare_cmd(name, md->name)) {

            if (md->get_value) {

                *pval = md->get_value(md, md->offset);

            } else {

                CPUState *env = mon_get_cpu();

                if (!env)

                    return -2;

                ptr = (uint8_t *)env + md->offset;

                switch(md->type) {

                case MD_I32:

                    *pval = *(int32_t *)ptr;

                    break;

                case MD_TLONG:

                    *pval = *(target_long *)ptr;

                    break;

                default:

                    *pval = 0;

                    break;

                }

            }

            return 0;

        }

    }

    return -1;

}


static int do_sigframe_return_v2(CPUState *env, target_ulong frame_addr,
                                 struct target_ucontext_v2 *uc)
{
    sigset_t host_set;
    abi_ulong *regspace;
    target_to_host_sigset(&host_set, &uc->tuc_sigmask);
    sigprocmask(SIG_SETMASK, &host_set, NULL);
    if (restore_sigcontext(env, &uc->tuc_mcontext))
    if (do_sigaltstack(frame_addr + offsetof(struct target_ucontext_v2, tuc_stack), 0, get_sp_from_cpustate(env)) == -EFAULT)
#if 0
    /* Send SIGTRAP if we're single-stepping */
    if (ptrace_cancel_bpt(current))
            send_sig(SIGTRAP, current, 1);
#endif
    return 0;


FWCfgState *pc_memory_init(MemoryRegion *system_memory,

                           const char *kernel_filename,

                           const char *kernel_cmdline,

                           const char *initrd_filename,

                           ram_addr_t below_4g_mem_size,

                           ram_addr_t above_4g_mem_size,

                           MemoryRegion *rom_memory,

                           MemoryRegion **ram_memory,

                           PcGuestInfo *guest_info)

{

    int linux_boot, i;

    MemoryRegion *ram, *option_rom_mr;

    MemoryRegion *ram_below_4g, *ram_above_4g;

    FWCfgState *fw_cfg;

    linux_boot = (kernel_filename != NULL);

    /* Allocate RAM.  We allocate it as a single memory region and use

     * aliases to address portions of it, mostly for backwards compatibility

     * with older qemus that used qemu_ram_alloc().

     */

    ram = g_malloc(sizeof(*ram));

    memory_region_init_ram(ram, NULL, "pc.ram",

                           below_4g_mem_size + above_4g_mem_size);

    vmstate_register_ram_global(ram);

    *ram_memory = ram;

    ram_below_4g = g_malloc(sizeof(*ram_below_4g));

    memory_region_init_alias(ram_below_4g, NULL, "ram-below-4g", ram,

                             0, below_4g_mem_size);

    memory_region_add_subregion(system_memory, 0, ram_below_4g);

    e820_add_entry(0, below_4g_mem_size, E820_RAM);

    if (above_4g_mem_size > 0) {

        ram_above_4g = g_malloc(sizeof(*ram_above_4g));

        memory_region_init_alias(ram_above_4g, NULL, "ram-above-4g", ram,

                                 below_4g_mem_size, above_4g_mem_size);

        memory_region_add_subregion(system_memory, 0x100000000ULL,

                                    ram_above_4g);

        e820_add_entry(0x100000000ULL, above_4g_mem_size, E820_RAM);

    }

    /* Initialize PC system firmware */

    pc_system_firmware_init(rom_memory, guest_info->isapc_ram_fw);

    option_rom_mr = g_malloc(sizeof(*option_rom_mr));

    memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE);

    vmstate_register_ram_global(option_rom_mr);

    memory_region_add_subregion_overlap(rom_memory,

                                        PC_ROM_MIN_VGA,

                                        option_rom_mr,

                                        1);

    fw_cfg = bochs_bios_init();

    rom_set_fw(fw_cfg);

    if (linux_boot) {

        load_linux(fw_cfg, kernel_filename, initrd_filename, kernel_cmdline, below_4g_mem_size);

    }

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

        rom_add_option(option_rom[i].name, option_rom[i].bootindex);

    }

    guest_info->fw_cfg = fw_cfg;

    return fw_cfg;

}


static void press_key(VncState *vs, int keysym)

{

    int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;

    qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);

    qemu_input_event_send_key_delay(0);

    qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);

    qemu_input_event_send_key_delay(0);

}


static void s390_virtio_device_sync(VirtIOS390Device *dev)

{

    VirtIOS390Bus *bus = DO_UPCAST(VirtIOS390Bus, bus, dev->qdev.parent_bus);

    ram_addr_t cur_offs;

    uint8_t num_vq;

    int i;

    virtio_reset(dev->vdev);

    /* Sync dev space */

    stb_phys(dev->dev_offs + VIRTIO_DEV_OFFS_TYPE, dev->vdev->device_id);

    stb_phys(dev->dev_offs + VIRTIO_DEV_OFFS_NUM_VQ, s390_virtio_device_num_vq(dev));

    stb_phys(dev->dev_offs + VIRTIO_DEV_OFFS_FEATURE_LEN, dev->feat_len);

    stb_phys(dev->dev_offs + VIRTIO_DEV_OFFS_CONFIG_LEN, dev->vdev->config_len);

    num_vq = s390_virtio_device_num_vq(dev);

    stb_phys(dev->dev_offs + VIRTIO_DEV_OFFS_NUM_VQ, num_vq);

    /* Sync virtqueues */

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

        ram_addr_t vq = (dev->dev_offs + VIRTIO_DEV_OFFS_CONFIG) +

                        (i * VIRTIO_VQCONFIG_LEN);

        ram_addr_t vring;

        vring = s390_virtio_next_ring(bus);

        virtio_queue_set_addr(dev->vdev, i, vring);

        virtio_queue_set_vector(dev->vdev, i, i);

        stq_phys(vq + VIRTIO_VQCONFIG_OFFS_ADDRESS, vring);

        stw_phys(vq + VIRTIO_VQCONFIG_OFFS_NUM, virtio_queue_get_num(dev->vdev, i));

    }

    cur_offs = dev->dev_offs;

    cur_offs += VIRTIO_DEV_OFFS_CONFIG;

    cur_offs += num_vq * VIRTIO_VQCONFIG_LEN;

    /* Sync feature bitmap */

    if (dev->vdev->get_features) {

        stl_phys(cur_offs, dev->vdev->get_features(dev->vdev));

    }

    dev->feat_offs = cur_offs + dev->feat_len;

    cur_offs += dev->feat_len * 2;

    /* Sync config space */

    if (dev->vdev->get_config) {

        dev->vdev->get_config(dev->vdev, dev->vdev->config);

    }

    cpu_physical_memory_rw(cur_offs, dev->vdev->config, dev->vdev->config_len, 1);

    cur_offs += dev->vdev->config_len;

}


static void FUNCC(pred8x8_left_dc)(uint8_t *_src, int stride){

    int i;

    int dc0, dc2;

    pixel4 dc0splat, dc2splat;

    pixel *src = (pixel*)_src;

    stride /= sizeof(pixel);

    dc0=dc2=0;

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

        dc0+= src[-1+i*stride];

        dc2+= src[-1+(i+4)*stride];

    }

    dc0splat = PIXEL_SPLAT_X4((dc0 + 2)>>2);

    dc2splat = PIXEL_SPLAT_X4((dc2 + 2)>>2);

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

        ((pixel4*)(src+i*stride))[0]=

        ((pixel4*)(src+i*stride))[1]= dc0splat;

    }

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

        ((pixel4*)(src+i*stride))[0]=

        ((pixel4*)(src+i*stride))[1]= dc2splat;

    }

}


static void alloc_and_copy(uint8_t **poutbuf,          int *poutbuf_size,

                           const uint8_t *sps_pps, uint32_t sps_pps_size,

                           const uint8_t *in,      uint32_t in_size) {

    uint32_t offset = *poutbuf_size;

    uint8_t nal_header_size = offset ? 3 : 4;

    *poutbuf_size += sps_pps_size+in_size+nal_header_size;

    *poutbuf = av_realloc(*poutbuf, *poutbuf_size);

    if (sps_pps)

        memcpy(*poutbuf+offset, sps_pps, sps_pps_size);

    memcpy(*poutbuf+sps_pps_size+nal_header_size+offset, in, in_size);

    if (!offset)

        AV_WB32(*poutbuf+sps_pps_size, 1);

    else {

        (*poutbuf+offset)[0] = (*poutbuf+offset)[1] = 0;

        (*poutbuf+offset)[2] = 1;

    }

}


void aio_set_event_notifier(AioContext *ctx,

                            EventNotifier *e,

                            EventNotifierHandler *io_notify,

                            AioFlushEventNotifierHandler *io_flush)

{

    AioHandler *node;

    QLIST_FOREACH(node, &ctx->aio_handlers, node) {

        if (node->e == e && !node->deleted) {

            break;

        }

    }

    /* Are we deleting the fd handler? */

    if (!io_notify) {

        if (node) {

            g_source_remove_poll(&ctx->source, &node->pfd);

            /* If the lock is held, just mark the node as deleted */

            if (ctx->walking_handlers) {

                node->deleted = 1;

                node->pfd.revents = 0;

            } else {

                /* Otherwise, delete it for real.  We can't just mark it as

                 * deleted because deleted nodes are only cleaned up after

                 * releasing the walking_handlers lock.

                 */

                QLIST_REMOVE(node, node);

                g_free(node);

            }

        }

    } else {

        if (node == NULL) {

            /* Alloc and insert if it's not already there */

            node = g_malloc0(sizeof(AioHandler));

            node->e = e;

            node->pfd.fd = (uintptr_t)event_notifier_get_handle(e);

            node->pfd.events = G_IO_IN;

            QLIST_INSERT_HEAD(&ctx->aio_handlers, node, node);

            g_source_add_poll(&ctx->source, &node->pfd);

        }

        /* Update handler with latest information */

        node->io_notify = io_notify;

        node->io_flush = io_flush;

    }

    aio_notify(ctx);

}


int float_near_ulp(float a, float b, unsigned max_ulp)

{

    union av_intfloat32 x, y;

    x.f = a;

    y.f = b;

    if (is_negative(x) != is_negative(y)) {

        // handle -0.0 == +0.0

        return a == b;

    }

    if (abs(x.i - y.i) <= max_ulp)

        return 1;

    return 0;

}


static av_cold int roq_dpcm_encode_init(AVCodecContext *avctx)

{

    ROQDPCMContext *context = avctx->priv_data;

    if (avctx->channels > 2) {

        av_log(avctx, AV_LOG_ERROR, "Audio must be mono or stereo\n");

        return -1;

    }

    if (avctx->sample_rate != 22050) {

        av_log(avctx, AV_LOG_ERROR, "Audio must be 22050 Hz\n");

        return -1;

    }

    if (avctx->sample_fmt != AV_SAMPLE_FMT_S16) {

        av_log(avctx, AV_LOG_ERROR, "Audio must be signed 16-bit\n");

        return -1;

    }

    avctx->frame_size = ROQ_FIRST_FRAME_SIZE;

    context->lastSample[0] = context->lastSample[1] = 0;

    avctx->coded_frame= avcodec_alloc_frame();

    return 0;

}