static int shorten_decode_frame(AVCodecContext *avctx,

        void *data, int *data_size,

        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    ShortenContext *s = avctx->priv_data;

    int i, input_buf_size = 0;

    int16_t *samples = data;

    if(s->max_framesize == 0){

        s->max_framesize= 1024; // should hopefully be enough for the first header

        s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->max_framesize);

    }

    if(1 && s->max_framesize){//FIXME truncated

        buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);

        input_buf_size= buf_size;

        if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){

            //                printf("memmove\n");

            memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);

            s->bitstream_index=0;

        }

        memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);

        buf= &s->bitstream[s->bitstream_index];

        buf_size += s->bitstream_size;

        s->bitstream_size= buf_size;

        if(buf_size < s->max_framesize){

            *data_size = 0;

            return input_buf_size;

        }

    }

    init_get_bits(&s->gb, buf, buf_size*8);

    skip_bits(&s->gb, s->bitindex);

    if (!s->blocksize)

    {

        int ret;

        if ((ret = read_header(s)) < 0)

            return ret;

        *data_size = 0;

    }

    else

    {

        int cmd;

        int len;

        cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);

        if (cmd > FN_VERBATIM) {

            av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);

            if (s->bitstream_size > 0) {

                s->bitstream_index++;

                s->bitstream_size--;

            }

            return -1;

        }

        if (!is_audio_command[cmd]) {

            /* process non-audio command */

            switch (cmd) {

                case FN_VERBATIM:

                    len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);

                    while (len--) {

                        get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);

                    }

                    break;

                case FN_BITSHIFT:

                    s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);

                    break;

                case FN_BLOCKSIZE: {

                    int blocksize = get_uint(s, av_log2(s->blocksize));

                    if (blocksize > s->blocksize) {

                        av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");

                        return AVERROR_PATCHWELCOME;

                    }

                    s->blocksize = blocksize;

                    break;

                }

                case FN_QUIT:

                    break;

            }

            *data_size = 0;

        } else {

            /* process audio command */

            int ret;

            int residual_size = 0;

            int channel = s->cur_chan;

            int32_t coffset;

            if (cmd != FN_ZERO) {

                residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);

                /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */

                if (s->version == 0)

                    residual_size--;

            }

            if (s->nmean == 0)

                coffset = s->offset[channel][0];

            else {

                int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;

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

                    sum += s->offset[channel][i];

                coffset = sum / s->nmean;

                if (s->version >= 2)

                    coffset >>= FFMIN(1, s->bitshift);

            }

            switch (cmd) {

                case FN_ZERO:

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

                        s->decoded[channel][i] = 0;

                    break;

                case FN_DIFF0:

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

                        s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + coffset;

                    break;

                case FN_DIFF1:

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

                        s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + s->decoded[channel][i - 1];

                    break;

                case FN_DIFF2:

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

                        s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + 2*s->decoded[channel][i-1]

                                                                                -   s->decoded[channel][i-2];

                    break;

                case FN_DIFF3:

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

                        s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + 3*s->decoded[channel][i-1]

                                                                                - 3*s->decoded[channel][i-2]

                                                                                +   s->decoded[channel][i-3];

                    break;

                case FN_QLPC:

                    if ((ret = decode_subframe_lpc(s, channel, residual_size, coffset)) < 0)

                        return ret;

                    break;

            }

            if (s->nmean > 0) {

                int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;

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

                    sum += s->decoded[channel][i];

                for (i=1; i<s->nmean; i++)

                    s->offset[channel][i-1] = s->offset[channel][i];

                if (s->version < 2)

                    s->offset[channel][s->nmean - 1] = sum / s->blocksize;

                else

                    s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;

            }

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

                s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];

            fix_bitshift(s, s->decoded[channel]);

            s->cur_chan++;

            if (s->cur_chan == s->channels) {

                samples = interleave_buffer(samples, s->channels, s->blocksize, s->decoded);

                s->cur_chan = 0;

                *data_size = (int8_t *)samples - (int8_t *)data;

            } else {

                *data_size = 0;

            }

        }

    }

    //    s->last_blocksize = s->blocksize;

    s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);

    i= (get_bits_count(&s->gb))/8;

    if (i > buf_size) {

        av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);

        s->bitstream_size=0;

        s->bitstream_index=0;

        return -1;

    }

    if (s->bitstream_size) {

        s->bitstream_index += i;

        s->bitstream_size  -= i;

        return input_buf_size;

    } else

        return i;

}


static int mm_decode_pal(MmContext *s)

{

    int i;

    bytestream2_skip(&s->gb, 4);

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

        s->palette[i] = 0xFF << 24 | bytestream2_get_be24(&s->gb);

        s->palette[i+128] = s->palette[i]<<2;

    }

    return 0;

}


static int img_snapshot(int argc, char **argv)

{

    BlockDriverState *bs;

    QEMUSnapshotInfo sn;

    char *filename, *snapshot_name = NULL;

    int c, ret = 0, bdrv_oflags;

    int action = 0;

    qemu_timeval tv;

    bool quiet = false;

    bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;

    /* Parse commandline parameters */

    for(;;) {

        c = getopt(argc, argv, "la:c:d:hq");

        if (c == -1) {

            break;

        }

        switch(c) {

        case '?':

        case 'h':

            help();

            return 0;

        case 'l':

            if (action) {

                help();

                return 0;

            }

            action = SNAPSHOT_LIST;

            bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */

            break;

        case 'a':

            if (action) {

                help();

                return 0;

            }

            action = SNAPSHOT_APPLY;

            snapshot_name = optarg;

            break;

        case 'c':

            if (action) {

                help();

                return 0;

            }

            action = SNAPSHOT_CREATE;

            snapshot_name = optarg;

            break;

        case 'd':

            if (action) {

                help();

                return 0;

            }

            action = SNAPSHOT_DELETE;

            snapshot_name = optarg;

            break;

        case 'q':

            quiet = true;

            break;

        }

    }

    if (optind != argc - 1) {

        help();

    }

    filename = argv[optind++];

    /* Open the image */

    bs = bdrv_new_open(filename, NULL, bdrv_oflags, true, quiet);

    if (!bs) {

        return 1;

    }

    /* Perform the requested action */

    switch(action) {

    case SNAPSHOT_LIST:

        dump_snapshots(bs);

        break;

    case SNAPSHOT_CREATE:

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

        pstrcpy(sn.name, sizeof(sn.name), snapshot_name);

        qemu_gettimeofday(&tv);

        sn.date_sec = tv.tv_sec;

        sn.date_nsec = tv.tv_usec * 1000;

        ret = bdrv_snapshot_create(bs, &sn);

        if (ret) {

            error_report("Could not create snapshot '%s': %d (%s)",

                snapshot_name, ret, strerror(-ret));

        }

        break;

    case SNAPSHOT_APPLY:

        ret = bdrv_snapshot_goto(bs, snapshot_name);

        if (ret) {

            error_report("Could not apply snapshot '%s': %d (%s)",

                snapshot_name, ret, strerror(-ret));

        }

        break;

    case SNAPSHOT_DELETE:

        ret = bdrv_snapshot_delete(bs, snapshot_name);

        if (ret) {

            error_report("Could not delete snapshot '%s': %d (%s)",

                snapshot_name, ret, strerror(-ret));

        }

        break;

    }

    /* Cleanup */

    bdrv_unref(bs);

    if (ret) {

        return 1;

    }

    return 0;

}


static void FUNCC(pred16x16_horizontal_add)(uint8_t *pix,

                                            const int *block_offset,

                                            const int16_t *block,

                                            ptrdiff_t stride)

{

    int i;

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

        FUNCC(pred4x4_horizontal_add)(pix + block_offset[i], block + i*16*sizeof(pixel), stride);

}


static void release_unused_pictures(H264Context *h, int remove_current)

{

    int i;

    /* release non reference frames */

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

        if (h->DPB[i].f.data[0] && !h->DPB[i].reference &&

            (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {

            unref_picture(h, &h->DPB[i]);

        }

    }

}


static av_noinline void emulated_edge_mc_sse(uint8_t * buf,const uint8_t *src,

                                             ptrdiff_t buf_stride,

                                             ptrdiff_t src_stride,

                                             int block_w, int block_h,

                                             int src_x, int src_y, int w, int h)

{

    emulated_edge_mc(buf, src, buf_stride, src_stride, block_w, block_h,

                     src_x, src_y, w, h, vfixtbl_sse, &ff_emu_edge_vvar_sse,

                     hfixtbl_sse, &ff_emu_edge_hvar_sse);

}


static inline int lock_hpte(void *hpte, target_ulong bits)

{

    uint64_t pteh;

    pteh = ldq_p(hpte);

    /* We're protected by qemu's global lock here */

    if (pteh & bits) {

        return 0;

    }

    stq_p(hpte, pteh | HPTE_V_HVLOCK);

    return 1;

}


static void iothread_set_poll_max_ns(Object *obj, Visitor *v,

        const char *name, void *opaque, Error **errp)

{

    IOThread *iothread = IOTHREAD(obj);

    Error *local_err = NULL;

    int64_t value;

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

    if (local_err) {

        goto out;

    }

    if (value < 0) {

        error_setg(&local_err, "poll_max_ns value must be in range "

                   "[0, %"PRId64"]", INT64_MAX);

        goto out;

    }

    iothread->poll_max_ns = value;

    if (iothread->ctx) {

        aio_context_set_poll_params(iothread->ctx, value, &local_err);

    }

out:

    error_propagate(errp, local_err);

}


int queue_signal(CPUArchState *env, int sig, target_siginfo_t *info)

{

    CPUState *cpu = ENV_GET_CPU(env);

    TaskState *ts = cpu->opaque;

    struct emulated_sigtable *k;

    struct sigqueue *q, **pq;

    abi_ulong handler;

    int queue;

    trace_user_queue_signal(env, sig);

    k = &ts->sigtab[sig - 1];

    queue = gdb_queuesig ();

    handler = sigact_table[sig - 1]._sa_handler;

    if (ts->sigsegv_blocked && sig == TARGET_SIGSEGV) {

        /* Guest has blocked SIGSEGV but we got one anyway. Assume this

         * is a forced SIGSEGV (ie one the kernel handles via force_sig_info

         * because it got a real MMU fault). A blocked SIGSEGV in that

         * situation is treated as if using the default handler. This is

         * not correct if some other process has randomly sent us a SIGSEGV

         * via kill(), but that is not easy to distinguish at this point,

         * so we assume it doesn't happen.

         */

        handler = TARGET_SIG_DFL;

    }

    if (!queue && handler == TARGET_SIG_DFL) {

        if (sig == TARGET_SIGTSTP || sig == TARGET_SIGTTIN || sig == TARGET_SIGTTOU) {

            kill(getpid(),SIGSTOP);

            return 0;

        } else

        /* default handler : ignore some signal. The other are fatal */

        if (sig != TARGET_SIGCHLD &&

            sig != TARGET_SIGURG &&

            sig != TARGET_SIGWINCH &&

            sig != TARGET_SIGCONT) {

            force_sig(sig);

        } else {

            return 0; /* indicate ignored */

        }

    } else if (!queue && handler == TARGET_SIG_IGN) {

        /* ignore signal */

        return 0;

    } else if (!queue && handler == TARGET_SIG_ERR) {

        force_sig(sig);

    } else {

        pq = &k->first;

        if (sig < TARGET_SIGRTMIN) {

            /* if non real time signal, we queue exactly one signal */

            if (!k->pending)

                q = &k->info;

            else

                return 0;

        } else {

            if (!k->pending) {

                /* first signal */

                q = &k->info;

            } else {

                q = alloc_sigqueue(env);

                if (!q)

                    return -EAGAIN;

                while (*pq != NULL)

                    pq = &(*pq)->next;

            }

        }

        *pq = q;

        q->info = *info;

        q->next = NULL;

        k->pending = 1;

        /* signal that a new signal is pending */

        ts->signal_pending = 1;

        return 1; /* indicates that the signal was queued */

    }

}


static void dss_sp_shift_sq_sub(const int32_t *filter_buf,

                                int32_t *error_buf, int32_t *dst)

{

    int a;

    for (a = 0; a < 72; a++) {

        int i, tmp;

        tmp = dst[a] * filter_buf[0];

        for (i = 14; i > 0; i--)

            tmp -= error_buf[i] * (unsigned)filter_buf[i];

        for (i = 14; i > 0; i--)

            error_buf[i] = error_buf[i - 1];

        tmp = (tmp + 4096) >> 13;

        error_buf[1] = tmp;

        dst[a] = av_clip_int16(tmp);

    }

}


static void gem_transmit(CadenceGEMState *s)
{
    unsigned    desc[2];
    hwaddr packet_desc_addr;
    uint8_t     tx_packet[2048];
    uint8_t     *p;
    unsigned    total_bytes;
    /* Do nothing if transmit is not enabled. */
    if (!(s->regs[GEM_NWCTRL] & GEM_NWCTRL_TXENA)) {
        return;
    DB_PRINT("\n");
    /* The packet we will hand off to QEMU.
     * Packets scattered across multiple descriptors are gathered to this
     * one contiguous buffer first.
     */
    p = tx_packet;
    total_bytes = 0;
    /* read current descriptor */
    packet_desc_addr = s->tx_desc_addr;
    DB_PRINT("read descriptor 0x%" HWADDR_PRIx "\n", packet_desc_addr);
    cpu_physical_memory_read(packet_desc_addr,
                             (uint8_t *)desc, sizeof(desc));
    /* Handle all descriptors owned by hardware */
    while (tx_desc_get_used(desc) == 0) {
        /* Do nothing if transmit is not enabled. */
        if (!(s->regs[GEM_NWCTRL] & GEM_NWCTRL_TXENA)) {
            return;
        print_gem_tx_desc(desc);
        /* The real hardware would eat this (and possibly crash).
         * For QEMU let's lend a helping hand.
         */
        if ((tx_desc_get_buffer(desc) == 0) ||
            (tx_desc_get_length(desc) == 0)) {
            DB_PRINT("Invalid TX descriptor @ 0x%x\n",
                     (unsigned)packet_desc_addr);
        /* Gather this fragment of the packet from "dma memory" to our contig.
         * buffer.
         */
        cpu_physical_memory_read(tx_desc_get_buffer(desc), p,
                                 tx_desc_get_length(desc));
        p += tx_desc_get_length(desc);
        total_bytes += tx_desc_get_length(desc);
        /* Last descriptor for this packet; hand the whole thing off */
        if (tx_desc_get_last(desc)) {
            unsigned    desc_first[2];
            /* Modify the 1st descriptor of this packet to be owned by
             * the processor.
             */
            cpu_physical_memory_read(s->tx_desc_addr, (uint8_t *)desc_first,
                                     sizeof(desc_first));
            tx_desc_set_used(desc_first);
            cpu_physical_memory_write(s->tx_desc_addr, (uint8_t *)desc_first,
                                      sizeof(desc_first));
            /* Advance the hardware current descriptor past this packet */
            if (tx_desc_get_wrap(desc)) {
                s->tx_desc_addr = s->regs[GEM_TXQBASE];
            } else {
                s->tx_desc_addr = packet_desc_addr + 8;
            DB_PRINT("TX descriptor next: 0x%08x\n", s->tx_desc_addr);
            s->regs[GEM_TXSTATUS] |= GEM_TXSTATUS_TXCMPL;
            s->regs[GEM_ISR] |= GEM_INT_TXCMPL & ~(s->regs[GEM_IMR]);
            /* Handle interrupt consequences */
            gem_update_int_status(s);
            /* Is checksum offload enabled? */
            if (s->regs[GEM_DMACFG] & GEM_DMACFG_TXCSUM_OFFL) {
                net_checksum_calculate(tx_packet, total_bytes);
            /* Update MAC statistics */
            gem_transmit_updatestats(s, tx_packet, total_bytes);
            /* Send the packet somewhere */
            if (s->phy_loop || (s->regs[GEM_NWCTRL] & GEM_NWCTRL_LOCALLOOP)) {
                gem_receive(qemu_get_queue(s->nic), tx_packet, total_bytes);
            } else {
                qemu_send_packet(qemu_get_queue(s->nic), tx_packet,
                                 total_bytes);
            /* Prepare for next packet */
            p = tx_packet;
            total_bytes = 0;
        /* read next descriptor */
        if (tx_desc_get_wrap(desc)) {
            packet_desc_addr = s->regs[GEM_TXQBASE];
        } else {
            packet_desc_addr += 8;
        DB_PRINT("read descriptor 0x%" HWADDR_PRIx "\n", packet_desc_addr);
        cpu_physical_memory_read(packet_desc_addr,
                                 (uint8_t *)desc, sizeof(desc));
    if (tx_desc_get_used(desc)) {
        s->regs[GEM_TXSTATUS] |= GEM_TXSTATUS_USED;
        s->regs[GEM_ISR] |= GEM_INT_TXUSED & ~(s->regs[GEM_IMR]);
        gem_update_int_status(s);


int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,

                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))

{

    AVPacketList **next_point, *this_pktl;

    AVStream *st   = s->streams[pkt->stream_index];

    int chunked    = s->max_chunk_size || s->max_chunk_duration;

    this_pktl      = av_mallocz(sizeof(AVPacketList));

    if (!this_pktl)

        return AVERROR(ENOMEM);

    this_pktl->pkt = *pkt;

    pkt->destruct  = NULL;           // do not free original but only the copy

    av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-allocated memory

    if (s->streams[pkt->stream_index]->last_in_packet_buffer) {

        next_point = &(st->last_in_packet_buffer->next);

    } else {

        next_point = &s->packet_buffer;

    }

    if (chunked) {

        uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);

        st->interleaver_chunk_size     += pkt->size;

        st->interleaver_chunk_duration += pkt->duration;

        if (   st->interleaver_chunk_size     > s->max_chunk_size-1U

            || st->interleaver_chunk_duration > max-1U) {

            st->interleaver_chunk_size     =

            st->interleaver_chunk_duration = 0;

            this_pktl->pkt.flags |= CHUNK_START;

        }

    }

    if (*next_point) {

        if (chunked && !(this_pktl->pkt.flags & CHUNK_START))

            goto next_non_null;

        if (compare(s, &s->packet_buffer_end->pkt, pkt)) {

            while (   *next_point

                   && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))

                       || !compare(s, &(*next_point)->pkt, pkt)))

                next_point = &(*next_point)->next;

            if (*next_point)

                goto next_non_null;

        } else {

            next_point = &(s->packet_buffer_end->next);

        }

    }

    av_assert1(!*next_point);

    s->packet_buffer_end = this_pktl;

next_non_null:

    this_pktl->next = *next_point;

    s->streams[pkt->stream_index]->last_in_packet_buffer =

        *next_point                                      = this_pktl;

    return 0;

}


static void sbr_qmf_synthesis(DSPContext *dsp, FFTContext *mdct,

                              float *out, float X[2][38][64],

                              float mdct_buf[2][64],

                              float *v0, int *v_off, const unsigned int div)

{

    int i, n;

    const float *sbr_qmf_window = div ? sbr_qmf_window_ds : sbr_qmf_window_us;

    const int step = 128 >> div;

    float *v;

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

        if (*v_off < step) {

            int saved_samples = (1280 - 128) >> div;

            memcpy(&v0[SBR_SYNTHESIS_BUF_SIZE - saved_samples], v0, saved_samples * sizeof(float));

            *v_off = SBR_SYNTHESIS_BUF_SIZE - saved_samples - step;

        } else {

            *v_off -= step;

        }

        v = v0 + *v_off;

        if (div) {

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

                X[0][i][   n] = -X[0][i][n];

                X[0][i][32+n] =  X[1][i][31-n];

            }

            mdct->imdct_half(mdct, mdct_buf[0], X[0][i]);

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

                v[     n] =  mdct_buf[0][63 - 2*n];

                v[63 - n] = -mdct_buf[0][62 - 2*n];

            }

        } else {

            for (n = 1; n < 64; n+=2) {

                X[1][i][n] = -X[1][i][n];

            }

            mdct->imdct_half(mdct, mdct_buf[0], X[0][i]);

            mdct->imdct_half(mdct, mdct_buf[1], X[1][i]);

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

                v[      n] = -mdct_buf[0][63 -   n] + mdct_buf[1][  n    ];

                v[127 - n] =  mdct_buf[0][63 -   n] + mdct_buf[1][  n    ];

            }

        }

        dsp->vector_fmul_add(out, v                , sbr_qmf_window               , zero64, 64 >> div);

        dsp->vector_fmul_add(out, v + ( 192 >> div), sbr_qmf_window + ( 64 >> div), out   , 64 >> div);

        dsp->vector_fmul_add(out, v + ( 256 >> div), sbr_qmf_window + (128 >> div), out   , 64 >> div);

        dsp->vector_fmul_add(out, v + ( 448 >> div), sbr_qmf_window + (192 >> div), out   , 64 >> div);

        dsp->vector_fmul_add(out, v + ( 512 >> div), sbr_qmf_window + (256 >> div), out   , 64 >> div);

        dsp->vector_fmul_add(out, v + ( 704 >> div), sbr_qmf_window + (320 >> div), out   , 64 >> div);

        dsp->vector_fmul_add(out, v + ( 768 >> div), sbr_qmf_window + (384 >> div), out   , 64 >> div);

        dsp->vector_fmul_add(out, v + ( 960 >> div), sbr_qmf_window + (448 >> div), out   , 64 >> div);

        dsp->vector_fmul_add(out, v + (1024 >> div), sbr_qmf_window + (512 >> div), out   , 64 >> div);

        dsp->vector_fmul_add(out, v + (1216 >> div), sbr_qmf_window + (576 >> div), out   , 64 >> div);

        out += 64 >> div;

    }

}


static int qdm2_decode(QDM2Context *q, const uint8_t *in, int16_t *out)

{

    int ch, i;

    const int frame_size = (q->frame_size * q->channels);

    /* select input buffer */

    q->compressed_data = in;

    q->compressed_size = q->checksum_size;

    /* copy old block, clear new block of output samples */

    memmove(q->output_buffer, &q->output_buffer[frame_size], frame_size * sizeof(float));

    memset(&q->output_buffer[frame_size], 0, frame_size * sizeof(float));

    /* decode block of QDM2 compressed data */

    if (q->sub_packet == 0) {

        q->has_errors = 0; // zero it for a new super block

        av_log(NULL,AV_LOG_DEBUG,"Superblock follows\n");

        qdm2_decode_super_block(q);

    }

    /* parse subpackets */

    if (!q->has_errors) {

        if (q->sub_packet == 2)

            qdm2_decode_fft_packets(q);

        qdm2_fft_tone_synthesizer(q, q->sub_packet);

    }

    /* sound synthesis stage 1 (FFT) */

    for (ch = 0; ch < q->channels; ch++) {

        qdm2_calculate_fft(q, ch, q->sub_packet);

        if (!q->has_errors && q->sub_packet_list_C[0].packet != NULL) {

            SAMPLES_NEEDED_2("has errors, and C list is not empty")

            return -1;

        }

    }

    /* sound synthesis stage 2 (MPEG audio like synthesis filter) */

    if (!q->has_errors && q->do_synth_filter)

        qdm2_synthesis_filter(q, q->sub_packet);

    q->sub_packet = (q->sub_packet + 1) % 16;

    /* clip and convert output float[] to 16bit signed samples */

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

        int value = (int)q->output_buffer[i];

        if (value > SOFTCLIP_THRESHOLD)

            value = (value >  HARDCLIP_THRESHOLD) ?  32767 :  softclip_table[ value - SOFTCLIP_THRESHOLD];

        else if (value < -SOFTCLIP_THRESHOLD)

            value = (value < -HARDCLIP_THRESHOLD) ? -32767 : -softclip_table[-value - SOFTCLIP_THRESHOLD];

        out[i] = value;

    }

    return 0;

}


int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)

{

    ByteIOContext pb;

    uint8_t *buf;

    int len;

    int rtcp_bytes;

    if (!s->rtp_ctx || (count < 1))

        return -1;

    /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */

    s->octet_count += count;

    rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /

        RTCP_TX_RATIO_DEN;

    rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?

    if (rtcp_bytes < 28)

        return -1;

    s->last_octet_count = s->octet_count;

    if (url_open_dyn_buf(&pb) < 0)

        return -1;

    // Receiver Report

    put_byte(&pb, (RTP_VERSION << 6) + 1); /* 1 report block */

    put_byte(&pb, 201);

    put_be16(&pb, 7); /* length in words - 1 */

    put_be32(&pb, s->ssrc); // our own SSRC

    put_be32(&pb, s->ssrc); // XXX: should be the server's here!

    // some placeholders we should really fill...

    put_be32(&pb, ((0 << 24) | (0 & 0x0ffffff))); /* 0% lost, total 0 lost */

    put_be32(&pb, (0 << 16) | s->seq);

    put_be32(&pb, 0x68); /* jitter */

    put_be32(&pb, -1); /* last SR timestamp */

    put_be32(&pb, 1); /* delay since last SR */

    // CNAME

    put_byte(&pb, (RTP_VERSION << 6) + 1); /* 1 report block */

    put_byte(&pb, 202);

    len = strlen(s->hostname);

    put_be16(&pb, (6 + len + 3) / 4); /* length in words - 1 */

    put_be32(&pb, s->ssrc);

    put_byte(&pb, 0x01);

    put_byte(&pb, len);

    put_buffer(&pb, s->hostname, len);

    // padding

    for (len = (6 + len) % 4; len % 4; len++) {

        put_byte(&pb, 0);

    }

    put_flush_packet(&pb);

    len = url_close_dyn_buf(&pb, &buf);

    if ((len > 0) && buf) {

#if defined(DEBUG)

        printf("sending %d bytes of RR\n", len);

#endif

        url_write(s->rtp_ctx, buf, len);

        av_free(buf);

    }

    return 0;

}


int ff_h263_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                         AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    MpegEncContext *s  = avctx->priv_data;

    int ret;

    int slice_ret = 0;

    AVFrame *pict = data;

    s->flags  = avctx->flags;

    s->flags2 = avctx->flags2;

    /* no supplementary picture */

    if (buf_size == 0) {

        /* special case for last picture */

        if (s->low_delay == 0 && s->next_picture_ptr) {

            if ((ret = av_frame_ref(pict, &s->next_picture_ptr->f)) < 0)

                return ret;

            s->next_picture_ptr = NULL;

            *got_frame = 1;

        }

        return 0;

    }

    if (s->flags & CODEC_FLAG_TRUNCATED) {

        int next;

        if (CONFIG_MPEG4_DECODER && s->codec_id == AV_CODEC_ID_MPEG4) {

            next = ff_mpeg4_find_frame_end(&s->parse_context, buf, buf_size);

        } else if (CONFIG_H263_DECODER && s->codec_id == AV_CODEC_ID_H263) {

            next = ff_h263_find_frame_end(&s->parse_context, buf, buf_size);

        } else if (CONFIG_H263P_DECODER && s->codec_id == AV_CODEC_ID_H263P) {

            next = ff_h263_find_frame_end(&s->parse_context, buf, buf_size);

        } else {

            av_log(s->avctx, AV_LOG_ERROR,

                   "this codec does not support truncated bitstreams\n");

            return AVERROR(ENOSYS);

        }

        if (ff_combine_frame(&s->parse_context, next, (const uint8_t **)&buf,

                             &buf_size) < 0)

            return buf_size;

    }

retry:

    if (s->divx_packed && s->bitstream_buffer_size) {

        int i;

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

            if (buf[i]==0 && buf[i+1]==0 && buf[i+2]==1) {

                if (buf[i+3]==0xB0) {

                    av_log(s->avctx, AV_LOG_WARNING, "Discarding excessive bitstream in packed xvid\n");

                    s->bitstream_buffer_size = 0;

                }

                break;

            }

        }

    }

    if (s->bitstream_buffer_size && (s->divx_packed || buf_size < 20)) // divx 5.01+/xvid frame reorder

        ret = init_get_bits8(&s->gb, s->bitstream_buffer,

                             s->bitstream_buffer_size);

    else

        ret = init_get_bits8(&s->gb, buf, buf_size);

    s->bitstream_buffer_size = 0;

    if (ret < 0)

        return ret;

    if (!s->context_initialized)

        // we need the idct permutaton for reading a custom matrix

        if ((ret = ff_MPV_common_init(s)) < 0)

            return ret;

    /* We need to set current_picture_ptr before reading the header,

     * otherwise we cannot store anyting in there */

    if (s->current_picture_ptr == NULL || s->current_picture_ptr->f.data[0]) {

        int i = ff_find_unused_picture(s, 0);

        if (i < 0)

            return i;

        s->current_picture_ptr = &s->picture[i];

    }

    /* let's go :-) */

    if (CONFIG_WMV2_DECODER && s->msmpeg4_version == 5) {

        ret = ff_wmv2_decode_picture_header(s);

    } else if (CONFIG_MSMPEG4_DECODER && s->msmpeg4_version) {

        ret = ff_msmpeg4_decode_picture_header(s);

    } else if (CONFIG_MPEG4_DECODER && avctx->codec_id == AV_CODEC_ID_MPEG4) {

        if (s->avctx->extradata_size && s->picture_number == 0) {

            GetBitContext gb;

            if (init_get_bits8(&gb, s->avctx->extradata, s->avctx->extradata_size) >= 0 )

                ff_mpeg4_decode_picture_header(avctx->priv_data, &gb);

        }

        ret = ff_mpeg4_decode_picture_header(avctx->priv_data, &s->gb);

    } else if (CONFIG_H263I_DECODER && s->codec_id == AV_CODEC_ID_H263I) {

        ret = ff_intel_h263_decode_picture_header(s);

    } else if (CONFIG_FLV_DECODER && s->h263_flv) {

        ret = ff_flv_decode_picture_header(s);

    } else {

        ret = ff_h263_decode_picture_header(s);

    }

    if (ret < 0 || ret == FRAME_SKIPPED) {

        if (   s->width  != avctx->coded_width

            || s->height != avctx->coded_height) {

                av_log(s->avctx, AV_LOG_WARNING, "Reverting picture dimensions change due to header decoding failure\n");

                s->width = avctx->coded_width;

                s->height= avctx->coded_height;

        }

    }

    if (ret == FRAME_SKIPPED)

        return get_consumed_bytes(s, buf_size);

    /* skip if the header was thrashed */

    if (ret < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");

        return ret;

    }

    avctx->has_b_frames = !s->low_delay;

    if (ff_mpeg4_workaround_bugs(avctx) == 1)

        goto retry;

    /* After H263 & mpeg4 header decode we have the height, width,

     * and other parameters. So then we could init the picture.

     * FIXME: By the way H263 decoder is evolving it should have

     * an H263EncContext */

    if (s->width  != avctx->coded_width  ||

        s->height != avctx->coded_height ||

        s->context_reinit) {

        /* H.263 could change picture size any time */

        s->context_reinit = 0;

        ret = ff_set_dimensions(avctx, s->width, s->height);

        if (ret < 0)

            return ret;

        if ((ret = ff_MPV_common_frame_size_change(s)))

            return ret;

    }

    if (s->codec_id == AV_CODEC_ID_H263  ||

        s->codec_id == AV_CODEC_ID_H263P ||

        s->codec_id == AV_CODEC_ID_H263I)

        s->gob_index = ff_h263_get_gob_height(s);

    // for skipping the frame

    s->current_picture.f.pict_type = s->pict_type;

    s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;

    /* skip B-frames if we don't have reference frames */

    if (s->last_picture_ptr == NULL &&

        (s->pict_type == AV_PICTURE_TYPE_B || s->droppable))

        return get_consumed_bytes(s, buf_size);

    if ((avctx->skip_frame >= AVDISCARD_NONREF &&

         s->pict_type == AV_PICTURE_TYPE_B)    ||

        (avctx->skip_frame >= AVDISCARD_NONKEY &&

         s->pict_type != AV_PICTURE_TYPE_I)    ||

        avctx->skip_frame >= AVDISCARD_ALL)

        return get_consumed_bytes(s, buf_size);

    if (s->next_p_frame_damaged) {

        if (s->pict_type == AV_PICTURE_TYPE_B)

            return get_consumed_bytes(s, buf_size);

        else

            s->next_p_frame_damaged = 0;

    }

    if ((!s->no_rounding) || s->pict_type == AV_PICTURE_TYPE_B) {

        s->me.qpel_put = s->dsp.put_qpel_pixels_tab;

        s->me.qpel_avg = s->dsp.avg_qpel_pixels_tab;

    } else {

        s->me.qpel_put = s->dsp.put_no_rnd_qpel_pixels_tab;

        s->me.qpel_avg = s->dsp.avg_qpel_pixels_tab;

    }

    if ((ret = ff_MPV_frame_start(s, avctx)) < 0)

        return ret;

    if (!s->divx_packed && !avctx->hwaccel)

        ff_thread_finish_setup(avctx);

    if (CONFIG_MPEG4_VDPAU_DECODER && (s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)) {

        ff_vdpau_mpeg4_decode_picture(s, s->gb.buffer, s->gb.buffer_end - s->gb.buffer);

        goto frame_end;

    }

    if (avctx->hwaccel) {

        ret = avctx->hwaccel->start_frame(avctx, s->gb.buffer,

                                          s->gb.buffer_end - s->gb.buffer);

        if (ret < 0 )

            return ret;

    }

    ff_mpeg_er_frame_start(s);

    /* the second part of the wmv2 header contains the MB skip bits which

     * are stored in current_picture->mb_type which is not available before

     * ff_MPV_frame_start() */

    if (CONFIG_WMV2_DECODER && s->msmpeg4_version == 5) {

        ret = ff_wmv2_decode_secondary_picture_header(s);

        if (ret < 0)

            return ret;

        if (ret == 1)

            goto frame_end;

    }

    /* decode each macroblock */

    s->mb_x = 0;

    s->mb_y = 0;

    slice_ret = decode_slice(s);

    while (s->mb_y < s->mb_height) {

        if (s->msmpeg4_version) {

            if (s->slice_height == 0 || s->mb_x != 0 ||

                (s->mb_y % s->slice_height) != 0 || get_bits_left(&s->gb) < 0)

                break;

        } else {

            int prev_x = s->mb_x, prev_y = s->mb_y;

            if (ff_h263_resync(s) < 0)

                break;

            if (prev_y * s->mb_width + prev_x < s->mb_y * s->mb_width + s->mb_x)

                s->er.error_occurred = 1;

        }

        if (s->msmpeg4_version < 4 && s->h263_pred)

            ff_mpeg4_clean_buffers(s);

        if (decode_slice(s) < 0)

            slice_ret = AVERROR_INVALIDDATA;

    }

    if (s->msmpeg4_version && s->msmpeg4_version < 4 &&

        s->pict_type == AV_PICTURE_TYPE_I)

        if (!CONFIG_MSMPEG4_DECODER ||

            ff_msmpeg4_decode_ext_header(s, buf_size) < 0)

            s->er.error_status_table[s->mb_num - 1] = ER_MB_ERROR;

    av_assert1(s->bitstream_buffer_size == 0);

frame_end:

    ff_er_frame_end(&s->er);

    if (avctx->hwaccel) {

        ret = avctx->hwaccel->end_frame(avctx);

        if (ret < 0)

            return ret;

    }

    ff_MPV_frame_end(s);

    /* divx 5.01+ bitstream reorder stuff */

    /* Since this clobbers the input buffer and hwaccel codecs still need the

     * data during hwaccel->end_frame we should not do this any earlier */

    if (s->codec_id == AV_CODEC_ID_MPEG4 && s->divx_packed) {

        int current_pos     = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3);

        int startcode_found = 0;

        if (buf_size - current_pos > 7) {

            int i;

            for (i = current_pos; i < buf_size - 4; i++)

                if (buf[i]     == 0 &&

                    buf[i + 1] == 0 &&

                    buf[i + 2] == 1 &&

                    buf[i + 3] == 0xB6) {

                    startcode_found = !(buf[i + 4] & 0x40);

                    break;

                }

        }

        if (startcode_found) {

            av_fast_malloc(&s->bitstream_buffer,

                           &s->allocated_bitstream_buffer_size,

                           buf_size - current_pos +

                           FF_INPUT_BUFFER_PADDING_SIZE);

            if (!s->bitstream_buffer)

                return AVERROR(ENOMEM);

            memcpy(s->bitstream_buffer, buf + current_pos,

                   buf_size - current_pos);

            s->bitstream_buffer_size = buf_size - current_pos;

        }

    }

    if (!s->divx_packed && avctx->hwaccel)

        ff_thread_finish_setup(avctx);

    av_assert1(s->current_picture.f.pict_type == s->current_picture_ptr->f.pict_type);

    av_assert1(s->current_picture.f.pict_type == s->pict_type);

    if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {

        if ((ret = av_frame_ref(pict, &s->current_picture_ptr->f)) < 0)

            return ret;

        ff_print_debug_info(s, s->current_picture_ptr, pict);

        ff_mpv_export_qp_table(s, pict, s->current_picture_ptr, FF_QSCALE_TYPE_MPEG1);

    } else if (s->last_picture_ptr != NULL) {

        if ((ret = av_frame_ref(pict, &s->last_picture_ptr->f)) < 0)

            return ret;

        ff_print_debug_info(s, s->last_picture_ptr, pict);

        ff_mpv_export_qp_table(s, pict, s->last_picture_ptr, FF_QSCALE_TYPE_MPEG1);

    }

    if (s->last_picture_ptr || s->low_delay) {

        if (   pict->format == AV_PIX_FMT_YUV420P

            && (s->codec_tag == AV_RL32("GEOV") || s->codec_tag == AV_RL32("GEOX"))) {

            int x, y, p;

            av_frame_make_writable(pict);

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

                int w = FF_CEIL_RSHIFT(pict-> width, !!p);

                int h = FF_CEIL_RSHIFT(pict->height, !!p);

                int linesize = pict->linesize[p];

                for (y=0; y<(h>>1); y++)

                    for (x=0; x<w; x++)

                        FFSWAP(int,

                               pict->data[p][x + y*linesize],

                               pict->data[p][x + (h-1-y)*linesize]);

            }

        }

        *got_frame = 1;

    }

    if (slice_ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))

        return ret;

    else

        return get_consumed_bytes(s, buf_size);

}


static void decorrelate_stereo_24(int32_t *buffer[MAX_CHANNELS],

                                  int32_t *buffer_out,

                                  int32_t *wasted_bits_buffer[MAX_CHANNELS],

                                  int wasted_bits,

                                  int numchannels, int numsamples,

                                  uint8_t interlacing_shift,

                                  uint8_t interlacing_leftweight)

{

    int i;

    if (numsamples <= 0)

        return;

    /* weighted interlacing */

    if (interlacing_leftweight) {

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

            int32_t a, b;

            a = buffer[0][i];

            b = buffer[1][i];

            a -= (b * interlacing_leftweight) >> interlacing_shift;

            b += a;

            if (wasted_bits) {

                b  = (b  << wasted_bits) | wasted_bits_buffer[0][i];

                a  = (a  << wasted_bits) | wasted_bits_buffer[1][i];

            }

            buffer_out[i * numchannels]     = b << 8;

            buffer_out[i * numchannels + 1] = a << 8;

        }

    } else {

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

            int32_t left, right;

            left  = buffer[0][i];

            right = buffer[1][i];

            if (wasted_bits) {

                left   = (left   << wasted_bits) | wasted_bits_buffer[0][i];

                right  = (right  << wasted_bits) | wasted_bits_buffer[1][i];

            }

            buffer_out[i * numchannels]     = left  << 8;

            buffer_out[i * numchannels + 1] = right << 8;

        }

    }

}


static int xwma_read_header(AVFormatContext *s)

{

    int64_t size;

    int ret = 0;

    uint32_t dpds_table_size = 0;

    uint32_t *dpds_table = NULL;

    unsigned int tag;

    AVIOContext *pb = s->pb;

    AVStream *st;

    XWMAContext *xwma = s->priv_data;

    int i;

    /* The following code is mostly copied from wav.c, with some

     * minor alterations.

     */

    /* check RIFF header */

    tag = avio_rl32(pb);

    if (tag != MKTAG('R', 'I', 'F', 'F'))

        return -1;

    avio_rl32(pb); /* file size */

    tag = avio_rl32(pb);

    if (tag != MKTAG('X', 'W', 'M', 'A'))

        return -1;

    /* parse fmt header */

    tag = avio_rl32(pb);

    if (tag != MKTAG('f', 'm', 't', ' '))

        return -1;

    size = avio_rl32(pb);

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    ret = ff_get_wav_header(pb, st->codec, size, 0);

    if (ret < 0)

        return ret;

    st->need_parsing = AVSTREAM_PARSE_NONE;

    /* All xWMA files I have seen contained WMAv2 data. If there are files

     * using WMA Pro or some other codec, then we need to figure out the right

     * extradata for that. Thus, ask the user for feedback, but try to go on

     * anyway.

     */

    if (st->codec->codec_id != AV_CODEC_ID_WMAV2) {

        avpriv_request_sample(s, "Unexpected codec (tag 0x04%x; id %d)",

                              st->codec->codec_tag, st->codec->codec_id);

    } else {

        /* In all xWMA files I have seen, there is no extradata. But the WMA

         * codecs require extradata, so we provide our own fake extradata.

         *

         * First, check that there really was no extradata in the header. If

         * there was, then try to use it, after asking the user to provide a

         * sample of this unusual file.

         */

        if (st->codec->extradata_size != 0) {

            /* Surprise, surprise: We *did* get some extradata. No idea

             * if it will work, but just go on and try it, after asking

             * the user for a sample.

             */

            avpriv_request_sample(s, "Unexpected extradata (%d bytes)",

                                  st->codec->extradata_size);

        } else {

            st->codec->extradata_size = 6;

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

            if (!st->codec->extradata)

                return AVERROR(ENOMEM);

            /* setup extradata with our experimentally obtained value */

            st->codec->extradata[4] = 31;

        }

    }

    if (!st->codec->channels) {

        av_log(s, AV_LOG_WARNING, "Invalid channel count: %d\n",

               st->codec->channels);

        return AVERROR_INVALIDDATA;

    }

    if (!st->codec->bits_per_coded_sample) {

        av_log(s, AV_LOG_WARNING, "Invalid bits_per_coded_sample: %d\n",

               st->codec->bits_per_coded_sample);

        return AVERROR_INVALIDDATA;

    }

    /* set the sample rate */

    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);

    /* parse the remaining RIFF chunks */

    for (;;) {

        if (pb->eof_reached) {

            ret = AVERROR_EOF;

            goto fail;

        }

        /* read next chunk tag */

        tag = avio_rl32(pb);

        size = avio_rl32(pb);

        if (tag == MKTAG('d', 'a', 't', 'a')) {

            /* We assume that the data chunk comes last. */

            break;

        } else if (tag == MKTAG('d','p','d','s')) {

            /* Quoting the MSDN xWMA docs on the dpds chunk: "Contains the

             * decoded packet cumulative data size array, each element is the

             * number of bytes accumulated after the corresponding xWMA packet

             * is decoded in order."

             *

             * Each packet has size equal to st->codec->block_align, which in

             * all cases I saw so far was always 2230. Thus, we can use the

             * dpds data to compute a seeking index.

             */

            /* Error out if there is more than one dpds chunk. */

            if (dpds_table) {

                av_log(s, AV_LOG_ERROR, "two dpds chunks present\n");

                ret = AVERROR_INVALIDDATA;

                goto fail;

            }

            /* Compute the number of entries in the dpds chunk. */

            if (size & 3) {  /* Size should be divisible by four */

                av_log(s, AV_LOG_WARNING,

                       "dpds chunk size %"PRId64" not divisible by 4\n", size);

            }

            dpds_table_size = size / 4;

            if (dpds_table_size == 0 || dpds_table_size >= INT_MAX / 4) {

                av_log(s, AV_LOG_ERROR,

                       "dpds chunk size %"PRId64" invalid\n", size);

                return AVERROR_INVALIDDATA;

            }

            /* Allocate some temporary storage to keep the dpds data around.

             * for processing later on.

             */

            dpds_table = av_malloc(dpds_table_size * sizeof(uint32_t));

            if (!dpds_table) {

                return AVERROR(ENOMEM);

            }

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

                dpds_table[i] = avio_rl32(pb);

                size -= 4;

            }

        }

        avio_skip(pb, size);

    }

    /* Determine overall data length */

    if (size < 0) {

        ret = AVERROR_INVALIDDATA;

        goto fail;

    }

    if (!size) {

        xwma->data_end = INT64_MAX;

    } else

        xwma->data_end = avio_tell(pb) + size;

    if (dpds_table && dpds_table_size) {

        int64_t cur_pos;

        const uint32_t bytes_per_sample

                = (st->codec->channels * st->codec->bits_per_coded_sample) >> 3;

        /* Estimate the duration from the total number of output bytes. */

        const uint64_t total_decoded_bytes = dpds_table[dpds_table_size - 1];

        if (!bytes_per_sample) {

            av_log(s, AV_LOG_ERROR,

                   "Invalid bits_per_coded_sample %d for %d channels\n",

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

            ret = AVERROR_INVALIDDATA;

            goto fail;

        }

        st->duration = total_decoded_bytes / bytes_per_sample;

        /* Use the dpds data to build a seek table.  We can only do this after

         * we know the offset to the data chunk, as we need that to determine

         * the actual offset to each input block.

         * Note: If we allowed ourselves to assume that the data chunk always

         * follows immediately after the dpds block, we could of course guess

         * the data block's start offset already while reading the dpds chunk.

         * I decided against that, just in case other chunks ever are

         * discovered.

         */

        cur_pos = avio_tell(pb);

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

            /* From the number of output bytes that would accumulate in the

             * output buffer after decoding the first (i+1) packets, we compute

             * an offset / timestamp pair.

             */

            av_add_index_entry(st,

                               cur_pos + (i+1) * st->codec->block_align, /* pos */

                               dpds_table[i] / bytes_per_sample,         /* timestamp */

                               st->codec->block_align,                   /* size */

                               0,                                        /* duration */

                               AVINDEX_KEYFRAME);

        }

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

        /* No dpds chunk was present (or only an empty one), so estimate

         * the total duration using the average bits per sample and the

         * total data length.

         */

        st->duration = (size<<3) * st->codec->sample_rate / st->codec->bit_rate;

    }

fail:

    av_free(dpds_table);

    return ret;

}


static void test_acpi_asl(test_data *data)

{

    int i;

    AcpiSdtTable *sdt, *exp_sdt;

    test_data exp_data;

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

    exp_data.ssdt_tables = load_expected_aml(data);

    dump_aml_files(data);

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

        GString *asl, *exp_asl;

        sdt = &g_array_index(data->ssdt_tables, AcpiSdtTable, i);

        exp_sdt = &g_array_index(exp_data.ssdt_tables, AcpiSdtTable, i);

        load_asl(data->ssdt_tables, sdt);

        asl = normalize_asl(sdt->asl);

        load_asl(exp_data.ssdt_tables, exp_sdt);

        exp_asl = normalize_asl(exp_sdt->asl);

        g_assert(!g_strcmp0(asl->str, exp_asl->str));

        g_string_free(asl, true);

        g_string_free(exp_asl, true);

    }

    free_test_data(&exp_data);

}


static void iscsi_nop_timed_event(void *opaque)

{

    IscsiLun *iscsilun = opaque;

    aio_context_acquire(iscsilun->aio_context);

    if (iscsi_get_nops_in_flight(iscsilun->iscsi) >= MAX_NOP_FAILURES) {

        error_report("iSCSI: NOP timeout. Reconnecting...");

        iscsilun->request_timed_out = true;

    } else if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {

        error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");

        goto out;

    }

    timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);

    iscsi_set_events(iscsilun);

out:

    aio_context_release(iscsilun->aio_context);

}


static bool sys_ops_accepts(void *opaque, target_phys_addr_t addr,

                            unsigned size, bool is_write)

{

    return is_write && size == 4;

}


static target_ulong h_set_mode_resouce_addr_trans_mode(PowerPCCPU *cpu,

                                                       target_ulong mflags,

                                                       target_ulong value1,

                                                       target_ulong value2)

{

    CPUState *cs;

    PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cpu);

    target_ulong prefix;

    if (!(pcc->insns_flags2 & PPC2_ISA207S)) {

        return H_P2;

    }

    if (value1) {

        return H_P3;

    }

    if (value2) {

        return H_P4;

    }

    switch (mflags) {

    case H_SET_MODE_ADDR_TRANS_NONE:

        prefix = 0;

        break;

    case H_SET_MODE_ADDR_TRANS_0001_8000:

        prefix = 0x18000;

        break;

    case H_SET_MODE_ADDR_TRANS_C000_0000_0000_4000:

        prefix = 0xC000000000004000;

        break;

    default:

        return H_UNSUPPORTED_FLAG;

    }

    CPU_FOREACH(cs) {

        CPUPPCState *env = &POWERPC_CPU(cpu)->env;

        set_spr(cs, SPR_LPCR, mflags << LPCR_AIL_SHIFT, LPCR_AIL);

        env->excp_prefix = prefix;

    }

    return H_SUCCESS;

}


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

{

    int packet_size, ret, width, height;

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

    width = st->codec->width;

    height = st->codec->height;

    packet_size = GET_PACKET_SIZE(width, height);

    if (packet_size < 0)

        return -1;

    ret = av_get_packet(s->pb, pkt, packet_size);

    pkt->pts = pkt->dts = pkt->pos / packet_size;

    pkt->stream_index = 0;

    if (ret < 0)

        return ret;

    return 0;

}


void op_dmtc0_ebase (void)

{

    /* vectored interrupts not implemented */

    /* Multi-CPU not implemented */

    /* XXX: 64bit addressing broken */

    env->CP0_EBase = (int32_t)0x80000000 | (T0 & 0x3FFFF000);

    RETURN();

}


static int vmdk_add_extent(BlockDriverState *bs,

                           BlockDriverState *file, bool flat, int64_t sectors,

                           int64_t l1_offset, int64_t l1_backup_offset,

                           uint32_t l1_size,

                           int l2_size, uint64_t cluster_sectors,

                           VmdkExtent **new_extent,

                           Error **errp)

{

    VmdkExtent *extent;

    BDRVVmdkState *s = bs->opaque;

    if (cluster_sectors > 0x200000) {

        /* 0x200000 * 512Bytes = 1GB for one cluster is unrealistic */

        error_setg(errp, "Invalid granularity, image may be corrupt");

        return -EFBIG;

    }

    if (l1_size > 512 * 1024 * 1024) {

        /* Although with big capacity and small l1_entry_sectors, we can get a

         * big l1_size, we don't want unbounded value to allocate the table.

         * Limit it to 512M, which is 16PB for default cluster and L2 table

         * size */

        error_setg(errp, "L1 size too big");

        return -EFBIG;

    }

    s->extents = g_realloc(s->extents,

                              (s->num_extents + 1) * sizeof(VmdkExtent));

    extent = &s->extents[s->num_extents];

    s->num_extents++;

    memset(extent, 0, sizeof(VmdkExtent));

    extent->file = file;

    extent->flat = flat;

    extent->sectors = sectors;

    extent->l1_table_offset = l1_offset;

    extent->l1_backup_table_offset = l1_backup_offset;

    extent->l1_size = l1_size;

    extent->l1_entry_sectors = l2_size * cluster_sectors;

    extent->l2_size = l2_size;

    extent->cluster_sectors = flat ? sectors : cluster_sectors;

    if (!flat) {

        bs->bl.write_zeroes_alignment =

            MAX(bs->bl.write_zeroes_alignment, cluster_sectors);

    }

    if (s->num_extents > 1) {

        extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;

    } else {

        extent->end_sector = extent->sectors;

    }

    bs->total_sectors = extent->end_sector;

    if (new_extent) {

        *new_extent = extent;

    }

    return 0;

}


static inline void tlb_protect_code1(CPUTLBEntry *tlb_entry, uint32_t addr)

{

    if (addr == (tlb_entry->address &

                 (TARGET_PAGE_MASK | TLB_INVALID_MASK)) &&

        (tlb_entry->address & ~TARGET_PAGE_MASK) != IO_MEM_CODE) {

        tlb_entry->address |= IO_MEM_CODE;

        tlb_entry->addend -= (unsigned long)phys_ram_base;

    }

}


static void disas_system(DisasContext *s, uint32_t insn)

{

    unsigned int l, op0, op1, crn, crm, op2, rt;

    l = extract32(insn, 21, 1);

    op0 = extract32(insn, 19, 2);

    op1 = extract32(insn, 16, 3);

    crn = extract32(insn, 12, 4);

    crm = extract32(insn, 8, 4);

    op2 = extract32(insn, 5, 3);

    rt = extract32(insn, 0, 5);

    if (op0 == 0) {

        if (l || rt != 31) {

            unallocated_encoding(s);

            return;

        }

        switch (crn) {

        case 2: /* C5.6.68 HINT */

            handle_hint(s, insn, op1, op2, crm);

            break;

        case 3: /* CLREX, DSB, DMB, ISB */

            handle_sync(s, insn, op1, op2, crm);

            break;

        case 4: /* C5.6.130 MSR (immediate) */

            handle_msr_i(s, insn, op1, op2, crm);

            break;

        default:

            unallocated_encoding(s);

            break;

        }

        return;

    }

    if (op0 == 1) {

        /* C5.6.204 SYS */

        handle_sys(s, insn, l, op1, op2, crn, crm, rt);

    } else if (l) { /* op0 > 1 */

        /* C5.6.129 MRS - move from system register */

        handle_mrs(s, insn, op0, op1, op2, crn, crm, rt);

    } else {

        /* C5.6.131 MSR (register) - move to system register */

        handle_msr(s, insn, op0, op1, op2, crn, crm, rt);

    }

}


POWERPC_FAMILY(POWER7P)(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);

    dc->fw_name = "PowerPC,POWER7+";

    dc->desc = "POWER7+";

    dc->props = powerpc_servercpu_properties;

    pcc->pvr_match = ppc_pvr_match_power7;

    pcc->pcr_mask = PCR_COMPAT_2_05 | PCR_COMPAT_2_06;

    pcc->init_proc = init_proc_POWER7;

    pcc->check_pow = check_pow_nocheck;

    pcc->insns_flags = PPC_INSNS_BASE | PPC_ISEL | PPC_STRING | PPC_MFTB |

                       PPC_FLOAT | PPC_FLOAT_FSEL | PPC_FLOAT_FRES |

                       PPC_FLOAT_FSQRT | PPC_FLOAT_FRSQRTE |

                       PPC_FLOAT_FRSQRTES |

                       PPC_FLOAT_STFIWX |

                       PPC_FLOAT_EXT |

                       PPC_CACHE | PPC_CACHE_ICBI | PPC_CACHE_DCBZ |

                       PPC_MEM_SYNC | PPC_MEM_EIEIO |

                       PPC_MEM_TLBIE | PPC_MEM_TLBSYNC |

                       PPC_64B | PPC_ALTIVEC |

                       PPC_SEGMENT_64B | PPC_SLBI |

                       PPC_POPCNTB | PPC_POPCNTWD;

    pcc->insns_flags2 = PPC2_VSX | PPC2_DFP | PPC2_DBRX | PPC2_ISA205 |

                        PPC2_PERM_ISA206 | PPC2_DIVE_ISA206 |

                        PPC2_ATOMIC_ISA206 | PPC2_FP_CVT_ISA206 |

                        PPC2_FP_TST_ISA206;

    pcc->msr_mask = (1ull << MSR_SF) |

                    (1ull << MSR_VR) |

                    (1ull << MSR_VSX) |

                    (1ull << MSR_EE) |

                    (1ull << MSR_PR) |

                    (1ull << MSR_FP) |

                    (1ull << MSR_ME) |

                    (1ull << MSR_FE0) |

                    (1ull << MSR_SE) |

                    (1ull << MSR_DE) |

                    (1ull << MSR_FE1) |

                    (1ull << MSR_IR) |

                    (1ull << MSR_DR) |

                    (1ull << MSR_PMM) |

                    (1ull << MSR_RI) |

                    (1ull << MSR_LE);

    pcc->mmu_model = POWERPC_MMU_2_06;

#if defined(CONFIG_SOFTMMU)

    pcc->handle_mmu_fault = ppc_hash64_handle_mmu_fault;

#endif

    pcc->excp_model = POWERPC_EXCP_POWER7;

    pcc->bus_model = PPC_FLAGS_INPUT_POWER7;

    pcc->bfd_mach = bfd_mach_ppc64;

    pcc->flags = POWERPC_FLAG_VRE | POWERPC_FLAG_SE |

                 POWERPC_FLAG_BE | POWERPC_FLAG_PMM |

                 POWERPC_FLAG_BUS_CLK | POWERPC_FLAG_CFAR |

                 POWERPC_FLAG_VSX;

    pcc->l1_dcache_size = 0x8000;

    pcc->l1_icache_size = 0x8000;

    pcc->interrupts_big_endian = ppc_cpu_interrupts_big_endian_lpcr;

}


static ssize_t mp_dacl_getxattr(FsContext *ctx, const char *path,

                                const char *name, void *value, size_t size)

{

    char buffer[PATH_MAX];

    return lgetxattr(rpath(ctx, path, buffer), MAP_ACL_DEFAULT, value, size);

}


static void fdt_add_timer_nodes(const VirtBoardInfo *vbi)

{

    /* Note that on A15 h/w these interrupts are level-triggered,

     * but for the GIC implementation provided by both QEMU and KVM

     * they are edge-triggered.

     */

    uint32_t irqflags = GIC_FDT_IRQ_FLAGS_EDGE_LO_HI;

    irqflags = deposit32(irqflags, GIC_FDT_IRQ_PPI_CPU_START,

                         GIC_FDT_IRQ_PPI_CPU_WIDTH, (1 << vbi->smp_cpus) - 1);

    qemu_fdt_add_subnode(vbi->fdt, "/timer");

    qemu_fdt_setprop_string(vbi->fdt, "/timer",

                                "compatible", "arm,armv7-timer");

    qemu_fdt_setprop_cells(vbi->fdt, "/timer", "interrupts",

                               GIC_FDT_IRQ_TYPE_PPI, 13, irqflags,

                               GIC_FDT_IRQ_TYPE_PPI, 14, irqflags,

                               GIC_FDT_IRQ_TYPE_PPI, 11, irqflags,

                               GIC_FDT_IRQ_TYPE_PPI, 10, irqflags);

}


static void eeprom24c0x_write(int scl, int sda)

{

    if (eeprom.scl && scl && (eeprom.sda != sda)) {

        logout("%u: scl = %u->%u, sda = %u->%u i2c %s\n",

                eeprom.tick, eeprom.scl, scl, eeprom.sda, sda, sda ? "stop" : "start");

        if (!sda) {

            eeprom.tick = 1;

            eeprom.command = 0;

        }

    } else if (eeprom.tick == 0 && !eeprom.ack) {

        /* Waiting for start. */

        logout("%u: scl = %u->%u, sda = %u->%u wait for i2c start\n",

                eeprom.tick, eeprom.scl, scl, eeprom.sda, sda);

    } else if (!eeprom.scl && scl) {

        logout("%u: scl = %u->%u, sda = %u->%u trigger bit\n",

                eeprom.tick, eeprom.scl, scl, eeprom.sda, sda);

        if (eeprom.ack) {

            logout("\ti2c ack bit = 0\n");

            sda = 0;

            eeprom.ack = 0;

        } else if (eeprom.sda == sda) {

            uint8_t bit = (sda != 0);

            logout("\ti2c bit = %d\n", bit);

            if (eeprom.tick < 9) {

                eeprom.command <<= 1;

                eeprom.command += bit;

                eeprom.tick++;

                if (eeprom.tick == 9) {

                    logout("\tcommand 0x%04x, %s\n", eeprom.command, bit ? "read" : "write");

                    eeprom.ack = 1;

                }

            } else if (eeprom.tick < 17) {

                if (eeprom.command & 1) {

                    sda = ((eeprom.data & 0x80) != 0);

                }

                eeprom.address <<= 1;

                eeprom.address += bit;

                eeprom.tick++;

                eeprom.data <<= 1;

                if (eeprom.tick == 17) {

                    eeprom.data = eeprom.contents[eeprom.address];

                    logout("\taddress 0x%04x, data 0x%02x\n", eeprom.address, eeprom.data);

                    eeprom.ack = 1;

                    eeprom.tick = 0;

                }

            } else if (eeprom.tick >= 17) {

                sda = 0;

            }

        } else {

            logout("\tsda changed with raising scl\n");

        }

    } else {

        logout("%u: scl = %u->%u, sda = %u->%u\n", eeprom.tick, eeprom.scl, scl, eeprom.sda, sda);

    }

    eeprom.scl = scl;

    eeprom.sda = sda;

}


static void cmd_mode_sense(IDEState *s, uint8_t *buf)

{

    int action, code;

    int max_len;

    if (buf[0] == GPCMD_MODE_SENSE_10) {

        max_len = ube16_to_cpu(buf + 7);

    } else {

        max_len = buf[4];

    }

    action = buf[2] >> 6;

    code = buf[2] & 0x3f;

    switch(action) {

    case 0: /* current values */

        switch(code) {

        case MODE_PAGE_R_W_ERROR: /* error recovery */

            cpu_to_ube16(&buf[0], 16 + 6);

            buf[2] = 0x70;

            buf[3] = 0;

            buf[4] = 0;

            buf[5] = 0;

            buf[6] = 0;

            buf[7] = 0;

            buf[8] = MODE_PAGE_R_W_ERROR;

            buf[9] = 16 - 10;

            buf[10] = 0x00;

            buf[11] = 0x05;

            buf[12] = 0x00;

            buf[13] = 0x00;

            buf[14] = 0x00;

            buf[15] = 0x00;

            ide_atapi_cmd_reply(s, 16, max_len);

            break;

        case MODE_PAGE_AUDIO_CTL:

            cpu_to_ube16(&buf[0], 24 + 6);

            buf[2] = 0x70;

            buf[3] = 0;

            buf[4] = 0;

            buf[5] = 0;

            buf[6] = 0;

            buf[7] = 0;

            buf[8] = MODE_PAGE_AUDIO_CTL;

            buf[9] = 24 - 10;

            /* Fill with CDROM audio volume */

            buf[17] = 0;

            buf[19] = 0;

            buf[21] = 0;

            buf[23] = 0;

            ide_atapi_cmd_reply(s, 24, max_len);

            break;

        case MODE_PAGE_CAPABILITIES:

            cpu_to_ube16(&buf[0], 28 + 6);

            buf[2] = 0x70;

            buf[3] = 0;

            buf[4] = 0;

            buf[5] = 0;

            buf[6] = 0;

            buf[7] = 0;

            buf[8] = MODE_PAGE_CAPABILITIES;

            buf[9] = 28 - 10;

            buf[10] = 0x00;

            buf[11] = 0x00;

            /* Claim PLAY_AUDIO capability (0x01) since some Linux

               code checks for this to automount media. */

            buf[12] = 0x71;

            buf[13] = 3 << 5;

            buf[14] = (1 << 0) | (1 << 3) | (1 << 5);

            if (s->tray_locked) {

                buf[6] |= 1 << 1;

            }

            buf[15] = 0x00;

            cpu_to_ube16(&buf[16], 706);

            buf[18] = 0;

            buf[19] = 2;

            cpu_to_ube16(&buf[20], 512);

            cpu_to_ube16(&buf[22], 706);

            buf[24] = 0;

            buf[25] = 0;

            buf[26] = 0;

            buf[27] = 0;

            ide_atapi_cmd_reply(s, 28, max_len);

            break;

        default:

            goto error_cmd;

        }

        break;

    case 1: /* changeable values */

        goto error_cmd;

    case 2: /* default values */

        goto error_cmd;

    default:

    case 3: /* saved values */

        ide_atapi_cmd_error(s, ILLEGAL_REQUEST,

                            ASC_SAVING_PARAMETERS_NOT_SUPPORTED);

        break;

    }

    return;

error_cmd:

    ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_INV_FIELD_IN_CMD_PACKET);

}


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

{

    const uint8_t *s = src;

    const uint8_t *end;

#if COMPILE_TEMPLATE_MMX

    const uint8_t *mm_end;

#endif

    uint16_t *d = (uint16_t *)dst;

    end = s + src_size;

#if COMPILE_TEMPLATE_MMX

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

    __asm__ volatile(

        "movq         %0, %%mm7     \n\t"

        "movq         %1, %%mm6     \n\t"

        ::"m"(red_16mask),"m"(green_16mask));

    mm_end = end - 11;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

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

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

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

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

            "movq       %%mm0, %%mm1    \n\t"

            "movq       %%mm0, %%mm2    \n\t"

            "movq       %%mm3, %%mm4    \n\t"

            "movq       %%mm3, %%mm5    \n\t"

            "psrlq         $3, %%mm0    \n\t"

            "psrlq         $3, %%mm3    \n\t"

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

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

            "psrlq         $5, %%mm1    \n\t"

            "psrlq         $5, %%mm4    \n\t"

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

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

            "psrlq         $8, %%mm2    \n\t"

            "psrlq         $8, %%mm5    \n\t"

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

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

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

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

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

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

            "psllq        $16, %%mm3    \n\t"

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

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

            :"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");

        d += 4;

        s += 12;

    }

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

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

#endif

    while (s < end) {

        const int b = *s++;

        const int g = *s++;

        const int r = *s++;

        *d++ = (b>>3) | ((g&0xFC)<<3) | ((r&0xF8)<<8);

    }

}


int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)

{

    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */

    char *tmp_filename = g_malloc0(PATH_MAX + 1);

    int64_t total_size;

    QemuOpts *opts = NULL;

    QDict *snapshot_options;

    BlockDriverState *bs_snapshot;

    Error *local_err;

    int ret;

    /* if snapshot, we create a temporary backing file and open it

       instead of opening 'filename' directly */

    /* Get the required size from the image */

    total_size = bdrv_getlength(bs);

    if (total_size < 0) {

        ret = total_size;

        error_setg_errno(errp, -total_size, "Could not get image size");

        goto out;

    }

    /* Create the temporary image */

    ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not get temporary filename");

        goto out;

    }

    opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,

                            &error_abort);

    qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);

    ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, &local_err);

    qemu_opts_del(opts);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not create temporary overlay "

                         "'%s': %s", tmp_filename,

                         error_get_pretty(local_err));

        error_free(local_err);

        goto out;

    }

    /* Prepare a new options QDict for the temporary file */

    snapshot_options = qdict_new();

    qdict_put(snapshot_options, "file.driver",

              qstring_from_str("file"));

    qdict_put(snapshot_options, "file.filename",

              qstring_from_str(tmp_filename));

    bs_snapshot = bdrv_new();

    ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,

                    flags, &bdrv_qcow2, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto out;

    }

    bdrv_append(bs_snapshot, bs);

out:

    g_free(tmp_filename);

    return ret;

}


void address_space_read(AddressSpace *as, target_phys_addr_t addr, uint8_t *buf, int len)

{

    address_space_rw(as, addr, buf, len, false);

}


static int ide_write_dma_cb(IDEState *s,

                            target_phys_addr_t phys_addr,

                            int transfer_size1)

{

    int len, transfer_size, n;

    int64_t sector_num;

    transfer_size = transfer_size1;

    for(;;) {

        len = s->io_buffer_size - s->io_buffer_index;

        if (len == 0) {

            n = s->io_buffer_size >> 9;

            sector_num = ide_get_sector(s);

            bdrv_write(s->bs, sector_num, s->io_buffer,

                       s->io_buffer_size >> 9);

            sector_num += n;

            ide_set_sector(s, sector_num);

            s->nsector -= n;

            n = s->nsector;

            if (n == 0) {

                /* end of transfer */

                s->status = READY_STAT | SEEK_STAT;

                ide_set_irq(s);

                return 0;

            }

            if (n > MAX_MULT_SECTORS)

                n = MAX_MULT_SECTORS;

            s->io_buffer_index = 0;

            s->io_buffer_size = n * 512;

            len = s->io_buffer_size;

        }

        if (transfer_size <= 0)

            break;

        if (len > transfer_size)

            len = transfer_size;

        cpu_physical_memory_read(phys_addr,

                                 s->io_buffer + s->io_buffer_index, len);

        s->io_buffer_index += len;

        transfer_size -= len;

        phys_addr += len;

    }

    return transfer_size1 - transfer_size;

}


static void pty_chr_update_read_handler_locked(CharDriverState *chr)

{

    PtyCharDriver *s = chr->opaque;

    GPollFD pfd;

    pfd.fd = g_io_channel_unix_get_fd(s->fd);

    pfd.events = G_IO_OUT;

    pfd.revents = 0;

    g_poll(&pfd, 1, 0);

    if (pfd.revents & G_IO_HUP) {

        pty_chr_state(chr, 0);

    } else {

        pty_chr_state(chr, 1);

    }

}


QObject *json_parser_parse_err(QList *tokens, va_list *ap, Error **errp)

{

    JSONParserContext ctxt = {};

    QList *working;

    QObject *result;

    if (!tokens) {

        return NULL;

    }

    working = qlist_copy(tokens);

    result = parse_value(&ctxt, &working, ap);

    QDECREF(working);

    error_propagate(errp, ctxt.err);

    return result;

}


int loader_exec(const char * filename, char ** argv, char ** envp,

             struct target_pt_regs * regs, struct image_info *infop,

             struct linux_binprm *bprm)

{

    int retval;

    int i;

    bprm->p = TARGET_PAGE_SIZE*MAX_ARG_PAGES-sizeof(unsigned int);

    memset(bprm->page, 0, sizeof(bprm->page));

    retval = open(filename, O_RDONLY);

    if (retval < 0) {

        return -errno;

    }

    bprm->fd = retval;

    bprm->filename = (char *)filename;

    bprm->argc = count(argv);

    bprm->argv = argv;

    bprm->envc = count(envp);

    bprm->envp = envp;

    retval = prepare_binprm(bprm);

    if(retval>=0) {

        if (bprm->buf[0] == 0x7f

                && bprm->buf[1] == 'E'

                && bprm->buf[2] == 'L'

                && bprm->buf[3] == 'F') {

            retval = load_elf_binary(bprm, regs, infop);

#if defined(TARGET_HAS_BFLT)

        } else if (bprm->buf[0] == 'b'

                && bprm->buf[1] == 'F'

                && bprm->buf[2] == 'L'

                && bprm->buf[3] == 'T') {

            retval = load_flt_binary(bprm,regs,infop);

#endif

        } else {

            return -ENOEXEC;

        }

    }

    if(retval>=0) {

        /* success.  Initialize important registers */

        do_init_thread(regs, infop);

        return retval;

    }

    /* Something went wrong, return the inode and free the argument pages*/

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

        g_free(bprm->page[i]);

    }

    return(retval);

}


int qemu_lock_fd_test(int fd, int64_t start, int64_t len, bool exclusive)

{

    int ret;

    struct flock fl = {

        .l_whence = SEEK_SET,

        .l_start  = start,

        .l_len    = len,

        .l_type   = exclusive ? F_WRLCK : F_RDLCK,

    };

    ret = fcntl(fd, QEMU_GETLK, &fl);

    if (ret == -1) {

        return -errno;

    } else {

        return fl.l_type == F_UNLCK ? 0 : -EAGAIN;

    }

}


static int swri_resample(ResampleContext *c,

                         uint8_t *dst, const uint8_t *src, int *consumed,

                         int src_size, int dst_size, int update_ctx)

{

    int fn_idx = c->format - AV_SAMPLE_FMT_S16P;

    if (c->filter_length == 1 && c->phase_shift == 0) {

        int index= c->index;

        int frac= c->frac;

        int64_t index2= (1LL<<32)*c->frac/c->src_incr + (1LL<<32)*index;

        int64_t incr= (1LL<<32) * c->dst_incr / c->src_incr;

        int new_size = (src_size * (int64_t)c->src_incr - frac + c->dst_incr - 1) / c->dst_incr;

        dst_size= FFMIN(dst_size, new_size);

        c->dsp.resample_one[fn_idx](dst, src, dst_size, index2, incr);

        index += dst_size * c->dst_incr_div;

        index += (frac + dst_size * (int64_t)c->dst_incr_mod) / c->src_incr;

        av_assert2(index >= 0);

        *consumed= index;

        if (update_ctx) {

            c->frac   = (frac + dst_size * (int64_t)c->dst_incr_mod) % c->src_incr;

            c->index = 0;

        }

    } else {

        int64_t end_index = (1LL + src_size - c->filter_length) << c->phase_shift;

        int64_t delta_frac = (end_index - c->index) * c->src_incr - c->frac;

        int delta_n = (delta_frac + c->dst_incr - 1) / c->dst_incr;

        dst_size = FFMIN(dst_size, delta_n);

        if (dst_size > 0) {

            if (!c->linear) {

                *consumed = c->dsp.resample_common[fn_idx](c, dst, src, dst_size, update_ctx);

            } else {

                *consumed = c->dsp.resample_linear[fn_idx](c, dst, src, dst_size, update_ctx);

            }

        } else {

            *consumed = 0;

        }

    }

    return dst_size;

}


static int dash_init(AVFormatContext *s)

{

    DASHContext *c = s->priv_data;

    int ret = 0, i;

    char *ptr;

    char basename[1024];

    if (c->single_file_name)

        c->single_file = 1;

    if (c->single_file)

        c->use_template = 0;

    av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));

    ptr = strrchr(c->dirname, '/');

    if (ptr) {

        av_strlcpy(basename, &ptr[1], sizeof(basename));

        ptr[1] = '\0';

    } else {

        c->dirname[0] = '\0';

        av_strlcpy(basename, s->filename, sizeof(basename));

    }

    ptr = strrchr(basename, '.');

    if (ptr)

        *ptr = '\0';

    c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);

    if (!c->streams)

        return AVERROR(ENOMEM);

    if ((ret = parse_adaptation_sets(s)) < 0)

        return ret;

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

        OutputStream *os = &c->streams[i];

        AdaptationSet *as = &c->as[os->as_idx - 1];

        AVFormatContext *ctx;

        AVStream *st;

        AVDictionary *opts = NULL;

        char filename[1024];

        os->bit_rate = s->streams[i]->codecpar->bit_rate;

        if (os->bit_rate) {

            snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),

                     " bandwidth=\"%d\"", os->bit_rate);

        } else {

            int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?

                        AV_LOG_ERROR : AV_LOG_WARNING;

            av_log(s, level, "No bit rate set for stream %d\n", i);

            if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)

                return AVERROR(EINVAL);

        }

        // copy AdaptationSet language and role from stream metadata

        dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");

        dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");

        ctx = avformat_alloc_context();

        if (!ctx)

            return AVERROR(ENOMEM);

        // choose muxer based on codec: webm for VP8/9 and opus, mp4 otherwise

        // note: os->format_name is also used as part of the mimetype of the

        //       representation, e.g. video/<format_name>

        if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP8 ||

            s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP9 ||

            s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||

            s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VORBIS) {

            snprintf(os->format_name, sizeof(os->format_name), "webm");

        } else {

            snprintf(os->format_name, sizeof(os->format_name), "mp4");

        }

        ctx->oformat = av_guess_format(os->format_name, NULL, NULL);

        if (!ctx->oformat)

            return AVERROR_MUXER_NOT_FOUND;

        os->ctx = ctx;

        ctx->interrupt_callback = s->interrupt_callback;

        ctx->opaque             = s->opaque;

        ctx->io_close           = s->io_close;

        ctx->io_open            = s->io_open;

        if (!(st = avformat_new_stream(ctx, NULL)))

            return AVERROR(ENOMEM);

        avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);

        st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;

        st->time_base = s->streams[i]->time_base;

        st->avg_frame_rate = s->streams[i]->avg_frame_rate;

        ctx->avoid_negative_ts = s->avoid_negative_ts;

        ctx->flags = s->flags;

        if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)

            return ret;

        if (c->single_file) {

            if (c->single_file_name)

                ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);

            else

                snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);

        } else {

            ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);

        }

        snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);

        ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, NULL);

        if (ret < 0)

            return ret;

        os->init_start_pos = 0;

        if (!strcmp(os->format_name, "mp4")) {

            av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);

        } else {

            av_dict_set_int(&opts, "cluster_time_limit", c->min_seg_duration / 1000, 0);

            av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit

            av_dict_set_int(&opts, "dash", 1, 0);

            av_dict_set_int(&opts, "dash_track_number", i + 1, 0);

            av_dict_set_int(&opts, "live", 1, 0);

        }

        if ((ret = avformat_init_output(ctx, &opts)) < 0)

            return ret;

        os->ctx_inited = 1;

        avio_flush(ctx->pb);

        av_dict_free(&opts);

        av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);

        // Flush init segment

        // except for mp4, since delay_moov is set and the init segment

        // is then flushed after the first packets

        if (strcmp(os->format_name, "mp4")) {

            flush_init_segment(s, os);

        }

        s->streams[i]->time_base = st->time_base;

        // If the muxer wants to shift timestamps, request to have them shifted

        // already before being handed to this muxer, so we don't have mismatches

        // between the MPD and the actual segments.

        s->avoid_negative_ts = ctx->avoid_negative_ts;

        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {

            AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;

            if (avg_frame_rate.num > 0) {

                if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)

                    as->min_frame_rate = avg_frame_rate;

                if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)

                    as->max_frame_rate = avg_frame_rate;

            } else {

                as->ambiguous_frame_rate = 1;

            }

            c->has_video = 1;

        }

        set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));

        os->first_pts = AV_NOPTS_VALUE;

        os->max_pts = AV_NOPTS_VALUE;

        os->last_dts = AV_NOPTS_VALUE;

        os->segment_index = 1;

    }

    if (!c->has_video && c->min_seg_duration <= 0) {

        av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");

        return AVERROR(EINVAL);

    }

    return 0;

}


static int lag_decode_zero_run_line(LagarithContext *l, uint8_t *dst,

                                    const uint8_t *src, int width,

                                    int esc_count)

{

    int i = 0;

    int count;

    uint8_t zero_run = 0;

    const uint8_t *start = src;

    uint8_t mask1 = -(esc_count < 2);

    uint8_t mask2 = -(esc_count < 3);

    uint8_t *end = dst + (width - 2);

output_zeros:

    if (l->zeros_rem) {

        count = FFMIN(l->zeros_rem, width - i);

        memset(dst, 0, count);

        l->zeros_rem -= count;

        dst += count;

    }

    while (dst < end) {

        i = 0;

        while (!zero_run && dst + i < end) {

            i++;

            zero_run =

                !(src[i] | (src[i + 1] & mask1) | (src[i + 2] & mask2));

        }

        if (zero_run) {

            zero_run = 0;

            i += esc_count;

            memcpy(dst, src, i);

            dst += i;

            l->zeros_rem = lag_calc_zero_run(src[i]);

            src += i + 1;

            goto output_zeros;

        } else {

            memcpy(dst, src, i);

            src += i;

        }

    }

    return start - src;

}


void av_force_cpu_flags(int arg){

    if (   (arg & ( AV_CPU_FLAG_3DNOW    |

                    AV_CPU_FLAG_3DNOWEXT |

                    AV_CPU_FLAG_MMXEXT   |

                    AV_CPU_FLAG_SSE      |

                    AV_CPU_FLAG_SSE2     |

                    AV_CPU_FLAG_SSE2SLOW |

                    AV_CPU_FLAG_SSE3     |

                    AV_CPU_FLAG_SSE3SLOW |

                    AV_CPU_FLAG_SSSE3    |

                    AV_CPU_FLAG_SSE4     |

                    AV_CPU_FLAG_SSE42    |

                    AV_CPU_FLAG_AVX      |

                    AV_CPU_FLAG_AVXSLOW  |

                    AV_CPU_FLAG_XOP      |

                    AV_CPU_FLAG_FMA3     |

                    AV_CPU_FLAG_FMA4     |

                    AV_CPU_FLAG_AVX2     ))

        && !(arg & AV_CPU_FLAG_MMX)) {

        av_log(NULL, AV_LOG_WARNING, "MMX implied by specified flags\n");

        arg |= AV_CPU_FLAG_MMX;

    }

    cpu_flags = arg;

}


static void put_uint32(QEMUFile *f, void *pv, size_t size)

{

    uint32_t *v = pv;

    qemu_put_be32s(f, v);

}


static int net_bridge_run_helper(const char *helper, const char *bridge)

{

    sigset_t oldmask, mask;

    int pid, status;

    char *args[5];

    char **parg;

    int sv[2];

    sigemptyset(&mask);

    sigaddset(&mask, SIGCHLD);

    sigprocmask(SIG_BLOCK, &mask, &oldmask);

    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {

        return -1;

    }

    /* try to launch bridge helper */

    pid = fork();

    if (pid == 0) {

        int open_max = sysconf(_SC_OPEN_MAX), i;

        char fd_buf[6+10];

        char br_buf[6+IFNAMSIZ] = {0};

        char helper_cmd[PATH_MAX + sizeof(fd_buf) + sizeof(br_buf) + 15];

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

            if (i != sv[1]) {

                close(i);

            }

        }

        snprintf(fd_buf, sizeof(fd_buf), "%s%d", "--fd=", sv[1]);

        if (strrchr(helper, ' ') || strrchr(helper, '\t')) {

            /* assume helper is a command */

            if (strstr(helper, "--br=") == NULL) {

                snprintf(br_buf, sizeof(br_buf), "%s%s", "--br=", bridge);

            }

            snprintf(helper_cmd, sizeof(helper_cmd), "%s %s %s %s",

                     helper, "--use-vnet", fd_buf, br_buf);

            parg = args;

            *parg++ = (char *)"sh";

            *parg++ = (char *)"-c";

            *parg++ = helper_cmd;

            *parg++ = NULL;

            execv("/bin/sh", args);

        } else {

            /* assume helper is just the executable path name */

            snprintf(br_buf, sizeof(br_buf), "%s%s", "--br=", bridge);

            parg = args;

            *parg++ = (char *)helper;

            *parg++ = (char *)"--use-vnet";

            *parg++ = fd_buf;

            *parg++ = br_buf;

            *parg++ = NULL;

            execv(helper, args);

        }

        _exit(1);

    } else if (pid > 0) {

        int fd;

        close(sv[1]);

        do {

            fd = recv_fd(sv[0]);

        } while (fd == -1 && errno == EINTR);

        close(sv[0]);

        while (waitpid(pid, &status, 0) != pid) {

            /* loop */

        }

        sigprocmask(SIG_SETMASK, &oldmask, NULL);

        if (fd < 0) {

            fprintf(stderr, "failed to recv file descriptor\n");

            return -1;

        }

        if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {

            return fd;

        }

    }

    fprintf(stderr, "failed to launch bridge helper\n");

    return -1;

}


static BlockDriverAIOCB *curl_aio_readv(BlockDriverState *bs,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockDriverCompletionFunc *cb, void *opaque)

{

    BDRVCURLState *s = bs->opaque;

    CURLAIOCB *acb;

    size_t start = sector_num * SECTOR_SIZE;

    size_t end;

    CURLState *state;

    acb = qemu_aio_get(&curl_aio_pool, bs, cb, opaque);

    if (!acb)

        return NULL;

    acb->qiov = qiov;

    // In case we have the requested data already (e.g. read-ahead),

    // we can just call the callback and be done.

    switch (curl_find_buf(s, start, nb_sectors * SECTOR_SIZE, acb)) {

        case FIND_RET_OK:

            qemu_aio_release(acb);

            // fall through

        case FIND_RET_WAIT:

            return &acb->common;

        default:

            break;

    }

    // No cache found, so let's start a new request

    state = curl_init_state(s);

    if (!state)

        return NULL;

    acb->start = 0;

    acb->end = (nb_sectors * SECTOR_SIZE);

    state->buf_off = 0;

    if (state->orig_buf)

        qemu_free(state->orig_buf);

    state->buf_start = start;

    state->buf_len = acb->end + READ_AHEAD_SIZE;

    end = MIN(start + state->buf_len, s->len) - 1;

    state->orig_buf = qemu_malloc(state->buf_len);

    state->acb[0] = acb;

    snprintf(state->range, 127, "%lld-%lld", (long long)start, (long long)end);

    dprintf("CURL (AIO): Reading %d at %lld (%s)\n", (nb_sectors * SECTOR_SIZE), start, state->range);

    curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);

    curl_multi_add_handle(s->multi, state->curl);

    curl_multi_do(s);

    return &acb->common;

}


static int alloc_f(BlockDriverState *bs, int argc, char **argv)

{

    int64_t offset, sector_num;

    int nb_sectors, remaining;

    char s1[64];

    int num, sum_alloc;

    int ret;

    offset = cvtnum(argv[1]);

    if (offset < 0) {

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

    } else if (offset & 0x1ff) {

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

               offset);

    if (argc == 3) {

        nb_sectors = cvtnum(argv[2]);

        if (nb_sectors < 0) {

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

    } else {

        nb_sectors = 1;

    remaining = nb_sectors;

    sum_alloc = 0;

    sector_num = offset >> 9;

    while (remaining) {

        ret = bdrv_is_allocated(bs, sector_num, remaining, &num);

        sector_num += num;

        remaining -= num;

        if (ret) {

            sum_alloc += num;

        if (num == 0) {

            nb_sectors -= remaining;

            remaining = 0;

    cvtstr(offset, s1, sizeof(s1));

    printf("%d/%d sectors allocated at offset %s\n",

           sum_alloc, nb_sectors, s1);


static void test_qga_fstrim(gconstpointer fix)

{

    const TestFixture *fixture = fix;

    QDict *ret;

    QList *list;

    const QListEntry *entry;

    ret = qmp_fd(fixture->fd, "{'execute': 'guest-fstrim',"

                 " arguments: { minimum: 4194304 } }");

    g_assert_nonnull(ret);

    qmp_assert_no_error(ret);

    list = qdict_get_qlist(ret, "return");

    entry = qlist_first(list);

    g_assert(qdict_haskey(qobject_to_qdict(entry->value), "paths"));

    QDECREF(ret);

}


static RemoveResult remove_hpte(CPUPPCState *env, target_ulong ptex,

                                target_ulong avpn,

                                target_ulong flags,

                                target_ulong *vp, target_ulong *rp)

{

    hwaddr hpte;

    target_ulong v, r, rb;

    if ((ptex * HASH_PTE_SIZE_64) & ~env->htab_mask) {

        return REMOVE_PARM;

    }

    hpte = ptex * HASH_PTE_SIZE_64;

    v = ppc_hash64_load_hpte0(env, hpte);

    r = ppc_hash64_load_hpte1(env, hpte);

    if ((v & HPTE64_V_VALID) == 0 ||

        ((flags & H_AVPN) && (v & ~0x7fULL) != avpn) ||

        ((flags & H_ANDCOND) && (v & avpn) != 0)) {

        return REMOVE_NOT_FOUND;

    }

    *vp = v;

    *rp = r;

    ppc_hash64_store_hpte0(env, hpte, HPTE64_V_HPTE_DIRTY);

    rb = compute_tlbie_rb(v, r, ptex);

    ppc_tlb_invalidate_one(env, rb);

    return REMOVE_SUCCESS;

}