static int pcm_decode_frame(AVCodecContext *avctx, void *data,

                            int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *src = avpkt->data;

    int buf_size       = avpkt->size;

    PCMDecode *s       = avctx->priv_data;

    int sample_size, c, n, ret, samples_per_block;

    uint8_t *samples;

    int32_t *dst_int32_t;

    sample_size = av_get_bits_per_sample(avctx->codec_id) / 8;

    /* av_get_bits_per_sample returns 0 for AV_CODEC_ID_PCM_DVD */

    samples_per_block = 1;

    if (AV_CODEC_ID_PCM_DVD == avctx->codec_id) {

        if (avctx->bits_per_coded_sample != 20 &&

            avctx->bits_per_coded_sample != 24) {

            av_log(avctx, AV_LOG_ERROR, "PCM DVD unsupported sample depth\n");

            return AVERROR(EINVAL);

        }

        /* 2 samples are interleaved per block in PCM_DVD */

        samples_per_block = 2;

        sample_size       = avctx->bits_per_coded_sample * 2 / 8;

    } else if (avctx->codec_id == AV_CODEC_ID_PCM_LXF) {

        /* we process 40-bit blocks per channel for LXF */

        samples_per_block = 2;

        sample_size       = 5;

    }

    if (sample_size == 0) {

        av_log(avctx, AV_LOG_ERROR, "Invalid sample_size\n");

        return AVERROR(EINVAL);

    }

    n = avctx->channels * sample_size;

    if (n && buf_size % n) {

        if (buf_size < n) {

            av_log(avctx, AV_LOG_ERROR, "invalid PCM packet\n");

            return -1;

        } else

            buf_size -= buf_size % n;

    }

    n = buf_size / sample_size;

    /* get output buffer */

    s->frame.nb_samples = n * samples_per_block / avctx->channels;

    if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {

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

        return ret;

    }

    samples = s->frame.data[0];

    switch (avctx->codec->id) {

    case AV_CODEC_ID_PCM_U32LE:

        DECODE(32, le32, src, samples, n, 0, 0x80000000)

        break;

    case AV_CODEC_ID_PCM_U32BE:

        DECODE(32, be32, src, samples, n, 0, 0x80000000)

        break;

    case AV_CODEC_ID_PCM_S24LE:

        DECODE(32, le24, src, samples, n, 8, 0)

        break;

    case AV_CODEC_ID_PCM_S24BE:

        DECODE(32, be24, src, samples, n, 8, 0)

        break;

    case AV_CODEC_ID_PCM_U24LE:

        DECODE(32, le24, src, samples, n, 8, 0x800000)

        break;

    case AV_CODEC_ID_PCM_U24BE:

        DECODE(32, be24, src, samples, n, 8, 0x800000)

        break;

    case AV_CODEC_ID_PCM_S24DAUD:

        for (; n > 0; n--) {

            uint32_t v = bytestream_get_be24(&src);

            v >>= 4; // sync flags are here

            AV_WN16A(samples, ff_reverse[(v >> 8) & 0xff] +

                             (ff_reverse[v        & 0xff] << 8));

            samples += 2;

        }

        break;

    case AV_CODEC_ID_PCM_S16LE_PLANAR:

    {

        n /= avctx->channels;

        for (c = 0; c < avctx->channels; c++) {

            samples = s->frame.extended_data[c];

#if HAVE_BIGENDIAN

            DECODE(16, le16, src, samples, n, 0, 0)

#else

            memcpy(samples, src, n * 2);

#endif

            src += n * 2;

        }

        break;

    }

    case AV_CODEC_ID_PCM_U16LE:

        DECODE(16, le16, src, samples, n, 0, 0x8000)

        break;

    case AV_CODEC_ID_PCM_U16BE:

        DECODE(16, be16, src, samples, n, 0, 0x8000)

        break;

    case AV_CODEC_ID_PCM_S8:

        for (; n > 0; n--)

            *samples++ = *src++ + 128;

        break;

#if HAVE_BIGENDIAN

    case AV_CODEC_ID_PCM_F64LE:

        DECODE(64, le64, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_S32LE:

    case AV_CODEC_ID_PCM_F32LE:

        DECODE(32, le32, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_S16LE:

        DECODE(16, le16, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_F64BE:

    case AV_CODEC_ID_PCM_F32BE:

    case AV_CODEC_ID_PCM_S32BE:

    case AV_CODEC_ID_PCM_S16BE:

#else

    case AV_CODEC_ID_PCM_F64BE:

        DECODE(64, be64, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_F32BE:

    case AV_CODEC_ID_PCM_S32BE:

        DECODE(32, be32, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_S16BE:

        DECODE(16, be16, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_F64LE:

    case AV_CODEC_ID_PCM_F32LE:

    case AV_CODEC_ID_PCM_S32LE:

    case AV_CODEC_ID_PCM_S16LE:

#endif /* HAVE_BIGENDIAN */

    case AV_CODEC_ID_PCM_U8:

        memcpy(samples, src, n * sample_size);

        break;

    case AV_CODEC_ID_PCM_ZORK:

        for (; n > 0; n--) {

            int v = *src++;

            if (v < 128)

                v = 128 - v;

            *samples++ = v;

        }

        break;

    case AV_CODEC_ID_PCM_ALAW:

    case AV_CODEC_ID_PCM_MULAW:

        for (; n > 0; n--) {

            AV_WN16A(samples, s->table[*src++]);

            samples += 2;

        }

        break;

    case AV_CODEC_ID_PCM_DVD:

    {

        const uint8_t *src8;

        dst_int32_t = (int32_t *)s->frame.data[0];

        n /= avctx->channels;

        switch (avctx->bits_per_coded_sample) {

        case 20:

            while (n--) {

                c    = avctx->channels;

                src8 = src + 4 * c;

                while (c--) {

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8   & 0xf0) <<  8);

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++ & 0x0f) << 12);

                }

                src = src8;

            }

            break;

        case 24:

            while (n--) {

                c    = avctx->channels;

                src8 = src + 4 * c;

                while (c--) {

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++) << 8);

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++) << 8);

                }

                src = src8;

            }

            break;

        }

        break;

    }

    case AV_CODEC_ID_PCM_LXF:

    {

        int i;

        n /= avctx->channels;

        for (c = 0; c < avctx->channels; c++) {

            dst_int32_t = (int32_t *)s->frame.extended_data[c];

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

                // extract low 20 bits and expand to 32 bits

                *dst_int32_t++ =  (src[2]         << 28) |

                                  (src[1]         << 20) |

                                  (src[0]         << 12) |

                                 ((src[2] & 0x0F) <<  8) |

                                   src[1];

                // extract high 20 bits and expand to 32 bits

                *dst_int32_t++ =  (src[4]         << 24) |

                                  (src[3]         << 16) |

                                 ((src[2] & 0xF0) <<  8) |

                                  (src[4]         <<  4) |

                                  (src[3]         >>  4);

                src += 5;

            }

        }

        break;

    }

    default:

        return -1;

    }

    *got_frame_ptr   = 1;

    *(AVFrame *)data = s->frame;

    return buf_size;

}


void bmdma_cmd_writeb(BMDMAState *bm, uint32_t val)

{

#ifdef DEBUG_IDE

    printf("%s: 0x%08x\n", __func__, val);

#endif

    /* Ignore writes to SSBM if it keeps the old value */

    if ((val & BM_CMD_START) != (bm->cmd & BM_CMD_START)) {

        if (!(val & BM_CMD_START)) {

            /*

             * We can't cancel Scatter Gather DMA in the middle of the

             * operation or a partial (not full) DMA transfer would reach

             * the storage so we wait for completion instead (we beahve

             * like if the DMA was completed by the time the guest trying

             * to cancel dma with bmdma_cmd_writeb with BM_CMD_START not

             * set).

             *

             * In the future we'll be able to safely cancel the I/O if the

             * whole DMA operation will be submitted to disk with a single

             * aio operation with preadv/pwritev.

             */

            if (bm->bus->dma->aiocb) {

                qemu_aio_flush();

                assert(bm->bus->dma->aiocb == NULL);

                assert((bm->status & BM_STATUS_DMAING) == 0);

            }

        } else {

            bm->cur_addr = bm->addr;

            if (!(bm->status & BM_STATUS_DMAING)) {

                bm->status |= BM_STATUS_DMAING;

                /* start dma transfer if possible */

                if (bm->dma_cb)

                    bm->dma_cb(bmdma_active_if(bm), 0);

            }

        }

    }

    bm->cmd = val & 0x09;

}


static void virtio_9p_get_config(VirtIODevice *vdev, uint8_t *config)

{

    struct virtio_9p_config *cfg;

    V9fsState *s = to_virtio_9p(vdev);

    cfg = g_malloc0(sizeof(struct virtio_9p_config) +

                        s->tag_len);

    stw_raw(&cfg->tag_len, s->tag_len);

    memcpy(cfg->tag, s->tag, s->tag_len);

    memcpy(config, cfg, s->config_size);

    g_free(cfg);

}


static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,

                                                const char *model,

                                                const char *name,

                                                int fd, int is_connected)

{

    struct sockaddr_in saddr;

    int newfd;

    socklen_t saddr_len;

    NetClientState *nc;

    NetSocketState *s;

    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it

     * Because this may be "shared" socket from a "master" process, datagrams would be recv()

     * by ONLY ONE process: we must "clone" this dgram socket --jjo

     */

    if (is_connected) {

        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {

            /* must be bound */

            if (saddr.sin_addr.s_addr == 0) {

                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, "

                        "cannot setup multicast dst addr\n", fd);

                goto err;

            }

            /* clone dgram socket */

            newfd = net_socket_mcast_create(&saddr, NULL);

            if (newfd < 0) {

                /* error already reported by net_socket_mcast_create() */

                goto err;

            }

            /* clone newfd to fd, close newfd */

            dup2(newfd, fd);

            close(newfd);

        } else {

            fprintf(stderr,

                    "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",

                    fd, strerror(errno));

            goto err;

        }

    }

    nc = qemu_new_net_client(&net_dgram_socket_info, peer, model, name);

    snprintf(nc->info_str, sizeof(nc->info_str),

            "socket: fd=%d (%s mcast=%s:%d)",

            fd, is_connected ? "cloned" : "",

            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));

    s = DO_UPCAST(NetSocketState, nc, nc);

    s->fd = fd;

    s->listen_fd = -1;

    s->send_fn = net_socket_send_dgram;

    net_socket_read_poll(s, true);

    /* mcast: save bound address as dst */

    if (is_connected) {

        s->dgram_dst = saddr;

    }

    return s;

err:

    closesocket(fd);

    return NULL;

}


static int qcow2_create2(const char *filename, int64_t total_size,

                         const char *backing_file, const char *backing_format,

                         int flags, size_t cluster_size, int prealloc,

                         QEMUOptionParameter *options, int version,

                         Error **errp)

{

    /* Calculate cluster_bits */

    int cluster_bits;

    cluster_bits = ffs(cluster_size) - 1;

    if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||

        (1 << cluster_bits) != cluster_size)

    {

        error_setg(errp, "Cluster size must be a power of two between %d and "

                   "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));

        return -EINVAL;

    }

    /*

     * Open the image file and write a minimal qcow2 header.

     *

     * We keep things simple and start with a zero-sized image. We also

     * do without refcount blocks or a L1 table for now. We'll fix the

     * inconsistency later.

     *

     * We do need a refcount table because growing the refcount table means

     * allocating two new refcount blocks - the seconds of which would be at

     * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file

     * size for any qcow2 image.

     */

    BlockDriverState* bs;

    QCowHeader header;

    uint8_t* refcount_table;

    Error *local_err = NULL;

    int ret;

    ret = bdrv_create_file(filename, options, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        return ret;

    }

    ret = bdrv_file_open(&bs, filename, NULL, BDRV_O_RDWR, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        return ret;

    }

    /* Write the header */

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

    header.magic = cpu_to_be32(QCOW_MAGIC);

    header.version = cpu_to_be32(version);

    header.cluster_bits = cpu_to_be32(cluster_bits);

    header.size = cpu_to_be64(0);

    header.l1_table_offset = cpu_to_be64(0);

    header.l1_size = cpu_to_be32(0);

    header.refcount_table_offset = cpu_to_be64(cluster_size);

    header.refcount_table_clusters = cpu_to_be32(1);

    header.refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT);

    header.header_length = cpu_to_be32(sizeof(header));

    if (flags & BLOCK_FLAG_ENCRYPT) {

        header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);

    } else {

        header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);

    }

    if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {

        header.compatible_features |=

            cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);

    }

    ret = bdrv_pwrite(bs, 0, &header, sizeof(header));

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not write qcow2 header");

        goto out;

    }

    /* Write an empty refcount table */

    refcount_table = g_malloc0(cluster_size);

    ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);

    g_free(refcount_table);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not write refcount table");

        goto out;

    }

    bdrv_close(bs);

    /*

     * And now open the image and make it consistent first (i.e. increase the

     * refcount of the cluster that is occupied by the header and the refcount

     * table)

     */

    BlockDriver* drv = bdrv_find_format("qcow2");

    assert(drv != NULL);

    ret = bdrv_open(bs, filename, NULL,

        BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto out;

    }

    ret = qcow2_alloc_clusters(bs, 2 * cluster_size);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "

                         "header and refcount table");

        goto out;

    } else if (ret != 0) {

        error_report("Huh, first cluster in empty image is already in use?");

        abort();

    }

    /* Okay, now that we have a valid image, let's give it the right size */

    ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not resize image");

        goto out;

    }

    /* Want a backing file? There you go.*/

    if (backing_file) {

        ret = bdrv_change_backing_file(bs, backing_file, backing_format);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not assign backing file '%s' "

                             "with format '%s'", backing_file, backing_format);

            goto out;

        }

    }

    /* And if we're supposed to preallocate metadata, do that now */

    if (prealloc) {

        BDRVQcowState *s = bs->opaque;

        qemu_co_mutex_lock(&s->lock);

        ret = preallocate(bs);

        qemu_co_mutex_unlock(&s->lock);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not preallocate metadata");

            goto out;

        }

    }

    bdrv_close(bs);

    /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */

    ret = bdrv_open(bs, filename, NULL,

                    BDRV_O_RDWR | BDRV_O_CACHE_WB, drv, &local_err);

    if (error_is_set(&local_err)) {

        error_propagate(errp, local_err);

        goto out;

    }

    ret = 0;

out:

    bdrv_unref(bs);

    return ret;

}


static void tci_out_label(TCGContext *s, TCGArg arg)

{

    TCGLabel *label = &s->labels[arg];

    if (label->has_value) {

        tcg_out_i(s, label->u.value);

        assert(label->u.value);

    } else {

        tcg_out_reloc(s, s->code_ptr, sizeof(tcg_target_ulong), arg, 0);

        s->code_ptr += sizeof(tcg_target_ulong);

    }

}


uint32_t lduw_le_phys(target_phys_addr_t addr)

{

    return lduw_phys_internal(addr, DEVICE_LITTLE_ENDIAN);

}


int get_async_context_id(void)

{

    return async_context->id;

}


static void piix4_pm_realize(PCIDevice *dev, Error **errp)

{

    PIIX4PMState *s = PIIX4_PM(dev);

    uint8_t *pci_conf;

    pci_conf = dev->config;

    pci_conf[0x06] = 0x80;

    pci_conf[0x07] = 0x02;

    pci_conf[0x09] = 0x00;

    pci_conf[0x3d] = 0x01; // interrupt pin 1

    /* APM */

    apm_init(dev, &s->apm, apm_ctrl_changed, s);

    if (!s->smm_enabled) {

        /* Mark SMM as already inited to prevent SMM from running.  KVM does not

         * support SMM mode. */

        pci_conf[0x5B] = 0x02;

    }

    /* XXX: which specification is used ? The i82731AB has different

       mappings */

    pci_conf[0x90] = s->smb_io_base | 1;

    pci_conf[0x91] = s->smb_io_base >> 8;

    pci_conf[0xd2] = 0x09;

    pm_smbus_init(DEVICE(dev), &s->smb);

    memory_region_set_enabled(&s->smb.io, pci_conf[0xd2] & 1);

    memory_region_add_subregion(pci_address_space_io(dev),

                                s->smb_io_base, &s->smb.io);

    memory_region_init(&s->io, OBJECT(s), "piix4-pm", 64);

    memory_region_set_enabled(&s->io, false);

    memory_region_add_subregion(pci_address_space_io(dev),

                                0, &s->io);

    acpi_pm_tmr_init(&s->ar, pm_tmr_timer, &s->io);

    acpi_pm1_evt_init(&s->ar, pm_tmr_timer, &s->io);

    acpi_pm1_cnt_init(&s->ar, &s->io, s->disable_s3, s->disable_s4, s->s4_val);

    acpi_gpe_init(&s->ar, GPE_LEN);

    s->powerdown_notifier.notify = piix4_pm_powerdown_req;

    qemu_register_powerdown_notifier(&s->powerdown_notifier);

    s->machine_ready.notify = piix4_pm_machine_ready;

    qemu_add_machine_init_done_notifier(&s->machine_ready);

    qemu_register_reset(piix4_reset, s);

    piix4_acpi_system_hot_add_init(pci_address_space_io(dev), dev->bus, s);

    piix4_pm_add_propeties(s);

}


static always_inline void gen_qemu_ldg (TCGv t0, TCGv t1, int flags)

{

    TCGv tmp = tcg_temp_new(TCG_TYPE_I64);

    tcg_gen_qemu_ld64(tmp, t1, flags);

    tcg_gen_helper_1_1(helper_memory_to_g, t0, tmp);

    tcg_temp_free(tmp);

}


static void register_subpage(MemoryRegionSection *section)

{

    subpage_t *subpage;

    target_phys_addr_t base = section->offset_within_address_space

        & TARGET_PAGE_MASK;

    MemoryRegionSection *existing = phys_page_find(base >> TARGET_PAGE_BITS);

    MemoryRegionSection subsection = {

        .offset_within_address_space = base,

        .size = TARGET_PAGE_SIZE,

    };

    target_phys_addr_t start, end;

    assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);

    if (!(existing->mr->subpage)) {

        subpage = subpage_init(base);

        subsection.mr = &subpage->iomem;

        phys_page_set(base >> TARGET_PAGE_BITS, 1,

                      phys_section_add(&subsection));

    } else {

        subpage = container_of(existing->mr, subpage_t, iomem);

    }

    start = section->offset_within_address_space & ~TARGET_PAGE_MASK;

    end = start + section->size - 1;

    subpage_register(subpage, start, end, phys_section_add(section));

}


static void do_fp_st(DisasContext *s, int srcidx, TCGv_i64 tcg_addr, int size)

{

    /* This writes the bottom N bits of a 128 bit wide vector to memory */

    TCGv_i64 tmp = tcg_temp_new_i64();

    tcg_gen_ld_i64(tmp, cpu_env, fp_reg_offset(srcidx, MO_64));

    if (size < 4) {

        tcg_gen_qemu_st_i64(tmp, tcg_addr, get_mem_index(s), MO_TE + size);

    } else {

        TCGv_i64 tcg_hiaddr = tcg_temp_new_i64();

        tcg_gen_qemu_st_i64(tmp, tcg_addr, get_mem_index(s), MO_TEQ);

        tcg_gen_qemu_st64(tmp, tcg_addr, get_mem_index(s));

        tcg_gen_ld_i64(tmp, cpu_env, fp_reg_hi_offset(srcidx));

        tcg_gen_addi_i64(tcg_hiaddr, tcg_addr, 8);

        tcg_gen_qemu_st_i64(tmp, tcg_hiaddr, get_mem_index(s), MO_TEQ);

        tcg_temp_free_i64(tcg_hiaddr);

    }

    tcg_temp_free_i64(tmp);

}


bool cpu_physical_memory_is_io(target_phys_addr_t phys_addr)

{

    MemoryRegionSection *section;

    section = phys_page_find(phys_addr >> TARGET_PAGE_BITS);

    return !(memory_region_is_ram(section->mr) ||

             memory_region_is_romd(section->mr));

}


void qemu_start_warp_timer(void)

{

    int64_t clock;

    int64_t deadline;

    if (!use_icount) {

        return;

    }

    /* Nothing to do if the VM is stopped: QEMU_CLOCK_VIRTUAL timers

     * do not fire, so computing the deadline does not make sense.

     */

    if (!runstate_is_running()) {

        return;

    }

    /* warp clock deterministically in record/replay mode */

    if (!replay_checkpoint(CHECKPOINT_CLOCK_WARP_START)) {

        return;

    }

    if (!all_cpu_threads_idle()) {

        return;

    }

    if (qtest_enabled()) {

        /* When testing, qtest commands advance icount.  */

        return;

    }

    /* We want to use the earliest deadline from ALL vm_clocks */

    clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT);

    deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);

    if (deadline < 0) {

        static bool notified;

        if (!icount_sleep && !notified) {

            error_report("WARNING: icount sleep disabled and no active timers");

            notified = true;

        }

        return;

    }

    if (deadline > 0) {

        /*

         * Ensure QEMU_CLOCK_VIRTUAL proceeds even when the virtual CPU goes to

         * sleep.  Otherwise, the CPU might be waiting for a future timer

         * interrupt to wake it up, but the interrupt never comes because

         * the vCPU isn't running any insns and thus doesn't advance the

         * QEMU_CLOCK_VIRTUAL.

         */

        if (!icount_sleep) {

            /*

             * We never let VCPUs sleep in no sleep icount mode.

             * If there is a pending QEMU_CLOCK_VIRTUAL timer we just advance

             * to the next QEMU_CLOCK_VIRTUAL event and notify it.

             * It is useful when we want a deterministic execution time,

             * isolated from host latencies.

             */

            seqlock_write_begin(&timers_state.vm_clock_seqlock);

            timers_state.qemu_icount_bias += deadline;

            seqlock_write_end(&timers_state.vm_clock_seqlock);

            qemu_clock_notify(QEMU_CLOCK_VIRTUAL);

        } else {

            /*

             * We do stop VCPUs and only advance QEMU_CLOCK_VIRTUAL after some

             * "real" time, (related to the time left until the next event) has

             * passed. The QEMU_CLOCK_VIRTUAL_RT clock will do this.

             * This avoids that the warps are visible externally; for example,

             * you will not be sending network packets continuously instead of

             * every 100ms.

             */

            seqlock_write_begin(&timers_state.vm_clock_seqlock);

            if (vm_clock_warp_start == -1 || vm_clock_warp_start > clock) {

                vm_clock_warp_start = clock;

            }

            seqlock_write_end(&timers_state.vm_clock_seqlock);

            timer_mod_anticipate(icount_warp_timer, clock + deadline);

        }

    } else if (deadline == 0) {

        qemu_clock_notify(QEMU_CLOCK_VIRTUAL);

    }

}


sdhci_writefn(void *opaque, hwaddr off, uint64_t val, unsigned sz)

{

    SDHCIState *s = (SDHCIState *)opaque;

    SDHCI_GET_CLASS(s)->mem_write(s, off, val, sz);

}


static void rtas_set_xive(sPAPREnvironment *spapr, uint32_t token,

                          uint32_t nargs, target_ulong args,

                          uint32_t nret, target_ulong rets)

{

    struct ics_state *ics = spapr->icp->ics;

    uint32_t nr, server, priority;

    if ((nargs != 3) || (nret != 1)) {

        rtas_st(rets, 0, -3);

        return;

    }

    nr = rtas_ld(args, 0);

    server = rtas_ld(args, 1);

    priority = rtas_ld(args, 2);

    if (!ics_valid_irq(ics, nr) || (server >= ics->icp->nr_servers)

        || (priority > 0xff)) {

        rtas_st(rets, 0, -3);

        return;

    }

    ics_write_xive(ics, nr, server, priority, priority);

    rtas_st(rets, 0, 0); /* Success */

}


static void test_validate_fail_list(TestInputVisitorData *data,

                                     const void *unused)

{

    UserDefOneList *head = NULL;

    Error *err = NULL;

    Visitor *v;

    v = validate_test_init(data, "[ { 'string': 'string0', 'integer': 42 }, { 'string': 'string1', 'integer': 43 }, { 'string': 'string2', 'integer': 44, 'extra': 'ggg' } ]");

    visit_type_UserDefOneList(v, NULL, &head, &err);

    error_free_or_abort(&err);

    g_assert(!head);

}


static int migrate_fd_cleanup(MigrationState *s)

{

    int ret = 0;

    qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);

    if (s->file) {

        DPRINTF("closing file\n");

        if (qemu_fclose(s->file) != 0) {

            ret = -1;

        }

        s->file = NULL;

    } else {

        if (s->mon) {

            monitor_resume(s->mon);

        }

    }

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

        close(s->fd);

        s->fd = -1;

    }

    return ret;

}


static bool all_cpu_threads_idle(void)

{

    CPUState *env;

    for (env = first_cpu; env != NULL; env = env->next_cpu) {

        if (!cpu_thread_is_idle(env)) {

            return false;

        }

    }

    return true;

}


static int vpc_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)

{

    BDRVVPCState *s = (BDRVVPCState *)bs->opaque;

    VHDFooter *footer = (VHDFooter *) s->footer_buf;

    if (cpu_to_be32(footer->type) != VHD_FIXED) {

        bdi->cluster_size = s->block_size;

    }

    bdi->unallocated_blocks_are_zero = true;

    return 0;

}


static int read_header_openmpt(AVFormatContext *s)

{

    AVStream *st;

    OpenMPTContext *openmpt = s->priv_data;

    int64_t size = avio_size(s->pb);

    if (!size)

        return AVERROR_INVALIDDATA;

    char *buf = av_malloc(size);

    int ret;

    if (!buf)

        return AVERROR(ENOMEM);

    size = avio_read(s->pb, buf, size);

    if (size < 0) {

        av_log(s, AV_LOG_ERROR, "Reading input buffer failed.\n");

        av_freep(&buf);

        return size;

    }

    openmpt->module = openmpt_module_create_from_memory(buf, size, openmpt_logfunc, s, NULL);

    av_freep(&buf);

    if (!openmpt->module)

            return AVERROR_INVALIDDATA;

    openmpt->channels   = av_get_channel_layout_nb_channels(openmpt->layout);

    openmpt->duration   = openmpt_module_get_duration_seconds(openmpt->module);

    add_meta(s, "artist",  openmpt_module_get_metadata(openmpt->module, "artist"));

    add_meta(s, "title",   openmpt_module_get_metadata(openmpt->module, "title"));

    add_meta(s, "encoder", openmpt_module_get_metadata(openmpt->module, "tracker"));

    add_meta(s, "comment", openmpt_module_get_metadata(openmpt->module, "message"));

    add_meta(s, "date",    openmpt_module_get_metadata(openmpt->module, "date"));

    if (openmpt->subsong >= openmpt_module_get_num_subsongs(openmpt->module)) {

        openmpt_module_destroy(openmpt->module);

        av_log(s, AV_LOG_ERROR, "Invalid subsong index: %d\n", openmpt->subsong);

        return AVERROR(EINVAL);

    }

    if (openmpt->subsong != -2) {

        if (openmpt->subsong >= 0) {

            av_dict_set_int(&s->metadata, "track", openmpt->subsong + 1, 0);

        }

        ret = openmpt_module_select_subsong(openmpt->module, openmpt->subsong);

        if (!ret){

            openmpt_module_destroy(openmpt->module);

            av_log(s, AV_LOG_ERROR, "Could not select requested subsong: %d", openmpt->subsong);

            return AVERROR(EINVAL);

        }

    }

    st = avformat_new_stream(s, NULL);

    if (!st) {

        openmpt_module_destroy(openmpt->module);

        openmpt->module = NULL;

        return AVERROR(ENOMEM);

    }

    avpriv_set_pts_info(st, 64, 1, AV_TIME_BASE);

    st->duration = llrint(openmpt->duration*AV_TIME_BASE);

    st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;

    st->codecpar->codec_id    = AV_NE(AV_CODEC_ID_PCM_F32BE, AV_CODEC_ID_PCM_F32LE);

    st->codecpar->channels    = openmpt->channels;

    st->codecpar->sample_rate = openmpt->sample_rate;

    return 0;

}


void helper_mtc0_hwrena(CPUMIPSState *env, target_ulong arg1)

{

    env->CP0_HWREna = arg1 & 0x0000000F;

}


void qemu_cpu_kick(void *_env)

{

    CPUState *env = _env;

    qemu_cond_broadcast(env->halt_cond);

    qemu_thread_signal(env->thread, SIG_IPI);

}


iscsi_inquiry_cb(struct iscsi_context *iscsi, int status, void *command_data,

                 void *opaque)

{

    struct IscsiTask *itask = opaque;

    struct scsi_task *task = command_data;

    struct scsi_inquiry_standard *inq;

    if (status != 0) {

        itask->status   = 1;

        itask->complete = 1;

        scsi_free_scsi_task(task);

        return;

    }

    inq = scsi_datain_unmarshall(task);

    if (inq == NULL) {

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

        itask->status   = 1;

        itask->complete = 1;

        scsi_free_scsi_task(task);

        return;

    }

    itask->iscsilun->type = inq->periperal_device_type;

    scsi_free_scsi_task(task);

    switch (itask->iscsilun->type) {

    case TYPE_DISK:

        task = iscsi_readcapacity16_task(iscsi, itask->iscsilun->lun,

                                   iscsi_readcapacity16_cb, opaque);

        if (task == NULL) {

            error_report("iSCSI: failed to send readcapacity16 command.");

            itask->status   = 1;

            itask->complete = 1;

            return;

        }

        break;

    case TYPE_ROM:

        task = iscsi_readcapacity10_task(iscsi, itask->iscsilun->lun,

                                   0, 0,

                                   iscsi_readcapacity10_cb, opaque);

        if (task == NULL) {

            error_report("iSCSI: failed to send readcapacity16 command.");

            itask->status   = 1;

            itask->complete = 1;

            return;

        }

        break;

    default:

        itask->status   = 0;

        itask->complete = 1;

    }

}


static inline uint8_t mipsdsp_lshift8(uint8_t a, uint8_t s, CPUMIPSState *env)

{

    uint8_t sign;

    uint8_t discard;

    if (s == 0) {

        return a;

    } else {

        sign = (a >> 7) & 0x01;

        if (sign != 0) {

            discard = (((0x01 << (8 - s)) - 1) << s) |

                      ((a >> (6 - (s - 1))) & ((0x01 << s) - 1));

        } else {

            discard = a >> (6 - (s - 1));

        }

        if (discard != 0x00) {

            set_DSPControl_overflow_flag(1, 22, env);

        }

        return a << s;

    }

}


static void dwt_encode97_float(DWTContext *s, float *t)

{

    int lev,

        w = s->linelen[s->ndeclevels-1][0];

    float *line = s->f_linebuf;

    line += 5;

    for (lev = s->ndeclevels-1; lev >= 0; lev--){

        int lh = s->linelen[lev][0],

            lv = s->linelen[lev][1],

            mh = s->mod[lev][0],

            mv = s->mod[lev][1],

            lp;

        float *l;

        // HOR_SD

        l = line + mh;

        for (lp = 0; lp < lv; lp++){

            int i, j = 0;

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

                l[i] = t[w*lp + i];

            sd_1d97_float(line, mh, mh + lh);

            // copy back and deinterleave

            for (i =   mh; i < lh; i+=2, j++)

                t[w*lp + j] = F_LFTG_X * l[i] / 2;

            for (i = 1-mh; i < lh; i+=2, j++)

                t[w*lp + j] = F_LFTG_K * l[i] / 2;

        }

        // VER_SD

        l = line + mv;

        for (lp = 0; lp < lh; lp++) {

            int i, j = 0;

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

                l[i] = t[w*i + lp];

            sd_1d97_float(line, mv, mv + lv);

            // copy back and deinterleave

            for (i =   mv; i < lv; i+=2, j++)

                t[w*j + lp] = F_LFTG_X * l[i] / 2;

            for (i = 1-mv; i < lv; i+=2, j++)

                t[w*j + lp] = F_LFTG_K * l[i] / 2;

        }

    }

}


static void taihu_405ep_init(ram_addr_t ram_size,

                             const char *boot_device,

                             const char *kernel_filename,

                             const char *kernel_cmdline,

                             const char *initrd_filename,

                             const char *cpu_model)

{

    char *filename;

    qemu_irq *pic;

    ram_addr_t bios_offset;

    target_phys_addr_t ram_bases[2], ram_sizes[2];

    long bios_size;

    target_ulong kernel_base, initrd_base;

    long kernel_size, initrd_size;

    int linux_boot;

    int fl_idx, fl_sectors;

    DriveInfo *dinfo;

    /* RAM is soldered to the board so the size cannot be changed */

    ram_bases[0] = qemu_ram_alloc(NULL, "taihu_405ep.ram-0", 0x04000000);

    ram_sizes[0] = 0x04000000;

    ram_bases[1] = qemu_ram_alloc(NULL, "taihu_405ep.ram-1", 0x04000000);

    ram_sizes[1] = 0x04000000;

    ram_size = 0x08000000;

#ifdef DEBUG_BOARD_INIT

    printf("%s: register cpu\n", __func__);

#endif

    ppc405ep_init(ram_bases, ram_sizes, 33333333, &pic,

                  kernel_filename == NULL ? 0 : 1);

    /* allocate and load BIOS */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register BIOS\n", __func__);

#endif

    fl_idx = 0;

#if defined(USE_FLASH_BIOS)

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

    if (dinfo) {

        bios_size = bdrv_getlength(dinfo->bdrv);

        /* XXX: should check that size is 2MB */

        //        bios_size = 2 * 1024 * 1024;

        fl_sectors = (bios_size + 65535) >> 16;

        bios_offset = qemu_ram_alloc(NULL, "taihu_405ep.bios", bios_size);

#ifdef DEBUG_BOARD_INIT

        printf("Register parallel flash %d size %lx"

               " at offset %08lx addr %lx '%s' %d\n",

               fl_idx, bios_size, bios_offset, -bios_size,

               bdrv_get_device_name(dinfo->bdrv), fl_sectors);

#endif

        pflash_cfi02_register((uint32_t)(-bios_size), bios_offset,

                              dinfo->bdrv, 65536, fl_sectors, 1,

                              4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,

                              1);

        fl_idx++;

    } else

#endif

    {

#ifdef DEBUG_BOARD_INIT

        printf("Load BIOS from file\n");

#endif

        if (bios_name == NULL)

            bios_name = BIOS_FILENAME;

        bios_offset = qemu_ram_alloc(NULL, "taihu_405ep.bios", BIOS_SIZE);

        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        if (filename) {

            bios_size = load_image(filename, qemu_get_ram_ptr(bios_offset));

        } else {

            bios_size = -1;

        }

        if (bios_size < 0 || bios_size > BIOS_SIZE) {

            fprintf(stderr, "qemu: could not load PowerPC bios '%s'\n",

                    bios_name);

            exit(1);

        }

        bios_size = (bios_size + 0xfff) & ~0xfff;

        cpu_register_physical_memory((uint32_t)(-bios_size),

                                     bios_size, bios_offset | IO_MEM_ROM);

    }

    /* Register Linux flash */

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

    if (dinfo) {

        bios_size = bdrv_getlength(dinfo->bdrv);

        /* XXX: should check that size is 32MB */

        bios_size = 32 * 1024 * 1024;

        fl_sectors = (bios_size + 65535) >> 16;

#ifdef DEBUG_BOARD_INIT

        printf("Register parallel flash %d size %lx"

               " at offset %08lx  addr " TARGET_FMT_lx " '%s'\n",

               fl_idx, bios_size, bios_offset, (target_ulong)0xfc000000,

               bdrv_get_device_name(dinfo->bdrv));

#endif

        bios_offset = qemu_ram_alloc(NULL, "taihu_405ep.flash", bios_size);

        pflash_cfi02_register(0xfc000000, bios_offset,

                              dinfo->bdrv, 65536, fl_sectors, 1,

                              4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,

                              1);

        fl_idx++;

    }

    /* Register CLPD & LCD display */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register CPLD\n", __func__);

#endif

    taihu_cpld_init(0x50100000);

    /* Load kernel */

    linux_boot = (kernel_filename != NULL);

    if (linux_boot) {

#ifdef DEBUG_BOARD_INIT

        printf("%s: load kernel\n", __func__);

#endif

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        kernel_size = load_image_targphys(kernel_filename, kernel_base,

                                          ram_size - kernel_base);

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                fprintf(stderr,

                        "qemu: could not load initial ram disk '%s'\n",

                        initrd_filename);

                exit(1);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

    }

#ifdef DEBUG_BOARD_INIT

    printf("%s: Done\n", __func__);

#endif

}


int ff_jpeg2000_init_component(Jpeg2000Component *comp,

                               Jpeg2000CodingStyle *codsty,

                               Jpeg2000QuantStyle *qntsty,

                               int cbps, int dx, int dy,

                               AVCodecContext *avctx)

{

    uint8_t log2_band_prec_width, log2_band_prec_height;

    int reslevelno, bandno, gbandno = 0, ret, i, j;

    uint32_t csize;

    if (!codsty->nreslevels2decode) {

        av_log(avctx, AV_LOG_ERROR, "nreslevels2decode uninitialized\n");

        return AVERROR_INVALIDDATA;

    }

    if (ret = ff_jpeg2000_dwt_init(&comp->dwt, comp->coord,

                                   codsty->nreslevels2decode - 1,

                                   codsty->transform))

        return ret;

    // component size comp->coord is uint16_t so ir cannot overflow

    csize = (comp->coord[0][1] - comp->coord[0][0]) *

            (comp->coord[1][1] - comp->coord[1][0]);

    if (codsty->transform == FF_DWT97) {

        comp->i_data = NULL;

        comp->f_data = av_malloc_array(csize, sizeof(*comp->f_data));

        if (!comp->f_data)

            return AVERROR(ENOMEM);

    } else {

        comp->f_data = NULL;

        comp->i_data = av_malloc_array(csize, sizeof(*comp->i_data));

        if (!comp->i_data)

            return AVERROR(ENOMEM);

    }

    comp->reslevel = av_malloc_array(codsty->nreslevels, sizeof(*comp->reslevel));

    if (!comp->reslevel)

        return AVERROR(ENOMEM);

    /* LOOP on resolution levels */

    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {

        int declvl = codsty->nreslevels - reslevelno;    // N_L -r see  ISO/IEC 15444-1:2002 B.5

        Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;

        /* Compute borders for each resolution level.

         * Computation of trx_0, trx_1, try_0 and try_1.

         * see ISO/IEC 15444-1:2002 eq. B.5 and B-14 */

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

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

                reslevel->coord[i][j] =

                    ff_jpeg2000_ceildivpow2(comp->coord_o[i][j], declvl - 1);

        // update precincts size: 2^n value

        reslevel->log2_prec_width  = codsty->log2_prec_widths[reslevelno];

        reslevel->log2_prec_height = codsty->log2_prec_heights[reslevelno];

        /* Number of bands for each resolution level */

        if (reslevelno == 0)

            reslevel->nbands = 1;

        else

            reslevel->nbands = 3;

        /* Number of precincts wich span the tile for resolution level reslevelno

         * see B.6 in ISO/IEC 15444-1:2002 eq. B-16

         * num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -| - (trx_0 / 2 ^ log2_prec_width)

         * num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| - (try_0 / 2 ^ log2_prec_width)

         * for Dcinema profiles in JPEG 2000

         * num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -|

         * num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| */

        if (reslevel->coord[0][1] == reslevel->coord[0][0])

            reslevel->num_precincts_x = 0;

        else

            reslevel->num_precincts_x =

                ff_jpeg2000_ceildivpow2(reslevel->coord[0][1],

                                        reslevel->log2_prec_width) -

                (reslevel->coord[0][0] >> reslevel->log2_prec_width);

        if (reslevel->coord[1][1] == reslevel->coord[1][0])

            reslevel->num_precincts_y = 0;

        else

            reslevel->num_precincts_y =

                ff_jpeg2000_ceildivpow2(reslevel->coord[1][1],

                                        reslevel->log2_prec_height) -

                (reslevel->coord[1][0] >> reslevel->log2_prec_height);

        reslevel->band = av_malloc_array(reslevel->nbands, sizeof(*reslevel->band));

        if (!reslevel->band)

            return AVERROR(ENOMEM);

        for (bandno = 0; bandno < reslevel->nbands; bandno++, gbandno++) {

            Jpeg2000Band *band = reslevel->band + bandno;

            int cblkno, precno;

            int nb_precincts;

            /* TODO: Implementation of quantization step not finished,

             * see ISO/IEC 15444-1:2002 E.1 and A.6.4. */

            switch (qntsty->quantsty) {

                uint8_t gain;

                int numbps;

            case JPEG2000_QSTY_NONE:

                /* TODO: to verify. No quantization in this case */

                band->f_stepsize = 1;

                break;

            case JPEG2000_QSTY_SI:

                /*TODO: Compute formula to implement. */

                numbps = cbps +

                         lut_gain[codsty->transform == FF_DWT53][bandno + (reslevelno > 0)];

                band->f_stepsize = SHL(2048 + qntsty->mant[gbandno],

                                       2 + numbps - qntsty->expn[gbandno]);

                break;

            case JPEG2000_QSTY_SE:

                /* Exponent quantization step.

                 * Formula:

                 * delta_b = 2 ^ (R_b - expn_b) * (1 + (mant_b / 2 ^ 11))

                 * R_b = R_I + log2 (gain_b )

                 * see ISO/IEC 15444-1:2002 E.1.1 eqn. E-3 and E-4 */

                /* TODO/WARN: value of log2 (gain_b ) not taken into account

                 * but it works (compared to OpenJPEG). Why?

                 * Further investigation needed. */

                gain            = cbps;

                band->f_stepsize  = pow(2.0, gain - qntsty->expn[gbandno]);

                band->f_stepsize *= qntsty->mant[gbandno] / 2048.0 + 1.0;

                break;

            default:

                band->f_stepsize = 0;

                av_log(avctx, AV_LOG_ERROR, "Unknown quantization format\n");

                break;

            }

            /* FIXME: In openjepg code stespize = stepsize * 0.5. Why?

             * If not set output of entropic decoder is not correct. */

            if (!av_codec_is_encoder(avctx->codec))

                band->f_stepsize *= 0.5;

            band->i_stepsize = band->f_stepsize * (1 << 16);

            /* computation of tbx_0, tbx_1, tby_0, tby_1

             * see ISO/IEC 15444-1:2002 B.5 eq. B-15 and tbl B.1

             * codeblock width and height is computed for

             * DCI JPEG 2000 codeblock_width = codeblock_width = 32 = 2 ^ 5 */

            if (reslevelno == 0) {

                /* for reslevelno = 0, only one band, x0_b = y0_b = 0 */

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

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

                        band->coord[i][j] =

                            ff_jpeg2000_ceildivpow2(comp->coord_o[i][j] - comp->coord_o[i][0],

                                                    declvl - 1);

                log2_band_prec_width  = reslevel->log2_prec_width;

                log2_band_prec_height = reslevel->log2_prec_height;

                /* see ISO/IEC 15444-1:2002 eq. B-17 and eq. B-15 */

                band->log2_cblk_width  = FFMIN(codsty->log2_cblk_width,

                                               reslevel->log2_prec_width);

                band->log2_cblk_height = FFMIN(codsty->log2_cblk_height,

                                               reslevel->log2_prec_height);

            } else {

                /* 3 bands x0_b = 1 y0_b = 0; x0_b = 0 y0_b = 1; x0_b = y0_b = 1 */

                /* x0_b and y0_b are computed with ((bandno + 1 >> i) & 1) */

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

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

                        /* Formula example for tbx_0 = ceildiv((tcx_0 - 2 ^ (declvl - 1) * x0_b) / declvl) */

                        band->coord[i][j] =

                            ff_jpeg2000_ceildivpow2(comp->coord_o[i][j] - comp->coord_o[i][0] -

                                                    (((bandno + 1 >> i) & 1) << declvl - 1),

                                                    declvl);

                /* TODO: Manage case of 3 band offsets here or

                 * in coding/decoding function? */

                /* see ISO/IEC 15444-1:2002 eq. B-17 and eq. B-15 */

                band->log2_cblk_width  = FFMIN(codsty->log2_cblk_width,

                                               reslevel->log2_prec_width - 1);

                band->log2_cblk_height = FFMIN(codsty->log2_cblk_height,

                                               reslevel->log2_prec_height - 1);

                log2_band_prec_width  = reslevel->log2_prec_width  - 1;

                log2_band_prec_height = reslevel->log2_prec_height - 1;

            }

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

                band->coord[0][j] = ff_jpeg2000_ceildiv(band->coord[0][j], dx);

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

                band->coord[1][j] = ff_jpeg2000_ceildiv(band->coord[1][j], dy);

            band->prec = av_malloc_array(reslevel->num_precincts_x *

                                         reslevel->num_precincts_y,

                                         sizeof(*band->prec));

            if (!band->prec)

                return AVERROR(ENOMEM);

            nb_precincts = reslevel->num_precincts_x * reslevel->num_precincts_y;

            for (precno = 0; precno < nb_precincts; precno++) {

                Jpeg2000Prec *prec = band->prec + precno;

                /* TODO: Explain formula for JPEG200 DCINEMA. */

                /* TODO: Verify with previous count of codeblocks per band */

                /* Compute P_x0 */

                prec->coord[0][0] = (precno % reslevel->num_precincts_x) *

                                    (1 << log2_band_prec_width);

                prec->coord[0][0] = FFMAX(prec->coord[0][0], band->coord[0][0]);

                /* Compute P_y0 */

                prec->coord[1][0] = (precno / reslevel->num_precincts_x) *

                                    (1 << log2_band_prec_height);

                prec->coord[1][0] = FFMAX(prec->coord[1][0], band->coord[1][0]);

                /* Compute P_x1 */

                prec->coord[0][1] = prec->coord[0][0] +

                                    (1 << log2_band_prec_width);

                prec->coord[0][1] = FFMIN(prec->coord[0][1], band->coord[0][1]);

                /* Compute P_y1 */

                prec->coord[1][1] = prec->coord[1][0] +

                                    (1 << log2_band_prec_height);

                prec->coord[1][1] = FFMIN(prec->coord[1][1], band->coord[1][1]);

                prec->nb_codeblocks_width =

                    ff_jpeg2000_ceildivpow2(prec->coord[0][1] -

                                            prec->coord[0][0],

                                            band->log2_cblk_width);

                prec->nb_codeblocks_height =

                    ff_jpeg2000_ceildivpow2(prec->coord[1][1] -

                                            prec->coord[1][0],

                                            band->log2_cblk_height);

                /* Tag trees initialization */

                prec->cblkincl =

                    ff_jpeg2000_tag_tree_init(prec->nb_codeblocks_width,

                                              prec->nb_codeblocks_height);

                if (!prec->cblkincl)

                    return AVERROR(ENOMEM);

                prec->zerobits =

                    ff_jpeg2000_tag_tree_init(prec->nb_codeblocks_width,

                                              prec->nb_codeblocks_height);

                if (!prec->zerobits)

                    return AVERROR(ENOMEM);

                prec->cblk = av_mallocz_array(prec->nb_codeblocks_width *

                                              prec->nb_codeblocks_height,

                                              sizeof(*prec->cblk));

                if (!prec->cblk)

                    return AVERROR(ENOMEM);

                for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {

                    Jpeg2000Cblk *cblk = prec->cblk + cblkno;

                    uint16_t Cx0, Cy0;

                    /* Compute coordinates of codeblocks */

                    /* Compute Cx0*/

                    Cx0 = (prec->coord[0][0] >> band->log2_cblk_width) << band->log2_cblk_width;

                    Cx0 = Cx0 + ((cblkno % prec->nb_codeblocks_width)  << band->log2_cblk_width);

                    cblk->coord[0][0] = FFMAX(Cx0, prec->coord[0][0]);

                    /* Compute Cy0*/

                    Cy0 = (prec->coord[1][0] >> band->log2_cblk_height) << band->log2_cblk_height;

                    Cy0 = Cy0 + ((cblkno / prec->nb_codeblocks_width)   << band->log2_cblk_height);

                    cblk->coord[1][0] = FFMAX(Cy0, prec->coord[1][0]);

                    /* Compute Cx1 */

                    cblk->coord[0][1] = FFMIN(Cx0 + (1 << band->log2_cblk_width),

                                              prec->coord[0][1]);

                    /* Compute Cy1 */

                    cblk->coord[1][1] = FFMIN(Cy0 + (1 << band->log2_cblk_height),

                                              prec->coord[1][1]);

                    /* Update code-blocks coordinates according sub-band position */

                    if ((bandno + !!reslevelno) & 1) {

                        cblk->coord[0][0] += comp->reslevel[reslevelno-1].coord[0][1] -

                                             comp->reslevel[reslevelno-1].coord[0][0];

                        cblk->coord[0][1] += comp->reslevel[reslevelno-1].coord[0][1] -

                                             comp->reslevel[reslevelno-1].coord[0][0];

                    }

                    if ((bandno + !!reslevelno) & 2) {

                        cblk->coord[1][0] += comp->reslevel[reslevelno-1].coord[1][1] -

                                             comp->reslevel[reslevelno-1].coord[1][0];

                        cblk->coord[1][1] += comp->reslevel[reslevelno-1].coord[1][1] -

                                             comp->reslevel[reslevelno-1].coord[1][0];

                    }

                    cblk->zero      = 0;

                    cblk->lblock    = 3;

                    cblk->length    = 0;

                    cblk->lengthinc = 0;

                    cblk->npasses   = 0;

                }

            }

        }

    }

    return 0;

}


static void bonito_writel(void *opaque, target_phys_addr_t addr,

                          uint64_t val, unsigned size)

{

    PCIBonitoState *s = opaque;

    uint32_t saddr;

    int reset = 0;

    saddr = (addr - BONITO_REGBASE) >> 2;

    DPRINTF("bonito_writel "TARGET_FMT_plx" val %x saddr %x\n", addr, val, saddr);

    switch (saddr) {

    case BONITO_BONPONCFG:

    case BONITO_IODEVCFG:

    case BONITO_SDCFG:

    case BONITO_PCIMAP:

    case BONITO_PCIMEMBASECFG:

    case BONITO_PCIMAP_CFG:

    case BONITO_GPIODATA:

    case BONITO_GPIOIE:

    case BONITO_INTEDGE:

    case BONITO_INTSTEER:

    case BONITO_INTPOL:

    case BONITO_PCIMAIL0:

    case BONITO_PCIMAIL1:

    case BONITO_PCIMAIL2:

    case BONITO_PCIMAIL3:

    case BONITO_PCICACHECTRL:

    case BONITO_PCICACHETAG:

    case BONITO_PCIBADADDR:

    case BONITO_PCIMSTAT:

    case BONITO_TIMECFG:

    case BONITO_CPUCFG:

    case BONITO_DQCFG:

    case BONITO_MEMSIZE:

        s->regs[saddr] = val;

        break;

    case BONITO_BONGENCFG:

        if (!(s->regs[saddr] & 0x04) && (val & 0x04)) {

            reset = 1; /* bit 2 jump from 0 to 1 cause reset */

        }

        s->regs[saddr] = val;

        if (reset) {

            qemu_system_reset_request();

        }

        break;

    case BONITO_INTENSET:

        s->regs[BONITO_INTENSET] = val;

        s->regs[BONITO_INTEN] |= val;

        break;

    case BONITO_INTENCLR:

        s->regs[BONITO_INTENCLR] = val;

        s->regs[BONITO_INTEN] &= ~val;

        break;

    case BONITO_INTEN:

    case BONITO_INTISR:

        DPRINTF("write to readonly bonito register %x\n", saddr);

        break;

    default:

        DPRINTF("write to unknown bonito register %x\n", saddr);

        break;

    }

}


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

                                const AVFrame *frame, int *got_packet)

{

    aacPlusAudioContext *s = avctx->priv_data;

    int32_t *input_buffer = (int32_t *)frame->data[0];

    int ret;

    if ((ret = ff_alloc_packet2(avctx, pkt, s->max_output_bytes)))

        return ret;

    pkt->size = aacplusEncEncode(s->aacplus_handle, input_buffer,

                                 s->samples_input, pkt->data, pkt->size);

    *got_packet   = 1;

    pkt->pts      = frame->pts;

    return 0;

}


static void test_acpi_fadt_table(test_data *data)

{

    AcpiFadtDescriptorRev1 *fadt_table = &data->fadt_table;

    uint32_t addr;

    /* FADT table comes first */

    addr = data->rsdt_tables_addr[0];

    ACPI_READ_TABLE_HEADER(fadt_table, addr);

    ACPI_READ_FIELD(fadt_table->firmware_ctrl, addr);

    ACPI_READ_FIELD(fadt_table->dsdt, addr);

    ACPI_READ_FIELD(fadt_table->model, addr);

    ACPI_READ_FIELD(fadt_table->reserved1, addr);

    ACPI_READ_FIELD(fadt_table->sci_int, addr);

    ACPI_READ_FIELD(fadt_table->smi_cmd, addr);

    ACPI_READ_FIELD(fadt_table->acpi_enable, addr);

    ACPI_READ_FIELD(fadt_table->acpi_disable, addr);

    ACPI_READ_FIELD(fadt_table->S4bios_req, addr);

    ACPI_READ_FIELD(fadt_table->reserved2, addr);

    ACPI_READ_FIELD(fadt_table->pm1a_evt_blk, addr);

    ACPI_READ_FIELD(fadt_table->pm1b_evt_blk, addr);

    ACPI_READ_FIELD(fadt_table->pm1a_cnt_blk, addr);

    ACPI_READ_FIELD(fadt_table->pm1b_cnt_blk, addr);

    ACPI_READ_FIELD(fadt_table->pm2_cnt_blk, addr);

    ACPI_READ_FIELD(fadt_table->pm_tmr_blk, addr);

    ACPI_READ_FIELD(fadt_table->gpe0_blk, addr);

    ACPI_READ_FIELD(fadt_table->gpe1_blk, addr);

    ACPI_READ_FIELD(fadt_table->pm1_evt_len, addr);

    ACPI_READ_FIELD(fadt_table->pm1_cnt_len, addr);

    ACPI_READ_FIELD(fadt_table->pm2_cnt_len, addr);

    ACPI_READ_FIELD(fadt_table->pm_tmr_len, addr);

    ACPI_READ_FIELD(fadt_table->gpe0_blk_len, addr);

    ACPI_READ_FIELD(fadt_table->gpe1_blk_len, addr);

    ACPI_READ_FIELD(fadt_table->gpe1_base, addr);

    ACPI_READ_FIELD(fadt_table->reserved3, addr);

    ACPI_READ_FIELD(fadt_table->plvl2_lat, addr);

    ACPI_READ_FIELD(fadt_table->plvl3_lat, addr);

    ACPI_READ_FIELD(fadt_table->flush_size, addr);

    ACPI_READ_FIELD(fadt_table->flush_stride, addr);

    ACPI_READ_FIELD(fadt_table->duty_offset, addr);

    ACPI_READ_FIELD(fadt_table->duty_width, addr);

    ACPI_READ_FIELD(fadt_table->day_alrm, addr);

    ACPI_READ_FIELD(fadt_table->mon_alrm, addr);

    ACPI_READ_FIELD(fadt_table->century, addr);

    ACPI_READ_FIELD(fadt_table->reserved4, addr);

    ACPI_READ_FIELD(fadt_table->reserved4a, addr);

    ACPI_READ_FIELD(fadt_table->reserved4b, addr);

    ACPI_READ_FIELD(fadt_table->flags, addr);

    ACPI_ASSERT_CMP(fadt_table->signature, "FACP");

    g_assert(!acpi_calc_checksum((uint8_t *)fadt_table, fadt_table->length));

}


opts_end_list(Visitor *v)

{

    OptsVisitor *ov = to_ov(v);

    assert(ov->list_mode == LM_STARTED ||

           ov->list_mode == LM_IN_PROGRESS ||

           ov->list_mode == LM_SIGNED_INTERVAL ||

           ov->list_mode == LM_UNSIGNED_INTERVAL);

    ov->repeated_opts = NULL;

    ov->list_mode = LM_NONE;

}


static void rate_start (SpiceRateCtl *rate)

{

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

    rate->start_ticks = qemu_get_clock (vm_clock);

}


void cpu_inject_ext(S390CPU *cpu, uint32_t code, uint32_t param,

                    uint64_t param64)

{

    CPUS390XState *env = &cpu->env;

    if (env->ext_index == MAX_EXT_QUEUE - 1) {

        /* ugh - can't queue anymore. Let's drop. */

        return;

    }

    env->ext_index++;

    assert(env->ext_index < MAX_EXT_QUEUE);

    env->ext_queue[env->ext_index].code = code;

    env->ext_queue[env->ext_index].param = param;

    env->ext_queue[env->ext_index].param64 = param64;

    env->pending_int |= INTERRUPT_EXT;

    cpu_interrupt(CPU(cpu), CPU_INTERRUPT_HARD);

}


static void virtio_serial_device_realize(DeviceState *dev, Error **errp)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(dev);

    VirtIOSerial *vser = VIRTIO_SERIAL(dev);

    uint32_t i, max_supported_ports;

    if (!vser->serial.max_virtserial_ports) {

        error_setg(errp, "Maximum number of serial ports not specified");

        return;

    }

    /* Each port takes 2 queues, and one pair is for the control queue */

    max_supported_ports = VIRTIO_QUEUE_MAX / 2 - 1;

    if (vser->serial.max_virtserial_ports > max_supported_ports) {

        error_setg(errp, "maximum ports supported: %u", max_supported_ports);

        return;

    }

    /* We don't support emergency write, skip it for now. */

    /* TODO: cleaner fix, depending on host features. */

    virtio_init(vdev, "virtio-serial", VIRTIO_ID_CONSOLE,

                offsetof(struct virtio_console_config, emerg_wr));

    /* Spawn a new virtio-serial bus on which the ports will ride as devices */

    qbus_create_inplace(&vser->bus, sizeof(vser->bus), TYPE_VIRTIO_SERIAL_BUS,

                        dev, vdev->bus_name);

    qbus_set_hotplug_handler(BUS(&vser->bus), DEVICE(vser), errp);

    vser->bus.vser = vser;

    QTAILQ_INIT(&vser->ports);

    vser->bus.max_nr_ports = vser->serial.max_virtserial_ports;

    vser->ivqs = g_malloc(vser->serial.max_virtserial_ports

                          * sizeof(VirtQueue *));

    vser->ovqs = g_malloc(vser->serial.max_virtserial_ports

                          * sizeof(VirtQueue *));

    /* Add a queue for host to guest transfers for port 0 (backward compat) */

    vser->ivqs[0] = virtio_add_queue(vdev, 128, handle_input);

    /* Add a queue for guest to host transfers for port 0 (backward compat) */

    vser->ovqs[0] = virtio_add_queue(vdev, 128, handle_output);

    /* TODO: host to guest notifications can get dropped

     * if the queue fills up. Implement queueing in host,

     * this might also make it possible to reduce the control

     * queue size: as guest preposts buffers there,

     * this will save 4Kbyte of guest memory per entry. */

    /* control queue: host to guest */

    vser->c_ivq = virtio_add_queue(vdev, 32, control_in);

    /* control queue: guest to host */

    vser->c_ovq = virtio_add_queue(vdev, 32, control_out);

    for (i = 1; i < vser->bus.max_nr_ports; i++) {

        /* Add a per-port queue for host to guest transfers */

        vser->ivqs[i] = virtio_add_queue(vdev, 128, handle_input);

        /* Add a per-per queue for guest to host transfers */

        vser->ovqs[i] = virtio_add_queue(vdev, 128, handle_output);

    }

    vser->ports_map = g_malloc0(((vser->serial.max_virtserial_ports + 31) / 32)

        * sizeof(vser->ports_map[0]));

    /*

     * Reserve location 0 for a console port for backward compat

     * (old kernel, new qemu)

     */

    mark_port_added(vser, 0);

    vser->post_load = NULL;

    QLIST_INSERT_HEAD(&vserdevices.devices, vser, next);

}


void object_property_set_qobject(Object *obj, QObject *value,

                                 const char *name, Error **errp)

{

    Visitor *v;

    /* TODO: Should we reject, rather than ignore, excess input? */

    v = qmp_input_visitor_new(value, false);

    object_property_set(obj, v, name, errp);

    visit_free(v);

}


static uint32_t pci_apb_ioreadb (void *opaque, target_phys_addr_t addr)

{

    uint32_t val;

    val = cpu_inb(addr & IOPORTS_MASK);

    return val;

}


static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(dev);

    VirtIOBlock *s = VIRTIO_BLK(dev);

    remove_migration_state_change_notifier(&s->migration_state_notifier);

    virtio_blk_data_plane_destroy(s->dataplane);

    s->dataplane = NULL;

    qemu_del_vm_change_state_handler(s->change);

    unregister_savevm(dev, "virtio-blk", s);

    blockdev_mark_auto_del(s->bs);

    virtio_cleanup(vdev);

}


static int exif_decode_tag(AVCodecContext *avctx, GetByteContext *gbytes, int le,

                           int depth, AVDictionary **metadata)

{

    int ret, cur_pos;

    unsigned id, count;

    enum TiffTypes type;

    if (depth > 2) {

        return 0;

    }

    ff_tread_tag(gbytes, le, &id, &type, &count, &cur_pos);

    if (!bytestream2_tell(gbytes)) {

        bytestream2_seek(gbytes, cur_pos, SEEK_SET);

        return 0;

    }

    // read count values and add it metadata

    // store metadata or proceed with next IFD

    ret = ff_tis_ifd(id);

    if (ret) {

        ret = avpriv_exif_decode_ifd(avctx, gbytes, le, depth + 1, metadata);

    } else {

        const char *name = exif_get_tag_name(id);

        char *use_name   = (char*) name;

        if (!use_name) {

            use_name = av_malloc(7);

            if (!use_name) {

                return AVERROR(ENOMEM);

            }

            snprintf(use_name, 7, "0x%04X", id);

        }

        ret = exif_add_metadata(avctx, count, type, use_name, NULL,

                                gbytes, le, metadata);

        if (!name) {

            av_freep(&use_name);

        }

    }

    bytestream2_seek(gbytes, cur_pos, SEEK_SET);

    return ret;

}


static int setup_sigcontext(struct target_sigcontext *sc, CPUAlphaState *env,

                            abi_ulong frame_addr, target_sigset_t *set)

{

    int i, err = 0;

    __put_user(on_sig_stack(frame_addr), &sc->sc_onstack);

    __put_user(set->sig[0], &sc->sc_mask);

    __put_user(env->pc, &sc->sc_pc);

    __put_user(8, &sc->sc_ps);

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

        __put_user(env->ir[i], &sc->sc_regs[i]);

    }

    __put_user(0, &sc->sc_regs[31]);

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

        __put_user(env->fir[i], &sc->sc_fpregs[i]);

    }

    __put_user(0, &sc->sc_fpregs[31]);

    __put_user(cpu_alpha_load_fpcr(env), &sc->sc_fpcr);

    __put_user(0, &sc->sc_traparg_a0); /* FIXME */

    __put_user(0, &sc->sc_traparg_a1); /* FIXME */

    __put_user(0, &sc->sc_traparg_a2); /* FIXME */

    return err;

}


static const char *full_name(QObjectInputVisitor *qiv, const char *name)

{

    StackObject *so;

    char buf[32];

    if (qiv->errname) {

        g_string_truncate(qiv->errname, 0);

    } else {

        qiv->errname = g_string_new("");

    }

    QSLIST_FOREACH(so , &qiv->stack, node) {

        if (qobject_type(so->obj) == QTYPE_QDICT) {

            g_string_prepend(qiv->errname, name);

            g_string_prepend_c(qiv->errname, '.');

        } else {

            snprintf(buf, sizeof(buf), "[%u]", so->index);

            g_string_prepend(qiv->errname, buf);

        }

        name = so->name;

    }

    if (name) {

        g_string_prepend(qiv->errname, name);

    } else if (qiv->errname->str[0] == '.') {

        g_string_erase(qiv->errname, 0, 1);

    } else {

        return "<anonymous>";

    }

    return qiv->errname->str;

}


static void tcg_out_tlb_read (TCGContext *s, int r0, int r1, int r2,

                              int addr_reg, int s_bits, int offset)

{

#ifdef TARGET_LONG_BITS

    tcg_out_rld (s, RLDICL, addr_reg, addr_reg, 0, 32);

    tcg_out32 (s, (RLWINM

                   | RA (r0)

                   | RS (addr_reg)

                   | SH (32 - (TARGET_PAGE_BITS - CPU_TLB_ENTRY_BITS))

                   | MB (32 - (CPU_TLB_BITS + CPU_TLB_ENTRY_BITS))

                   | ME (31 - CPU_TLB_ENTRY_BITS)

                   )

        );

    tcg_out32 (s, ADD | RT (r0) | RA (r0) | RB (TCG_AREG0));

    tcg_out32 (s, (LWZU | RT (r1) | RA (r0) | offset));

    tcg_out32 (s, (RLWINM

                   | RA (r2)

                   | RS (addr_reg)

                   | SH (0)

                   | MB ((32 - s_bits) & 31)

                   | ME (31 - TARGET_PAGE_BITS)

                   )

        );

#else

    tcg_out_rld (s, RLDICL, r0, addr_reg,

                 64 - TARGET_PAGE_BITS,

                 64 - CPU_TLB_BITS);

    tcg_out_rld (s, RLDICR, r0, r0,

                 CPU_TLB_ENTRY_BITS,

                 63 - CPU_TLB_ENTRY_BITS);

    tcg_out32 (s, ADD | TAB (r0, r0, TCG_AREG0));

    tcg_out32 (s, LD_ADDR | RT (r1) | RA (r0) | offset);

    if (!s_bits) {

        tcg_out_rld (s, RLDICR, r2, addr_reg, 0, 63 - TARGET_PAGE_BITS);

    }

    else {

        tcg_out_rld (s, RLDICL, r2, addr_reg,

                     64 - TARGET_PAGE_BITS,

                     TARGET_PAGE_BITS - s_bits);

        tcg_out_rld (s, RLDICL, r2, r2, TARGET_PAGE_BITS, 0);

    }

#endif

}


float32 HELPER(ucf64_si2sf)(float32 x, CPUUniCore32State *env)

{

    return int32_to_float32(ucf64_stoi(x), &env->ucf64.fp_status);

}


static void v7m_push_stack(ARMCPU *cpu)

{

    /* Do the "set up stack frame" part of exception entry,

     * similar to pseudocode PushStack().

     */

    CPUARMState *env = &cpu->env;

    uint32_t xpsr = xpsr_read(env);

    /* Align stack pointer if the guest wants that */

    if ((env->regs[13] & 4) && (env->v7m.ccr & R_V7M_CCR_STKALIGN_MASK)) {

        env->regs[13] -= 4;

        xpsr |= XPSR_SPREALIGN;

    }

    /* Switch to the handler mode.  */

    v7m_push(env, xpsr);

    v7m_push(env, env->regs[15]);

    v7m_push(env, env->regs[14]);

    v7m_push(env, env->regs[12]);

    v7m_push(env, env->regs[3]);

    v7m_push(env, env->regs[2]);

    v7m_push(env, env->regs[1]);

    v7m_push(env, env->regs[0]);

}


int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)

{

    if (bs->peer) {

        return -EBUSY;

    }

    bs->peer = qdev;

    return 0;

}


static void vnc_init_timer(VncDisplay *vd)

{

    vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;

    if (vd->timer == NULL && !QTAILQ_EMPTY(&vd->clients)) {

        vd->timer = qemu_new_timer(rt_clock, vnc_refresh, vd);

        vnc_dpy_resize(vd->ds);

        vnc_refresh(vd);

    }

}


static int pxa2xx_pic_load(QEMUFile *f, void *opaque, int version_id)

{

    PXA2xxPICState *s = (PXA2xxPICState *) opaque;

    int i;

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

        qemu_get_be32s(f, &s->int_enabled[i]);

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

        qemu_get_be32s(f, &s->int_pending[i]);

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

        qemu_get_be32s(f, &s->is_fiq[i]);

    qemu_get_be32s(f, &s->int_idle);

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

        qemu_get_be32s(f, &s->priority[i]);

    pxa2xx_pic_update(opaque);

    return 0;

}


static void lsi_mmio_write(void *opaque, target_phys_addr_t addr,

                           uint64_t val, unsigned size)

{

    LSIState *s = opaque;

    lsi_reg_writeb(s, addr & 0xff, val);

}


static void pmac_ide_writew (void *opaque,

                             target_phys_addr_t addr, uint32_t val)

{

    MACIOIDEState *d = opaque;

    addr = (addr & 0xFFF) >> 4;

    val = bswap16(val);

    if (addr == 0) {

        ide_data_writew(&d->bus, 0, val);

    }

}


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

                    int lower_transport, const char *real_challenge)

{

    RTSPState *rt = s->priv_data;

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

    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 */

    for(j = RTSP_RTP_PORT_MIN, 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 */

            if (RTSP_RTP_PORT_MIN != 0) {

                while(j <= RTSP_RTP_PORT_MAX) {

                    snprintf(buf, sizeof(buf), "rtp://%s?localport=%d", host, j);

                    j += 2; /* we will use two port by rtp stream (rtp and rtcp) */

                    if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0) {

                        goto rtp_opened;

                    }

                }

            }

/*            then try on any port

**            if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {

**                err = AVERROR_INVALIDDATA;

**                goto fail;

**            }

*/

        rtp_opened:

            port = rtp_get_local_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 &&

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

                continue;

            snprintf(transport, sizeof(transport) - 1,

                     "%s/TCP;", trans_pref);

            if (rt->server_type == RTSP_SERVER_WMS)

                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 (rt->server_type == RTSP_SERVER_REAL ||

            rt->server_type == RTSP_SERVER_WMS)

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

        snprintf(cmd, sizeof(cmd),

                 "SETUP %s RTSP/1.0\r\n"

                 "Transport: %s\r\n",

                 rtsp_st->control_url, transport);

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

            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);

        }

        rtsp_send_cmd(s, 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;

        }

        /* close RTP connection if not choosen */

        if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&

            (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {

            url_close(rtsp_st->rtp_handle);

            rtsp_st->rtp_handle = NULL;

        }

        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];

                /* XXX: also use address if specified */

                snprintf(url, sizeof(url), "rtp://%s:%d",

                         host, reply->transports[0].server_port_min);

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

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

                    err = AVERROR_INVALIDDATA;

                    goto fail;

                }

            }

            break;

        case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:

            {

                char url[1024];

                struct in_addr in;

                int port, ttl;

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

                    in.s_addr = htonl(reply->transports[0].destination);

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

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

                } else {

                    in        = rtsp_st->sdp_ip;

                    port      = rtsp_st->sdp_port;

                    ttl       = rtsp_st->sdp_ttl;

                }

                snprintf(url, sizeof(url), "rtp://%s:%d?ttl=%d",

                         inet_ntoa(in), port, ttl);

                if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 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:

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

        if (rt->rtsp_streams[i]->rtp_handle) {

            url_close(rt->rtsp_streams[i]->rtp_handle);

            rt->rtsp_streams[i]->rtp_handle = NULL;

        }

    }

    return err;

}


static void test_dst_table(AcpiSdtTable *sdt_table, uint32_t addr)

{

    uint8_t checksum;

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

    ACPI_READ_TABLE_HEADER(&sdt_table->header, addr);

    sdt_table->aml_len = le32_to_cpu(sdt_table->header.length)

                         - sizeof(AcpiTableHeader);

    sdt_table->aml = g_malloc0(sdt_table->aml_len);

    ACPI_READ_ARRAY_PTR(sdt_table->aml, sdt_table->aml_len, addr);

    checksum = acpi_calc_checksum((uint8_t *)sdt_table,

                                  sizeof(AcpiTableHeader)) +

               acpi_calc_checksum((uint8_t *)sdt_table->aml,

                                  sdt_table->aml_len);

    g_assert(!checksum);

}


static void piix4_device_plug_cb(HotplugHandler *hotplug_dev,

                                 DeviceState *dev, Error **errp)

{

    PIIX4PMState *s = PIIX4_PM(hotplug_dev);

    if (s->acpi_memory_hotplug.is_enabled &&

        object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {

        if (object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM)) {

            nvdimm_acpi_plug_cb(hotplug_dev, dev);

        } else {

            acpi_memory_plug_cb(hotplug_dev, &s->acpi_memory_hotplug,

                                dev, errp);

        }

    } else if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {

        if (!xen_enabled()) {

            acpi_pcihp_device_plug_cb(hotplug_dev, &s->acpi_pci_hotplug, dev,

                                      errp);

        }

    } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) {

        if (s->cpu_hotplug_legacy) {

            legacy_acpi_cpu_plug_cb(hotplug_dev, &s->gpe_cpu, dev, errp);

        } else {

            acpi_cpu_plug_cb(hotplug_dev, &s->cpuhp_state, dev, errp);

        }

    } else {

        error_setg(errp, "acpi: device plug request for not supported device"

                   " type: %s", object_get_typename(OBJECT(dev)));

    }

}


static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)

{

    AVFilterContext  *ctx = inlink->dst;

    ASyncContext       *s = ctx->priv;

    AVFilterLink *outlink = ctx->outputs[0];

    int nb_channels = av_get_channel_layout_nb_channels(buf->audio->channel_layout);

    int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :

                  av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);

    int out_size, ret;

    int64_t delta;

    /* buffer data until we get the first timestamp */

    if (s->pts == AV_NOPTS_VALUE) {

        if (pts != AV_NOPTS_VALUE) {

            s->pts = pts - get_delay(s);

        }

        return write_to_fifo(s, buf);

    }

    /* now wait for the next timestamp */

    if (pts == AV_NOPTS_VALUE) {

        return write_to_fifo(s, buf);

    }

    /* when we have two timestamps, compute how many samples would we have

     * to add/remove to get proper sync between data and timestamps */

    delta    = pts - s->pts - get_delay(s);

    out_size = avresample_available(s->avr);

    if (labs(delta) > s->min_delta) {

        av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);

        out_size = av_clipl_int32((int64_t)out_size + delta);

    } else {

        if (s->resample) {

            int comp = av_clip(delta, -s->max_comp, s->max_comp);

            av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);

            avresample_set_compensation(s->avr, delta, inlink->sample_rate);

        }

        delta = 0;

    }

    if (out_size > 0) {

        AVFilterBufferRef *buf_out = ff_get_audio_buffer(outlink, AV_PERM_WRITE,

                                                         out_size);

        if (!buf_out) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        avresample_read(s->avr, buf_out->extended_data, out_size);

        buf_out->pts = s->pts;

        if (delta > 0) {

            av_samples_set_silence(buf_out->extended_data, out_size - delta,

                                   delta, nb_channels, buf->format);

        }

        ret = ff_filter_frame(outlink, buf_out);

        if (ret < 0)

            goto fail;

        s->got_output = 1;

    } else {

        av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "

               "whole buffer.\n");

    }

    /* drain any remaining buffered data */

    avresample_read(s->avr, NULL, avresample_available(s->avr));

    s->pts = pts - avresample_get_delay(s->avr);

    ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,

                             buf->linesize[0], buf->audio->nb_samples);

fail:

    avfilter_unref_buffer(buf);

    return ret;

}


static void test_tco2_status_bits(void)

{

    TestData d;

    uint16_t ticks = 8;

    uint16_t val;

    int ret;

    d.args = NULL;

    d.noreboot = true;

    test_init(&d);

    stop_tco(&d);

    clear_tco_status(&d);

    reset_on_second_timeout(true);

    set_tco_timeout(&d, ticks);

    load_tco(&d);

    start_tco(&d);

    clock_step(ticks * TCO_TICK_NSEC * 2);

    val = qpci_io_readw(d.dev, d.tco_io_base + TCO2_STS);

    ret = val & (TCO_SECOND_TO_STS | TCO_BOOT_STS) ? 1 : 0;

    g_assert(ret == 1);

    qpci_io_writew(d.dev, d.tco_io_base + TCO2_STS, val);

    g_assert_cmpint(qpci_io_readw(d.dev, d.tco_io_base + TCO2_STS), ==, 0);

    qtest_end();

}


static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)

{

    AVStream *st = c->fc->streams[c->fc->nb_streams-1];

    MOVStreamContext *sc = st->priv_data;

    int j, entries, pseudo_stream_id;

    get_byte(pb); /* version */

    get_be24(pb); /* flags */

    entries = get_be32(pb);

    for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {

        //Parsing Sample description table

        enum CodecID id;

        int dref_id = 1;

        MOVAtom a = { 0, 0, 0 };

        int64_t start_pos = url_ftell(pb);

        int size = get_be32(pb); /* size */

        uint32_t format = get_le32(pb); /* data format */

        if (size >= 16) {

            get_be32(pb); /* reserved */

            get_be16(pb); /* reserved */

            dref_id = get_be16(pb);

        }

        if (st->codec->codec_tag &&

            st->codec->codec_tag != format &&

            (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id

                                   : st->codec->codec_tag != MKTAG('j','p','e','g'))

           ){

            /* Multiple fourcc, we skip JPEG. This is not correct, we should

             * export it as a separate AVStream but this needs a few changes

             * in the MOV demuxer, patch welcome. */

            av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");

            url_fskip(pb, size - (url_ftell(pb) - start_pos));

            continue;

        }

        sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;

        sc->dref_id= dref_id;

        st->codec->codec_tag = format;

        id = ff_codec_get_id(codec_movaudio_tags, format);

        if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))

            id = ff_codec_get_id(ff_codec_wav_tags, bswap_32(format)&0xFFFF);

        if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {

            st->codec->codec_type = CODEC_TYPE_AUDIO;

        } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */

                   format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */

            id = ff_codec_get_id(codec_movvideo_tags, format);

            if (id <= 0)

                id = ff_codec_get_id(ff_codec_bmp_tags, format);

            if (id > 0)

                st->codec->codec_type = CODEC_TYPE_VIDEO;

            else if(st->codec->codec_type == CODEC_TYPE_DATA){

                id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);

                if(id > 0)

                    st->codec->codec_type = CODEC_TYPE_SUBTITLE;

            }

        }

        dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,

                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,

                (format >> 24) & 0xff, st->codec->codec_type);

        if(st->codec->codec_type==CODEC_TYPE_VIDEO) {

            uint8_t codec_name[32];

            unsigned int color_depth;

            int color_greyscale;

            st->codec->codec_id = id;

            get_be16(pb); /* version */

            get_be16(pb); /* revision level */

            get_be32(pb); /* vendor */

            get_be32(pb); /* temporal quality */

            get_be32(pb); /* spatial quality */

            st->codec->width = get_be16(pb); /* width */

            st->codec->height = get_be16(pb); /* height */

            get_be32(pb); /* horiz resolution */

            get_be32(pb); /* vert resolution */

            get_be32(pb); /* data size, always 0 */

            get_be16(pb); /* frames per samples */

            get_buffer(pb, codec_name, 32); /* codec name, pascal string */

            if (codec_name[0] <= 31) {

                memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);

                st->codec->codec_name[codec_name[0]] = 0;

            }

            st->codec->bits_per_coded_sample = get_be16(pb); /* depth */

            st->codec->color_table_id = get_be16(pb); /* colortable id */

            dprintf(c->fc, "depth %d, ctab id %d\n",

                   st->codec->bits_per_coded_sample, st->codec->color_table_id);

            /* figure out the palette situation */

            color_depth = st->codec->bits_per_coded_sample & 0x1F;

            color_greyscale = st->codec->bits_per_coded_sample & 0x20;

            /* if the depth is 2, 4, or 8 bpp, file is palettized */

            if ((color_depth == 2) || (color_depth == 4) ||

                (color_depth == 8)) {

                /* for palette traversal */

                unsigned int color_start, color_count, color_end;

                unsigned char r, g, b;

                st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));

                if (color_greyscale) {

                    int color_index, color_dec;

                    /* compute the greyscale palette */

                    st->codec->bits_per_coded_sample = color_depth;

                    color_count = 1 << color_depth;

                    color_index = 255;

                    color_dec = 256 / (color_count - 1);

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

                        r = g = b = color_index;

                        st->codec->palctrl->palette[j] =

                            (r << 16) | (g << 8) | (b);

                        color_index -= color_dec;

                        if (color_index < 0)

                            color_index = 0;

                    }

                } else if (st->codec->color_table_id) {

                    const uint8_t *color_table;

                    /* if flag bit 3 is set, use the default palette */

                    color_count = 1 << color_depth;

                    if (color_depth == 2)

                        color_table = ff_qt_default_palette_4;

                    else if (color_depth == 4)

                        color_table = ff_qt_default_palette_16;

                    else

                        color_table = ff_qt_default_palette_256;

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

                        r = color_table[j * 3 + 0];

                        g = color_table[j * 3 + 1];

                        b = color_table[j * 3 + 2];

                        st->codec->palctrl->palette[j] =

                            (r << 16) | (g << 8) | (b);

                    }

                } else {

                    /* load the palette from the file */

                    color_start = get_be32(pb);

                    color_count = get_be16(pb);

                    color_end = get_be16(pb);

                    if ((color_start <= 255) &&

                        (color_end <= 255)) {

                        for (j = color_start; j <= color_end; j++) {

                            /* each R, G, or B component is 16 bits;

                             * only use the top 8 bits; skip alpha bytes

                             * up front */

                            get_byte(pb);

                            get_byte(pb);

                            r = get_byte(pb);

                            get_byte(pb);

                            g = get_byte(pb);

                            get_byte(pb);

                            b = get_byte(pb);

                            get_byte(pb);

                            st->codec->palctrl->palette[j] =

                                (r << 16) | (g << 8) | (b);

                        }

                    }

                }

                st->codec->palctrl->palette_changed = 1;

            }

        } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {

            int bits_per_sample, flags;

            uint16_t version = get_be16(pb);

            st->codec->codec_id = id;

            get_be16(pb); /* revision level */

            get_be32(pb); /* vendor */

            st->codec->channels = get_be16(pb);             /* channel count */

            dprintf(c->fc, "audio channels %d\n", st->codec->channels);

            st->codec->bits_per_coded_sample = get_be16(pb);      /* sample size */

            sc->audio_cid = get_be16(pb);

            get_be16(pb); /* packet size = 0 */

            st->codec->sample_rate = ((get_be32(pb) >> 16));

            //Read QT version 1 fields. In version 0 these do not exist.

            dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);

            if(!c->isom) {

                if(version==1) {

                    sc->samples_per_frame = get_be32(pb);

                    get_be32(pb); /* bytes per packet */

                    sc->bytes_per_frame = get_be32(pb);

                    get_be32(pb); /* bytes per sample */

                } else if(version==2) {

                    get_be32(pb); /* sizeof struct only */

                    st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */

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

                    get_be32(pb); /* always 0x7F000000 */

                    st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */

                    flags = get_be32(pb); /* lcpm format specific flag */

                    sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */

                    sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */

                    if (format == MKTAG('l','p','c','m'))

                        st->codec->codec_id = mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);

                }

            }

            switch (st->codec->codec_id) {

            case CODEC_ID_PCM_S8:

            case CODEC_ID_PCM_U8:

                if (st->codec->bits_per_coded_sample == 16)

                    st->codec->codec_id = CODEC_ID_PCM_S16BE;

                break;

            case CODEC_ID_PCM_S16LE:

            case CODEC_ID_PCM_S16BE:

                if (st->codec->bits_per_coded_sample == 8)

                    st->codec->codec_id = CODEC_ID_PCM_S8;

                else if (st->codec->bits_per_coded_sample == 24)

                    st->codec->codec_id =

                        st->codec->codec_id == CODEC_ID_PCM_S16BE ?

                        CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;

                break;

            /* set values for old format before stsd version 1 appeared */

            case CODEC_ID_MACE3:

                sc->samples_per_frame = 6;

                sc->bytes_per_frame = 2*st->codec->channels;

                break;

            case CODEC_ID_MACE6:

                sc->samples_per_frame = 6;

                sc->bytes_per_frame = 1*st->codec->channels;

                break;

            case CODEC_ID_ADPCM_IMA_QT:

                sc->samples_per_frame = 64;

                sc->bytes_per_frame = 34*st->codec->channels;

                break;

            case CODEC_ID_GSM:

                sc->samples_per_frame = 160;

                sc->bytes_per_frame = 33;

                break;

            default:

                break;

            }

            bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);

            if (bits_per_sample) {

                st->codec->bits_per_coded_sample = bits_per_sample;

                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;

            }

        } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){

            // ttxt stsd contains display flags, justification, background

            // color, fonts, and default styles, so fake an atom to read it

            MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };

            if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom

                mov_read_glbl(c, pb, fake_atom);

            st->codec->codec_id= id;

            st->codec->width = sc->width;

            st->codec->height = sc->height;

        } else {

            /* other codec type, just skip (rtp, mp4s, tmcd ...) */

            url_fskip(pb, size - (url_ftell(pb) - start_pos));

        }

        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */

        a.size = size - (url_ftell(pb) - start_pos);

        if (a.size > 8) {

            if (mov_read_default(c, pb, a) < 0)

                return -1;

        } else if (a.size > 0)

            url_fskip(pb, a.size);

    }

    if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)

        st->codec->sample_rate= sc->time_scale;

    /* special codec parameters handling */

    switch (st->codec->codec_id) {

#if CONFIG_DV_DEMUXER

    case CODEC_ID_DVAUDIO:

        c->dv_fctx = avformat_alloc_context();

        c->dv_demux = dv_init_demux(c->dv_fctx);

        if (!c->dv_demux) {

            av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");

            return -1;

        }

        sc->dv_audio_container = 1;

        st->codec->codec_id = CODEC_ID_PCM_S16LE;

        break;

#endif

    /* no ifdef since parameters are always those */

    case CODEC_ID_QCELP:

        // force sample rate for qcelp when not stored in mov

        if (st->codec->codec_tag != MKTAG('Q','c','l','p'))

            st->codec->sample_rate = 8000;

        st->codec->frame_size= 160;

        st->codec->channels= 1; /* really needed */

        break;

    case CODEC_ID_AMR_NB:

    case CODEC_ID_AMR_WB:

        st->codec->frame_size= sc->samples_per_frame;

        st->codec->channels= 1; /* really needed */

        /* force sample rate for amr, stsd in 3gp does not store sample rate */

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

            st->codec->sample_rate = 8000;

        else if (st->codec->codec_id == CODEC_ID_AMR_WB)

            st->codec->sample_rate = 16000;

        break;

    case CODEC_ID_MP2:

    case CODEC_ID_MP3:

        st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */

        st->need_parsing = AVSTREAM_PARSE_FULL;

        break;

    case CODEC_ID_GSM:

    case CODEC_ID_ADPCM_MS:

    case CODEC_ID_ADPCM_IMA_WAV:

        st->codec->block_align = sc->bytes_per_frame;

        break;

    case CODEC_ID_ALAC:

        if (st->codec->extradata_size == 36) {

            st->codec->frame_size = AV_RB32(st->codec->extradata+12);

            st->codec->channels   = AV_RB8 (st->codec->extradata+21);

        }

        break;

    default:

        break;

    }

    return 0;

}


void rgb15tobgr24(const uint8_t *src, uint8_t *dst, unsigned int src_size)

{

	const uint16_t *end;

	uint8_t *d = (uint8_t *)dst;

	const uint16_t *s = (uint16_t *)src;

	end = s + src_size/2;

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

		*d++ = (bgr&0x7C00)>>7;

		*d++ = (bgr&0x3E0)>>2;

		*d++ = (bgr&0x1F)<<3;

	}

}