matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
                     int is_keyframe, int is_bframe)
{
    int res = 0;
    int track;
    AVStream *st;
    AVPacket *pkt;
    uint8_t *origdata = data;
    int16_t block_time;
    uint32_t *lace_size = NULL;
    int n, flags, laces = 0;
    uint64_t num;
    int stream_index;
    /* first byte(s): tracknum */
    if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
        av_free(origdata);
        return res;
    }
    data += n;
    size -= n;
    /* fetch track from num */
    track = matroska_find_track_by_num(matroska, num);
    if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
        av_log(matroska->ctx, AV_LOG_INFO,
               "Invalid stream %d or size %u\n", track, size);
        av_free(origdata);
        return res;
    }
    stream_index = matroska->tracks[track]->stream_index;
    if (stream_index < 0 || stream_index >= matroska->ctx->nb_streams) {
        av_free(origdata);
        return res;
    }
    st = matroska->ctx->streams[stream_index];
    if (st->discard >= AVDISCARD_ALL) {
        av_free(origdata);
        return res;
    }
    if (duration == AV_NOPTS_VALUE)
        duration = matroska->tracks[track]->default_duration / matroska->time_scale;
    /* block_time (relative to cluster time) */
    block_time = AV_RB16(data);
    data += 2;
    flags = *data++;
    size -= 3;
    if (is_keyframe == -1)
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
    if (matroska->skip_to_keyframe) {
        if (!is_keyframe || st != matroska->skip_to_stream) {
            av_free(origdata);
            return res;
        }
        matroska->skip_to_keyframe = 0;
    }
    switch ((flags & 0x06) >> 1) {
        case 0x0: /* no lacing */
            laces = 1;
            lace_size = av_mallocz(sizeof(int));
            lace_size[0] = size;
            break;
        case 0x1: /* xiph lacing */
        case 0x2: /* fixed-size lacing */
        case 0x3: /* EBML lacing */
            assert(size>0); // size <=3 is checked before size-=3 above
            laces = (*data) + 1;
            data += 1;
            size -= 1;
            lace_size = av_mallocz(laces * sizeof(int));
            switch ((flags & 0x06) >> 1) {
                case 0x1: /* xiph lacing */ {
                    uint8_t temp;
                    uint32_t total = 0;
                    for (n = 0; res == 0 && n < laces - 1; n++) {
                        while (1) {
                            if (size == 0) {
                                res = -1;
                                break;
                            }
                            temp = *data;
                            lace_size[n] += temp;
                            data += 1;
                            size -= 1;
                            if (temp != 0xff)
                                break;
                        }
                        total += lace_size[n];
                    }
                    lace_size[n] = size - total;
                    break;
                }
                case 0x2: /* fixed-size lacing */
                    for (n = 0; n < laces; n++)
                        lace_size[n] = size / laces;
                    break;
                case 0x3: /* EBML lacing */ {
                    uint32_t total;
                    n = matroska_ebmlnum_uint(data, size, &num);
                    if (n < 0) {
                        av_log(matroska->ctx, AV_LOG_INFO,
                               "EBML block data error\n");
                        break;
                    }
                    data += n;
                    size -= n;
                    total = lace_size[0] = num;
                    for (n = 1; res == 0 && n < laces - 1; n++) {
                        int64_t snum;
                        int r;
                        r = matroska_ebmlnum_sint (data, size, &snum);
                        if (r < 0) {
                            av_log(matroska->ctx, AV_LOG_INFO,
                                   "EBML block data error\n");
                            break;
                        }
                        data += r;
                        size -= r;
                        lace_size[n] = lace_size[n - 1] + snum;
                        total += lace_size[n];
                    }
                    lace_size[n] = size - total;
                    break;
                }
            }
            break;
    }
    if (res == 0) {
        uint64_t timecode = AV_NOPTS_VALUE;
        if (cluster_time != (uint64_t)-1
            && (block_time >= 0 || cluster_time >= -block_time))
            timecode = cluster_time + block_time;
        for (n = 0; n < laces; n++) {
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
                st->codec->codec_id == CODEC_ID_COOK ||
                st->codec->codec_id == CODEC_ID_ATRAC3) {
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
                int a = st->codec->block_align;
                int sps = audiotrack->sub_packet_size;
                int cfs = audiotrack->coded_framesize;
                int h = audiotrack->sub_packet_h;
                int y = audiotrack->sub_packet_cnt;
                int w = audiotrack->frame_size;
                int x;
                if (!audiotrack->pkt_cnt) {
                    if (st->codec->codec_id == CODEC_ID_RA_288)
                        for (x=0; x<h/2; x++)
                            memcpy(audiotrack->buf+x*2*w+y*cfs,
                                   data+x*cfs, cfs);
                    else
                        for (x=0; x<w/sps; x++)
                            memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
                    if (++audiotrack->sub_packet_cnt >= h) {
                        audiotrack->sub_packet_cnt = 0;
                        audiotrack->pkt_cnt = h*w / a;
                    }
                }
                while (audiotrack->pkt_cnt) {
                    pkt = av_mallocz(sizeof(AVPacket));
                    av_new_packet(pkt, a);
                    memcpy(pkt->data, audiotrack->buf
                           + a * (h*w / a - audiotrack->pkt_cnt--), a);
                    pkt->pos = pos;
                    pkt->stream_index = stream_index;
                    matroska_queue_packet(matroska, pkt);
                }
            } else {
                int result, offset = 0, ilen, olen, pkt_size = lace_size[n];
                uint8_t *pkt_data = data;
                if (matroska->tracks[track]->encoding_scope & 1) {
                    switch (matroska->tracks[track]->encoding_algo) {
                    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
                        offset = matroska->tracks[track]->encoding_settings_len;
                        break;
                    case MATROSKA_TRACK_ENCODING_COMP_LZO:
                        pkt_data = NULL;
                        do {
                            ilen = lace_size[n];
                            olen = pkt_size *= 3;
                            pkt_data = av_realloc(pkt_data,
                                                  pkt_size+LZO_OUTPUT_PADDING);
                            result = lzo1x_decode(pkt_data, &olen, data, &ilen);
                        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
                        if (result) {
                            continue;
                        }
                        pkt_size -= olen;
                        break;
#ifdef CONFIG_ZLIB
                    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
                        z_stream zstream = {0};
                        pkt_data = NULL;
                        if (inflateInit(&zstream) != Z_OK)
                            continue;
                        zstream.next_in = data;
                        zstream.avail_in = lace_size[n];
                        do {
                            pkt_size *= 3;
                            pkt_data = av_realloc(pkt_data, pkt_size);
                            zstream.avail_out = pkt_size - zstream.total_out;
                            zstream.next_out = pkt_data + zstream.total_out;
                            result = inflate(&zstream, Z_NO_FLUSH);
                        } while (result==Z_OK && pkt_size<10000000);
                        pkt_size = zstream.total_out;
                        inflateEnd(&zstream);
                        if (result != Z_STREAM_END) {
                            continue;
                        }
                        break;
                    }
#endif
#ifdef CONFIG_BZLIB
                    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
                        bz_stream bzstream = {0};
                        pkt_data = NULL;
                        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
                            continue;
                        bzstream.next_in = data;
                        bzstream.avail_in = lace_size[n];
                        do {
                            pkt_size *= 3;
                            pkt_data = av_realloc(pkt_data, pkt_size);
                            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
                            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
                            result = BZ2_bzDecompress(&bzstream);
                        } while (result==BZ_OK && pkt_size<10000000);
                        pkt_size = bzstream.total_out_lo32;
                        BZ2_bzDecompressEnd(&bzstream);
                        if (result != BZ_STREAM_END) {
                            continue;
                        }
                        break;
                    }
#endif
                    }
                }
                pkt = av_mallocz(sizeof(AVPacket));
                /* XXX: prevent data copy... */
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
                    av_free(pkt);
                    res = AVERROR(ENOMEM);
                    n = laces-1;
                    break;
                }
                if (offset)
                    memcpy (pkt->data, matroska->tracks[track]->encoding_settings, offset);
                memcpy (pkt->data+offset, pkt_data, pkt_size);
                if (n == 0)
                    pkt->flags = is_keyframe;
                pkt->stream_index = stream_index;
                pkt->pts = timecode;
                pkt->pos = pos;
                pkt->duration = duration;
                matroska_queue_packet(matroska, pkt);
            }
            if (timecode != AV_NOPTS_VALUE)
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
            data += lace_size[n];
        }
    }
    av_free(lace_size);
    av_free(origdata);
    return res;
}


void ff_vp56_init_range_decoder(VP56RangeCoder *c, const uint8_t *buf, int buf_size)

{

    c->high = 255;

    c->bits = -16;

    c->buffer = buf;

    c->end = buf + buf_size;

    c->code_word = bytestream_get_be24(&c->buffer);

}


int vring_pop(VirtIODevice *vdev, Vring *vring,

              VirtQueueElement **p_elem)

{

    struct vring_desc desc;

    unsigned int i, head, found = 0, num = vring->vr.num;

    uint16_t avail_idx, last_avail_idx;

    VirtQueueElement *elem = NULL;

    int ret;

    /* If there was a fatal error then refuse operation */

    if (vring->broken) {

        ret = -EFAULT;

        goto out;

    }

    /* Check it isn't doing very strange things with descriptor numbers. */

    last_avail_idx = vring->last_avail_idx;

    avail_idx = vring->vr.avail->idx;

    barrier(); /* load indices now and not again later */

    if (unlikely((uint16_t)(avail_idx - last_avail_idx) > num)) {

        error_report("Guest moved used index from %u to %u",

                     last_avail_idx, avail_idx);

        ret = -EFAULT;

        goto out;

    }

    /* If there's nothing new since last we looked. */

    if (avail_idx == last_avail_idx) {

        ret = -EAGAIN;

        goto out;

    }

    /* Only get avail ring entries after they have been exposed by guest. */

    smp_rmb();

    /* Grab the next descriptor number they're advertising, and increment

     * the index we've seen. */

    head = vring->vr.avail->ring[last_avail_idx % num];

    elem = g_slice_new(VirtQueueElement);

    elem->index = head;

    elem->in_num = elem->out_num = 0;

    /* If their number is silly, that's an error. */

    if (unlikely(head >= num)) {

        error_report("Guest says index %u > %u is available", head, num);

        ret = -EFAULT;

        goto out;

    }

    if (vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) {

        vring_avail_event(&vring->vr) = vring->vr.avail->idx;

    }

    i = head;

    do {

        if (unlikely(i >= num)) {

            error_report("Desc index is %u > %u, head = %u", i, num, head);

            ret = -EFAULT;

            goto out;

        }

        if (unlikely(++found > num)) {

            error_report("Loop detected: last one at %u vq size %u head %u",

                         i, num, head);

            ret = -EFAULT;

            goto out;

        }

        desc = vring->vr.desc[i];

        /* Ensure descriptor is loaded before accessing fields */

        barrier();

        if (desc.flags & VRING_DESC_F_INDIRECT) {

            ret = get_indirect(vring, elem, &desc);

            if (ret < 0) {

                goto out;

            }

            continue;

        }

        ret = get_desc(vring, elem, &desc);

        if (ret < 0) {

            goto out;

        }

        i = desc.next;

    } while (desc.flags & VRING_DESC_F_NEXT);

    /* On success, increment avail index. */

    vring->last_avail_idx++;

    *p_elem = elem;

    return head;

out:

    assert(ret < 0);

    if (ret == -EFAULT) {

        vring->broken = true;

    }

    if (elem) {

        vring_unmap_element(elem);

        g_slice_free(VirtQueueElement, elem);

    }

    *p_elem = NULL;

    return ret;

}


static int ftp_connect_control_connection(URLContext *h)

{

    char buf[CONTROL_BUFFER_SIZE], opts_format[20];

    int err;

    AVDictionary *opts = NULL;

    FTPContext *s = h->priv_data;

    const int connect_codes[] = {220, 0};

    s->conn_control_block_flag = 0;

    if (!s->conn_control) {

        ff_url_join(buf, sizeof(buf), "tcp", NULL,

                    s->hostname, s->server_control_port, NULL);

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

            snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);

            av_dict_set(&opts, "timeout", opts_format, 0);

        } /* if option is not given, don't pass it and let tcp use its own default */

        err = ffurl_open(&s->conn_control, buf, AVIO_FLAG_READ_WRITE,

                         &s->conn_control_interrupt_cb, &opts);

        av_dict_free(&opts);

        if (err < 0) {

            av_log(h, AV_LOG_ERROR, "Cannot open control connection\n");

            return err;

        }

        /* consume all messages from server */

        if (!ftp_status(s, NULL, connect_codes)) {

            av_log(h, AV_LOG_ERROR, "FTP server not ready for new users\n");

            err = AVERROR(EACCES);

            return err;

        }

        if ((err = ftp_auth(s)) < 0) {

            av_log(h, AV_LOG_ERROR, "FTP authentication failed\n");

            return err;

        }

        if ((err = ftp_type(s)) < 0) {

            av_dlog(h, "Set content type failed\n");

            return err;

        }

    }

    return 0;

}


void qpci_memread(QPCIDevice *dev, void *data, void *buf, size_t len)

{

    uintptr_t addr = (uintptr_t)data;

    g_assert(addr >= QPCI_PIO_LIMIT);

    dev->bus->memread(dev->bus, addr, buf, len);

}


static int is_intra_more_likely(ERContext *s)

{

    int is_intra_likely, i, j, undamaged_count, skip_amount, mb_x, mb_y;

    if (!s->last_pic.f || !s->last_pic.f->data[0])

        return 1; // no previous frame available -> use spatial prediction

    undamaged_count = 0;

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

        const int mb_xy = s->mb_index2xy[i];

        const int error = s->error_status_table[mb_xy];

        if (!((error & ER_DC_ERROR) && (error & ER_MV_ERROR)))

            undamaged_count++;

    }

    if (s->avctx->codec_id == AV_CODEC_ID_H264 && s->ref_count <= 0)

        return 1;

    if (undamaged_count < 5)

        return 0; // almost all MBs damaged -> use temporal prediction

#if FF_API_XVMC

FF_DISABLE_DEPRECATION_WARNINGS

    // prevent dsp.sad() check, that requires access to the image

    if (CONFIG_MPEG_XVMC_DECODER    &&

        s->avctx->xvmc_acceleration &&

        s->cur_pic.f->pict_type == AV_PICTURE_TYPE_I)

        return 1;

FF_ENABLE_DEPRECATION_WARNINGS

#endif /* FF_API_XVMC */

    skip_amount     = FFMAX(undamaged_count / 50, 1); // check only up to 50 MBs

    is_intra_likely = 0;

    j = 0;

    for (mb_y = 0; mb_y < s->mb_height - 1; mb_y++) {

        for (mb_x = 0; mb_x < s->mb_width; mb_x++) {

            int error;

            const int mb_xy = mb_x + mb_y * s->mb_stride;

            error = s->error_status_table[mb_xy];

            if ((error & ER_DC_ERROR) && (error & ER_MV_ERROR))

                continue; // skip damaged

            j++;

            // skip a few to speed things up

            if ((j % skip_amount) != 0)

                continue;

            if (s->cur_pic.f->pict_type == AV_PICTURE_TYPE_I) {

                int *linesize = s->cur_pic.f->linesize;

                uint8_t *mb_ptr      = s->cur_pic.f->data[0] +

                                       mb_x * 16 + mb_y * 16 * linesize[0];

                uint8_t *last_mb_ptr = s->last_pic.f->data[0] +

                                       mb_x * 16 + mb_y * 16 * linesize[0];

                if (s->avctx->codec_id == AV_CODEC_ID_H264) {

                    // FIXME

                } else {

                    ff_thread_await_progress(s->last_pic.tf, mb_y, 0);

                }

                is_intra_likely += s->mecc->sad[0](NULL, last_mb_ptr, mb_ptr,

                                                   linesize[0], 16);

                is_intra_likely -= s->mecc->sad[0](NULL, last_mb_ptr,

                                                   last_mb_ptr + linesize[0] * 16,

                                                   linesize[0], 16);

            } else {

                if (IS_INTRA(s->cur_pic.mb_type[mb_xy]))

                   is_intra_likely++;

                else

                   is_intra_likely--;

            }

        }

    }

    return is_intra_likely > 0;

}


void Release(void *ctx)

{

    ContextInfo *ci;

    ci = (ContextInfo *) ctx;

    if (ci->cache) {

        imlib_context_set_image(ci->cache->image);

        imlib_free_image();

        av_free(ci->cache);

    }

    if (ctx) {

        if (ci->imageOverlaid) {

            imlib_context_set_image(ci->imageOverlaid);

            imlib_free_image();

        }

        ff_eval_free(ci->expr_x);

        ff_eval_free(ci->expr_y);

        ff_eval_free(ci->expr_R);

        ff_eval_free(ci->expr_G);

        ff_eval_free(ci->expr_B);

        sws_freeContext(ci->toRGB_convert_ctx);

        sws_freeContext(ci->fromRGB_convert_ctx);

        av_free(ctx);

    }

}


void qemu_aio_flush(void)

{

    AioHandler *node;

    int ret;

    do {

        ret = 0;

	/*

	 * If there are pending emulated aio start them now so flush

	 * will be able to return 1.

	 */

        qemu_aio_wait();

        LIST_FOREACH(node, &aio_handlers, node) {

            ret |= node->io_flush(node->opaque);

        }

    } while (ret > 0);

}


static void quantize_and_encode_band_cost_ZERO_mips(struct AACEncContext *s,

                                                         PutBitContext *pb, const float *in, float *out,

                                                         const float *scaled, int size, int scale_idx,

                                                         int cb, const float lambda, const float uplim,

                                                         int *bits, const float ROUNDING) {

    int i;

    if (bits)

        *bits = 0;

    if (out) {

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

           out[i  ] = 0.0f;

           out[i+1] = 0.0f;

           out[i+2] = 0.0f;

           out[i+3] = 0.0f;

        }

    }

}


static int xen_platform_initfn(PCIDevice *dev)
{
    PCIXenPlatformState *d = XEN_PLATFORM(dev);
    uint8_t *pci_conf;
    pci_conf = dev->config;
    pci_set_word(pci_conf + PCI_COMMAND, PCI_COMMAND_IO | PCI_COMMAND_MEMORY);
    pci_config_set_prog_interface(pci_conf, 0);
    pci_conf[PCI_INTERRUPT_PIN] = 1;
    platform_ioport_bar_setup(d);
    pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &d->bar);
    /* reserve 16MB mmio address for share memory*/
    platform_mmio_setup(d);
    pci_register_bar(dev, 1, PCI_BASE_ADDRESS_MEM_PREFETCH,
                     &d->mmio_bar);
    platform_fixed_ioport_init(d);
    return 0;
}


static void mmap_release_buffer(AVPacket *pkt)

{

    struct v4l2_buffer buf;

    int res, fd;

    struct buff_data *buf_descriptor = pkt->priv;

    if (pkt->data == NULL)

        return;

    memset(&buf, 0, sizeof(struct v4l2_buffer));

    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    buf.memory = V4L2_MEMORY_MMAP;

    buf.index = buf_descriptor->index;

    fd = buf_descriptor->fd;

    av_free(buf_descriptor);

    res = ioctl(fd, VIDIOC_QBUF, &buf);

    if (res < 0)

        av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",

               strerror(errno));

    pkt->data = NULL;

    pkt->size = 0;

}


static void coroutine_fn c1_fn(void *opaque)

{

    Coroutine *c2 = opaque;

    qemu_coroutine_enter(c2, NULL);

}


static int write_target_commit(BlockDriverState *bs, int64_t sector_num,

	const uint8_t* buffer, int nb_sectors) {

    BDRVVVFATState* s = bs->opaque;

    return try_commit(s);

}


static void show_packets(AVFormatContext *fmt_ctx)

{

    AVPacket pkt;

    av_init_packet(&pkt);

    probe_array_header("packets", 0);

    while (!av_read_frame(fmt_ctx, &pkt))

        show_packet(fmt_ctx, &pkt);

    probe_array_footer("packets", 0);

}


static void sdhci_write_dataport(SDHCIState *s, uint32_t value, unsigned size)

{

    unsigned i;

    /* Check that there is free space left in a buffer */

    if (!(s->prnsts & SDHC_SPACE_AVAILABLE)) {

        ERRPRINT("Can't write to data buffer: buffer full\n");

        return;

    }

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

        s->fifo_buffer[s->data_count] = value & 0xFF;

        s->data_count++;

        value >>= 8;

        if (s->data_count >= (s->blksize & 0x0fff)) {

            DPRINT_L2("write buffer filled with %u bytes of data\n",

                    s->data_count);

            s->data_count = 0;

            s->prnsts &= ~SDHC_SPACE_AVAILABLE;

            if (s->prnsts & SDHC_DOING_WRITE) {

                SDHCI_GET_CLASS(s)->write_block_to_card(s);

            }

        }

    }

}


static uint64_t omap_ulpd_pm_read(void *opaque, target_phys_addr_t addr,

                                  unsigned size)

{

    struct omap_mpu_state_s *s = (struct omap_mpu_state_s *) opaque;

    uint16_t ret;

    if (size != 2) {

        return omap_badwidth_read16(opaque, addr);

    }

    switch (addr) {

    case 0x14:	/* IT_STATUS */

        ret = s->ulpd_pm_regs[addr >> 2];

        s->ulpd_pm_regs[addr >> 2] = 0;

        qemu_irq_lower(s->irq[1][OMAP_INT_GAUGE_32K]);

        return ret;

    case 0x18:	/* Reserved */

    case 0x1c:	/* Reserved */

    case 0x20:	/* Reserved */

    case 0x28:	/* Reserved */

    case 0x2c:	/* Reserved */

        OMAP_BAD_REG(addr);

    case 0x00:	/* COUNTER_32_LSB */

    case 0x04:	/* COUNTER_32_MSB */

    case 0x08:	/* COUNTER_HIGH_FREQ_LSB */

    case 0x0c:	/* COUNTER_HIGH_FREQ_MSB */

    case 0x10:	/* GAUGING_CTRL */

    case 0x24:	/* SETUP_ANALOG_CELL3_ULPD1 */

    case 0x30:	/* CLOCK_CTRL */

    case 0x34:	/* SOFT_REQ */

    case 0x38:	/* COUNTER_32_FIQ */

    case 0x3c:	/* DPLL_CTRL */

    case 0x40:	/* STATUS_REQ */

        /* XXX: check clk::usecount state for every clock */

    case 0x48:	/* LOCL_TIME */

    case 0x4c:	/* APLL_CTRL */

    case 0x50:	/* POWER_CTRL */

        return s->ulpd_pm_regs[addr >> 2];

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static int milkymist_memcard_init(SysBusDevice *dev)

{

    MilkymistMemcardState *s = MILKYMIST_MEMCARD(dev);

    DriveInfo *dinfo;

    BlockDriverState *bs;

    dinfo = drive_get_next(IF_SD);

    bs = dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL;

    s->card = sd_init(bs, false);

    if (s->card == NULL) {

        return -1;

    }

    s->enabled = bs && bdrv_is_inserted(bs);

    memory_region_init_io(&s->regs_region, OBJECT(s), &memcard_mmio_ops, s,

            "milkymist-memcard", R_MAX * 4);

    sysbus_init_mmio(dev, &s->regs_region);

    return 0;

}


static void visitor_output_setup_internal(TestOutputVisitorData *data,

                                          bool human)

{

    data->human = human;

    data->sov = string_output_visitor_new(human);

    g_assert(data->sov);

    data->ov = string_output_get_visitor(data->sov);

    g_assert(data->ov);

}


static int get_riff(AVFormatContext *s, AVIOContext *pb)

{

    AVIContext *avi = s->priv_data;

    char header[8];

    int i;

    /* check RIFF header */

    avio_read(pb, header, 4);

    avi->riff_end = avio_rl32(pb);  /* RIFF chunk size */

    avi->riff_end += avio_tell(pb); /* RIFF chunk end */

    avio_read(pb, header+4, 4);

    for(i=0; avi_headers[i][0]; i++)

        if(!memcmp(header, avi_headers[i], 8))

            break;

    if(!avi_headers[i][0])

        return -1;

    if(header[7] == 0x19)

        av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");

    return 0;

}


_eth_get_rss_ex_src_addr(const struct iovec *pkt, int pkt_frags,

                        size_t dsthdr_offset,

                        struct ip6_ext_hdr *ext_hdr,

                        struct in6_address *src_addr)

{

    size_t bytes_left = (ext_hdr->ip6r_len + 1) * 8 - sizeof(*ext_hdr);

    struct ip6_option_hdr opthdr;

    size_t opt_offset = dsthdr_offset + sizeof(*ext_hdr);

    while (bytes_left > sizeof(opthdr)) {

        size_t input_size = iov_size(pkt, pkt_frags);

        size_t bytes_read, optlen;

        if (input_size < opt_offset) {

            return false;

        }

        bytes_read = iov_to_buf(pkt, pkt_frags, opt_offset,

                                &opthdr, sizeof(opthdr));

        if (bytes_read != sizeof(opthdr)) {

            return false;

        }

        optlen = (opthdr.type == IP6_OPT_PAD1) ? 1

                                               : (opthdr.len + sizeof(opthdr));

        if (optlen > bytes_left) {

            return false;

        }

        if (opthdr.type == IP6_OPT_HOME) {

            size_t input_size = iov_size(pkt, pkt_frags);

            if (input_size < opt_offset + sizeof(opthdr)) {

                return false;

            }

            bytes_read = iov_to_buf(pkt, pkt_frags,

                                    opt_offset + sizeof(opthdr),

                                    src_addr, sizeof(*src_addr));

            return bytes_read == sizeof(src_addr);

        }

        opt_offset += optlen;

        bytes_left -= optlen;

    }

    return false;

}


static int altivec_uyvy_rgb32 (SwsContext *c,

			       unsigned char **in, int *instrides,

			       int srcSliceY,	int srcSliceH,

			       unsigned char **oplanes, int *outstrides)

{

  int w = c->srcW;

  int h = srcSliceH;

  int i,j;

  vector unsigned char uyvy;

  vector signed   short Y,U,V;

  vector signed   short vx,ux,uvx;

  vector signed   short R0,G0,B0,R1,G1,B1;

  vector unsigned char  R,G,B;

  vector unsigned char *out;

  ubyte *img;

  img = in[0];

  out = (vector unsigned char *)(oplanes[0]+srcSliceY*outstrides[0]);

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

    for (j=0;j<w/16;j++) {

      uyvy = vec_ld (0, img);

      U = (vector signed short)

	vec_perm (uyvy, (vector unsigned char)(0), demux_u);

      V = (vector signed short)

	vec_perm (uyvy, (vector unsigned char)(0), demux_v);

      Y = (vector signed short)

	vec_perm (uyvy, (vector unsigned char)(0), demux_y);

      cvtyuvtoRGB (c, Y,U,V,&R0,&G0,&B0);

      uyvy = vec_ld (16, img);

      U = (vector signed short)

	vec_perm (uyvy, (vector unsigned char)(0), demux_u);

      V = (vector signed short)

	vec_perm (uyvy, (vector unsigned char)(0), demux_v);

      Y = (vector signed short)

	vec_perm (uyvy, (vector unsigned char)(0), demux_y);

      cvtyuvtoRGB (c, Y,U,V,&R1,&G1,&B1);

      R  = vec_packclp (R0,R1);

      G  = vec_packclp (G0,G1);

      B  = vec_packclp (B0,B1);

      //      vec_mstbgr24 (R,G,B, out);

      out_rgba (R,G,B,out);

      img += 32;

    }

  }

  return srcSliceH;

}


static void inc_refcounts(BlockDriverState *bs,

                          BdrvCheckResult *res,

                          uint16_t *refcount_table,

                          int refcount_table_size,

                          int64_t offset, int64_t size)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t start, last, cluster_offset, k;

    if (size <= 0)

        return;

    start = start_of_cluster(s, offset);

    last = start_of_cluster(s, offset + size - 1);

    for(cluster_offset = start; cluster_offset <= last;

        cluster_offset += s->cluster_size) {

        k = cluster_offset >> s->cluster_bits;

        if (k >= refcount_table_size) {

            fprintf(stderr, "Warning: cluster offset=0x%" PRIx64 " is after "

                "the end of the image file, can't properly check refcounts.\n",

                cluster_offset);

            res->check_errors++;

        } else {

            if (++refcount_table[k] == 0) {

                fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64

                    "\n", cluster_offset);

                res->corruptions++;

            }

        }

    }

}


void stw_phys(target_phys_addr_t addr, uint32_t val)

{

    uint16_t v = tswap16(val);

    cpu_physical_memory_write(addr, (const uint8_t *)&v, 2);

}


static void gen_branch(DisasContext *ctx, int insn_bytes)

{

    if (ctx->hflags & MIPS_HFLAG_BMASK) {

        int proc_hflags = ctx->hflags & MIPS_HFLAG_BMASK;

        /* Branches completion */

        ctx->hflags &= ~MIPS_HFLAG_BMASK;

        ctx->bstate = BS_BRANCH;

        save_cpu_state(ctx, 0);

        /* FIXME: Need to clear can_do_io.  */

        switch (proc_hflags & MIPS_HFLAG_BMASK_BASE) {

        case MIPS_HFLAG_FBNSLOT:

            MIPS_DEBUG("forbidden slot");

            gen_goto_tb(ctx, 0, ctx->pc + insn_bytes);

            break;

        case MIPS_HFLAG_B:

            /* unconditional branch */

            MIPS_DEBUG("unconditional branch");

            if (proc_hflags & MIPS_HFLAG_BX) {

                tcg_gen_xori_i32(hflags, hflags, MIPS_HFLAG_M16);

            }

            gen_goto_tb(ctx, 0, ctx->btarget);

            break;

        case MIPS_HFLAG_BL:

            /* blikely taken case */

            MIPS_DEBUG("blikely branch taken");

            gen_goto_tb(ctx, 0, ctx->btarget);

            break;

        case MIPS_HFLAG_BC:

            /* Conditional branch */

            MIPS_DEBUG("conditional branch");

            {

                int l1 = gen_new_label();

                tcg_gen_brcondi_tl(TCG_COND_NE, bcond, 0, l1);

                gen_goto_tb(ctx, 1, ctx->pc + insn_bytes);

                gen_set_label(l1);

                gen_goto_tb(ctx, 0, ctx->btarget);

            }

            break;

        case MIPS_HFLAG_BR:

            /* unconditional branch to register */

            MIPS_DEBUG("branch to register");

            if (ctx->insn_flags & (ASE_MIPS16 | ASE_MICROMIPS)) {

                TCGv t0 = tcg_temp_new();

                TCGv_i32 t1 = tcg_temp_new_i32();

                tcg_gen_andi_tl(t0, btarget, 0x1);

                tcg_gen_trunc_tl_i32(t1, t0);

                tcg_temp_free(t0);

                tcg_gen_andi_i32(hflags, hflags, ~(uint32_t)MIPS_HFLAG_M16);

                tcg_gen_shli_i32(t1, t1, MIPS_HFLAG_M16_SHIFT);

                tcg_gen_or_i32(hflags, hflags, t1);

                tcg_temp_free_i32(t1);

                tcg_gen_andi_tl(cpu_PC, btarget, ~(target_ulong)0x1);

            } else {

                tcg_gen_mov_tl(cpu_PC, btarget);

            }

            if (ctx->singlestep_enabled) {

                save_cpu_state(ctx, 0);

                gen_helper_0e0i(raise_exception, EXCP_DEBUG);

            }

            tcg_gen_exit_tb(0);

            break;

        default:

            MIPS_DEBUG("unknown branch");

            break;

        }

    }

}


void slirp_cleanup(Slirp *slirp)

{

    TAILQ_REMOVE(&slirp_instances, slirp, entry);

    unregister_savevm("slirp", slirp);

    qemu_free(slirp->tftp_prefix);

    qemu_free(slirp->bootp_filename);

    qemu_free(slirp);

}


void scsi_req_abort(SCSIRequest *req, int status)

{

    if (!req->enqueued) {

        return;

    }

    scsi_req_ref(req);

    scsi_req_dequeue(req);

    req->io_canceled = true;

    if (req->ops->cancel_io) {

        req->ops->cancel_io(req);

    }

    scsi_req_complete(req, status);

    scsi_req_unref(req);

}


rdt_free_extradata (PayloadContext *rdt)

{

    int i;

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

        if (rdt->rmst[i]) {

            ff_rm_free_rmstream(rdt->rmst[i]);

            av_freep(&rdt->rmst[i]);

        }

    if (rdt->rmctx)

        av_close_input_stream(rdt->rmctx);

    av_freep(&rdt->mlti_data);

    av_free(rdt);

}


build_dsdt(GArray *table_data, GArray *linker,

           AcpiPmInfo *pm, AcpiMiscInfo *misc,

           PcPciInfo *pci, MachineState *machine)

{

    CrsRangeEntry *entry;

    Aml *dsdt, *sb_scope, *scope, *dev, *method, *field, *pkg, *crs;

    GPtrArray *mem_ranges = g_ptr_array_new_with_free_func(crs_range_free);

    GPtrArray *io_ranges = g_ptr_array_new_with_free_func(crs_range_free);

    PCMachineState *pcms = PC_MACHINE(machine);

    uint32_t nr_mem = machine->ram_slots;

    int root_bus_limit = 0xFF;

    PCIBus *bus = NULL;

    int i;

    dsdt = init_aml_allocator();

    /* Reserve space for header */

    acpi_data_push(dsdt->buf, sizeof(AcpiTableHeader));

    build_dbg_aml(dsdt);

    if (misc->is_piix4) {

        sb_scope = aml_scope("_SB");

        dev = aml_device("PCI0");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));

        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));

        aml_append(dev, aml_name_decl("_UID", aml_int(1)));

        aml_append(sb_scope, dev);

        aml_append(dsdt, sb_scope);

        build_hpet_aml(dsdt);

        build_piix4_pm(dsdt);

        build_piix4_isa_bridge(dsdt);

        build_isa_devices_aml(dsdt);

        build_piix4_pci_hotplug(dsdt);

        build_piix4_pci0_int(dsdt);

    } else {

        sb_scope = aml_scope("_SB");

        aml_append(sb_scope,

            aml_operation_region("PCST", AML_SYSTEM_IO, aml_int(0xae00), 0x0c));

        aml_append(sb_scope,

            aml_operation_region("PCSB", AML_SYSTEM_IO, aml_int(0xae0c), 0x01));

        field = aml_field("PCSB", AML_ANY_ACC, AML_NOLOCK, AML_WRITE_AS_ZEROS);

        aml_append(field, aml_named_field("PCIB", 8));

        aml_append(sb_scope, field);

        aml_append(dsdt, sb_scope);

        sb_scope = aml_scope("_SB");

        dev = aml_device("PCI0");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A08")));

        aml_append(dev, aml_name_decl("_CID", aml_eisaid("PNP0A03")));

        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));

        aml_append(dev, aml_name_decl("_UID", aml_int(1)));

        aml_append(dev, aml_name_decl("SUPP", aml_int(0)));

        aml_append(dev, aml_name_decl("CTRL", aml_int(0)));

        aml_append(dev, build_q35_osc_method());

        aml_append(sb_scope, dev);

        aml_append(dsdt, sb_scope);

        build_hpet_aml(dsdt);

        build_q35_isa_bridge(dsdt);

        build_isa_devices_aml(dsdt);

        build_q35_pci0_int(dsdt);

    }

    build_legacy_cpu_hotplug_aml(dsdt, machine, pm->cpu_hp_io_base);

    build_memory_hotplug_aml(dsdt, nr_mem, pm->mem_hp_io_base,

                             pm->mem_hp_io_len);

    scope =  aml_scope("_GPE");

    {

        aml_append(scope, aml_name_decl("_HID", aml_string("ACPI0006")));

        if (misc->is_piix4) {

            method = aml_method("_E01", 0, AML_NOTSERIALIZED);

            aml_append(method,

                aml_acquire(aml_name("\\_SB.PCI0.BLCK"), 0xFFFF));

            aml_append(method, aml_call0("\\_SB.PCI0.PCNT"));

            aml_append(method, aml_release(aml_name("\\_SB.PCI0.BLCK")));

            aml_append(scope, method);

        }

        method = aml_method("_E03", 0, AML_NOTSERIALIZED);

        aml_append(method, aml_call0(MEMORY_HOTPLUG_HANDLER_PATH));

        aml_append(scope, method);

    }

    aml_append(dsdt, scope);

    bus = PC_MACHINE(machine)->bus;

    if (bus) {

        QLIST_FOREACH(bus, &bus->child, sibling) {

            uint8_t bus_num = pci_bus_num(bus);

            uint8_t numa_node = pci_bus_numa_node(bus);

            /* look only for expander root buses */

            if (!pci_bus_is_root(bus)) {

                continue;

            }

            if (bus_num < root_bus_limit) {

                root_bus_limit = bus_num - 1;

            }

            scope = aml_scope("\\_SB");

            dev = aml_device("PC%.02X", bus_num);

            aml_append(dev, aml_name_decl("_UID", aml_int(bus_num)));

            aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));

            aml_append(dev, aml_name_decl("_BBN", aml_int(bus_num)));

            if (numa_node != NUMA_NODE_UNASSIGNED) {

                aml_append(dev, aml_name_decl("_PXM", aml_int(numa_node)));

            }

            aml_append(dev, build_prt(false));

            crs = build_crs(PCI_HOST_BRIDGE(BUS(bus)->parent),

                            io_ranges, mem_ranges);

            aml_append(dev, aml_name_decl("_CRS", crs));

            aml_append(scope, dev);

            aml_append(dsdt, scope);

        }

    }

    scope = aml_scope("\\_SB.PCI0");

    /* build PCI0._CRS */

    crs = aml_resource_template();

    aml_append(crs,

        aml_word_bus_number(AML_MIN_FIXED, AML_MAX_FIXED, AML_POS_DECODE,

                            0x0000, 0x0, root_bus_limit,

                            0x0000, root_bus_limit + 1));

    aml_append(crs, aml_io(AML_DECODE16, 0x0CF8, 0x0CF8, 0x01, 0x08));

    aml_append(crs,

        aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,

                    AML_POS_DECODE, AML_ENTIRE_RANGE,

                    0x0000, 0x0000, 0x0CF7, 0x0000, 0x0CF8));

    crs_replace_with_free_ranges(io_ranges, 0x0D00, 0xFFFF);

    for (i = 0; i < io_ranges->len; i++) {

        entry = g_ptr_array_index(io_ranges, i);

        aml_append(crs,

            aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,

                        AML_POS_DECODE, AML_ENTIRE_RANGE,

                        0x0000, entry->base, entry->limit,

                        0x0000, entry->limit - entry->base + 1));

    }

    aml_append(crs,

        aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                         AML_CACHEABLE, AML_READ_WRITE,

                         0, 0x000A0000, 0x000BFFFF, 0, 0x00020000));

    crs_replace_with_free_ranges(mem_ranges, pci->w32.begin, pci->w32.end - 1);

    for (i = 0; i < mem_ranges->len; i++) {

        entry = g_ptr_array_index(mem_ranges, i);

        aml_append(crs,

            aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                             AML_NON_CACHEABLE, AML_READ_WRITE,

                             0, entry->base, entry->limit,

                             0, entry->limit - entry->base + 1));

    }

    if (pci->w64.begin) {

        aml_append(crs,

            aml_qword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                             AML_CACHEABLE, AML_READ_WRITE,

                             0, pci->w64.begin, pci->w64.end - 1, 0,

                             pci->w64.end - pci->w64.begin));

    }

    if (misc->tpm_version != TPM_VERSION_UNSPEC) {

        aml_append(crs, aml_memory32_fixed(TPM_TIS_ADDR_BASE,

                   TPM_TIS_ADDR_SIZE, AML_READ_WRITE));

    }

    aml_append(scope, aml_name_decl("_CRS", crs));

    /* reserve GPE0 block resources */

    dev = aml_device("GPE0");

    aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));

    aml_append(dev, aml_name_decl("_UID", aml_string("GPE0 resources")));

    /* device present, functioning, decoding, not shown in UI */

    aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

    crs = aml_resource_template();

    aml_append(crs,

        aml_io(AML_DECODE16, pm->gpe0_blk, pm->gpe0_blk, 1, pm->gpe0_blk_len)

    );

    aml_append(dev, aml_name_decl("_CRS", crs));

    aml_append(scope, dev);

    g_ptr_array_free(io_ranges, true);

    g_ptr_array_free(mem_ranges, true);

    /* reserve PCIHP resources */

    if (pm->pcihp_io_len) {

        dev = aml_device("PHPR");

        aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));

        aml_append(dev,

            aml_name_decl("_UID", aml_string("PCI Hotplug resources")));

        /* device present, functioning, decoding, not shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, pm->pcihp_io_base, pm->pcihp_io_base, 1,

                   pm->pcihp_io_len)

        );

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(scope, dev);

    }

    aml_append(dsdt, scope);

    /*  create S3_ / S4_ / S5_ packages if necessary */

    scope = aml_scope("\\");

    if (!pm->s3_disabled) {

        pkg = aml_package(4);

        aml_append(pkg, aml_int(1)); /* PM1a_CNT.SLP_TYP */

        aml_append(pkg, aml_int(1)); /* PM1b_CNT.SLP_TYP, FIXME: not impl. */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(scope, aml_name_decl("_S3", pkg));

    }

    if (!pm->s4_disabled) {

        pkg = aml_package(4);

        aml_append(pkg, aml_int(pm->s4_val)); /* PM1a_CNT.SLP_TYP */

        /* PM1b_CNT.SLP_TYP, FIXME: not impl. */

        aml_append(pkg, aml_int(pm->s4_val));

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(scope, aml_name_decl("_S4", pkg));

    }

    pkg = aml_package(4);

    aml_append(pkg, aml_int(0)); /* PM1a_CNT.SLP_TYP */

    aml_append(pkg, aml_int(0)); /* PM1b_CNT.SLP_TYP not impl. */

    aml_append(pkg, aml_int(0)); /* reserved */

    aml_append(pkg, aml_int(0)); /* reserved */

    aml_append(scope, aml_name_decl("_S5", pkg));

    aml_append(dsdt, scope);

    /* create fw_cfg node, unconditionally */

    {

        /* when using port i/o, the 8-bit data register *always* overlaps

         * with half of the 16-bit control register. Hence, the total size

         * of the i/o region used is FW_CFG_CTL_SIZE; when using DMA, the

         * DMA control register is located at FW_CFG_DMA_IO_BASE + 4 */

        uint8_t io_size = object_property_get_bool(OBJECT(pcms->fw_cfg),

                                                   "dma_enabled", NULL) ?

                          ROUND_UP(FW_CFG_CTL_SIZE, 4) + sizeof(dma_addr_t) :

                          FW_CFG_CTL_SIZE;

        scope = aml_scope("\\_SB.PCI0");

        dev = aml_device("FWCF");

        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0002")));

        /* device present, functioning, decoding, not shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, FW_CFG_IO_BASE, FW_CFG_IO_BASE, 0x01, io_size)

        );

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(scope, dev);

        aml_append(dsdt, scope);

    }

    if (misc->applesmc_io_base) {

        scope = aml_scope("\\_SB.PCI0.ISA");

        dev = aml_device("SMC");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("APP0001")));

        /* device present, functioning, decoding, not shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, misc->applesmc_io_base, misc->applesmc_io_base,

                   0x01, APPLESMC_MAX_DATA_LENGTH)

        );

        aml_append(crs, aml_irq_no_flags(6));

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(scope, dev);

        aml_append(dsdt, scope);

    }

    if (misc->pvpanic_port) {

        scope = aml_scope("\\_SB.PCI0.ISA");

        dev = aml_device("PEVT");

        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0001")));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, misc->pvpanic_port, misc->pvpanic_port, 1, 1)

        );

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(dev, aml_operation_region("PEOR", AML_SYSTEM_IO,

                                              aml_int(misc->pvpanic_port), 1));

        field = aml_field("PEOR", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);

        aml_append(field, aml_named_field("PEPT", 8));

        aml_append(dev, field);

        /* device present, functioning, decoding, shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));

        method = aml_method("RDPT", 0, AML_NOTSERIALIZED);

        aml_append(method, aml_store(aml_name("PEPT"), aml_local(0)));

        aml_append(method, aml_return(aml_local(0)));

        aml_append(dev, method);

        method = aml_method("WRPT", 1, AML_NOTSERIALIZED);

        aml_append(method, aml_store(aml_arg(0), aml_name("PEPT")));

        aml_append(dev, method);

        aml_append(scope, dev);

        aml_append(dsdt, scope);

    }

    sb_scope = aml_scope("\\_SB");

    {

        build_memory_devices(sb_scope, nr_mem, pm->mem_hp_io_base,

                             pm->mem_hp_io_len);

        {

            Object *pci_host;

            PCIBus *bus = NULL;

            pci_host = acpi_get_i386_pci_host();

            if (pci_host) {

                bus = PCI_HOST_BRIDGE(pci_host)->bus;

            }

            if (bus) {

                Aml *scope = aml_scope("PCI0");

                /* Scan all PCI buses. Generate tables to support hotplug. */

                build_append_pci_bus_devices(scope, bus, pm->pcihp_bridge_en);

                if (misc->tpm_version != TPM_VERSION_UNSPEC) {

                    dev = aml_device("ISA.TPM");

                    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C31")));

                    aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));

                    crs = aml_resource_template();

                    aml_append(crs, aml_memory32_fixed(TPM_TIS_ADDR_BASE,

                               TPM_TIS_ADDR_SIZE, AML_READ_WRITE));

                    /*

                        FIXME: TPM_TIS_IRQ=5 conflicts with PNP0C0F irqs,

                        Rewrite to take IRQ from TPM device model and

                        fix default IRQ value there to use some unused IRQ

                     */

                    /* aml_append(crs, aml_irq_no_flags(TPM_TIS_IRQ)); */

                    aml_append(dev, aml_name_decl("_CRS", crs));

                    aml_append(scope, dev);

                }

                aml_append(sb_scope, scope);

            }

        }

        aml_append(dsdt, sb_scope);

    }

    /* copy AML table into ACPI tables blob and patch header there */

    g_array_append_vals(table_data, dsdt->buf->data, dsdt->buf->len);

    build_header(linker, table_data,

        (void *)(table_data->data + table_data->len - dsdt->buf->len),

        "DSDT", dsdt->buf->len, 1, NULL, NULL);

    free_aml_allocator();

}


static void arm_cpu_do_interrupt_aarch64(CPUState *cs)

{

    ARMCPU *cpu = ARM_CPU(cs);

    CPUARMState *env = &cpu->env;

    unsigned int new_el = env->exception.target_el;

    target_ulong addr = env->cp15.vbar_el[new_el];

    unsigned int new_mode = aarch64_pstate_mode(new_el, true);

    if (arm_current_el(env) < new_el) {

        if (env->aarch64) {

            addr += 0x400;

        } else {

            addr += 0x600;

        }

    } else if (pstate_read(env) & PSTATE_SP) {

        addr += 0x200;

    }

    switch (cs->exception_index) {

    case EXCP_PREFETCH_ABORT:

    case EXCP_DATA_ABORT:

        env->cp15.far_el[new_el] = env->exception.vaddress;

        qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",

                      env->cp15.far_el[new_el]);

        /* fall through */

    case EXCP_BKPT:

    case EXCP_UDEF:

    case EXCP_SWI:

    case EXCP_HVC:

    case EXCP_HYP_TRAP:

    case EXCP_SMC:

        env->cp15.esr_el[new_el] = env->exception.syndrome;

        break;

    case EXCP_IRQ:

    case EXCP_VIRQ:

        addr += 0x80;

        break;

    case EXCP_FIQ:

    case EXCP_VFIQ:

        addr += 0x100;

        break;

    case EXCP_SEMIHOST:

        qemu_log_mask(CPU_LOG_INT,

                      "...handling as semihosting call 0x%" PRIx64 "\n",

                      env->xregs[0]);

        env->xregs[0] = do_arm_semihosting(env);

        return;

    default:

        cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);

    }

    if (is_a64(env)) {

        env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);

        aarch64_save_sp(env, arm_current_el(env));

        env->elr_el[new_el] = env->pc;

    } else {

        env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);

        if (!env->thumb) {

            env->cp15.esr_el[new_el] |= 1 << 25;

        }

        env->elr_el[new_el] = env->regs[15];

        aarch64_sync_32_to_64(env);

        env->condexec_bits = 0;

    }

    qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",

                  env->elr_el[new_el]);

    pstate_write(env, PSTATE_DAIF | new_mode);

    env->aarch64 = 1;

    aarch64_restore_sp(env, new_el);

    env->pc = addr;

    qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",

                  new_el, env->pc, pstate_read(env));

}


static bool pc_machine_get_nvdimm(Object *obj, Error **errp)

{

    PCMachineState *pcms = PC_MACHINE(obj);

    return pcms->nvdimm;

}


build_header(GArray *linker, GArray *table_data,

             AcpiTableHeader *h, const char *sig, int len, uint8_t rev,

             const char *oem_table_id)

{

    memcpy(&h->signature, sig, 4);

    h->length = cpu_to_le32(len);

    h->revision = rev;

    memcpy(h->oem_id, ACPI_BUILD_APPNAME6, 6);

    if (oem_table_id) {

        strncpy((char *)h->oem_table_id, oem_table_id, sizeof(h->oem_table_id));

    } else {

        memcpy(h->oem_table_id, ACPI_BUILD_APPNAME4, 4);

        memcpy(h->oem_table_id + 4, sig, 4);

    }

    h->oem_revision = cpu_to_le32(1);

    memcpy(h->asl_compiler_id, ACPI_BUILD_APPNAME4, 4);

    h->asl_compiler_revision = cpu_to_le32(1);

    h->checksum = 0;

    /* Checksum to be filled in by Guest linker */

    bios_linker_loader_add_checksum(linker, ACPI_BUILD_TABLE_FILE,

                                    table_data->data, h, len, &h->checksum);

}


static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale)

{

    int v;

    int i = 0;

    uint8_t state[CONTEXT_SIZE];

    memset(state, 128, sizeof(state));

    for (v = 0; i < 128; v++) {

        unsigned len = get_symbol(c, state, 0) + 1;

        if (len > 128 - i)

            return AVERROR_INVALIDDATA;

        while (len--) {

            quant_table[i] = scale * v;

            i++;

        }

    }

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

        quant_table[256 - i] = -quant_table[i];

    quant_table[128] = -quant_table[127];

    return 2 * v - 1;

}


static int tb_unreliable(AVCodecContext *c)

{

    if (c->time_base.den >= 101L * c->time_base.num ||

        c->time_base.den <    5L * c->time_base.num ||

        // c->codec_tag == AV_RL32("DIVX") ||

        // c->codec_tag == AV_RL32("XVID") ||

        c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||

        c->codec_id == AV_CODEC_ID_H264)

        return 1;

    return 0;

}


int swr_init(struct SwrContext *s){

    s->in_buffer_index= 0;

    s->in_buffer_count= 0;

    s->resample_in_constraint= 0;

    free_temp(&s->postin);

    free_temp(&s->midbuf);

    free_temp(&s->preout);

    free_temp(&s->in_buffer);

    swri_audio_convert_free(&s-> in_convert);

    swri_audio_convert_free(&s->out_convert);

    swri_audio_convert_free(&s->full_convert);

    s-> in.planar= av_sample_fmt_is_planar(s-> in_sample_fmt);

    s->out.planar= av_sample_fmt_is_planar(s->out_sample_fmt);

    s-> in_sample_fmt= av_get_alt_sample_fmt(s-> in_sample_fmt, 0);

    s->out_sample_fmt= av_get_alt_sample_fmt(s->out_sample_fmt, 0);

    if(s-> in_sample_fmt >= AV_SAMPLE_FMT_NB){

        av_log(s, AV_LOG_ERROR, "Requested sample format %s is invalid\n", av_get_sample_fmt_name(s->in_sample_fmt));

        return AVERROR(EINVAL);

    }

    if(s->out_sample_fmt >= AV_SAMPLE_FMT_NB){

        av_log(s, AV_LOG_ERROR, "Requested sample format %s is invalid\n", av_get_sample_fmt_name(s->out_sample_fmt));

        return AVERROR(EINVAL);

    }

    if(   s->int_sample_fmt != AV_SAMPLE_FMT_S16

        &&s->int_sample_fmt != AV_SAMPLE_FMT_FLT){

        av_log(s, AV_LOG_ERROR, "Requested sample format %s is not supported internally, only float & S16 is supported\n", av_get_sample_fmt_name(s->int_sample_fmt));

        return AVERROR(EINVAL);

    }

    //FIXME should we allow/support using FLT on material that doesnt need it ?

    if(s->in_sample_fmt <= AV_SAMPLE_FMT_S16 || s->int_sample_fmt==AV_SAMPLE_FMT_S16){

        s->int_sample_fmt= AV_SAMPLE_FMT_S16;

    }else

        s->int_sample_fmt= AV_SAMPLE_FMT_FLT;

    if (s->out_sample_rate!=s->in_sample_rate || (s->flags & SWR_FLAG_RESAMPLE)){

        s->resample = swri_resample_init(s->resample, s->out_sample_rate, s->in_sample_rate, 16, 10, 0, 0.8);

    }else

        swri_resample_free(&s->resample);

    if(s->int_sample_fmt != AV_SAMPLE_FMT_S16 && s->resample){

        av_log(s, AV_LOG_ERROR, "Resampling only supported with internal s16 currently\n"); //FIXME

        return -1;

    }

    if(!s->used_ch_count)

        s->used_ch_count= s->in.ch_count;

    if(s->used_ch_count && s-> in_ch_layout && s->used_ch_count != av_get_channel_layout_nb_channels(s-> in_ch_layout)){

        av_log(s, AV_LOG_WARNING, "Input channel layout has a different number of channels than the number of used channels, ignoring layout\n");

        s-> in_ch_layout= 0;

    }

    if(!s-> in_ch_layout)

        s-> in_ch_layout= av_get_default_channel_layout(s->used_ch_count);

    if(!s->out_ch_layout)

        s->out_ch_layout= av_get_default_channel_layout(s->out.ch_count);

    s->rematrix= s->out_ch_layout  !=s->in_ch_layout || s->rematrix_volume!=1.0;

#define RSC 1 //FIXME finetune

    if(!s-> in.ch_count)

        s-> in.ch_count= av_get_channel_layout_nb_channels(s-> in_ch_layout);

    if(!s->used_ch_count)

        s->used_ch_count= s->in.ch_count;

    if(!s->out.ch_count)

        s->out.ch_count= av_get_channel_layout_nb_channels(s->out_ch_layout);

av_assert0(s-> in.ch_count);

av_assert0(s->used_ch_count);

av_assert0(s->out.ch_count);

    s->resample_first= RSC*s->out.ch_count/s->in.ch_count - RSC < s->out_sample_rate/(float)s-> in_sample_rate - 1.0;

    s-> in.bps= av_get_bytes_per_sample(s-> in_sample_fmt);

    s->int_bps= av_get_bytes_per_sample(s->int_sample_fmt);

    s->out.bps= av_get_bytes_per_sample(s->out_sample_fmt);

    if(!s->resample && !s->rematrix && !s->channel_map){

        s->full_convert = swri_audio_convert_alloc(s->out_sample_fmt,

                                                   s-> in_sample_fmt, s-> in.ch_count, NULL, 0);

        return 0;

    }

    s->in_convert = swri_audio_convert_alloc(s->int_sample_fmt,

                                             s-> in_sample_fmt, s->used_ch_count, s->channel_map, 0);

    s->out_convert= swri_audio_convert_alloc(s->out_sample_fmt,

                                             s->int_sample_fmt, s->out.ch_count, NULL, 0);

    s->postin= s->in;

    s->preout= s->out;

    s->midbuf= s->in;

    s->in_buffer= s->in;

    if(s->channel_map){

        s->postin.ch_count=

        s->midbuf.ch_count=

        s->in_buffer.ch_count= s->used_ch_count;

    }

    if(!s->resample_first){

        s->midbuf.ch_count= s->out.ch_count;

        s->in_buffer.ch_count = s->out.ch_count;

    }

    s->in_buffer.bps = s->postin.bps = s->midbuf.bps = s->preout.bps =  s->int_bps;

    s->in_buffer.planar = s->postin.planar = s->midbuf.planar = s->preout.planar =  1;

    if(s->rematrix)

        return swri_rematrix_init(s);

    return 0;

}


static int svq1_decode_init(AVCodecContext *avctx)

{

    MpegEncContext *s = avctx->priv_data;

    int i;

    MPV_decode_defaults(s);

    s->avctx = avctx;

    s->width = (avctx->width+3)&~3;

    s->height = (avctx->height+3)&~3;

    s->codec_id= avctx->codec->id;

    avctx->pix_fmt = PIX_FMT_YUV410P;

    avctx->has_b_frames= 1; // not true, but DP frames and these behave like unidirectional b frames

    s->flags= avctx->flags;

    if (MPV_common_init(s) < 0) return -1;

    init_vlc(&svq1_block_type, 2, 4,

        &svq1_block_type_vlc[0][1], 2, 1,

        &svq1_block_type_vlc[0][0], 2, 1);

    init_vlc(&svq1_motion_component, 7, 33,

        &mvtab[0][1], 2, 1,

        &mvtab[0][0], 2, 1);

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

        init_vlc(&svq1_intra_multistage[i], 3, 8,

            &svq1_intra_multistage_vlc[i][0][1], 2, 1,

            &svq1_intra_multistage_vlc[i][0][0], 2, 1);

        init_vlc(&svq1_inter_multistage[i], 3, 8,

            &svq1_inter_multistage_vlc[i][0][1], 2, 1,

            &svq1_inter_multistage_vlc[i][0][0], 2, 1);

    }

    init_vlc(&svq1_intra_mean, 8, 256,

        &svq1_intra_mean_vlc[0][1], 4, 2,

        &svq1_intra_mean_vlc[0][0], 4, 2);

    init_vlc(&svq1_inter_mean, 9, 512,

        &svq1_inter_mean_vlc[0][1], 4, 2,

        &svq1_inter_mean_vlc[0][0], 4, 2);

    return 0;

}


static int rm_read_audio_stream_info(AVFormatContext *s, AVIOContext *pb,

                                     AVStream *st, RMStream *ast, int read_all)

{

    char buf[256];

    uint32_t version;

    int ret;

    /* ra type header */

    version = avio_rb16(pb); /* version */

    if (version == 3) {

        unsigned bytes_per_minute;

        int header_size = avio_rb16(pb);

        int64_t startpos = avio_tell(pb);

        avio_skip(pb, 8);

        bytes_per_minute = avio_rb16(pb);

        avio_skip(pb, 4);

        rm_read_metadata(s, 0);

        if ((startpos + header_size) >= avio_tell(pb) + 2) {

            // fourcc (should always be "lpcJ")

            avio_r8(pb);

            get_str8(pb, buf, sizeof(buf));

        }

        // Skip extra header crap (this should never happen)

        if ((startpos + header_size) > avio_tell(pb))

            avio_skip(pb, header_size + startpos - avio_tell(pb));

        if (bytes_per_minute)

            st->codec->bit_rate = 8LL * bytes_per_minute / 60;

        st->codec->sample_rate = 8000;

        st->codec->channels = 1;

        st->codec->channel_layout = AV_CH_LAYOUT_MONO;

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_id = AV_CODEC_ID_RA_144;

        ast->deint_id = DEINT_ID_INT0;

    } else {

        int flavor, sub_packet_h, coded_framesize, sub_packet_size;

        int codecdata_length;

        unsigned bytes_per_minute;

        /* old version (4) */

        avio_skip(pb, 2); /* unused */

        avio_rb32(pb); /* .ra4 */

        avio_rb32(pb); /* data size */

        avio_rb16(pb); /* version2 */

        avio_rb32(pb); /* header size */

        flavor= avio_rb16(pb); /* add codec info / flavor */

        ast->coded_framesize = coded_framesize = avio_rb32(pb); /* coded frame size */

        avio_rb32(pb); /* ??? */

        bytes_per_minute = avio_rb32(pb);

        if (version == 4) {

            if (bytes_per_minute)

                st->codec->bit_rate = 8LL * bytes_per_minute / 60;

        }

        avio_rb32(pb); /* ??? */

        ast->sub_packet_h = sub_packet_h = avio_rb16(pb); /* 1 */

        st->codec->block_align= avio_rb16(pb); /* frame size */

        ast->sub_packet_size = sub_packet_size = avio_rb16(pb); /* sub packet size */

        avio_rb16(pb); /* ??? */

        if (version == 5) {

            avio_rb16(pb); avio_rb16(pb); avio_rb16(pb);

        }

        st->codec->sample_rate = avio_rb16(pb);

        avio_rb32(pb);

        st->codec->channels = avio_rb16(pb);

        if (version == 5) {

            ast->deint_id = avio_rl32(pb);

            avio_read(pb, buf, 4);

            buf[4] = 0;

        } else {

            get_str8(pb, buf, sizeof(buf)); /* desc */

            ast->deint_id = AV_RL32(buf);

            get_str8(pb, buf, sizeof(buf)); /* desc */

        }

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_tag  = AV_RL32(buf);

        st->codec->codec_id   = ff_codec_get_id(ff_rm_codec_tags,

                                                st->codec->codec_tag);

        switch (st->codec->codec_id) {

        case AV_CODEC_ID_AC3:

            st->need_parsing = AVSTREAM_PARSE_FULL;

            break;

        case AV_CODEC_ID_RA_288:

            st->codec->extradata_size= 0;

            ast->audio_framesize = st->codec->block_align;

            st->codec->block_align = coded_framesize;

            break;

        case AV_CODEC_ID_COOK:

            st->need_parsing = AVSTREAM_PARSE_HEADERS;

        case AV_CODEC_ID_ATRAC3:

        case AV_CODEC_ID_SIPR:

            if (read_all) {

                codecdata_length = 0;

            } else {

                avio_rb16(pb); avio_r8(pb);

                if (version == 5)

                    avio_r8(pb);

                codecdata_length = avio_rb32(pb);

                if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){

                    av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");

                    return -1;

                }

            }

            ast->audio_framesize = st->codec->block_align;

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

                if (flavor > 3) {

                    av_log(s, AV_LOG_ERROR, "bad SIPR file flavor %d\n",

                           flavor);

                    return -1;

                }

                st->codec->block_align = ff_sipr_subpk_size[flavor];

            } else {

                if(sub_packet_size <= 0){

                    av_log(s, AV_LOG_ERROR, "sub_packet_size is invalid\n");

                    return -1;

                }

                st->codec->block_align = ast->sub_packet_size;

            }

            if ((ret = rm_read_extradata(pb, st->codec, codecdata_length)) < 0)

                return ret;

            break;

        case AV_CODEC_ID_AAC:

            avio_rb16(pb); avio_r8(pb);

            if (version == 5)

                avio_r8(pb);

            codecdata_length = avio_rb32(pb);

            if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){

                av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");

                return -1;

            }

            if (codecdata_length >= 1) {

                avio_r8(pb);

                if ((ret = rm_read_extradata(pb, st->codec, codecdata_length - 1)) < 0)

                    return ret;

            }

            break;

        default:

            av_strlcpy(st->codec->codec_name, buf, sizeof(st->codec->codec_name));

        }

        if (ast->deint_id == DEINT_ID_INT4 ||

            ast->deint_id == DEINT_ID_GENR ||

            ast->deint_id == DEINT_ID_SIPR) {

            if (st->codec->block_align <= 0 ||

                ast->audio_framesize * sub_packet_h > (unsigned)INT_MAX ||

                ast->audio_framesize * sub_packet_h < st->codec->block_align)

                return AVERROR_INVALIDDATA;

            if (av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h) < 0)

                return AVERROR(ENOMEM);

        }

        switch (ast->deint_id) {

        case DEINT_ID_INT4:

            if (ast->coded_framesize > ast->audio_framesize ||

                sub_packet_h <= 1 ||

                ast->coded_framesize * sub_packet_h > (2 + (sub_packet_h & 1)) * ast->audio_framesize)

                return AVERROR_INVALIDDATA;

            break;

        case DEINT_ID_GENR:

            if (ast->sub_packet_size <= 0 ||

                ast->sub_packet_size > ast->audio_framesize)

                return AVERROR_INVALIDDATA;

            break;

        case DEINT_ID_SIPR:

        case DEINT_ID_INT0:

        case DEINT_ID_VBRS:

        case DEINT_ID_VBRF:

            break;

        default:

            av_log(s, AV_LOG_ERROR, "Unknown interleaver %X\n", ast->deint_id);

            return AVERROR_INVALIDDATA;

        }

        if (read_all) {

            avio_r8(pb);

            avio_r8(pb);

            avio_r8(pb);

            rm_read_metadata(s, 0);

        }

    }

    return 0;

}


int show_license(void *optctx, const char *opt, const char *arg)

{

    printf(

#if CONFIG_NONFREE

    "This version of %s has nonfree parts compiled in.\n"

    "Therefore it is not legally redistributable.\n",

    program_name

#elif CONFIG_GPLV3

    "%s is free software; you can redistribute it and/or modify\n"

    "it under the terms of the GNU General Public License as published by\n"

    "the Free Software Foundation; either version 3 of the License, or\n"

    "(at your option) any later version.\n"

    "\n"

    "%s is distributed in the hope that it will be useful,\n"

    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"

    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"

    "GNU General Public License for more details.\n"

    "\n"

    "You should have received a copy of the GNU General Public License\n"

    "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",

    program_name, program_name, program_name

#elif CONFIG_GPL

    "%s is free software; you can redistribute it and/or modify\n"

    "it under the terms of the GNU General Public License as published by\n"

    "the Free Software Foundation; either version 2 of the License, or\n"

    "(at your option) any later version.\n"

    "\n"

    "%s is distributed in the hope that it will be useful,\n"

    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"

    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"

    "GNU General Public License for more details.\n"

    "\n"

    "You should have received a copy of the GNU General Public License\n"

    "along with %s; if not, write to the Free Software\n"

    "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",

    program_name, program_name, program_name

#elif CONFIG_LGPLV3

    "%s is free software; you can redistribute it and/or modify\n"

    "it under the terms of the GNU Lesser General Public License as published by\n"

    "the Free Software Foundation; either version 3 of the License, or\n"

    "(at your option) any later version.\n"

    "\n"

    "%s is distributed in the hope that it will be useful,\n"

    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"

    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"

    "GNU Lesser General Public License for more details.\n"

    "\n"

    "You should have received a copy of the GNU Lesser General Public License\n"

    "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",

    program_name, program_name, program_name

#else

    "%s is free software; you can redistribute it and/or\n"

    "modify it under the terms of the GNU Lesser General Public\n"

    "License as published by the Free Software Foundation; either\n"

    "version 2.1 of the License, or (at your option) any later version.\n"

    "\n"

    "%s is distributed in the hope that it will be useful,\n"

    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"

    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"

    "Lesser General Public License for more details.\n"

    "\n"

    "You should have received a copy of the GNU Lesser General Public\n"

    "License along with %s; if not, write to the Free Software\n"

    "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",

    program_name, program_name, program_name

#endif

    );

    return 0;

}


int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,

                              int lower_transport, const char *real_challenge)

{

    RTSPState *rt = s->priv_data;

    int rtx = 0, j, i, err, interleave = 0, port_off;

    RTSPStream *rtsp_st;

    RTSPMessageHeader reply1, *reply = &reply1;

    char cmd[2048];

    const char *trans_pref;

    if (rt->transport == RTSP_TRANSPORT_RDT)

        trans_pref = "x-pn-tng";

    else

        trans_pref = "RTP/AVP";

    /* default timeout: 1 minute */

    rt->timeout = 60;

    /* for each stream, make the setup request */

    /* XXX: we assume the same server is used for the control of each

     * RTSP stream */

    /* Choose a random starting offset within the first half of the

     * port range, to allow for a number of ports to try even if the offset

     * happens to be at the end of the random range. */

    port_off = av_get_random_seed() % ((rt->rtp_port_max - rt->rtp_port_min)/2);

    /* even random offset */

    port_off -= port_off & 0x01;

    for (j = rt->rtp_port_min + port_off, i = 0; i < rt->nb_rtsp_streams; ++i) {

        char transport[2048];

        /*

         * WMS serves all UDP data over a single connection, the RTX, which

         * isn't necessarily the first in the SDP but has to be the first

         * to be set up, else the second/third SETUP will fail with a 461.

         */

        if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&

             rt->server_type == RTSP_SERVER_WMS) {

            if (i == 0) {

                /* rtx first */

                for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {

                    int len = strlen(rt->rtsp_streams[rtx]->control_url);

                    if (len >= 4 &&

                        !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,

                                "/rtx"))

                        break;

                }

                if (rtx == rt->nb_rtsp_streams)

                    return -1; /* no RTX found */

                rtsp_st = rt->rtsp_streams[rtx];

            } else

                rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];

        } else

            rtsp_st = rt->rtsp_streams[i];

        /* RTP/UDP */

        if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {

            char buf[256];

            if (rt->server_type == RTSP_SERVER_WMS && i > 1) {

                port = reply->transports[0].client_port_min;

                goto have_port;

            }

            /* first try in specified port range */

            while (j <= rt->rtp_port_max) {

                ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,

                            "?localport=%d", j);

                /* we will use two ports per rtp stream (rtp and rtcp) */

                j += 2;

                if (!ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_FLAG_READ_WRITE,

                               &s->interrupt_callback, NULL))

                    goto rtp_opened;

            }

            av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");

            err = AVERROR(EIO);

            goto fail;

        rtp_opened:

            port = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);

        have_port:

            snprintf(transport, sizeof(transport) - 1,

                     "%s/UDP;", trans_pref);

            if (rt->server_type != RTSP_SERVER_REAL)

                av_strlcat(transport, "unicast;", sizeof(transport));

            av_strlcatf(transport, sizeof(transport),

                     "client_port=%d", port);

            if (rt->transport == RTSP_TRANSPORT_RTP &&

                !(rt->server_type == RTSP_SERVER_WMS && i > 0))

                av_strlcatf(transport, sizeof(transport), "-%d", port + 1);

        }

        /* RTP/TCP */

        else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {

            /* For WMS streams, the application streams are only used for

             * UDP. When trying to set it up for TCP streams, the server

             * will return an error. Therefore, we skip those streams. */

            if (rt->server_type == RTSP_SERVER_WMS &&

                (rtsp_st->stream_index < 0 ||

                 s->streams[rtsp_st->stream_index]->codec->codec_type ==

                    AVMEDIA_TYPE_DATA))

                continue;

            snprintf(transport, sizeof(transport) - 1,

                     "%s/TCP;", trans_pref);

            if (rt->transport != RTSP_TRANSPORT_RDT)

                av_strlcat(transport, "unicast;", sizeof(transport));

            av_strlcatf(transport, sizeof(transport),

                        "interleaved=%d-%d",

                        interleave, interleave + 1);

            interleave += 2;

        }

        else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {

            snprintf(transport, sizeof(transport) - 1,

                     "%s/UDP;multicast", trans_pref);

        }

        if (s->oformat) {

            av_strlcat(transport, ";mode=receive", sizeof(transport));

        } else if (rt->server_type == RTSP_SERVER_REAL ||

                   rt->server_type == RTSP_SERVER_WMS)

            av_strlcat(transport, ";mode=play", sizeof(transport));

        snprintf(cmd, sizeof(cmd),

                 "Transport: %s\r\n",

                 transport);

        if (rt->accept_dynamic_rate)

            av_strlcat(cmd, "x-Dynamic-Rate: 0\r\n", sizeof(cmd));

        if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {

            char real_res[41], real_csum[9];

            ff_rdt_calc_response_and_checksum(real_res, real_csum,

                                              real_challenge);

            av_strlcatf(cmd, sizeof(cmd),

                        "If-Match: %s\r\n"

                        "RealChallenge2: %s, sd=%s\r\n",

                        rt->session_id, real_res, real_csum);

        }

        ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);

        if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {

            err = 1;

            goto fail;

        } else if (reply->status_code != RTSP_STATUS_OK ||

                   reply->nb_transports != 1) {

            err = AVERROR_INVALIDDATA;

            goto fail;

        }

        /* XXX: same protocol for all streams is required */

        if (i > 0) {

            if (reply->transports[0].lower_transport != rt->lower_transport ||

                reply->transports[0].transport != rt->transport) {

                err = AVERROR_INVALIDDATA;

                goto fail;

            }

        } else {

            rt->lower_transport = reply->transports[0].lower_transport;

            rt->transport = reply->transports[0].transport;

        }

        /* Fail if the server responded with another lower transport mode

         * than what we requested. */

        if (reply->transports[0].lower_transport != lower_transport) {

            av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");

            err = AVERROR_INVALIDDATA;

            goto fail;

        }

        switch(reply->transports[0].lower_transport) {

        case RTSP_LOWER_TRANSPORT_TCP:

            rtsp_st->interleaved_min = reply->transports[0].interleaved_min;

            rtsp_st->interleaved_max = reply->transports[0].interleaved_max;

            break;

        case RTSP_LOWER_TRANSPORT_UDP: {

            char url[1024], options[30] = "";

            if (rt->rtsp_flags & RTSP_FLAG_FILTER_SRC)

                av_strlcpy(options, "?connect=1", sizeof(options));

            /* Use source address if specified */

            if (reply->transports[0].source[0]) {

                ff_url_join(url, sizeof(url), "rtp", NULL,

                            reply->transports[0].source,

                            reply->transports[0].server_port_min, "%s", options);

            } else {

                ff_url_join(url, sizeof(url), "rtp", NULL, host,

                            reply->transports[0].server_port_min, "%s", options);

            }

            if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&

                ff_rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {

                err = AVERROR_INVALIDDATA;

                goto fail;

            }

            /* Try to initialize the connection state in a

             * potential NAT router by sending dummy packets.

             * RTP/RTCP dummy packets are used for RDT, too.

             */

            if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&

                CONFIG_RTPDEC)

                ff_rtp_send_punch_packets(rtsp_st->rtp_handle);

            break;

        }

        case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {

            char url[1024], namebuf[50], optbuf[20] = "";

            struct sockaddr_storage addr;

            int port, ttl;

            if (reply->transports[0].destination.ss_family) {

                addr      = reply->transports[0].destination;

                port      = reply->transports[0].port_min;

                ttl       = reply->transports[0].ttl;

            } else {

                addr      = rtsp_st->sdp_ip;

                port      = rtsp_st->sdp_port;

                ttl       = rtsp_st->sdp_ttl;

            }

            if (ttl > 0)

                snprintf(optbuf, sizeof(optbuf), "?ttl=%d", ttl);

            getnameinfo((struct sockaddr*) &addr, sizeof(addr),

                        namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);

            ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,

                        port, "%s", optbuf);

            if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,

                           &s->interrupt_callback, NULL) < 0) {

                err = AVERROR_INVALIDDATA;

                goto fail;

            }

            break;

        }

        }

        if ((err = rtsp_open_transport_ctx(s, rtsp_st)))

            goto fail;

    }

    if (reply->timeout > 0)

        rt->timeout = reply->timeout;

    if (rt->server_type == RTSP_SERVER_REAL)

        rt->need_subscription = 1;

    return 0;

fail:

    ff_rtsp_undo_setup(s);

    return err;

}


static int parse_fmtp(AVFormatContext *s,

                      AVStream *stream, PayloadContext *data,

                      const char *attr, const char *value)

{

    AVCodecParameters *par = stream->codecpar;

    int res, i;

    if (!strcmp(attr, "config")) {

        res = parse_fmtp_config(par, value);

        if (res < 0)

            return res;

    }

    if (par->codec_id == AV_CODEC_ID_AAC) {

        /* Looking for a known attribute */

        for (i = 0; attr_names[i].str; ++i) {

            if (!av_strcasecmp(attr, attr_names[i].str)) {

                if (attr_names[i].type == ATTR_NAME_TYPE_INT) {

                    *(int *)((char *)data+

                        attr_names[i].offset) = atoi(value);

                } else if (attr_names[i].type == ATTR_NAME_TYPE_STR)

                    *(char **)((char *)data+

                        attr_names[i].offset) = av_strdup(value);

            }

        }

    }

    return 0;

}


static int ffserver_set_int_param(int *dest, const char *value, int factor,

                                  int min, int max, FFServerConfig *config,

                                  const char *error_msg, ...)

{

    int tmp;

    char *tailp;

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

        goto error;

    errno = 0;

    tmp = strtol(value, &tailp, 0);

    if (tmp < min || tmp > max)

        goto error;

    if (factor) {

        if (FFABS(tmp) > INT_MAX / FFABS(factor))

            goto error;

        tmp *= factor;

    }

    if (tailp[0] || errno)

        goto error;

    if (dest)

        *dest = tmp;

    return 0;

  error:

    if (config) {

        va_list vl;

        va_start(vl, error_msg);

        vreport_config_error(config->filename, config->line_num, AV_LOG_ERROR,

                &config->errors, error_msg, vl);

        va_end(vl);

    }

    return AVERROR(EINVAL);

}


static int64_t find_tag(AVIOContext *pb, uint32_t tag1)

{

    unsigned int tag;

    int64_t size;

    for (;;) {

        if (url_feof(pb))

            return AVERROR_EOF;

        size = next_tag(pb, &tag);

        if (tag == tag1)

            break;

        wav_seek_tag(pb, size, SEEK_CUR);

    }

    return size;

}


av_cold void ff_float_dsp_init_x86(AVFloatDSPContext *fdsp)

{

    int cpu_flags = av_get_cpu_flags();

#if HAVE_6REGS && HAVE_INLINE_ASM

    if (INLINE_AMD3DNOWEXT(cpu_flags)) {

        fdsp->vector_fmul_window  = vector_fmul_window_3dnowext;

    }

    if (INLINE_SSE(cpu_flags)) {

        fdsp->vector_fmul_window = vector_fmul_window_sse;

    }

#endif

    if (EXTERNAL_SSE(cpu_flags)) {

        fdsp->vector_fmul = ff_vector_fmul_sse;

        fdsp->vector_fmac_scalar = ff_vector_fmac_scalar_sse;

        fdsp->vector_fmul_scalar = ff_vector_fmul_scalar_sse;

        fdsp->vector_fmul_add    = ff_vector_fmul_add_sse;

        fdsp->vector_fmul_reverse = ff_vector_fmul_reverse_sse;

        fdsp->scalarproduct_float = ff_scalarproduct_float_sse;

        fdsp->butterflies_float   = ff_butterflies_float_sse;

    }

    if (EXTERNAL_SSE2(cpu_flags)) {

        fdsp->vector_dmul_scalar = ff_vector_dmul_scalar_sse2;

    }

    if (EXTERNAL_AVX(cpu_flags)) {

        fdsp->vector_fmul = ff_vector_fmul_avx;

        fdsp->vector_fmac_scalar = ff_vector_fmac_scalar_avx;

        fdsp->vector_dmul_scalar = ff_vector_dmul_scalar_avx;

        fdsp->vector_fmul_add    = ff_vector_fmul_add_avx;

        fdsp->vector_fmul_reverse = ff_vector_fmul_reverse_avx;

    }

}


static uint64_t omap2_inth_read(void *opaque, target_phys_addr_t addr,

                                unsigned size)

{

    struct omap_intr_handler_s *s = (struct omap_intr_handler_s *) opaque;

    int offset = addr;

    int bank_no, line_no;

    struct omap_intr_handler_bank_s *bank = NULL;

    if ((offset & 0xf80) == 0x80) {

        bank_no = (offset & 0x60) >> 5;

        if (bank_no < s->nbanks) {

            offset &= ~0x60;

            bank = &s->bank[bank_no];

        }

    }

    switch (offset) {

    case 0x00:	/* INTC_REVISION */

        return s->revision;

    case 0x10:	/* INTC_SYSCONFIG */

        return (s->autoidle >> 2) & 1;

    case 0x14:	/* INTC_SYSSTATUS */

        return 1;						/* RESETDONE */

    case 0x40:	/* INTC_SIR_IRQ */

        return s->sir_intr[0];

    case 0x44:	/* INTC_SIR_FIQ */

        return s->sir_intr[1];

    case 0x48:	/* INTC_CONTROL */

        return (!s->mask) << 2;					/* GLOBALMASK */

    case 0x4c:	/* INTC_PROTECTION */

    case 0x50:	/* INTC_IDLE */

        return s->autoidle & 3;

    /* Per-bank registers */

    case 0x80:	/* INTC_ITR */

        return bank->inputs;

    case 0x84:	/* INTC_MIR */

        return bank->mask;

    case 0x88:	/* INTC_MIR_CLEAR */

    case 0x8c:	/* INTC_MIR_SET */

    case 0x90:	/* INTC_ISR_SET */

        return bank->swi;

    case 0x94:	/* INTC_ISR_CLEAR */

    case 0x98:	/* INTC_PENDING_IRQ */

        return bank->irqs & ~bank->mask & ~bank->fiq;

    case 0x9c:	/* INTC_PENDING_FIQ */

        return bank->irqs & ~bank->mask & bank->fiq;

    /* Per-line registers */

    case 0x100 ... 0x300:	/* INTC_ILR */

        bank_no = (offset - 0x100) >> 7;

        if (bank_no > s->nbanks)

            break;

        bank = &s->bank[bank_no];

        line_no = (offset & 0x7f) >> 2;

        return (bank->priority[line_no] << 2) |

                ((bank->fiq >> line_no) & 1);

    }

}


static inline void get_limits(MpegEncContext *s, int *range, int *xmin, int *ymin, int *xmax, int *ymax, int f_code)

{

    *range = 8 * (1 << (f_code - 1));

    /* XXX: temporary kludge to avoid overflow for msmpeg4 */

    if (s->out_format == FMT_H263 && !s->h263_msmpeg4)

	*range *= 2;

    if (s->unrestricted_mv) {

        *xmin = -16;

        *ymin = -16;

        if (s->h263_plus)

            *range *= 2;

        if(s->avctx->codec->id!=CODEC_ID_MPEG4){

            *xmax = s->mb_width*16;

            *ymax = s->mb_height*16;

        }else {

            *xmax = s->width;

            *ymax = s->height;

        }

    } else {

        *xmin = 0;

        *ymin = 0;

        *xmax = s->mb_width*16 - 16;

        *ymax = s->mb_height*16 - 16;

    }

}


static int device_try_init(AVFormatContext *ctx,

                           enum AVPixelFormat pix_fmt,

                           int *width,

                           int *height,

                           uint32_t *desired_format,

                           enum AVCodecID *codec_id)

{

    int ret, i;

    *desired_format = avpriv_fmt_ff2v4l(pix_fmt, ctx->video_codec_id);

    if (*desired_format) {

        ret = device_init(ctx, width, height, *desired_format);

        if (ret < 0) {

            *desired_format = 0;

            if (ret != AVERROR(EINVAL))

                return ret;

        }

    }

    if (!*desired_format) {

        for (i = 0; avpriv_fmt_conversion_table[i].codec_id != AV_CODEC_ID_NONE; i++) {

            if (ctx->video_codec_id == AV_CODEC_ID_NONE ||

                avpriv_fmt_conversion_table[i].codec_id == ctx->video_codec_id) {

                av_log(ctx, AV_LOG_DEBUG, "Trying to set codec:%s pix_fmt:%s\n",

                       avcodec_get_name(avpriv_fmt_conversion_table[i].codec_id),

                       (char *)av_x_if_null(av_get_pix_fmt_name(avpriv_fmt_conversion_table[i].ff_fmt), "none"));

                *desired_format = avpriv_fmt_conversion_table[i].v4l2_fmt;

                ret = device_init(ctx, width, height, *desired_format);

                if (ret >= 0)

                    break;

                else if (ret != AVERROR(EINVAL))

                    return ret;

                *desired_format = 0;

            }

        }

        if (*desired_format == 0) {

            av_log(ctx, AV_LOG_ERROR, "Cannot find a proper format for "

                   "codec '%s' (id %d), pixel format '%s' (id %d)\n",

                   avcodec_get_name(ctx->video_codec_id), ctx->video_codec_id,

                   (char *)av_x_if_null(av_get_pix_fmt_name(pix_fmt), "none"), pix_fmt);

            ret = AVERROR(EINVAL);

        }

    }

    *codec_id = avpriv_fmt_v4l2codec(*desired_format);

    av_assert0(*codec_id != AV_CODEC_ID_NONE);

    return ret;

}


static void lsi_soft_reset(LSIState *s)

{

    lsi_request *p;

    DPRINTF("Reset\n");

    s->carry = 0;

    s->msg_action = 0;

    s->msg_len = 0;

    s->waiting = 0;

    s->dsa = 0;

    s->dnad = 0;

    s->dbc = 0;

    s->temp = 0;

    memset(s->scratch, 0, sizeof(s->scratch));

    s->istat0 = 0;

    s->istat1 = 0;

    s->dcmd = 0x40;

    s->dstat = LSI_DSTAT_DFE;

    s->dien = 0;

    s->sist0 = 0;

    s->sist1 = 0;

    s->sien0 = 0;

    s->sien1 = 0;

    s->mbox0 = 0;

    s->mbox1 = 0;

    s->dfifo = 0;

    s->ctest2 = LSI_CTEST2_DACK;

    s->ctest3 = 0;

    s->ctest4 = 0;

    s->ctest5 = 0;

    s->ccntl0 = 0;

    s->ccntl1 = 0;

    s->dsp = 0;

    s->dsps = 0;

    s->dmode = 0;

    s->dcntl = 0;

    s->scntl0 = 0xc0;

    s->scntl1 = 0;

    s->scntl2 = 0;

    s->scntl3 = 0;

    s->sstat0 = 0;

    s->sstat1 = 0;

    s->scid = 7;

    s->sxfer = 0;

    s->socl = 0;

    s->sdid = 0;

    s->ssid = 0;

    s->stest1 = 0;

    s->stest2 = 0;

    s->stest3 = 0;

    s->sidl = 0;

    s->stime0 = 0;

    s->respid0 = 0x80;

    s->respid1 = 0;

    s->mmrs = 0;

    s->mmws = 0;

    s->sfs = 0;

    s->drs = 0;

    s->sbms = 0;

    s->dbms = 0;

    s->dnad64 = 0;

    s->pmjad1 = 0;

    s->pmjad2 = 0;

    s->rbc = 0;

    s->ua = 0;

    s->ia = 0;

    s->sbc = 0;

    s->csbc = 0;

    s->sbr = 0;

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

        p = QTAILQ_FIRST(&s->queue);

        QTAILQ_REMOVE(&s->queue, p, next);

        g_free(p);

    }

    if (s->current) {

        g_free(s->current);

        s->current = NULL;

    }

}


static void mclms_predict(WmallDecodeCtx *s, int icoef, int *pred)

{

    int ich, i;

    int order        = s->mclms_order;

    int num_channels = s->num_channels;

    for (ich = 0; ich < num_channels; ich++) {

        pred[ich] = 0;

        if (!s->is_channel_coded[ich])

            continue;

        for (i = 0; i < order * num_channels; i++)

            pred[ich] += s->mclms_prevvalues[i + s->mclms_recent] *

                         s->mclms_coeffs[i + order * num_channels * ich];

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

            pred[ich] += s->channel_residues[i][icoef] *

                         s->mclms_coeffs_cur[i + num_channels * ich];

        pred[ich] += 1 << s->mclms_scaling - 1;

        pred[ich] >>= s->mclms_scaling;

        s->channel_residues[ich][icoef] += pred[ich];

    }

}


static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)

{

    VncDisplay *vd = ds->opaque;

    VncState *vs = vd->clients;

    while (vs != NULL) {

        if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT))

            vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);

        else /* TODO */

            vnc_update(vs, dst_x, dst_y, w, h);

        vs = vs->next;

    }

}


static int emulated_exitfn(CCIDCardState *base)

{

    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);

    VEvent *vevent = vevent_new(VEVENT_LAST, NULL, NULL);

    vevent_queue_vevent(vevent); /* stop vevent thread */

    qemu_mutex_lock(&card->apdu_thread_quit_mutex);

    card->quit_apdu_thread = 1; /* stop handle_apdu thread */

    qemu_cond_signal(&card->handle_apdu_cond);

    qemu_cond_wait(&card->apdu_thread_quit_cond,

                      &card->apdu_thread_quit_mutex);

    /* handle_apdu thread stopped, can destroy all of it's mutexes */

    qemu_cond_destroy(&card->handle_apdu_cond);

    qemu_cond_destroy(&card->apdu_thread_quit_cond);

    qemu_mutex_destroy(&card->apdu_thread_quit_mutex);

    qemu_mutex_destroy(&card->handle_apdu_mutex);

    qemu_mutex_destroy(&card->vreader_mutex);

    qemu_mutex_destroy(&card->event_list_mutex);

    return 0;

}


static inline int get_chroma_qp(H264Context *h, int qscale){

    return h->pps.chroma_qp_table[qscale & 0xff];

}


int AAC_RENAME(ff_ps_read_data)(AVCodecContext *avctx, GetBitContext *gb_host, PSContext *ps, int bits_left)

{

    int e;

    int bit_count_start = get_bits_count(gb_host);

    int header;

    int bits_consumed;

    GetBitContext gbc = *gb_host, *gb = &gbc;

    header = get_bits1(gb);

    if (header) {     //enable_ps_header

        ps->enable_iid = get_bits1(gb);

        if (ps->enable_iid) {

            int iid_mode = get_bits(gb, 3);

            if (iid_mode > 5) {

                av_log(avctx, AV_LOG_ERROR, "iid_mode %d is reserved.\n",

                       iid_mode);

                goto err;

            }

            ps->nr_iid_par    = nr_iidicc_par_tab[iid_mode];

            ps->iid_quant     = iid_mode > 2;

            ps->nr_ipdopd_par = nr_iidopd_par_tab[iid_mode];

        }

        ps->enable_icc = get_bits1(gb);

        if (ps->enable_icc) {

            ps->icc_mode = get_bits(gb, 3);

            if (ps->icc_mode > 5) {

                av_log(avctx, AV_LOG_ERROR, "icc_mode %d is reserved.\n",

                       ps->icc_mode);

                goto err;

            }

            ps->nr_icc_par = nr_iidicc_par_tab[ps->icc_mode];

        }

        ps->enable_ext = get_bits1(gb);

    }

    ps->frame_class = get_bits1(gb);

    ps->num_env_old = ps->num_env;

    ps->num_env     = num_env_tab[ps->frame_class][get_bits(gb, 2)];

    ps->border_position[0] = -1;

    if (ps->frame_class) {

        for (e = 1; e <= ps->num_env; e++)

            ps->border_position[e] = get_bits(gb, 5);

    } else

        for (e = 1; e <= ps->num_env; e++)

            ps->border_position[e] = (e * numQMFSlots >> ff_log2_tab[ps->num_env]) - 1;

    if (ps->enable_iid) {

        for (e = 0; e < ps->num_env; e++) {

            int dt = get_bits1(gb);

            if (read_iid_data(avctx, gb, ps, ps->iid_par, huff_iid[2*dt+ps->iid_quant], e, dt))

                goto err;

        }

    } else

        memset(ps->iid_par, 0, sizeof(ps->iid_par));

    if (ps->enable_icc)

        for (e = 0; e < ps->num_env; e++) {

            int dt = get_bits1(gb);

            if (read_icc_data(avctx, gb, ps, ps->icc_par, dt ? huff_icc_dt : huff_icc_df, e, dt))

                goto err;

        }

    else

        memset(ps->icc_par, 0, sizeof(ps->icc_par));

    if (ps->enable_ext) {

        int cnt = get_bits(gb, 4);

        if (cnt == 15) {

            cnt += get_bits(gb, 8);

        }

        cnt *= 8;

        while (cnt > 7) {

            int ps_extension_id = get_bits(gb, 2);

            cnt -= 2 + ps_read_extension_data(gb, ps, ps_extension_id);

        }

        if (cnt < 0) {

            av_log(avctx, AV_LOG_ERROR, "ps extension overflow %d\n", cnt);

            goto err;

        }

        skip_bits(gb, cnt);

    }

    ps->enable_ipdopd &= !PS_BASELINE;

    //Fix up envelopes

    if (!ps->num_env || ps->border_position[ps->num_env] < numQMFSlots - 1) {

        //Create a fake envelope

        int source = ps->num_env ? ps->num_env - 1 : ps->num_env_old - 1;

        int b;

        if (source >= 0 && source != ps->num_env) {

            if (ps->enable_iid) {

                memcpy(ps->iid_par+ps->num_env, ps->iid_par+source, sizeof(ps->iid_par[0]));

            }

            if (ps->enable_icc) {

                memcpy(ps->icc_par+ps->num_env, ps->icc_par+source, sizeof(ps->icc_par[0]));

            }

            if (ps->enable_ipdopd) {

                memcpy(ps->ipd_par+ps->num_env, ps->ipd_par+source, sizeof(ps->ipd_par[0]));

                memcpy(ps->opd_par+ps->num_env, ps->opd_par+source, sizeof(ps->opd_par[0]));

            }

        }

        if (ps->enable_iid){

            for (b = 0; b < ps->nr_iid_par; b++) {

                if (FFABS(ps->iid_par[ps->num_env][b]) > 7 + 8 * ps->iid_quant) {

                    av_log(avctx, AV_LOG_ERROR, "iid_par invalid\n");

                    goto err;

                }

            }

        }

        if (ps->enable_icc){

            for (b = 0; b < ps->nr_iid_par; b++) {

                if (ps->icc_par[ps->num_env][b] > 7U) {

                    av_log(avctx, AV_LOG_ERROR, "icc_par invalid\n");

                    goto err;

                }

            }

        }

        ps->num_env++;

        ps->border_position[ps->num_env] = numQMFSlots - 1;

    }

    ps->is34bands_old = ps->is34bands;

    if (!PS_BASELINE && (ps->enable_iid || ps->enable_icc))

        ps->is34bands = (ps->enable_iid && ps->nr_iid_par == 34) ||

                        (ps->enable_icc && ps->nr_icc_par == 34);

    //Baseline

    if (!ps->enable_ipdopd) {

        memset(ps->ipd_par, 0, sizeof(ps->ipd_par));

        memset(ps->opd_par, 0, sizeof(ps->opd_par));

    }

    if (header)

        ps->start = 1;

    bits_consumed = get_bits_count(gb) - bit_count_start;

    if (bits_consumed <= bits_left) {

        skip_bits_long(gb_host, bits_consumed);

        return bits_consumed;

    }

    av_log(avctx, AV_LOG_ERROR, "Expected to read %d PS bits actually read %d.\n", bits_left, bits_consumed);

err:

    ps->start = 0;

    skip_bits_long(gb_host, bits_left);

    memset(ps->iid_par, 0, sizeof(ps->iid_par));

    memset(ps->icc_par, 0, sizeof(ps->icc_par));

    memset(ps->ipd_par, 0, sizeof(ps->ipd_par));

    memset(ps->opd_par, 0, sizeof(ps->opd_par));

    return bits_left;

}