static int spapr_tce_table_realize(DeviceState *dev)

{

    sPAPRTCETable *tcet = SPAPR_TCE_TABLE(dev);

    if (kvm_enabled()) {

        tcet->table = kvmppc_create_spapr_tce(tcet->liobn,

                                              tcet->window_size,

                                              &tcet->fd);

    }

    if (!tcet->table) {

        size_t table_size = (tcet->window_size >> SPAPR_TCE_PAGE_SHIFT)

            * sizeof(uint64_t);

        tcet->table = g_malloc0(table_size);

    }

    tcet->nb_table = tcet->window_size >> SPAPR_TCE_PAGE_SHIFT;

    trace_spapr_iommu_new_table(tcet->liobn, tcet, tcet->table, tcet->fd);

    memory_region_init_iommu(&tcet->iommu, OBJECT(dev), &spapr_iommu_ops,

                             "iommu-spapr", UINT64_MAX);

    QLIST_INSERT_HEAD(&spapr_tce_tables, tcet, list);

    vmstate_register(DEVICE(tcet), tcet->liobn, &vmstate_spapr_tce_table,

                     tcet);

    return 0;

}


static int avi_write_header(AVFormatContext *s)

{

    AVIContext *avi = s->priv_data;

    AVIOContext *pb = s->pb;

    int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;

    AVCodecContext *stream, *video_enc;

    int64_t list1, list2, strh, strf;

    AVDictionaryEntry *t = NULL;

    if (s->nb_streams > AVI_MAX_STREAM_COUNT) {

        av_log(s, AV_LOG_ERROR, "AVI does not support >%d streams\n",

               AVI_MAX_STREAM_COUNT);

        return -1;

    }

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

        s->streams[n]->priv_data = av_mallocz(sizeof(AVIStream));

        if (!s->streams[n]->priv_data)

            return AVERROR(ENOMEM);

    }

    /* header list */

    avi->riff_id = 0;

    list1 = avi_start_new_riff(s, pb, "AVI ", "hdrl");

    /* avi header */

    ffio_wfourcc(pb, "avih");

    avio_wl32(pb, 14 * 4);

    bitrate = 0;

    video_enc = NULL;

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

        stream   = s->streams[n]->codec;

        bitrate += stream->bit_rate;

        if (stream->codec_type == AVMEDIA_TYPE_VIDEO)

            video_enc = stream;

    }

    nb_frames = 0;

    if (video_enc)

        avio_wl32(pb, (uint32_t) (INT64_C(1000000) * video_enc->time_base.num /

                                  video_enc->time_base.den));

    else

        avio_wl32(pb, 0);

    avio_wl32(pb, bitrate / 8); /* XXX: not quite exact */

    avio_wl32(pb, 0); /* padding */

    if (!pb->seekable)

        avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED);  /* flags */

    else

        avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED);  /* flags */

    avi->frames_hdr_all = avio_tell(pb); /* remember this offset to fill later */

    avio_wl32(pb, nb_frames); /* nb frames, filled later */

    avio_wl32(pb, 0); /* initial frame */

    avio_wl32(pb, s->nb_streams); /* nb streams */

    avio_wl32(pb, 1024 * 1024); /* suggested buffer size */

    if (video_enc) {

        avio_wl32(pb, video_enc->width);

        avio_wl32(pb, video_enc->height);

    } else {

        avio_wl32(pb, 0);

        avio_wl32(pb, 0);

    }

    avio_wl32(pb, 0); /* reserved */

    avio_wl32(pb, 0); /* reserved */

    avio_wl32(pb, 0); /* reserved */

    avio_wl32(pb, 0); /* reserved */

    /* stream list */

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

        AVIStream *avist = s->streams[i]->priv_data;

        list2 = ff_start_tag(pb, "LIST");

        ffio_wfourcc(pb, "strl");

        stream = s->streams[i]->codec;

        /* stream generic header */

        strh = ff_start_tag(pb, "strh");

        switch (stream->codec_type) {

        case AVMEDIA_TYPE_SUBTITLE:

            // XSUB subtitles behave like video tracks, other subtitles

            // are not (yet) supported.

            if (stream->codec_id != AV_CODEC_ID_XSUB) {

                av_log(s, AV_LOG_ERROR,

                       "Subtitle streams other than DivX XSUB are not supported by the AVI muxer.\n");

                return AVERROR_PATCHWELCOME;

            }

        case AVMEDIA_TYPE_VIDEO:

            ffio_wfourcc(pb, "vids");

            break;

        case AVMEDIA_TYPE_AUDIO:

            ffio_wfourcc(pb, "auds");

            break;

//      case AVMEDIA_TYPE_TEXT:

//          ffio_wfourcc(pb, "txts");

//          break;

        case AVMEDIA_TYPE_DATA:

            ffio_wfourcc(pb, "dats");

            break;

        }

        if (stream->codec_type == AVMEDIA_TYPE_VIDEO ||

            stream->codec_id == AV_CODEC_ID_XSUB)

            avio_wl32(pb, stream->codec_tag);

        else

            avio_wl32(pb, 1);

        avio_wl32(pb, 0); /* flags */

        avio_wl16(pb, 0); /* priority */

        avio_wl16(pb, 0); /* language */

        avio_wl32(pb, 0); /* initial frame */

        ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);

        avio_wl32(pb, au_scale); /* scale */

        avio_wl32(pb, au_byterate); /* rate */

        avpriv_set_pts_info(s->streams[i], 64, au_scale, au_byterate);

        avio_wl32(pb, 0); /* start */

        /* remember this offset to fill later */

        avist->frames_hdr_strm = avio_tell(pb);

        if (!pb->seekable)

            /* FIXME: this may be broken, but who cares */

            avio_wl32(pb, AVI_MAX_RIFF_SIZE);

        else

            avio_wl32(pb, 0);  /* length, XXX: filled later */

        /* suggested buffer size */ //FIXME set at the end to largest chunk

        if (stream->codec_type == AVMEDIA_TYPE_VIDEO)

            avio_wl32(pb, 1024 * 1024);

        else if (stream->codec_type == AVMEDIA_TYPE_AUDIO)

            avio_wl32(pb, 12 * 1024);

        else

            avio_wl32(pb, 0);

        avio_wl32(pb, -1); /* quality */

        avio_wl32(pb, au_ssize); /* sample size */

        avio_wl32(pb, 0);

        avio_wl16(pb, stream->width);

        avio_wl16(pb, stream->height);

        ff_end_tag(pb, strh);

        if (stream->codec_type != AVMEDIA_TYPE_DATA) {

            strf = ff_start_tag(pb, "strf");

            switch (stream->codec_type) {

            case AVMEDIA_TYPE_SUBTITLE:

                /* XSUB subtitles behave like video tracks, other subtitles

                 * are not (yet) supported. */

                if (stream->codec_id != AV_CODEC_ID_XSUB)

                    break;

            case AVMEDIA_TYPE_VIDEO:

                ff_put_bmp_header(pb, stream, ff_codec_bmp_tags, 0);

                break;

            case AVMEDIA_TYPE_AUDIO:

                if (ff_put_wav_header(pb, stream) < 0)

                    return -1;

                break;

            default:

                return -1;

            }

            ff_end_tag(pb, strf);

            if ((t = av_dict_get(s->streams[i]->metadata, "title", NULL, 0))) {

                ff_riff_write_info_tag(s->pb, "strn", t->value);

                t = NULL;

            }

        }

        if (pb->seekable) {

            unsigned char tag[5];

            int j;

            /* Starting to lay out AVI OpenDML master index.

             * We want to make it JUNK entry for now, since we'd

             * like to get away without making AVI an OpenDML one

             * for compatibility reasons. */

            avist->indexes.entry      = avist->indexes.ents_allocated = 0;

            avist->indexes.indx_start = ff_start_tag(pb, "JUNK");

            avio_wl16(pb, 4);   /* wLongsPerEntry */

            avio_w8(pb, 0);     /* bIndexSubType (0 == frame index) */

            avio_w8(pb, 0);     /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */

            avio_wl32(pb, 0);   /* nEntriesInUse (will fill out later on) */

            ffio_wfourcc(pb, avi_stream2fourcc(tag, i, stream->codec_type));

                                /* dwChunkId */

            avio_wl64(pb, 0);   /* dwReserved[3] */

            // avio_wl32(pb, 0);   /* Must be 0.    */

            for (j = 0; j < AVI_MASTER_INDEX_SIZE * 2; j++)

                avio_wl64(pb, 0);

            ff_end_tag(pb, avist->indexes.indx_start);

        }

        if (stream->codec_type == AVMEDIA_TYPE_VIDEO   &&

            s->streams[i]->sample_aspect_ratio.num > 0 &&

            s->streams[i]->sample_aspect_ratio.den > 0) {

            int vprp       = ff_start_tag(pb, "vprp");

            AVRational dar = av_mul_q(s->streams[i]->sample_aspect_ratio,

                                      (AVRational) { stream->width,

                                                     stream->height });

            int num, den;

            av_reduce(&num, &den, dar.num, dar.den, 0xFFFF);

            avio_wl32(pb, 0); // video format   = unknown

            avio_wl32(pb, 0); // video standard = unknown

            avio_wl32(pb, lrintf(1.0 / av_q2d(stream->time_base)));

            avio_wl32(pb, stream->width);

            avio_wl32(pb, stream->height);

            avio_wl16(pb, den);

            avio_wl16(pb, num);

            avio_wl32(pb, stream->width);

            avio_wl32(pb, stream->height);

            avio_wl32(pb, 1); // progressive FIXME

            avio_wl32(pb, stream->height);

            avio_wl32(pb, stream->width);

            avio_wl32(pb, stream->height);

            avio_wl32(pb, stream->width);

            avio_wl32(pb, 0);

            avio_wl32(pb, 0);

            avio_wl32(pb, 0);

            avio_wl32(pb, 0);

            ff_end_tag(pb, vprp);

        }

        ff_end_tag(pb, list2);

    }

    if (pb->seekable) {

        /* AVI could become an OpenDML one, if it grows beyond 2Gb range */

        avi->odml_list = ff_start_tag(pb, "JUNK");

        ffio_wfourcc(pb, "odml");

        ffio_wfourcc(pb, "dmlh");

        avio_wl32(pb, 248);

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

            avio_wl32(pb, 0);

        ff_end_tag(pb, avi->odml_list);

    }

    ff_end_tag(pb, list1);

    ff_riff_write_info(s);

    /* some padding for easier tag editing */

    list2 = ff_start_tag(pb, "JUNK");

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

        avio_wl32(pb, 0);

    ff_end_tag(pb, list2);

    avi->movi_list = ff_start_tag(pb, "LIST");

    ffio_wfourcc(pb, "movi");

    avio_flush(pb);

    return 0;

}


void ide_dma_cb(void *opaque, int ret)

{

    IDEState *s = opaque;

    int n;

    int64_t sector_num;

    bool stay_active = false;

    if (ret == -ECANCELED) {

        return;

    }

    if (ret < 0) {

        int op = IDE_RETRY_DMA;

        if (s->dma_cmd == IDE_DMA_READ)

            op |= IDE_RETRY_READ;

        else if (s->dma_cmd == IDE_DMA_TRIM)

            op |= IDE_RETRY_TRIM;

        if (ide_handle_rw_error(s, -ret, op)) {

            return;

        }

    }

    n = s->io_buffer_size >> 9;

    if (n > s->nsector) {

        /* The PRDs were longer than needed for this request. Shorten them so

         * we don't get a negative remainder. The Active bit must remain set

         * after the request completes. */

        n = s->nsector;

        stay_active = true;

    }

    sector_num = ide_get_sector(s);

    if (n > 0) {

        dma_buf_commit(s);

        sector_num += n;

        ide_set_sector(s, sector_num);

        s->nsector -= n;

    }

    /* end of transfer ? */

    if (s->nsector == 0) {

        s->status = READY_STAT | SEEK_STAT;

        ide_set_irq(s->bus);

        goto eot;

    }

    /* launch next transfer */

    n = s->nsector;

    s->io_buffer_index = 0;

    s->io_buffer_size = n * 512;

    if (s->bus->dma->ops->prepare_buf(s->bus->dma, ide_cmd_is_read(s)) == 0) {

        /* The PRDs were too short. Reset the Active bit, but don't raise an

         * interrupt. */

        s->status = READY_STAT | SEEK_STAT;

        goto eot;

    }

#ifdef DEBUG_AIO

    printf("ide_dma_cb: sector_num=%" PRId64 " n=%d, cmd_cmd=%d\n",

           sector_num, n, s->dma_cmd);

#endif

    if ((s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) &&

        !ide_sect_range_ok(s, sector_num, n)) {

        dma_buf_commit(s);

        ide_dma_error(s);

        return;

    }

    switch (s->dma_cmd) {

    case IDE_DMA_READ:

        s->bus->dma->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num,

                                           ide_dma_cb, s);

        break;

    case IDE_DMA_WRITE:

        s->bus->dma->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num,

                                            ide_dma_cb, s);

        break;

    case IDE_DMA_TRIM:

        s->bus->dma->aiocb = dma_bdrv_io(s->bs, &s->sg, sector_num,

                                         ide_issue_trim, ide_dma_cb, s,

                                         DMA_DIRECTION_TO_DEVICE);

        break;

    }

    return;

eot:

    if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) {

        block_acct_done(bdrv_get_stats(s->bs), &s->acct);

    }

    ide_set_inactive(s, stay_active);

}


int load_elf(const char *filename, int64_t address_offset,

             uint64_t *pentry, uint64_t *lowaddr, uint64_t *highaddr,

             int big_endian, int elf_machine, int clear_lsb)

{

    int fd, data_order, target_data_order, must_swab, ret;

    uint8_t e_ident[EI_NIDENT];

    fd = open(filename, O_RDONLY | O_BINARY);

    if (fd < 0) {

        perror(filename);

        return -1;

    }

    if (read(fd, e_ident, sizeof(e_ident)) != sizeof(e_ident))

        goto fail;

    if (e_ident[0] != ELFMAG0 ||

        e_ident[1] != ELFMAG1 ||

        e_ident[2] != ELFMAG2 ||

        e_ident[3] != ELFMAG3)

        goto fail;

#ifdef HOST_WORDS_BIGENDIAN

    data_order = ELFDATA2MSB;

#else

    data_order = ELFDATA2LSB;

#endif

    must_swab = data_order != e_ident[EI_DATA];

    if (big_endian) {

        target_data_order = ELFDATA2MSB;

    } else {

        target_data_order = ELFDATA2LSB;

    }

    if (target_data_order != e_ident[EI_DATA])

        return -1;

    lseek(fd, 0, SEEK_SET);

    if (e_ident[EI_CLASS] == ELFCLASS64) {

        ret = load_elf64(fd, address_offset, must_swab, pentry,

                         lowaddr, highaddr, elf_machine, clear_lsb);

    } else {

        ret = load_elf32(fd, address_offset, must_swab, pentry,

                         lowaddr, highaddr, elf_machine, clear_lsb);

    }

    close(fd);

    return ret;

 fail:

    close(fd);

    return -1;

}


static CharDriverState *qemu_chr_open_pty(const char *id,

                                          ChardevBackend *backend,

                                          ChardevReturn *ret,

                                          Error **errp)

{

    CharDriverState *chr;

    PtyCharDriver *s;

    int master_fd, slave_fd;

    char pty_name[PATH_MAX];

    master_fd = qemu_openpty_raw(&slave_fd, pty_name);

    if (master_fd < 0) {

        error_setg_errno(errp, errno, "Failed to create PTY");

        return NULL;

    }

    close(slave_fd);

    qemu_set_nonblock(master_fd);

    chr = qemu_chr_alloc();

    chr->filename = g_strdup_printf("pty:%s", pty_name);

    ret->pty = g_strdup(pty_name);

    ret->has_pty = true;

    fprintf(stderr, "char device redirected to %s (label %s)\n",

            pty_name, id);

    s = g_new0(PtyCharDriver, 1);

    chr->opaque = s;

    chr->chr_write = pty_chr_write;

    chr->chr_update_read_handler = pty_chr_update_read_handler;

    chr->chr_close = pty_chr_close;

    chr->chr_add_watch = pty_chr_add_watch;

    chr->explicit_be_open = true;

    s->fd = io_channel_from_fd(master_fd);

    s->timer_tag = 0;

    return chr;

}


static uint64_t cirrus_linear_read(void *opaque, target_phys_addr_t addr,

                                   unsigned size)

{

    CirrusVGAState *s = opaque;

    uint32_t ret;

    addr &= s->cirrus_addr_mask;

    if (((s->vga.sr[0x17] & 0x44) == 0x44) &&

        ((addr & s->linear_mmio_mask) == s->linear_mmio_mask)) {

	/* memory-mapped I/O */

	ret = cirrus_mmio_blt_read(s, addr & 0xff);

    } else if (0) {

	/* XXX handle bitblt */

	ret = 0xff;

    } else {

	/* video memory */

	if ((s->vga.gr[0x0B] & 0x14) == 0x14) {

	    addr <<= 4;

	} else if (s->vga.gr[0x0B] & 0x02) {

	    addr <<= 3;

	}

	addr &= s->cirrus_addr_mask;

	ret = *(s->vga.vram_ptr + addr);

    }

    return ret;

}


static int qemu_gluster_create(const char *filename,

                               QemuOpts *opts, Error **errp)

{

    BlockdevOptionsGluster *gconf;

    struct glfs *glfs;

    struct glfs_fd *fd;

    int ret = 0;

    int prealloc = 0;

    int64_t total_size = 0;

    char *tmp = NULL;

    gconf = g_new0(BlockdevOptionsGluster, 1);

    gconf->debug = qemu_opt_get_number_del(opts, GLUSTER_OPT_DEBUG,

                                           GLUSTER_DEBUG_DEFAULT);

    if (gconf->debug < 0) {

        gconf->debug = 0;

    } else if (gconf->debug > GLUSTER_DEBUG_MAX) {

        gconf->debug = GLUSTER_DEBUG_MAX;

    }

    gconf->has_debug = true;

    gconf->logfile = qemu_opt_get_del(opts, GLUSTER_OPT_LOGFILE);

    if (!gconf->logfile) {

        gconf->logfile = g_strdup(GLUSTER_LOGFILE_DEFAULT);

    }

    gconf->has_logfile = true;

    glfs = qemu_gluster_init(gconf, filename, NULL, errp);

    if (!glfs) {

        ret = -errno;

        goto out;

    }

    total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),

                          BDRV_SECTOR_SIZE);

    tmp = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);

    if (!tmp || !strcmp(tmp, "off")) {

        prealloc = 0;

    } else if (!strcmp(tmp, "full") && gluster_supports_zerofill()) {

        prealloc = 1;

    } else {

        error_setg(errp, "Invalid preallocation mode: '%s'"

                         " or GlusterFS doesn't support zerofill API", tmp);

        ret = -EINVAL;

        goto out;

    }

    fd = glfs_creat(glfs, gconf->path,

                    O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IRUSR | S_IWUSR);

    if (!fd) {

        ret = -errno;

    } else {

        if (!glfs_ftruncate(fd, total_size)) {

            if (prealloc && qemu_gluster_zerofill(fd, 0, total_size)) {

                ret = -errno;

            }

        } else {

            ret = -errno;

        }

        if (glfs_close(fd) != 0) {

            ret = -errno;

        }

    }

out:

    g_free(tmp);

    qapi_free_BlockdevOptionsGluster(gconf);

    glfs_clear_preopened(glfs);

    return ret;

}


static void memory_region_iorange_read(IORange *iorange,

                                       uint64_t offset,

                                       unsigned width,

                                       uint64_t *data)

{

    MemoryRegion *mr = container_of(iorange, MemoryRegion, iorange);

    if (mr->ops->old_portio) {

        const MemoryRegionPortio *mrp = find_portio(mr, offset, width, false);

        *data = ((uint64_t)1 << (width * 8)) - 1;

        if (mrp) {

            *data = mrp->read(mr->opaque, offset - mrp->offset);

        }

        return;

    }

    *data = mr->ops->read(mr->opaque, offset, width);

}


static int ide_drive_initfn(IDEDevice *dev)

{

    return ide_dev_initfn(dev,

                          bdrv_get_type_hint(dev->conf.bs) == BDRV_TYPE_CDROM

                          ? IDE_CD : IDE_HD);

}


static av_cold void h264dsp_init_neon(H264DSPContext *c, const int bit_depth,

                                      const int chroma_format_idc)

{

#if HAVE_NEON

    if (bit_depth == 8) {

        c->h264_v_loop_filter_luma   = ff_h264_v_loop_filter_luma_neon;

        c->h264_h_loop_filter_luma   = ff_h264_h_loop_filter_luma_neon;

        if(chroma_format_idc == 1){

        c->h264_v_loop_filter_chroma = ff_h264_v_loop_filter_chroma_neon;

        c->h264_h_loop_filter_chroma = ff_h264_h_loop_filter_chroma_neon;

        }

        c->weight_h264_pixels_tab[0] = ff_weight_h264_pixels_16_neon;

        c->weight_h264_pixels_tab[1] = ff_weight_h264_pixels_8_neon;

        c->weight_h264_pixels_tab[2] = ff_weight_h264_pixels_4_neon;

        c->biweight_h264_pixels_tab[0] = ff_biweight_h264_pixels_16_neon;

        c->biweight_h264_pixels_tab[1] = ff_biweight_h264_pixels_8_neon;

        c->biweight_h264_pixels_tab[2] = ff_biweight_h264_pixels_4_neon;

        c->h264_idct_add        = ff_h264_idct_add_neon;

        c->h264_idct_dc_add     = ff_h264_idct_dc_add_neon;

        c->h264_idct_add16      = ff_h264_idct_add16_neon;

        c->h264_idct_add16intra = ff_h264_idct_add16intra_neon;

        if (chroma_format_idc <= 1)

            c->h264_idct_add8   = ff_h264_idct_add8_neon;

        c->h264_idct8_add       = ff_h264_idct8_add_neon;

        c->h264_idct8_dc_add    = ff_h264_idct8_dc_add_neon;

        c->h264_idct8_add4      = ff_h264_idct8_add4_neon;

    }

#endif // HAVE_NEON

}


int load_vmstate(Monitor *mon, const char *name)

{

    DriveInfo *dinfo;

    BlockDriverState *bs, *bs1;

    QEMUSnapshotInfo sn;

    QEMUFile *f;

    int ret;

    bs = get_bs_snapshots();

    if (!bs) {

        monitor_printf(mon, "No block device supports snapshots\n");

        return -EINVAL;

    }

    /* Flush all IO requests so they don't interfere with the new state.  */

    qemu_aio_flush();

    TAILQ_FOREACH(dinfo, &drives, next) {

        bs1 = dinfo->bdrv;

        if (bdrv_has_snapshot(bs1)) {

            ret = bdrv_snapshot_goto(bs1, name);

            if (ret < 0) {

                if (bs != bs1)

                    monitor_printf(mon, "Warning: ");

                switch(ret) {

                case -ENOTSUP:

                    monitor_printf(mon,

                                   "Snapshots not supported on device '%s'\n",

                                   bdrv_get_device_name(bs1));

                    break;

                case -ENOENT:

                    monitor_printf(mon, "Could not find snapshot '%s' on "

                                   "device '%s'\n",

                                   name, bdrv_get_device_name(bs1));

                    break;

                default:

                    monitor_printf(mon, "Error %d while activating snapshot on"

                                   " '%s'\n", ret, bdrv_get_device_name(bs1));

                    break;

                }

                /* fatal on snapshot block device */

                if (bs == bs1)

                    return 0;

            }

        }

    }

    /* Don't even try to load empty VM states */

    ret = bdrv_snapshot_find(bs, &sn, name);

    if ((ret >= 0) && (sn.vm_state_size == 0))

        return -EINVAL;

    /* restore the VM state */

    f = qemu_fopen_bdrv(bs, 0);

    if (!f) {

        monitor_printf(mon, "Could not open VM state file\n");

        return -EINVAL;

    }

    ret = qemu_loadvm_state(f);

    qemu_fclose(f);

    if (ret < 0) {

        monitor_printf(mon, "Error %d while loading VM state\n", ret);

        return ret;

    }

    return 0;

}


static void spapr_tce_reset(DeviceState *dev)

{

    sPAPRTCETable *tcet = SPAPR_TCE_TABLE(dev);

    size_t table_size = tcet->nb_table * sizeof(uint64_t);

    tcet->bypass = false;

    memset(tcet->table, 0, table_size);

}


AVIOContext *avio_alloc_context(

                  unsigned char *buffer,

                  int buffer_size,

                  int write_flag,

                  void *opaque,

                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),

                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),

                  int64_t (*seek)(void *opaque, int64_t offset, int whence))

{

    AVIOContext *s = av_mallocz(sizeof(AVIOContext));

    ffio_init_context(s, buffer, buffer_size, write_flag, opaque,

                  read_packet, write_packet, seek);

    return s;

}


static void slirp_guestfwd(SlirpState *s, Monitor *mon, const char *config_str,

                           int legacy_format)

{

    struct in_addr server = { .s_addr = 0 };

    struct GuestFwd *fwd;

    const char *p;

    char buf[128];

    char *end;

    int port;

    p = config_str;

    if (legacy_format) {

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

            goto fail_syntax;

        }

    } else {

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

            goto fail_syntax;

        }

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

            goto fail_syntax;

        }

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

            goto fail_syntax;

        }

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

            goto fail_syntax;

        }

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

            goto fail_syntax;

        }

    }

    port = strtol(buf, &end, 10);

    if (*end != '\0' || port < 1 || port > 65535) {

        goto fail_syntax;

    }

    fwd = qemu_malloc(sizeof(struct GuestFwd));

    snprintf(buf, sizeof(buf), "guestfwd.tcp:%d", port);

    fwd->hd = qemu_chr_open(buf, p, NULL);

    if (!fwd->hd) {

        config_error(mon, "could not open guest forwarding device '%s'\n",

                     buf);

        qemu_free(fwd);

        return;

    }

    if (slirp_add_exec(s->slirp, 3, fwd->hd, &server, port) < 0) {

        config_error(mon, "conflicting/invalid host:port in guest forwarding "

                     "rule '%s'\n", config_str);

        qemu_free(fwd);

        return;

    }

    fwd->server = server;

    fwd->port = port;

    fwd->slirp = s->slirp;

    qemu_chr_add_handlers(fwd->hd, guestfwd_can_read, guestfwd_read,

                          NULL, fwd);

    return;

 fail_syntax:

    config_error(mon, "invalid guest forwarding rule '%s'\n", config_str);

}


int s390_virtio_hypercall(CPUState *env, uint64_t mem, uint64_t hypercall)

{

    int r = 0, i;

    dprintf("KVM hypercall: %ld\n", hypercall);

    switch (hypercall) {

    case KVM_S390_VIRTIO_NOTIFY:

        if (mem > ram_size) {

            VirtIOS390Device *dev = s390_virtio_bus_find_vring(s390_bus,

                                                               mem, &i);

            if (dev) {

                virtio_queue_notify(dev->vdev, i);

            } else {

                r = -EINVAL;

            }

        } else {

            /* Early printk */

        }

        break;

    case KVM_S390_VIRTIO_RESET:

    {

        VirtIOS390Device *dev;

        dev = s390_virtio_bus_find_mem(s390_bus, mem);

        virtio_reset(dev->vdev);

        s390_virtio_device_sync(dev);

        break;

    }

    case KVM_S390_VIRTIO_SET_STATUS:

    {

        VirtIOS390Device *dev;

        dev = s390_virtio_bus_find_mem(s390_bus, mem);

        if (dev) {

            s390_virtio_device_update_status(dev);

        } else {

            r = -EINVAL;

        }

        break;

    }

    default:

        r = -EINVAL;

        break;

    }

    return r;

}


PXA2xxPCMCIAState *pxa2xx_pcmcia_init(MemoryRegion *sysmem,

                                      hwaddr base)

{

    DeviceState *dev;

    PXA2xxPCMCIAState *s;

    dev = qdev_create(NULL, TYPE_PXA2XX_PCMCIA);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, base);

    s = PXA2XX_PCMCIA(dev);

    if (base == 0x30000000) {

        s->slot.slot_string = "PXA PC Card Socket 1";

    } else {

        s->slot.slot_string = "PXA PC Card Socket 0";

    }

    qdev_init_nofail(dev);

    return s;

}


static void qxl_exit_vga_mode(PCIQXLDevice *d)

{

    if (d->mode != QXL_MODE_VGA) {

        return;

    }

    trace_qxl_exit_vga_mode(d->id);

    qxl_destroy_primary(d, QXL_SYNC);

}


static int synth_frame(AVCodecContext *ctx, GetBitContext *gb, int frame_idx,

                       float *samples,

                       const double *lsps, const double *prev_lsps,

                       float *excitation, float *synth)

{

    WMAVoiceContext *s = ctx->priv_data;

    int n, n_blocks_x2, log_n_blocks_x2, cur_pitch_val;

    int pitch[MAX_BLOCKS], last_block_pitch;

    /* Parse frame type ("frame header"), see frame_descs */

    int bd_idx = s->vbm_tree[get_vlc2(gb, frame_type_vlc.table, 6, 3)], block_nsamples;

    if (bd_idx < 0) {

        av_log(ctx, AV_LOG_ERROR,

               "Invalid frame type VLC code, skipping\n");

        return -1;

    }

    block_nsamples = MAX_FRAMESIZE / frame_descs[bd_idx].n_blocks;

    /* Pitch calculation for ACB_TYPE_ASYMMETRIC ("pitch-per-frame") */

    if (frame_descs[bd_idx].acb_type == ACB_TYPE_ASYMMETRIC) {

        /* Pitch is provided per frame, which is interpreted as the pitch of

         * the last sample of the last block of this frame. We can interpolate

         * the pitch of other blocks (and even pitch-per-sample) by gradually

         * incrementing/decrementing prev_frame_pitch to cur_pitch_val. */

        n_blocks_x2      = frame_descs[bd_idx].n_blocks << 1;

        log_n_blocks_x2  = frame_descs[bd_idx].log_n_blocks + 1;

        cur_pitch_val    = s->min_pitch_val + get_bits(gb, s->pitch_nbits);

        cur_pitch_val    = FFMIN(cur_pitch_val, s->max_pitch_val - 1);

        if (s->last_acb_type == ACB_TYPE_NONE ||

            20 * abs(cur_pitch_val - s->last_pitch_val) >

                (cur_pitch_val + s->last_pitch_val))

            s->last_pitch_val = cur_pitch_val;

        /* pitch per block */

        for (n = 0; n < frame_descs[bd_idx].n_blocks; n++) {

            int fac = n * 2 + 1;

            pitch[n] = (MUL16(fac,                 cur_pitch_val) +

                        MUL16((n_blocks_x2 - fac), s->last_pitch_val) +

                        frame_descs[bd_idx].n_blocks) >> log_n_blocks_x2;

        }

        /* "pitch-diff-per-sample" for calculation of pitch per sample */

        s->pitch_diff_sh16 =

            ((cur_pitch_val - s->last_pitch_val) << 16) / MAX_FRAMESIZE;

    }

    /* Global gain (if silence) and pitch-adaptive window coordinates */

    switch (frame_descs[bd_idx].fcb_type) {

    case FCB_TYPE_SILENCE:

        s->silence_gain = wmavoice_gain_silence[get_bits(gb, 8)];

        break;

    case FCB_TYPE_AW_PULSES:

        aw_parse_coords(s, gb, pitch);

        break;

    }

    for (n = 0; n < frame_descs[bd_idx].n_blocks; n++) {

        int bl_pitch_sh2;

        /* Pitch calculation for ACB_TYPE_HAMMING ("pitch-per-block") */

        switch (frame_descs[bd_idx].acb_type) {

        case ACB_TYPE_HAMMING: {

            /* Pitch is given per block. Per-block pitches are encoded as an

             * absolute value for the first block, and then delta values

             * relative to this value) for all subsequent blocks. The scale of

             * this pitch value is semi-logaritmic compared to its use in the

             * decoder, so we convert it to normal scale also. */

            int block_pitch,

                t1 = (s->block_conv_table[1] - s->block_conv_table[0]) << 2,

                t2 = (s->block_conv_table[2] - s->block_conv_table[1]) << 1,

                t3 =  s->block_conv_table[3] - s->block_conv_table[2] + 1;

            if (n == 0) {

                block_pitch = get_bits(gb, s->block_pitch_nbits);

            } else

                block_pitch = last_block_pitch - s->block_delta_pitch_hrange +

                                 get_bits(gb, s->block_delta_pitch_nbits);

            /* Convert last_ so that any next delta is within _range */

            last_block_pitch = av_clip(block_pitch,

                                       s->block_delta_pitch_hrange,

                                       s->block_pitch_range -

                                           s->block_delta_pitch_hrange);

            /* Convert semi-log-style scale back to normal scale */

            if (block_pitch < t1) {

                bl_pitch_sh2 = (s->block_conv_table[0] << 2) + block_pitch;

            } else {

                block_pitch -= t1;

                if (block_pitch < t2) {

                    bl_pitch_sh2 =

                        (s->block_conv_table[1] << 2) + (block_pitch << 1);

                } else {

                    block_pitch -= t2;

                    if (block_pitch < t3) {

                        bl_pitch_sh2 =

                            (s->block_conv_table[2] + block_pitch) << 2;

                    } else

                        bl_pitch_sh2 = s->block_conv_table[3] << 2;

                }

            }

            pitch[n] = bl_pitch_sh2 >> 2;

            break;

        }

        case ACB_TYPE_ASYMMETRIC: {

            bl_pitch_sh2 = pitch[n] << 2;

            break;

        }

        default: // ACB_TYPE_NONE has no pitch

            bl_pitch_sh2 = 0;

            break;

        }

        synth_block(s, gb, n, block_nsamples, bl_pitch_sh2,

                    lsps, prev_lsps, &frame_descs[bd_idx],

                    &excitation[n * block_nsamples],

                    &synth[n * block_nsamples]);

    }

    /* Averaging projection filter, if applicable. Else, just copy samples

     * from synthesis buffer */

    if (s->do_apf) {

        double i_lsps[MAX_LSPS];

        float lpcs[MAX_LSPS];

        for (n = 0; n < s->lsps; n++) // LSF -> LSP

            i_lsps[n] = cos(0.5 * (prev_lsps[n] + lsps[n]));

        ff_acelp_lspd2lpc(i_lsps, lpcs, s->lsps >> 1);

        postfilter(s, synth, samples, 80, lpcs,

                   &s->zero_exc_pf[s->history_nsamples + MAX_FRAMESIZE * frame_idx],

                   frame_descs[bd_idx].fcb_type, pitch[0]);

        for (n = 0; n < s->lsps; n++) // LSF -> LSP

            i_lsps[n] = cos(lsps[n]);

        ff_acelp_lspd2lpc(i_lsps, lpcs, s->lsps >> 1);

        postfilter(s, &synth[80], &samples[80], 80, lpcs,

                   &s->zero_exc_pf[s->history_nsamples + MAX_FRAMESIZE * frame_idx + 80],

                   frame_descs[bd_idx].fcb_type, pitch[0]);

    } else

        memcpy(samples, synth, 160 * sizeof(synth[0]));

    /* Cache values for next frame */

    s->frame_cntr++;

    if (s->frame_cntr >= 0xFFFF) s->frame_cntr -= 0xFFFF; // i.e. modulo (%)

    s->last_acb_type = frame_descs[bd_idx].acb_type;

    switch (frame_descs[bd_idx].acb_type) {

    case ACB_TYPE_NONE:

        s->last_pitch_val = 0;

        break;

    case ACB_TYPE_ASYMMETRIC:

        s->last_pitch_val = cur_pitch_val;

        break;

    case ACB_TYPE_HAMMING:

        s->last_pitch_val = pitch[frame_descs[bd_idx].n_blocks - 1];

        break;

    }

    return 0;

}


int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd)

{

    int64_t r = 0;

    av_assert2(c > 0);

    av_assert2(b >=0);

    av_assert2((unsigned)(rnd&~AV_ROUND_PASS_MINMAX)<=5 && (rnd&~AV_ROUND_PASS_MINMAX)!=4);

    if (c <= 0 || b < 0 || !((unsigned)(rnd&~AV_ROUND_PASS_MINMAX)<=5 && (rnd&~AV_ROUND_PASS_MINMAX)!=4))

        return INT64_MIN;

    if (rnd & AV_ROUND_PASS_MINMAX) {

        if (a == INT64_MIN || a == INT64_MAX)

            return a;

        rnd -= AV_ROUND_PASS_MINMAX;

    }

    if (a < 0 && a != INT64_MIN)

        return -av_rescale_rnd(-a, b, c, rnd ^ ((rnd >> 1) & 1));

    if (rnd == AV_ROUND_NEAR_INF)

        r = c / 2;

    else if (rnd & 1)

        r = c - 1;

    if (b <= INT_MAX && c <= INT_MAX) {

        if (a <= INT_MAX)

            return (a * b + r) / c;

        else

            return a / c * b + (a % c * b + r) / c;

    } else {

#if 1

        uint64_t a0  = a & 0xFFFFFFFF;

        uint64_t a1  = a >> 32;

        uint64_t b0  = b & 0xFFFFFFFF;

        uint64_t b1  = b >> 32;

        uint64_t t1  = a0 * b1 + a1 * b0;

        uint64_t t1a = t1 << 32;

        int i;

        a0  = a0 * b0 + t1a;

        a1  = a1 * b1 + (t1 >> 32) + (a0 < t1a);

        a0 += r;

        a1 += a0 < r;

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

            a1 += a1 + ((a0 >> i) & 1);

            t1 += t1;

            if (c <= a1) {

                a1 -= c;

                t1++;

            }

        }

        return t1;

    }

#else

        AVInteger ai;

        ai = av_mul_i(av_int2i(a), av_int2i(b));

        ai = av_add_i(ai, av_int2i(r));

        return av_i2int(av_div_i(ai, av_int2i(c)));

    }

#endif

}


static inline void RENAME(rgb24tobgr32)(const uint8_t *src, uint8_t *dst, long src_size)

{

    uint8_t *dest = dst;

    const uint8_t *s = src;

    const uint8_t *end;

#if COMPILE_TEMPLATE_MMX

    const uint8_t *mm_end;

#endif

    end = s + src_size;

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");

    mm_end = end - 23;

    __asm__ volatile("movq        %0, %%mm7"::"m"(mask32a):"memory");

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            MOVNTQ"     %%mm3, 24%0"

            :"=m"(*dest)

            :"m"(*s)

            :"memory");

        dest += 32;

        s += 24;

    }

    __asm__ volatile(SFENCE:::"memory");

    __asm__ volatile(EMMS:::"memory");

#endif

    while (s < end) {

#if HAVE_BIGENDIAN

        /* RGB24 (= R,G,B) -> RGB32 (= A,B,G,R) */

        *dest++ = 255;

        *dest++ = s[2];

        *dest++ = s[1];

        *dest++ = s[0];

        s+=3;

#else

        *dest++ = *s++;

        *dest++ = *s++;

        *dest++ = *s++;

        *dest++ = 255;

#endif

    }

}


static void FUNC(transquant_bypass16x16)(uint8_t *_dst, int16_t *coeffs,

                                         ptrdiff_t stride)

{

    int x, y;

    pixel *dst = (pixel *)_dst;

    stride /= sizeof(pixel);

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

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

            dst[x] += *coeffs;

            coeffs++;

        }

        dst += stride;

    }

}


static int CUDAAPI cuvid_handle_video_sequence(void *opaque, CUVIDEOFORMAT* format)

{

    AVCodecContext *avctx = opaque;

    CuvidContext *ctx = avctx->priv_data;

    AVHWFramesContext *hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;

    CUVIDDECODECREATEINFO cuinfo;

    int surface_fmt;

    enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,

                                       AV_PIX_FMT_NONE,  // Will be updated below

                                       AV_PIX_FMT_NONE };

    av_log(avctx, AV_LOG_TRACE, "pfnSequenceCallback, progressive_sequence=%d\n", format->progressive_sequence);

    ctx->internal_error = 0;

    switch (format->bit_depth_luma_minus8) {

    case 0: // 8-bit

        pix_fmts[1] = AV_PIX_FMT_NV12;

        break;

    case 2: // 10-bit

        pix_fmts[1] = AV_PIX_FMT_P010;

        break;

    case 4: // 12-bit

        pix_fmts[1] = AV_PIX_FMT_P016;

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "unsupported bit depth: %d\n",

               format->bit_depth_luma_minus8 + 8);

        ctx->internal_error = AVERROR(EINVAL);

        return 0;

    }

    surface_fmt = ff_get_format(avctx, pix_fmts);

    if (surface_fmt < 0) {

        av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", surface_fmt);

        ctx->internal_error = AVERROR(EINVAL);

        return 0;

    }

    av_log(avctx, AV_LOG_VERBOSE, "Formats: Original: %s | HW: %s | SW: %s\n",

           av_get_pix_fmt_name(avctx->pix_fmt),

           av_get_pix_fmt_name(surface_fmt),

           av_get_pix_fmt_name(avctx->sw_pix_fmt));

    avctx->pix_fmt = surface_fmt;

    // Update our hwframe ctx, as the get_format callback might have refreshed it!

    if (avctx->hw_frames_ctx) {

        av_buffer_unref(&ctx->hwframe);

        ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);

        if (!ctx->hwframe) {

            ctx->internal_error = AVERROR(ENOMEM);

            return 0;

        }

        hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;

    }

    avctx->width = format->display_area.right;

    avctx->height = format->display_area.bottom;

    ff_set_sar(avctx, av_div_q(

        (AVRational){ format->display_aspect_ratio.x, format->display_aspect_ratio.y },

        (AVRational){ avctx->width, avctx->height }));

    if (!format->progressive_sequence && ctx->deint_mode == cudaVideoDeinterlaceMode_Weave)

        avctx->flags |= AV_CODEC_FLAG_INTERLACED_DCT;

    else

        avctx->flags &= ~AV_CODEC_FLAG_INTERLACED_DCT;

    if (format->video_signal_description.video_full_range_flag)

        avctx->color_range = AVCOL_RANGE_JPEG;

    else

        avctx->color_range = AVCOL_RANGE_MPEG;

    avctx->color_primaries = format->video_signal_description.color_primaries;

    avctx->color_trc = format->video_signal_description.transfer_characteristics;

    avctx->colorspace = format->video_signal_description.matrix_coefficients;

    if (format->bitrate)

        avctx->bit_rate = format->bitrate;

    if (format->frame_rate.numerator && format->frame_rate.denominator) {

        avctx->framerate.num = format->frame_rate.numerator;

        avctx->framerate.den = format->frame_rate.denominator;

    }

    if (ctx->cudecoder

            && avctx->coded_width == format->coded_width

            && avctx->coded_height == format->coded_height

            && ctx->chroma_format == format->chroma_format

            && ctx->codec_type == format->codec)

        return 1;

    if (ctx->cudecoder) {

        av_log(avctx, AV_LOG_TRACE, "Re-initializing decoder\n");

        ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder));

        if (ctx->internal_error < 0)

            return 0;

        ctx->cudecoder = NULL;

    }

    if (hwframe_ctx->pool && (

            hwframe_ctx->width < avctx->width ||

            hwframe_ctx->height < avctx->height ||

            hwframe_ctx->format != AV_PIX_FMT_CUDA ||

            hwframe_ctx->sw_format != avctx->sw_pix_fmt)) {

        av_log(avctx, AV_LOG_ERROR, "AVHWFramesContext is already initialized with incompatible parameters\n");

        ctx->internal_error = AVERROR(EINVAL);

        return 0;

    }

    if (format->chroma_format != cudaVideoChromaFormat_420) {

        av_log(avctx, AV_LOG_ERROR, "Chroma formats other than 420 are not supported\n");

        ctx->internal_error = AVERROR(EINVAL);

        return 0;

    }

    avctx->coded_width = format->coded_width;

    avctx->coded_height = format->coded_height;

    ctx->chroma_format = format->chroma_format;

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

    cuinfo.CodecType = ctx->codec_type = format->codec;

    cuinfo.ChromaFormat = format->chroma_format;

    switch (avctx->sw_pix_fmt) {

    case AV_PIX_FMT_NV12:

        cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;

        break;

    case AV_PIX_FMT_P010:

    case AV_PIX_FMT_P016:

        cuinfo.OutputFormat = cudaVideoSurfaceFormat_P016;

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Output formats other than NV12, P010 or P016 are not supported\n");

        ctx->internal_error = AVERROR(EINVAL);

        return 0;

    }

    cuinfo.ulWidth = avctx->coded_width;

    cuinfo.ulHeight = avctx->coded_height;

    cuinfo.ulTargetWidth = cuinfo.ulWidth;

    cuinfo.ulTargetHeight = cuinfo.ulHeight;

    cuinfo.target_rect.left = 0;

    cuinfo.target_rect.top = 0;

    cuinfo.target_rect.right = cuinfo.ulWidth;

    cuinfo.target_rect.bottom = cuinfo.ulHeight;

    cuinfo.ulNumDecodeSurfaces = ctx->nb_surfaces;

    cuinfo.ulNumOutputSurfaces = 1;

    cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;

    cuinfo.bitDepthMinus8 = format->bit_depth_luma_minus8;

    if (format->progressive_sequence) {

        ctx->deint_mode = cuinfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Weave;

    } else {

        cuinfo.DeinterlaceMode = ctx->deint_mode;

    }

    if (ctx->deint_mode != cudaVideoDeinterlaceMode_Weave)

        avctx->framerate = av_mul_q(avctx->framerate, (AVRational){2, 1});

    ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidCreateDecoder(&ctx->cudecoder, &cuinfo));

    if (ctx->internal_error < 0)

        return 0;

    if (!hwframe_ctx->pool) {

        hwframe_ctx->format = AV_PIX_FMT_CUDA;

        hwframe_ctx->sw_format = avctx->sw_pix_fmt;

        hwframe_ctx->width = avctx->width;

        hwframe_ctx->height = avctx->height;

        if ((ctx->internal_error = av_hwframe_ctx_init(ctx->hwframe)) < 0) {

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

            return 0;

        }

    }

    return 1;

}


static void set_stream_info_from_input_stream(AVStream *st, struct playlist *pls, AVStream *ist)

{

    avcodec_parameters_copy(st->codecpar, ist->codecpar);

    if (pls->is_id3_timestamped) /* custom timestamps via id3 */

        avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);

    else

        avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);

    st->internal->need_context_update = 1;

}


void ff_rtp_send_h264(AVFormatContext *s1, const uint8_t *buf1, int size)

{

    const uint8_t *r, *end = buf1 + size;

    RTPMuxContext *s = s1->priv_data;

    s->timestamp = s->cur_timestamp;

    s->buf_ptr   = s->buf;

    if (s->nal_length_size)

        r = ff_avc_mp4_find_startcode(buf1, end, s->nal_length_size) ? buf1 : end;

    else

        r = ff_avc_find_startcode(buf1, end);

    while (r < end) {

        const uint8_t *r1;

        if (s->nal_length_size) {

            r1 = ff_avc_mp4_find_startcode(r, end, s->nal_length_size);

            if (!r1)

                r1 = end;

            r += s->nal_length_size;

        } else {

            while (!*(r++));

            r1 = ff_avc_find_startcode(r, end);

        }

        nal_send(s1, r, r1 - r, r1 == end);

        r = r1;

    }

    flush_buffered(s1, 1);

}


static inline void idct4col_put(uint8_t *dest, int line_size, const DCTELEM *col)

{

    int c0, c1, c2, c3, a0, a1, a2, a3;

    const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    a0 = col[8*0];

    a1 = col[8*2];

    a2 = col[8*4];

    a3 = col[8*6];

    c0 = ((a0 + a2) << (CN_SHIFT - 1)) + (1 << (C_SHIFT - 1));

    c2 = ((a0 - a2) << (CN_SHIFT - 1)) + (1 << (C_SHIFT - 1));

    c1 = a1 * C1 + a3 * C2;

    c3 = a1 * C2 - a3 * C1;

    dest[0] = cm[(c0 + c1) >> C_SHIFT];

    dest += line_size;

    dest[0] = cm[(c2 + c3) >> C_SHIFT];

    dest += line_size;

    dest[0] = cm[(c2 - c3) >> C_SHIFT];

    dest += line_size;

    dest[0] = cm[(c0 - c1) >> C_SHIFT];

}


static ExitStatus gen_fbcond(DisasContext *ctx, TCGCond cond, int ra,

                             int32_t disp)

{

    TCGv cmp_tmp = tcg_temp_new();

    gen_fold_mzero(cond, cmp_tmp, load_fpr(ctx, ra));

    return gen_bcond_internal(ctx, cond, cmp_tmp, disp);

}


int cpu_ppc_handle_mmu_fault (CPUState *env, target_ulong address, int rw,

                              int is_user, int is_softmmu)

{

    mmu_ctx_t ctx;

    int access_type;

    int ret = 0;

    if (rw == 2) {

        /* code access */

        rw = 0;

        access_type = ACCESS_CODE;

    } else {

        /* data access */

        /* XXX: put correct access by using cpu_restore_state()

           correctly */

        access_type = ACCESS_INT;

        //        access_type = env->access_type;

    }

    ret = get_physical_address(env, &ctx, address, rw, access_type, 1);

    if (ret == 0) {

        ret = tlb_set_page(env, address & TARGET_PAGE_MASK,

                           ctx.raddr & TARGET_PAGE_MASK, ctx.prot,

                           is_user, is_softmmu);

    } else if (ret < 0) {

#if defined (DEBUG_MMU)

        if (loglevel != 0)

            cpu_dump_state(env, logfile, fprintf, 0);

#endif

        if (access_type == ACCESS_CODE) {

            switch (ret) {

            case -1:

                /* No matches in page tables or TLB */

                switch (env->mmu_model) {

                case POWERPC_MMU_SOFT_6xx:

                    env->exception_index = POWERPC_EXCP_IFTLB;

                    env->error_code = 1 << 18;

                    env->spr[SPR_IMISS] = address;

                    env->spr[SPR_ICMP] = 0x80000000 | ctx.ptem;

                    goto tlb_miss;

                case POWERPC_MMU_SOFT_74xx:

                    env->exception_index = POWERPC_EXCP_IFTLB;

                    goto tlb_miss_74xx;

                case POWERPC_MMU_SOFT_4xx:

                case POWERPC_MMU_SOFT_4xx_Z:

                    env->exception_index = POWERPC_EXCP_ITLB;

                    env->error_code = 0;

                    env->spr[SPR_40x_DEAR] = address;

                    env->spr[SPR_40x_ESR] = 0x00000000;

                    break;

                case POWERPC_MMU_32B:

#if defined(TARGET_PPC64)

                case POWERPC_MMU_64B:

                case POWERPC_MMU_64BRIDGE:

#endif

                    env->exception_index = POWERPC_EXCP_ISI;

                    env->error_code = 0x40000000;

                    break;

                case POWERPC_MMU_601:

                    /* XXX: TODO */

                    cpu_abort(env, "MMU model not implemented\n");

                    return -1;

                case POWERPC_MMU_BOOKE:

                    /* XXX: TODO */

                    cpu_abort(env, "MMU model not implemented\n");

                    return -1;

                case POWERPC_MMU_BOOKE_FSL:

                    /* XXX: TODO */

                    cpu_abort(env, "MMU model not implemented\n");

                    return -1;

                case POWERPC_MMU_REAL_4xx:

                    cpu_abort(env, "PowerPC 401 should never raise any MMU "

                              "exceptions\n");

                    return -1;

                default:

                    cpu_abort(env, "Unknown or invalid MMU model\n");

                    return -1;

                }

                break;

            case -2:

                /* Access rights violation */

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x08000000;

                break;

            case -3:

                /* No execute protection violation */

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x10000000;

                break;

            case -4:

                /* Direct store exception */

                /* No code fetch is allowed in direct-store areas */

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x10000000;

                break;

#if defined(TARGET_PPC64)

            case -5:

                /* No match in segment table */

                env->exception_index = POWERPC_EXCP_ISEG;

                env->error_code = 0;

                break;

#endif

            }

        } else {

            switch (ret) {

            case -1:

                /* No matches in page tables or TLB */

                switch (env->mmu_model) {

                case POWERPC_MMU_SOFT_6xx:

                    if (rw == 1) {

                        env->exception_index = POWERPC_EXCP_DSTLB;

                        env->error_code = 1 << 16;

                    } else {

                        env->exception_index = POWERPC_EXCP_DLTLB;

                        env->error_code = 0;

                    }

                    env->spr[SPR_DMISS] = address;

                    env->spr[SPR_DCMP] = 0x80000000 | ctx.ptem;

                tlb_miss:

                    env->error_code |= ctx.key << 19;

                    env->spr[SPR_HASH1] = ctx.pg_addr[0];

                    env->spr[SPR_HASH2] = ctx.pg_addr[1];

                    break;

                case POWERPC_MMU_SOFT_74xx:

                    if (rw == 1) {

                        env->exception_index = POWERPC_EXCP_DSTLB;

                    } else {

                        env->exception_index = POWERPC_EXCP_DLTLB;

                    }

                tlb_miss_74xx:

                    /* Implement LRU algorithm */

                    env->error_code = ctx.key << 19;

                    env->spr[SPR_TLBMISS] = (address & ~((target_ulong)0x3)) |

                        ((env->last_way + 1) & (env->nb_ways - 1));

                    env->spr[SPR_PTEHI] = 0x80000000 | ctx.ptem;

                    break;

                case POWERPC_MMU_SOFT_4xx:

                case POWERPC_MMU_SOFT_4xx_Z:

                    env->exception_index = POWERPC_EXCP_DTLB;

                    env->error_code = 0;

                    env->spr[SPR_40x_DEAR] = address;

                    if (rw)

                        env->spr[SPR_40x_ESR] = 0x00800000;

                    else

                        env->spr[SPR_40x_ESR] = 0x00000000;

                    break;

                case POWERPC_MMU_32B:

#if defined(TARGET_PPC64)

                case POWERPC_MMU_64B:

                case POWERPC_MMU_64BRIDGE:

#endif

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1)

                        env->spr[SPR_DSISR] = 0x42000000;

                    else

                        env->spr[SPR_DSISR] = 0x40000000;

                    break;

                case POWERPC_MMU_601:

                    /* XXX: TODO */

                    cpu_abort(env, "MMU model not implemented\n");

                    return -1;

                case POWERPC_MMU_BOOKE:

                    /* XXX: TODO */

                    cpu_abort(env, "MMU model not implemented\n");

                    return -1;

                case POWERPC_MMU_BOOKE_FSL:

                    /* XXX: TODO */

                    cpu_abort(env, "MMU model not implemented\n");

                    return -1;

                case POWERPC_MMU_REAL_4xx:

                    cpu_abort(env, "PowerPC 401 should never raise any MMU "

                              "exceptions\n");

                    return -1;

                default:

                    cpu_abort(env, "Unknown or invalid MMU model\n");

                    return -1;

                }

                break;

            case -2:

                /* Access rights violation */

                env->exception_index = POWERPC_EXCP_DSI;

                env->error_code = 0;

                env->spr[SPR_DAR] = address;

                if (rw == 1)

                    env->spr[SPR_DSISR] = 0x0A000000;

                else

                    env->spr[SPR_DSISR] = 0x08000000;

                break;

            case -4:

                /* Direct store exception */

                switch (access_type) {

                case ACCESS_FLOAT:

                    /* Floating point load/store */

                    env->exception_index = POWERPC_EXCP_ALIGN;

                    env->error_code = POWERPC_EXCP_ALIGN_FP;

                    env->spr[SPR_DAR] = address;

                    break;

                case ACCESS_RES:

                    /* lwarx, ldarx or stwcx. */

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1)

                        env->spr[SPR_DSISR] = 0x06000000;

                    else

                        env->spr[SPR_DSISR] = 0x04000000;

                    break;

                case ACCESS_EXT:

                    /* eciwx or ecowx */

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1)

                        env->spr[SPR_DSISR] = 0x06100000;

                    else

                        env->spr[SPR_DSISR] = 0x04100000;

                    break;

                default:

                    printf("DSI: invalid exception (%d)\n", ret);

                    env->exception_index = POWERPC_EXCP_PROGRAM;

                    env->error_code =

                        POWERPC_EXCP_INVAL | POWERPC_EXCP_INVAL_INVAL;

                    env->spr[SPR_DAR] = address;

                    break;

                }

                break;

#if defined(TARGET_PPC64)

            case -5:

                /* No match in segment table */

                env->exception_index = POWERPC_EXCP_DSEG;

                env->error_code = 0;

                env->spr[SPR_DAR] = address;

                break;

#endif

            }

        }

#if 0

        printf("%s: set exception to %d %02x\n", __func__,

               env->exception, env->error_code);

#endif

        ret = 1;

    }

    return ret;

}


static inline void writer_print_string(WriterContext *wctx,

                                       const char *key, const char *val)

{

    wctx->writer->print_string(wctx, key, val);

    wctx->nb_item++;

}


static av_cold int cinvideo_decode_init(AVCodecContext *avctx)

{

    CinVideoContext *cin = avctx->priv_data;

    unsigned int i;

    cin->avctx = avctx;

    avctx->pix_fmt = AV_PIX_FMT_PAL8;

    cin->frame.data[0] = NULL;

    cin->bitmap_size = avctx->width * avctx->height;

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

        cin->bitmap_table[i] = av_mallocz(cin->bitmap_size);

        if (!cin->bitmap_table[i])

            av_log(avctx, AV_LOG_ERROR, "Can't allocate bitmap buffers.\n");

    }

    return 0;

}


static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,

                    unsigned *nb_files_alloc)

{

    ConcatContext *cat = avf->priv_data;

    ConcatFile *file;

    char *url;

    size_t url_len;

    url_len = strlen(avf->filename) + strlen(filename) + 16;

    if (!(url = av_malloc(url_len)))

        return AVERROR(ENOMEM);

    ff_make_absolute_url(url, url_len, avf->filename, filename);

    av_free(filename);

    if (cat->nb_files >= *nb_files_alloc) {

        unsigned n = FFMAX(*nb_files_alloc * 2, 16);

        ConcatFile *new_files;

        if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||

            !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))

            return AVERROR(ENOMEM);

        cat->files = new_files;

        *nb_files_alloc = n;

    }

    file = &cat->files[cat->nb_files++];

    memset(file, 0, sizeof(*file));

    *rfile = file;

    file->url        = url;

    file->start_time = AV_NOPTS_VALUE;

    file->duration   = AV_NOPTS_VALUE;

    return 0;

}


int kvm_arch_remove_hw_breakpoint(target_ulong addr, target_ulong len, int type)

{

    return -EINVAL;

}


static double compute_target_time(double frame_current_pts, VideoState *is)

{

    double delay, sync_threshold, diff;

    /* compute nominal delay */

    delay = frame_current_pts - is->frame_last_pts;

    if (delay <= 0 || delay >= 10.0) {

        /* if incorrect delay, use previous one */

        delay = is->frame_last_delay;

    } else {

        is->frame_last_delay = delay;

    }

    is->frame_last_pts = frame_current_pts;

    /* update delay to follow master synchronisation source */

    if (((is->av_sync_type == AV_SYNC_AUDIO_MASTER && is->audio_st) ||

         is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {

        /* if video is slave, we try to correct big delays by

           duplicating or deleting a frame */

        diff = get_video_clock(is) - get_master_clock(is);

        /* skip or repeat frame. We take into account the

           delay to compute the threshold. I still don't know

           if it is the best guess */

        sync_threshold = FFMAX(AV_SYNC_THRESHOLD, delay);

        if (fabs(diff) < AV_NOSYNC_THRESHOLD) {

            if (diff <= -sync_threshold)

                delay = 0;

            else if (diff >= sync_threshold)

                delay = 2 * delay;

        }

    }

    is->frame_timer += delay;

    av_log(NULL, AV_LOG_TRACE, "video: delay=%0.3f pts=%0.3f A-V=%f\n",

            delay, frame_current_pts, -diff);

    return is->frame_timer;

}


long target_mmap(target_ulong start, target_ulong len, int prot,

                 int flags, int fd, target_ulong offset)

{

    target_ulong ret, end, real_start, real_end, retaddr, host_offset, host_len;

    long host_start;

#if defined(__alpha__) || defined(__sparc__) || defined(__x86_64__) || \

        defined(__ia64) || defined(__mips__)

    static target_ulong last_start = 0x40000000;

#elif defined(__CYGWIN__)

    /* Cygwin doesn't have a whole lot of address space.  */

    static target_ulong last_start = 0x18000000;

#endif

#ifdef DEBUG_MMAP

    {

        printf("mmap: start=0x%lx len=0x%lx prot=%c%c%c flags=",

               start, len,

               prot & PROT_READ ? 'r' : '-',

               prot & PROT_WRITE ? 'w' : '-',

               prot & PROT_EXEC ? 'x' : '-');

        if (flags & MAP_FIXED)

            printf("MAP_FIXED ");

        if (flags & MAP_ANONYMOUS)

            printf("MAP_ANON ");

        switch(flags & MAP_TYPE) {

        case MAP_PRIVATE:

            printf("MAP_PRIVATE ");

            break;

        case MAP_SHARED:

            printf("MAP_SHARED ");

            break;

        default:

            printf("[MAP_TYPE=0x%x] ", flags & MAP_TYPE);

            break;

        }

        printf("fd=%d offset=%lx\n", fd, offset);

    }

#endif

    if (offset & ~TARGET_PAGE_MASK) {

        errno = EINVAL;

        return -1;

    }

    len = TARGET_PAGE_ALIGN(len);

    if (len == 0)

        return start;

    real_start = start & qemu_host_page_mask;

    if (!(flags & MAP_FIXED)) {

#if defined(__alpha__) || defined(__sparc__) || defined(__x86_64__) || \

    defined(__ia64) || defined(__mips__) || defined(__CYGWIN__)

        /* tell the kernel to search at the same place as i386 */

        if (real_start == 0) {

            real_start = last_start;

            last_start += HOST_PAGE_ALIGN(len);

        }

#endif

        if (0 && qemu_host_page_size != qemu_real_host_page_size) {

            /* NOTE: this code is only for debugging with '-p' option */

            /* ??? Can also occur when TARGET_PAGE_SIZE > host page size.  */

            /* reserve a memory area */

            /* ??? This needs fixing for remapping.  */

abort();

            host_len = HOST_PAGE_ALIGN(len) + qemu_host_page_size - TARGET_PAGE_SIZE;

            real_start = (long)mmap(g2h(real_start), host_len, PROT_NONE,

                                    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

            if (real_start == -1)

                return real_start;

            real_end = real_start + host_len;

            start = HOST_PAGE_ALIGN(real_start);

            end = start + HOST_PAGE_ALIGN(len);

            if (start > real_start)

                munmap((void *)real_start, start - real_start);

            if (end < real_end)

                munmap((void *)end, real_end - end);

            /* use it as a fixed mapping */

            flags |= MAP_FIXED;

        } else {

            /* if not fixed, no need to do anything */

            host_offset = offset & qemu_host_page_mask;

            host_len = len + offset - host_offset;

            host_start = (long)mmap(real_start ? g2h(real_start) : NULL,

                                    host_len, prot, flags, fd, host_offset);

            if (host_start == -1)

                return host_start;

            /* update start so that it points to the file position at 'offset' */

            if (!(flags & MAP_ANONYMOUS))

                host_start += offset - host_offset;

            start = h2g(host_start);

            goto the_end1;

        }

    }

    if (start & ~TARGET_PAGE_MASK) {

        errno = EINVAL;

        return -1;

    }

    end = start + len;

    real_end = HOST_PAGE_ALIGN(end);

    /* worst case: we cannot map the file because the offset is not

       aligned, so we read it */

    if (!(flags & MAP_ANONYMOUS) &&

        (offset & ~qemu_host_page_mask) != (start & ~qemu_host_page_mask)) {

        /* msync() won't work here, so we return an error if write is

           possible while it is a shared mapping */

        if ((flags & MAP_TYPE) == MAP_SHARED &&

            (prot & PROT_WRITE)) {

            errno = EINVAL;

            return -1;

        }

        retaddr = target_mmap(start, len, prot | PROT_WRITE,

                              MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS,

                              -1, 0);

        if (retaddr == -1)

            return retaddr;

        pread(fd, g2h(start), len, offset);

        if (!(prot & PROT_WRITE)) {

            ret = target_mprotect(start, len, prot);

            if (ret != 0)

                return ret;

        }

        goto the_end;

    }

    /* handle the start of the mapping */

    if (start > real_start) {

        if (real_end == real_start + qemu_host_page_size) {

            /* one single host page */

            ret = mmap_frag(real_start, start, end,

                            prot, flags, fd, offset);

            if (ret == -1)

                return ret;

            goto the_end1;

        }

        ret = mmap_frag(real_start, start, real_start + qemu_host_page_size,

                        prot, flags, fd, offset);

        if (ret == -1)

            return ret;

        real_start += qemu_host_page_size;

    }

    /* handle the end of the mapping */

    if (end < real_end) {

        ret = mmap_frag(real_end - qemu_host_page_size,

                        real_end - qemu_host_page_size, real_end,

                        prot, flags, fd,

                        offset + real_end - qemu_host_page_size - start);

        if (ret == -1)

            return ret;

        real_end -= qemu_host_page_size;

    }

    /* map the middle (easier) */

    if (real_start < real_end) {

        unsigned long offset1;

	if (flags & MAP_ANONYMOUS)

	  offset1 = 0;

	else

	  offset1 = offset + real_start - start;

        ret = (long)mmap(g2h(real_start), real_end - real_start,

                         prot, flags, fd, offset1);

        if (ret == -1)

            return ret;

    }

 the_end1:

    page_set_flags(start, start + len, prot | PAGE_VALID);

 the_end:

#ifdef DEBUG_MMAP

    printf("ret=0x%lx\n", (long)start);

    page_dump(stdout);

    printf("\n");

#endif

    return start;

}


read_f(int argc, char **argv)

{

	struct timeval t1, t2;

	int Cflag = 0, pflag = 0, qflag = 0, vflag = 0;

	int Pflag = 0, sflag = 0, lflag = 0;

	int c, cnt;

	char *buf;

	int64_t offset;

	int count;

        /* Some compilers get confused and warn if this is not initialized.  */

        int total = 0;

	int pattern = 0, pattern_offset = 0, pattern_count = 0;

	while ((c = getopt(argc, argv, "Cl:pP:qs:v")) != EOF) {

		switch (c) {

		case 'C':

			Cflag = 1;

			break;

		case 'l':

			lflag = 1;

			pattern_count = cvtnum(optarg);

			if (pattern_count < 0) {

				printf("non-numeric length argument -- %s\n", optarg);

				return 0;

			}

			break;

		case 'p':

			pflag = 1;

			break;

		case 'P':

			Pflag = 1;

			pattern = atoi(optarg);

			break;

		case 'q':

			qflag = 1;

			break;

		case 's':

			sflag = 1;

			pattern_offset = cvtnum(optarg);

			if (pattern_offset < 0) {

				printf("non-numeric length argument -- %s\n", optarg);

				return 0;

			}

			break;

		case 'v':

			vflag = 1;

			break;

		default:

			return command_usage(&read_cmd);

		}

	}

	if (optind != argc - 2)

		return command_usage(&read_cmd);

	offset = cvtnum(argv[optind]);

	if (offset < 0) {

		printf("non-numeric length argument -- %s\n", argv[optind]);

		return 0;

	}

	optind++;

	count = cvtnum(argv[optind]);

	if (count < 0) {

		printf("non-numeric length argument -- %s\n", argv[optind]);

		return 0;

	}

    if (!Pflag && (lflag || sflag)) {

        return command_usage(&read_cmd);

    }

    if (!lflag) {

        pattern_count = count - pattern_offset;

    }

    if ((pattern_count < 0) || (pattern_count + pattern_offset > count))  {

        printf("pattern verfication range exceeds end of read data\n");

        return 0;

    }

	if (!pflag)

		if (offset & 0x1ff) {

			printf("offset %lld is not sector aligned\n",

				(long long)offset);

			return 0;

		if (count & 0x1ff) {

			printf("count %d is not sector aligned\n",

				count);

			return 0;

		}

	}

	buf = qemu_io_alloc(count, 0xab);

	gettimeofday(&t1, NULL);

	if (pflag)

		cnt = do_pread(buf, offset, count, &total);

	else

		cnt = do_read(buf, offset, count, &total);

	gettimeofday(&t2, NULL);

	if (cnt < 0) {

		printf("read failed: %s\n", strerror(-cnt));

		return 0;

	}

	if (Pflag) {

		void* cmp_buf = malloc(pattern_count);

		memset(cmp_buf, pattern, pattern_count);

		if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) {

			printf("Pattern verification failed at offset %lld, "

				"%d bytes\n",

				(long long) offset + pattern_offset, pattern_count);

		}

		free(cmp_buf);

	}

	if (qflag)

		return 0;

        if (vflag)

		dump_buffer(buf, offset, count);

	/* Finally, report back -- -C gives a parsable format */

	t2 = tsub(t2, t1);

	print_report("read", &t2, offset, count, total, cnt, Cflag);

	qemu_io_free(buf);

	return 0;

}


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

{

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

    struct e1000_rx_desc desc;

    target_phys_addr_t base;

    unsigned int n, rdt;

    uint32_t rdh_start;

    uint16_t vlan_special = 0;

    uint8_t vlan_status = 0, vlan_offset = 0;

    uint8_t min_buf[MIN_BUF_SIZE];

    size_t desc_offset;

    size_t desc_size;

    size_t total_size;

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

        return -1;

    /* Pad to minimum Ethernet frame length */

    if (size < sizeof(min_buf)) {

        memcpy(min_buf, buf, size);

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

        buf = min_buf;

        size = sizeof(min_buf);

    }

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

        return size;

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

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

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

        vlan_status = E1000_RXD_STAT_VP;

        vlan_offset = 4;

        size -= 4;

    }

    rdh_start = s->mac_reg[RDH];

    desc_offset = 0;

    total_size = size + fcs_len(s);

    do {

        desc_size = total_size - desc_offset;

        if (desc_size > s->rxbuf_size) {

            desc_size = s->rxbuf_size;

        }

        if (s->mac_reg[RDH] == s->mac_reg[RDT] && s->check_rxov) {

            /* Discard all data written so far */

            s->mac_reg[RDH] = rdh_start;

            set_ics(s, 0, E1000_ICS_RXO);

            return -1;

        }

        base = ((uint64_t)s->mac_reg[RDBAH] << 32) + s->mac_reg[RDBAL] +

               sizeof(desc) * s->mac_reg[RDH];

        cpu_physical_memory_read(base, (void *)&desc, sizeof(desc));

        desc.special = vlan_special;

        desc.status |= (vlan_status | E1000_RXD_STAT_DD);

        if (desc.buffer_addr) {

            if (desc_offset < size) {

                size_t copy_size = size - desc_offset;

                if (copy_size > s->rxbuf_size) {

                    copy_size = s->rxbuf_size;

                }

                cpu_physical_memory_write(le64_to_cpu(desc.buffer_addr),

                                          (void *)(buf + desc_offset + vlan_offset),

                                          copy_size);

            }

            desc_offset += desc_size;

            desc.length = cpu_to_le16(desc_size);

            if (desc_offset >= total_size) {

                desc.status |= E1000_RXD_STAT_EOP | E1000_RXD_STAT_IXSM;

            } else {

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

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

                desc.status &= ~E1000_RXD_STAT_EOP;

            }

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

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

        }

        cpu_physical_memory_write(base, (void *)&desc, sizeof(desc));

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

            s->mac_reg[RDH] = 0;

        s->check_rxov = 1;

        /* see comment in start_xmit; same here */

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

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

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

            set_ics(s, 0, E1000_ICS_RXO);

            return -1;

        }

    } while (desc_offset < total_size);

    s->mac_reg[GPRC]++;

    s->mac_reg[TPR]++;

    /* TOR - Total Octets Received:

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

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

     */

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

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

        s->mac_reg[TORH]++;

    s->mac_reg[TORL] = n;

    n = E1000_ICS_RXT0;

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

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

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

        s->rxbuf_min_shift)

        n |= E1000_ICS_RXDMT0;

    set_ics(s, 0, n);

    return size;

}


static void ehci_update_frindex(EHCIState *ehci, int uframes)

{

    int i;

    if (!ehci_enabled(ehci) && ehci->pstate == EST_INACTIVE) {

        return;

    }

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

        ehci->frindex++;

        if (ehci->frindex == 0x00002000) {

            ehci_raise_irq(ehci, USBSTS_FLR);

        }

        if (ehci->frindex == 0x00004000) {

            ehci_raise_irq(ehci, USBSTS_FLR);

            ehci->frindex = 0;

            if (ehci->usbsts_frindex >= 0x00004000) {

                ehci->usbsts_frindex -= 0x00004000;

            } else {

                ehci->usbsts_frindex = 0;

            }

        }

    }

}


static int tee_write_header(AVFormatContext *avf)

{

    TeeContext *tee = avf->priv_data;

    unsigned nb_slaves = 0, i;

    const char *filename = avf->filename;

    char *slaves[MAX_SLAVES];

    int ret;

    while (*filename) {

        if (nb_slaves == MAX_SLAVES) {

            av_log(avf, AV_LOG_ERROR, "Maximum %d slave muxers reached.\n",

                   MAX_SLAVES);

            ret = AVERROR_PATCHWELCOME;

            goto fail;

        }

        if (!(slaves[nb_slaves++] = av_get_token(&filename, slave_delim))) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        if (strspn(filename, slave_delim))

            filename++;

    }

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

        if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0)

            goto fail;

        log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);

        av_freep(&slaves[i]);

    }

    tee->nb_slaves = nb_slaves;

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

        int j, mapped = 0;

        for (j = 0; j < tee->nb_slaves; j++)

            mapped += tee->slaves[j].stream_map[i] >= 0;

        if (!mapped)

            av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "

                   "to any slave.\n", i);

    }

    return 0;

fail:

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

        av_freep(&slaves[i]);

    close_slaves(avf);

    return ret;

}


static int css_add_virtual_chpid(uint8_t cssid, uint8_t chpid, uint8_t type)

{

    CssImage *css;

    trace_css_chpid_add(cssid, chpid, type);

    if (cssid > MAX_CSSID) {

        return -EINVAL;

    }

    css = channel_subsys.css[cssid];

    if (!css) {

        return -EINVAL;

    }

    if (css->chpids[chpid].in_use) {

        return -EEXIST;

    }

    css->chpids[chpid].in_use = 1;

    css->chpids[chpid].type = type;

    css->chpids[chpid].is_virtual = 1;

    css_generate_chp_crws(cssid, chpid);

    return 0;

}


iscsi_readcapacity10_cb(struct iscsi_context *iscsi, int status,

                        void *command_data, void *opaque)

{

    struct IscsiTask *itask = opaque;

    struct scsi_readcapacity10 *rc10;

    struct scsi_task *task = command_data;

    if (status != 0) {

        error_report("iSCSI: Failed to read capacity of iSCSI lun. %s",

                     iscsi_get_error(iscsi));

        itask->status   = 1;

        itask->complete = 1;

        scsi_free_scsi_task(task);

        return;

    }

    rc10 = scsi_datain_unmarshall(task);

    if (rc10 == NULL) {

        error_report("iSCSI: Failed to unmarshall readcapacity10 data.");

        itask->status   = 1;

        itask->complete = 1;

        scsi_free_scsi_task(task);

        return;

    }

    itask->iscsilun->block_size = rc10->block_size;

    if (rc10->lba == 0) {

        /* blank disk loaded */

        itask->iscsilun->num_blocks = 0;

    } else {

        itask->iscsilun->num_blocks = rc10->lba + 1;

    }

    itask->bs->total_sectors    = itask->iscsilun->num_blocks *

                               itask->iscsilun->block_size / BDRV_SECTOR_SIZE ;

    itask->status   = 0;

    itask->complete = 1;

    scsi_free_scsi_task(task);

}


bool qemu_net_queue_flush(NetQueue *queue)

{

    while (!QTAILQ_EMPTY(&queue->packets)) {

        NetPacket *packet;

        int ret;

        packet = QTAILQ_FIRST(&queue->packets);

        QTAILQ_REMOVE(&queue->packets, packet, entry);

        ret = qemu_net_queue_deliver(queue,

                                     packet->sender,

                                     packet->flags,

                                     packet->data,

                                     packet->size);

        if (ret == 0) {

            queue->nq_count++;

            QTAILQ_INSERT_HEAD(&queue->packets, packet, entry);

            return false;

        }

        if (packet->sent_cb) {

            packet->sent_cb(packet->sender, ret);

        }

        g_free(packet);

    }

    return true;

}


void ffserver_parse_acl_row(FFServerStream *stream, FFServerStream* feed,
                            FFServerIPAddressACL *ext_acl,
                            const char *p, const char *filename, int line_num)
{
    char arg[1024];
    FFServerIPAddressACL acl;
    FFServerIPAddressACL *nacl;
    FFServerIPAddressACL **naclp;
    ffserver_get_arg(arg, sizeof(arg), &p);
    if (av_strcasecmp(arg, "allow") == 0)
        acl.action = IP_ALLOW;
    else if (av_strcasecmp(arg, "deny") == 0)
        acl.action = IP_DENY;
    else {
        fprintf(stderr, "%s:%d: ACL action '%s' should be ALLOW or DENY.\n",
                filename, line_num, arg);
    ffserver_get_arg(arg, sizeof(arg), &p);
    if (resolve_host(&acl.first, arg)) {
        fprintf(stderr,
                "%s:%d: ACL refers to invalid host or IP address '%s'\n",
                filename, line_num, arg);
    acl.last = acl.first;
    ffserver_get_arg(arg, sizeof(arg), &p);
    if (arg[0]) {
        if (resolve_host(&acl.last, arg)) {
            fprintf(stderr,
                    "%s:%d: ACL refers to invalid host or IP address '%s'\n",
                    filename, line_num, arg);
    nacl = av_mallocz(sizeof(*nacl));
    naclp = 0;
    acl.next = 0;
    *nacl = acl;
    if (stream)
        naclp = &stream->acl;
    else if (feed)
        naclp = &feed->acl;
    else if (ext_acl)
        naclp = &ext_acl;
    else
        fprintf(stderr, "%s:%d: ACL found not in <Stream> or <Feed>\n",
                filename, line_num);
    if (naclp) {
        while (*naclp)
            naclp = &(*naclp)->next;
        *naclp = nacl;
    } else
        av_free(nacl);
bail:
  return;


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

                           BdrvCheckMode fix, uint16_t **refcount_table,

                           int64_t *nb_clusters)

{

    BDRVQcowState *s = bs->opaque;

    int64_t i, size;

    int ret;

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

        uint64_t offset, cluster;

        offset = s->refcount_table[i];

        cluster = offset >> s->cluster_bits;

        /* Refcount blocks are cluster aligned */

        if (offset_into_cluster(s, offset)) {

            fprintf(stderr, "ERROR refcount block %" PRId64 " is not "

                "cluster aligned; refcount table entry corrupted\n", i);

            res->corruptions++;

            continue;

        }

        if (cluster >= *nb_clusters) {

            fprintf(stderr, "%s refcount block %" PRId64 " is outside image\n",

                    fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR", i);

            if (fix & BDRV_FIX_ERRORS) {

                int64_t old_nb_clusters = *nb_clusters;

                uint16_t *new_refcount_table;

                if (offset > INT64_MAX - s->cluster_size) {

                    ret = -EINVAL;

                    goto resize_fail;

                }

                ret = bdrv_truncate(bs->file, offset + s->cluster_size);

                if (ret < 0) {

                    goto resize_fail;

                }

                size = bdrv_getlength(bs->file);

                if (size < 0) {

                    ret = size;

                    goto resize_fail;

                }

                *nb_clusters = size_to_clusters(s, size);

                assert(*nb_clusters >= old_nb_clusters);

                new_refcount_table = g_try_realloc(*refcount_table,

                                                   *nb_clusters *

                                                   sizeof(**refcount_table));

                if (!new_refcount_table) {

                    *nb_clusters = old_nb_clusters;

                    res->check_errors++;

                    return -ENOMEM;

                }

                *refcount_table = new_refcount_table;

                memset(*refcount_table + old_nb_clusters, 0,

                       (*nb_clusters - old_nb_clusters) *

                       sizeof(**refcount_table));

                if (cluster >= *nb_clusters) {

                    ret = -EINVAL;

                    goto resize_fail;

                }

                res->corruptions_fixed++;

                ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                                    offset, s->cluster_size);

                if (ret < 0) {

                    return ret;

                }

                /* No need to check whether the refcount is now greater than 1:

                 * This area was just allocated and zeroed, so it can only be

                 * exactly 1 after inc_refcounts() */

                continue;

resize_fail:

                res->corruptions++;

                fprintf(stderr, "ERROR could not resize image: %s\n",

                        strerror(-ret));

            } else {

                res->corruptions++;

            }

            continue;

        }

        if (offset != 0) {

            ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                                offset, s->cluster_size);

            if (ret < 0) {

                return ret;

            }

            if ((*refcount_table)[cluster] != 1) {

                fprintf(stderr, "%s refcount block %" PRId64

                    " refcount=%d\n",

                    fix & BDRV_FIX_ERRORS ? "Repairing" :

                                            "ERROR",

                    i, (*refcount_table)[cluster]);

                if (fix & BDRV_FIX_ERRORS) {

                    int64_t new_offset;

                    new_offset = realloc_refcount_block(bs, i, offset);

                    if (new_offset < 0) {

                        res->corruptions++;

                        continue;

                    }

                    /* update refcounts */

                    if ((new_offset >> s->cluster_bits) >= *nb_clusters) {

                        /* increase refcount_table size if necessary */

                        int old_nb_clusters = *nb_clusters;

                        *nb_clusters = (new_offset >> s->cluster_bits) + 1;

                        *refcount_table = g_renew(uint16_t, *refcount_table,

                                                  *nb_clusters);

                        memset(&(*refcount_table)[old_nb_clusters], 0,

                               (*nb_clusters - old_nb_clusters) *

                               sizeof(**refcount_table));

                    }

                    (*refcount_table)[cluster]--;

                    ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                                        new_offset, s->cluster_size);

                    if (ret < 0) {

                        return ret;

                    }

                    res->corruptions_fixed++;

                } else {

                    res->corruptions++;

                }

            }

        }

    }

    return 0;

}


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

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

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

{

    const ARMCPRegInfo *ri;

    TCGv_i64 tcg_rt;

    ri = get_arm_cp_reginfo(s->cp_regs,

                            ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP,

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

    if (!ri) {

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

         * unimplemented feature.

         */

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

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

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

        unallocated_encoding(s);

        return;

    }

    /* Check access permissions */

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

        unallocated_encoding(s);

        return;

    }

    if (ri->accessfn) {

        /* Emit code to perform further access permissions checks at

         * runtime; this may result in an exception.

         */

        TCGv_ptr tmpptr;

        gen_a64_set_pc_im(s->pc - 4);

        tmpptr = tcg_const_ptr(ri);

        gen_helper_access_check_cp_reg(cpu_env, tmpptr);

        tcg_temp_free_ptr(tmpptr);

    }

    /* Handle special cases first */

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

    case ARM_CP_NOP:

        return;

    case ARM_CP_NZCV:

        tcg_rt = cpu_reg(s, rt);

        if (isread) {

            gen_get_nzcv(tcg_rt);

        } else {

            gen_set_nzcv(tcg_rt);

        }

        return;

    case ARM_CP_CURRENTEL:

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

         * guaranteed to be constant by the tb flags.

         */

        tcg_rt = cpu_reg(s, rt);

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

        return;

    default:

        break;

    }

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

        gen_io_start();

    }

    tcg_rt = cpu_reg(s, rt);

    if (isread) {

        if (ri->type & ARM_CP_CONST) {

            tcg_gen_movi_i64(tcg_rt, ri->resetvalue);

        } else if (ri->readfn) {

            TCGv_ptr tmpptr;

            tmpptr = tcg_const_ptr(ri);

            gen_helper_get_cp_reg64(tcg_rt, cpu_env, tmpptr);

            tcg_temp_free_ptr(tmpptr);

        } else {

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

        }

    } else {

        if (ri->type & ARM_CP_CONST) {

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

            return;

        } else if (ri->writefn) {

            TCGv_ptr tmpptr;

            tmpptr = tcg_const_ptr(ri);

            gen_helper_set_cp_reg64(cpu_env, tmpptr, tcg_rt);

            tcg_temp_free_ptr(tmpptr);

        } else {

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

        }

    }

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

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

        gen_io_end();

        s->is_jmp = DISAS_UPDATE;

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

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

         * but allow this to be suppressed by the register definition

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

         */

        s->is_jmp = DISAS_UPDATE;

    }

}


soread(so)

	struct socket *so;

{

	int n, nn, lss, total;

	struct sbuf *sb = &so->so_snd;

	int len = sb->sb_datalen - sb->sb_cc;

	struct iovec iov[2];

	int mss = so->so_tcpcb->t_maxseg;

	DEBUG_CALL("soread");

	DEBUG_ARG("so = %lx", (long )so);

	/*

	 * No need to check if there's enough room to read.

	 * soread wouldn't have been called if there weren't

	 */

	len = sb->sb_datalen - sb->sb_cc;

	iov[0].iov_base = sb->sb_wptr;

	if (sb->sb_wptr < sb->sb_rptr) {

		iov[0].iov_len = sb->sb_rptr - sb->sb_wptr;

		/* Should never succeed, but... */

		if (iov[0].iov_len > len)

		   iov[0].iov_len = len;

		if (iov[0].iov_len > mss)

		   iov[0].iov_len -= iov[0].iov_len%mss;

		n = 1;

	} else {

		iov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_wptr;

		/* Should never succeed, but... */

		if (iov[0].iov_len > len) iov[0].iov_len = len;

		len -= iov[0].iov_len;

		if (len) {

			iov[1].iov_base = sb->sb_data;

			iov[1].iov_len = sb->sb_rptr - sb->sb_data;

			if(iov[1].iov_len > len)

			   iov[1].iov_len = len;

			total = iov[0].iov_len + iov[1].iov_len;

			if (total > mss) {

				lss = total%mss;

				if (iov[1].iov_len > lss) {

					iov[1].iov_len -= lss;

					n = 2;

				} else {

					lss -= iov[1].iov_len;

					iov[0].iov_len -= lss;

					n = 1;

				}

			} else

				n = 2;

		} else {

			if (iov[0].iov_len > mss)

			   iov[0].iov_len -= iov[0].iov_len%mss;

			n = 1;

		}

	}

#ifdef HAVE_READV

	nn = readv(so->s, (struct iovec *)iov, n);

	DEBUG_MISC((dfd, " ... read nn = %d bytes\n", nn));

#else

	nn = recv(so->s, iov[0].iov_base, iov[0].iov_len,0);

#endif

	if (nn <= 0) {

		if (nn < 0 && (errno == EINTR || errno == EAGAIN))

			return 0;

		else {

			DEBUG_MISC((dfd, " --- soread() disconnected, nn = %d, errno = %d-%s\n", nn, errno,strerror(errno)));

			sofcantrcvmore(so);

			tcp_sockclosed(sototcpcb(so));

			return -1;

		}

	}

#ifndef HAVE_READV

	/*

	 * If there was no error, try and read the second time round

	 * We read again if n = 2 (ie, there's another part of the buffer)

	 * and we read as much as we could in the first read

	 * We don't test for <= 0 this time, because there legitimately

	 * might not be any more data (since the socket is non-blocking),

	 * a close will be detected on next iteration.

	 * A return of -1 wont (shouldn't) happen, since it didn't happen above

	 */

	if (n == 2 && nn == iov[0].iov_len) {

            int ret;

            ret = recv(so->s, iov[1].iov_base, iov[1].iov_len,0);

            if (ret > 0)

                nn += ret;

        }

	DEBUG_MISC((dfd, " ... read nn = %d bytes\n", nn));

#endif

	/* Update fields */

	sb->sb_cc += nn;

	sb->sb_wptr += nn;

	if (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))

		sb->sb_wptr -= sb->sb_datalen;

	return nn;

}


static void decode_422_bitstream(HYuvContext *s, int count)

{

    int i;

    count /= 2;

    if (count >= (get_bits_left(&s->gb)) / (31 * 4)) {

        for (i = 0; i < count && get_bits_left(&s->gb) > 0; i++) {

            READ_2PIX(s->temp[0][2 * i    ], s->temp[1][i], 1);

            READ_2PIX(s->temp[0][2 * i + 1], s->temp[2][i], 2);

        }

    } else {

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

            READ_2PIX(s->temp[0][2 * i    ], s->temp[1][i], 1);

            READ_2PIX(s->temp[0][2 * i + 1], s->temp[2][i], 2);

        }

    }

}


static int dv_extract_audio(uint8_t* frame, uint8_t* ppcm[4],
                            const DVprofile *sys)
{
    int size, chan, i, j, d, of, smpls, freq, quant, half_ch;
    uint16_t lc, rc;
    const uint8_t* as_pack;
    uint8_t *pcm, ipcm;
    as_pack = dv_extract_pack(frame, dv_audio_source);
    if (!as_pack)    /* No audio ? */
        return 0;
    smpls =  as_pack[1] & 0x3f;       /* samples in this frame - min. samples */
    freq  = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */
    quant =  as_pack[4] & 0x07;       /* 0 - 16bit linear, 1 - 12bit nonlinear */
    if (quant > 1)
        return -1; /* unsupported quantization */
    if (freq >= FF_ARRAY_ELEMS(dv_audio_frequency))
    size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */
    half_ch = sys->difseg_size / 2;
    /* We work with 720p frames split in half, thus even frames have
     * channels 0,1 and odd 2,3. */
    ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0;
    /* for each DIF channel */
    for (chan = 0; chan < sys->n_difchan; chan++) {
        av_assert0(ipcm<4);
        pcm = ppcm[ipcm++];
        if (!pcm)
            break;
        /* for each DIF segment */
        for (i = 0; i < sys->difseg_size; i++) {
            frame += 6 * 80; /* skip DIF segment header */
            if (quant == 1 && i == half_ch) {
                /* next stereo channel (12bit mode only) */
                av_assert0(ipcm<4);
                pcm = ppcm[ipcm++];
                if (!pcm)
                    break;
            /* for each AV sequence */
            for (j = 0; j < 9; j++) {
                for (d = 8; d < 80; d += 2) {
                    if (quant == 0) {  /* 16bit quantization */
                        of = sys->audio_shuffle[i][j] + (d - 8) / 2 * sys->audio_stride;
                        if (of*2 >= size)
                            continue;
                        pcm[of*2]   = frame[d+1]; // FIXME: maybe we have to admit
                        pcm[of*2+1] = frame[d];   //        that DV is a big-endian PCM
                        if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00)
                            pcm[of*2+1] = 0;
                    } else {           /* 12bit quantization */
                        lc = ((uint16_t)frame[d]   << 4) |
                             ((uint16_t)frame[d+2] >> 4);
                        rc = ((uint16_t)frame[d+1] << 4) |
                             ((uint16_t)frame[d+2] & 0x0f);
                        lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc));
                        rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc));
                        of = sys->audio_shuffle[i%half_ch][j] + (d - 8) / 3 * sys->audio_stride;
                        if (of*2 >= size)
                            continue;
                        pcm[of*2]   = lc & 0xff; // FIXME: maybe we have to admit
                        pcm[of*2+1] = lc >> 8;   //        that DV is a big-endian PCM
                        of = sys->audio_shuffle[i%half_ch+half_ch][j] +
                            (d - 8) / 3 * sys->audio_stride;
                        pcm[of*2]   = rc & 0xff; // FIXME: maybe we have to admit
                        pcm[of*2+1] = rc >> 8;   //        that DV is a big-endian PCM
                        ++d;
                frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
    return size;


void ff_mpeg4_encode_picture_header(MpegEncContext *s, int picture_number)

{

    int time_incr;

    int time_div, time_mod;

    if (s->pict_type == AV_PICTURE_TYPE_I) {

        if (!(s->avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {

            if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT)  // HACK, the reference sw is buggy

                mpeg4_encode_visual_object_header(s);

            if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number == 0)  // HACK, the reference sw is buggy

                mpeg4_encode_vol_header(s, 0, 0);

        }

        if (!(s->workaround_bugs & FF_BUG_MS))

            mpeg4_encode_gop_header(s);

    }

    s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;

    put_bits(&s->pb, 16, 0);                /* vop header */

    put_bits(&s->pb, 16, VOP_STARTCODE);    /* vop header */

    put_bits(&s->pb, 2, s->pict_type - 1);  /* pict type: I = 0 , P = 1 */

    time_div  = FFUDIV(s->time, s->avctx->time_base.den);

    time_mod  = FFUMOD(s->time, s->avctx->time_base.den);

    time_incr = time_div - s->last_time_base;

    av_assert0(time_incr >= 0);

    while (time_incr--)

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

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

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

    put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */

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

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

    if (s->pict_type == AV_PICTURE_TYPE_P) {

        put_bits(&s->pb, 1, s->no_rounding);    /* rounding type */

    }

    put_bits(&s->pb, 3, 0);     /* intra dc VLC threshold */

    if (!s->progressive_sequence) {

        put_bits(&s->pb, 1, s->current_picture_ptr->f->top_field_first);

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

    }

    // FIXME sprite stuff

    put_bits(&s->pb, 5, s->qscale);

    if (s->pict_type != AV_PICTURE_TYPE_I)

        put_bits(&s->pb, 3, s->f_code);  /* fcode_for */

    if (s->pict_type == AV_PICTURE_TYPE_B)

        put_bits(&s->pb, 3, s->b_code);  /* fcode_back */

}