matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,

                     int64_t pos, uint64_t cluster_time,

                     int is_keyframe, int *ptrack, AVPacket **ppkt)

{

    int res = 0;

    int track;

    AVPacket *pkt;

    uint8_t *origdata = data;

    int16_t block_time;

    uint32_t *lace_size = NULL;

    int n, flags, laces = 0;

    uint64_t num;

    /* first byte(s): tracknum */

    if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {

        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");

        av_free(origdata);

        return res;

    }

    data += n;

    size -= n;

    /* fetch track from num */

    track = matroska_find_track_by_num(matroska, num);

    if (ptrack)  *ptrack = track;

    if (size <= 3 || track < 0 || track >= matroska->num_tracks) {

        av_log(matroska->ctx, AV_LOG_INFO,

               "Invalid stream %d or size %u\n", track, size);

        av_free(origdata);

        return res;

    }

    if(matroska->ctx->streams[ matroska->tracks[track]->stream_index ]->discard >= AVDISCARD_ALL){

        av_free(origdata);

        return res;

    }

    /* block_time (relative to cluster time) */

    block_time = (data[0] << 8) | data[1];

    data += 2;

    size -= 2;

    flags = *data;

    data += 1;

    size -= 1;

    if (is_keyframe == -1)

        is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;

    switch ((flags & 0x06) >> 1) {

        case 0x0: /* no lacing */

            laces = 1;

            lace_size = av_mallocz(sizeof(int));

            lace_size[0] = size;

            break;

        case 0x1: /* xiph lacing */

        case 0x2: /* fixed-size lacing */

        case 0x3: /* EBML lacing */

            if (size == 0) {

                res = -1;

                break;

            }

            laces = (*data) + 1;

            data += 1;

            size -= 1;

            lace_size = av_mallocz(laces * sizeof(int));

            switch ((flags & 0x06) >> 1) {

                case 0x1: /* xiph lacing */ {

                    uint8_t temp;

                    uint32_t total = 0;

                    for (n = 0; res == 0 && n < laces - 1; n++) {

                        while (1) {

                            if (size == 0) {

                                res = -1;

                                break;

                            }

                            temp = *data;

                            lace_size[n] += temp;

                            data += 1;

                            size -= 1;

                            if (temp != 0xff)

                                break;

                        }

                        total += lace_size[n];

                    }

                    lace_size[n] = size - total;

                    break;

                }

                case 0x2: /* fixed-size lacing */

                    for (n = 0; n < laces; n++)

                        lace_size[n] = size / laces;

                    break;

                case 0x3: /* EBML lacing */ {

                    uint32_t total;

                    n = matroska_ebmlnum_uint(data, size, &num);

                    if (n < 0) {

                        av_log(matroska->ctx, AV_LOG_INFO,

                               "EBML block data error\n");

                        break;

                    }

                    data += n;

                    size -= n;

                    total = lace_size[0] = num;

                    for (n = 1; res == 0 && n < laces - 1; n++) {

                        int64_t snum;

                        int r;

                        r = matroska_ebmlnum_sint (data, size, &snum);

                        if (r < 0) {

                            av_log(matroska->ctx, AV_LOG_INFO,

                                   "EBML block data error\n");

                            break;

                        }

                        data += r;

                        size -= r;

                        lace_size[n] = lace_size[n - 1] + snum;

                        total += lace_size[n];

                    }

                    lace_size[n] = size - total;

                    break;

                }

            }

            break;

    }

    if (res == 0) {

        int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;

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

            uint64_t timecode = AV_NOPTS_VALUE;

            int slice, slices = 1;

            if (real_v) {

                slices = *data++ + 1;

                lace_size[n]--;

            }

            if (cluster_time != (uint64_t)-1 && n == 0) {

                if (cluster_time + block_time >= 0)

                    timecode = (cluster_time + block_time) * matroska->time_scale;

            }

            /* FIXME: duration */

            for (slice=0; slice<slices; slice++) {

                int slice_size, slice_offset = 0;

                if (real_v)

                    slice_offset = rv_offset(data, slice, slices);

                if (slice+1 == slices)

                    slice_size = lace_size[n] - slice_offset;

                else

                    slice_size = rv_offset(data, slice+1, slices) - slice_offset;

                pkt = av_mallocz(sizeof(AVPacket));

                if (ppkt)  *ppkt = pkt;

                /* XXX: prevent data copy... */

                if (av_new_packet(pkt, slice_size) < 0) {

                    res = AVERROR_NOMEM;

                    n = laces-1;

                    break;

                }

                memcpy (pkt->data, data+slice_offset, slice_size);

                if (n == 0)

                    pkt->flags = is_keyframe;

                pkt->stream_index = matroska->tracks[track]->stream_index;

                pkt->pts = timecode;

                pkt->pos = pos;

                matroska_queue_packet(matroska, pkt);

            }

            data += lace_size[n];

        }

    }

    av_free(lace_size);

    av_free(origdata);

    return res;

}


Visitor *qmp_input_visitor_new(QObject *obj, bool strict)

{

    QmpInputVisitor *v;

    assert(obj);

    v = g_malloc0(sizeof(*v));

    v->visitor.type = VISITOR_INPUT;

    v->visitor.start_struct = qmp_input_start_struct;

    v->visitor.check_struct = qmp_input_check_struct;

    v->visitor.end_struct = qmp_input_pop;

    v->visitor.start_list = qmp_input_start_list;

    v->visitor.next_list = qmp_input_next_list;

    v->visitor.end_list = qmp_input_pop;

    v->visitor.start_alternate = qmp_input_start_alternate;

    v->visitor.type_int64 = qmp_input_type_int64;

    v->visitor.type_uint64 = qmp_input_type_uint64;

    v->visitor.type_bool = qmp_input_type_bool;

    v->visitor.type_str = qmp_input_type_str;

    v->visitor.type_number = qmp_input_type_number;

    v->visitor.type_any = qmp_input_type_any;

    v->visitor.type_null = qmp_input_type_null;

    v->visitor.optional = qmp_input_optional;

    v->visitor.free = qmp_input_free;

    v->strict = strict;

    v->root = obj;

    qobject_incref(obj);

    return &v->visitor;

}


static gboolean tcp_chr_accept(QIOChannel *channel,

                               GIOCondition cond,

                               void *opaque)

{

    CharDriverState *chr = opaque;

    TCPCharDriver *s = chr->opaque;

    QIOChannelSocket *sioc;

    sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),

                                     NULL);

    if (!sioc) {

        return TRUE;

    }

    if (s->do_telnetopt) {

        tcp_chr_telnet_init(QIO_CHANNEL(sioc));

    }

    tcp_chr_new_client(chr, sioc);

    object_unref(OBJECT(sioc));

    return TRUE;

}


void qemu_timer_notify_cb(void *opaque, QEMUClockType type)

{

    qemu_notify_event();

}


static void return_frame(AVFilterContext *ctx, int is_second)

{

    YADIFContext *yadif = ctx->priv;

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

    int tff;

    if (yadif->parity == -1) {

        tff = yadif->cur->video->interlaced ?

            yadif->cur->video->top_field_first : 1;

    } else {

        tff = yadif->parity^1;

    }

    if (is_second) {

        yadif->out = ff_get_video_buffer(link, AV_PERM_WRITE | AV_PERM_PRESERVE |

                                         AV_PERM_REUSE, link->w, link->h);

        avfilter_copy_buffer_ref_props(yadif->out, yadif->cur);

        yadif->out->video->interlaced = 0;

    }

    if (!yadif->csp)

        yadif->csp = &av_pix_fmt_descriptors[link->format];

    if (yadif->csp->comp[0].depth_minus1 / 8 == 1)

        yadif->filter_line = filter_line_c_16bit;

    filter(ctx, yadif->out, tff ^ !is_second, tff);

    if (is_second) {

        int64_t cur_pts  = yadif->cur->pts;

        int64_t next_pts = yadif->next->pts;

        if (next_pts != AV_NOPTS_VALUE && cur_pts != AV_NOPTS_VALUE) {

            yadif->out->pts = cur_pts + next_pts;

        } else {

            yadif->out->pts = AV_NOPTS_VALUE;

        }

        ff_start_frame(ctx->outputs[0], yadif->out);

    }

    ff_draw_slice(ctx->outputs[0], 0, link->h, 1);

    ff_end_frame(ctx->outputs[0]);

    yadif->frame_pending = (yadif->mode&1) && !is_second;

}


static void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb,

                                     const float *in, int size, int scale_idx,

                                     int cb, const float lambda)

{

    const float IQ = ff_aac_pow2sf_tab[200 + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];

    const float  Q = ff_aac_pow2sf_tab[200 - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];

    const float CLIPPED_ESCAPE = 165140.0f*IQ;

    const int dim = (cb < FIRST_PAIR_BT) ? 4 : 2;

    int i, j, k;

#ifndef USE_REALLY_FULL_SEARCH

    const float  Q34 = sqrtf(Q * sqrtf(Q));

    const int range  = aac_cb_range[cb];

    const int maxval = aac_cb_maxval[cb];

    int offs[4];

    float *scaled = s->scoefs;

#endif /* USE_REALLY_FULL_SEARCH */

//START_TIMER

    if (!cb)

        return;

#ifndef USE_REALLY_FULL_SEARCH

    offs[0] = 1;

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

        offs[i] = offs[i-1]*range;

    abs_pow34_v(scaled, in, size);

    quantize_bands(s->qcoefs, in, scaled, size, Q34, !IS_CODEBOOK_UNSIGNED(cb), maxval);

#endif /* USE_REALLY_FULL_SEARCH */

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

        float mincost;

        int minidx  = 0;

        int minbits = 0;

        const float *vec;

#ifndef USE_REALLY_FULL_SEARCH

        int (*quants)[2] = &s->qcoefs[i];

        mincost = 0.0f;

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

            mincost += in[i+j]*in[i+j]*lambda;

        minidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;

        minbits = ff_aac_spectral_bits[cb-1][minidx];

        mincost += minbits;

        for (j = 0; j < (1<<dim); j++) {

            float rd = 0.0f;

            int curbits;

            int curidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;

            int same   = 0;

            for (k = 0; k < dim; k++) {

                if ((j & (1 << k)) && quants[k][0] == quants[k][1]) {

                    same = 1;

                    break;

                }

            }

            if (same)

                continue;

            for (k = 0; k < dim; k++)

                curidx += quants[k][!!(j & (1 << k))] * offs[dim - 1 - k];

            curbits =  ff_aac_spectral_bits[cb-1][curidx];

            vec     = &ff_aac_codebook_vectors[cb-1][curidx*dim];

#else

        vec = ff_aac_codebook_vectors[cb-1];

        mincost = INFINITY;

        for (j = 0; j < ff_aac_spectral_sizes[cb-1]; j++, vec += dim) {

            float rd = 0.0f;

            int curbits = ff_aac_spectral_bits[cb-1][j];

            int curidx  = j;

#endif /* USE_REALLY_FULL_SEARCH */

            if (IS_CODEBOOK_UNSIGNED(cb)) {

                for (k = 0; k < dim; k++) {

                    float t = fabsf(in[i+k]);

                    float di;

                    //do not code with escape sequence small values

                    if (vec[k] == 64.0f && t < 39.0f*IQ) {

                        rd = INFINITY;

                        break;

                    }

                    if (vec[k] == 64.0f) { //FIXME: slow

                        if (t >= CLIPPED_ESCAPE) {

                            di = t - CLIPPED_ESCAPE;

                            curbits += 21;

                        } else {

                            int c = av_clip(quant(t, Q), 0, 8191);

                            di = t - c*cbrt(c)*IQ;

                            curbits += av_log2(c)*2 - 4 + 1;

                        }

                    } else {

                        di = t - vec[k]*IQ;

                    }

                    if (vec[k] != 0.0f)

                        curbits++;

                    rd += di*di*lambda;

                }

            } else {

                for (k = 0; k < dim; k++) {

                    float di = in[i+k] - vec[k]*IQ;

                    rd += di*di*lambda;

                }

            }

            rd += curbits;

            if (rd < mincost) {

                mincost = rd;

                minidx  = curidx;

                minbits = curbits;

            }

        }

        put_bits(pb, ff_aac_spectral_bits[cb-1][minidx], ff_aac_spectral_codes[cb-1][minidx]);

        if (IS_CODEBOOK_UNSIGNED(cb))

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

                if (ff_aac_codebook_vectors[cb-1][minidx*dim+j] != 0.0f)

                    put_bits(pb, 1, in[i+j] < 0.0f);

        if (cb == ESC_BT) {

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

                if (ff_aac_codebook_vectors[cb-1][minidx*2+j] == 64.0f) {

                    int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191);

                    int len = av_log2(coef);

                    put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);

                    put_bits(pb, len, coef & ((1 << len) - 1));

                }

            }

        }

    }

//STOP_TIMER("quantize_and_encode")

}


static int seg_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)

{

    SegmentContext *seg = s->priv_data;

    AVFormatContext *oc = seg->avf;

    if (oc->oformat->check_bitstream) {

        int ret = oc->oformat->check_bitstream(oc, pkt);

        if (ret == 1) {

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

            AVStream *ost = oc->streams[pkt->stream_index];

            st->internal->bsfcs = ost->internal->bsfcs;

            st->internal->nb_bsfcs = ost->internal->nb_bsfcs;

            ost->internal->bsfcs = NULL;

            ost->internal->nb_bsfcs = 0;

        }

        return ret;

    }

    return 1;

}


static int gen_check_bw(URLContext *s, RTMPContext *rt)

{

    RTMPPacket pkt;

    uint8_t *p;

    int ret;

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,

                                     0, 21)) < 0)

        return ret;

    p = pkt.data;

    ff_amf_write_string(&p, "_checkbw");

    ff_amf_write_number(&p, ++rt->nb_invokes);

    ff_amf_write_null(&p);

    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size,

                               rt->prev_pkt[1]);

    ff_rtmp_packet_destroy(&pkt);

    return ret;

}


static void scsi_generic_purge_requests(SCSIGenericState *s)

{

    SCSIGenericReq *r;

    while (!QTAILQ_EMPTY(&s->qdev.requests)) {

        r = DO_UPCAST(SCSIGenericReq, req, QTAILQ_FIRST(&s->qdev.requests));

        if (r->req.aiocb) {

            bdrv_aio_cancel(r->req.aiocb);

        }

        scsi_remove_request(r);

    }

}


static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)

{

    AVFrame *decoded_frame, *f;

    int i, ret = 0, err = 0;

    if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))

        return AVERROR(ENOMEM);

    if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))

        return AVERROR(ENOMEM);

    decoded_frame = ist->decoded_frame;

    ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt);

    if (!*got_output || ret < 0)

        return ret;

    ist->frames_decoded++;

    if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {

        err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);

        if (err < 0)

            goto fail;

    }

    ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;

    decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pts,

                                           decoded_frame->pkt_dts);

    if (ist->framerate.num)

        decoded_frame->pts = ist->cfr_next_pts++;

    if (ist->st->sample_aspect_ratio.num)

        decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;

    for (i = 0; i < ist->nb_filters; i++) {

        if (i < ist->nb_filters - 1) {

            f = ist->filter_frame;

            err = av_frame_ref(f, decoded_frame);

            if (err < 0)

                break;

        } else

            f = decoded_frame;

        err = ifilter_send_frame(ist->filters[i], f);

        if (err < 0)

            break;

    }

fail:

    av_frame_unref(ist->filter_frame);

    av_frame_unref(decoded_frame);

    return err < 0 ? err : ret;

}


int boot_sector_init(const char *fname)

{

    FILE *f = fopen(fname, "w");

    size_t len = sizeof boot_sector;

    if (!f) {

        fprintf(stderr, "Couldn't open \"%s\": %s", fname, strerror(errno));

        return 1;

    }

    /* For Open Firmware based system, we can use a Forth script instead */

    if (strcmp(qtest_get_arch(), "ppc64") == 0) {

        len = sprintf((char *)boot_sector, "\\ Bootscript\n%x %x c! %x %x c!\n",

                LOW(SIGNATURE), BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET,

                HIGH(SIGNATURE), BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET + 1);

    }

    fwrite(boot_sector, 1, len, f);

    fclose(f);

    return 0;

}


static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

    AVIContext *avi = s->priv_data;

    AVStream *st;

    int i, index;

    int64_t pos, pos_min;

    AVIStream *ast;

    if (!avi->index_loaded) {

        /* we only load the index on demand */

        avi_load_index(s);

        avi->index_loaded = 1;

    }

    assert(stream_index>= 0);

    st = s->streams[stream_index];

    ast= st->priv_data;

    index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);

    if(index<0)

        return -1;

    /* find the position */

    pos = st->index_entries[index].pos;

    timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);

//    av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);

    if (CONFIG_DV_DEMUXER && avi->dv_demux) {

        /* One and only one real stream for DV in AVI, and it has video  */

        /* offsets. Calling with other stream indexes should have failed */

        /* the av_index_search_timestamp call above.                     */

        assert(stream_index == 0);

        /* Feed the DV video stream version of the timestamp to the */

        /* DV demux so it can synthesize correct timestamps.        */

        dv_offset_reset(avi->dv_demux, timestamp);

        avio_seek(s->pb, pos, SEEK_SET);

        avi->stream_index= -1;

        return 0;

    }

    pos_min= pos;

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

        AVStream *st2 = s->streams[i];

        AVIStream *ast2 = st2->priv_data;

        ast2->packet_size=

        ast2->remaining= 0;

        if (ast2->sub_ctx) {

            seek_subtitle(st, st2, timestamp);

            continue;

        }

        if (st2->nb_index_entries <= 0)

            continue;

//        assert(st2->codec->block_align);

        assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);

        index = av_index_search_timestamp(

                st2,

                av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),

                flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));

        if(index<0)

            index=0;

        ast2->seek_pos= st2->index_entries[index].pos;

        pos_min= FFMIN(pos_min,ast2->seek_pos);

    }

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

        AVStream *st2 = s->streams[i];

        AVIStream *ast2 = st2->priv_data;

        if (ast2->sub_ctx || st2->nb_index_entries <= 0)

            continue;

        index = av_index_search_timestamp(

                st2,

                av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),

                flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));

        if(index<0)

            index=0;

        while(!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)

            index--;

        ast2->frame_offset = st2->index_entries[index].timestamp;

    }

    /* do the seek */

    avio_seek(s->pb, pos_min, SEEK_SET);

    avi->stream_index= -1;

    avi->dts_max= INT_MIN;

    return 0;

}


static void timer_enable(struct xlx_timer *xt)

{

    uint64_t count;

    D(printf("%s timer=%d down=%d\n", __func__,

              xt->nr, xt->regs[R_TCSR] & TCSR_UDT));

    ptimer_stop(xt->ptimer);

    if (xt->regs[R_TCSR] & TCSR_UDT)

        count = xt->regs[R_TLR];

    else

        count = ~0 - xt->regs[R_TLR];

    ptimer_set_count(xt->ptimer, count);

    ptimer_run(xt->ptimer, 1);

}


static int colo_packet_compare_tcp(Packet *spkt, Packet *ppkt)

{

    struct tcphdr *ptcp, *stcp;

    int res;

    trace_colo_compare_main("compare tcp");

    ptcp = (struct tcphdr *)ppkt->transport_header;

    stcp = (struct tcphdr *)spkt->transport_header;

    /*

     * The 'identification' field in the IP header is *very* random

     * it almost never matches.  Fudge this by ignoring differences in

     * unfragmented packets; they'll normally sort themselves out if different

     * anyway, and it should recover at the TCP level.

     * An alternative would be to get both the primary and secondary to rewrite

     * somehow; but that would need some sync traffic to sync the state

     */

    if (ntohs(ppkt->ip->ip_off) & IP_DF) {

        spkt->ip->ip_id = ppkt->ip->ip_id;

        /* and the sum will be different if the IDs were different */

        spkt->ip->ip_sum = ppkt->ip->ip_sum;

    }

    /*

     * Check tcp header length for tcp option field.

     * th_off > 5 means this tcp packet have options field.

     * The tcp options maybe always different.

     * for example:

     * From RFC 7323.

     * TCP Timestamps option (TSopt):

     * Kind: 8

     *

     * Length: 10 bytes

     *

     *    +-------+-------+---------------------+---------------------+

     *    |Kind=8 |  10   |   TS Value (TSval)  |TS Echo Reply (TSecr)|

     *    +-------+-------+---------------------+---------------------+

     *       1       1              4                     4

     *

     * In this case the primary guest's timestamp always different with

     * the secondary guest's timestamp. COLO just focus on payload,

     * so we just need skip this field.

     */

    if (ptcp->th_off > 5) {

        ptrdiff_t tcp_offset;

        tcp_offset = ppkt->transport_header - (uint8_t *)ppkt->data

                     + (ptcp->th_off * 4) - ppkt->vnet_hdr_len;

        res = colo_packet_compare_common(ppkt, spkt, tcp_offset);

    } else if (ptcp->th_sum == stcp->th_sum) {

        res = colo_packet_compare_common(ppkt, spkt, ETH_HLEN);

    } else {

        res = -1;

    }

    if (res != 0 && trace_event_get_state(TRACE_COLO_COMPARE_MISCOMPARE)) {

        char pri_ip_src[20], pri_ip_dst[20], sec_ip_src[20], sec_ip_dst[20];

        strcpy(pri_ip_src, inet_ntoa(ppkt->ip->ip_src));

        strcpy(pri_ip_dst, inet_ntoa(ppkt->ip->ip_dst));

        strcpy(sec_ip_src, inet_ntoa(spkt->ip->ip_src));

        strcpy(sec_ip_dst, inet_ntoa(spkt->ip->ip_dst));

        trace_colo_compare_ip_info(ppkt->size, pri_ip_src,

                                   pri_ip_dst, spkt->size,

                                   sec_ip_src, sec_ip_dst);

        trace_colo_compare_tcp_info("pri tcp packet",

                                    ntohl(ptcp->th_seq),

                                    ntohl(ptcp->th_ack),

                                    res, ptcp->th_flags,

                                    ppkt->size);

        trace_colo_compare_tcp_info("sec tcp packet",

                                    ntohl(stcp->th_seq),

                                    ntohl(stcp->th_ack),

                                    res, stcp->th_flags,

                                    spkt->size);

        qemu_hexdump((char *)ppkt->data, stderr,

                     "colo-compare ppkt", ppkt->size);

        qemu_hexdump((char *)spkt->data, stderr,

                     "colo-compare spkt", spkt->size);

    }

    return res;

}


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

{

    AVIOContext *pb = s->pb;

    uint32_t frame_size;

    int ret, first = 1;

    if (avio_feof(pb))

        return AVERROR_EOF;

    if (av_get_packet(pb, pkt, 12) != 12)

        return AVERROR(EIO);

    while (!avio_feof(pb)) {

        if (!first) {

            ret = av_append_packet(pb, pkt, 12);

            if (ret < 0) {

                return ret;

            }

        } else

            first = 0;

        frame_size = AV_RL32(pkt->data + pkt->size - 8);

        if (frame_size > INT_MAX - 4) {

            av_log(s, AV_LOG_ERROR, "Too large chunk size: %"PRIu32"\n", frame_size);

            return AVERROR(EIO);

        }

        if (AV_RL32(pkt->data + pkt->size - 12) == MKTAG('E', 'O', 'F', 'R')) {

            if (frame_size) {

                av_log(s, AV_LOG_WARNING,

                       "skipping %"PRIu32" bytes of end-of-frame marker chunk\n",

                       frame_size);

                avio_skip(pb, frame_size);

            }

            return 0;

        }

        ret = av_append_packet(pb, pkt, frame_size);

        if (ret < 0) {

            return ret;

        }

    }

    return 0;

}


static int nut_read_close(AVFormatContext *s)

{

    NUTContext *nut = s->priv_data;

    av_freep(&nut->time_base);

    av_freep(&nut->stream);

    return 0;

}


static int64_t pva_read_timestamp(struct AVFormatContext *s, int stream_index,

                                          int64_t *pos, int64_t pos_limit) {

    ByteIOContext *pb = s->pb;

    PVAContext *pvactx = s->priv_data;

    int length, streamid;

    int64_t res;

    pos_limit = FFMIN(*pos+PVA_MAX_PAYLOAD_LENGTH*8, (uint64_t)*pos+pos_limit);

    while (*pos < pos_limit) {

        res = AV_NOPTS_VALUE;

        url_fseek(pb, *pos, SEEK_SET);

        pvactx->continue_pes = 0;

        if (read_part_of_packet(s, &res, &length, &streamid, 0)) {

            (*pos)++;

            continue;

        }

        if (streamid - 1 != stream_index || res == AV_NOPTS_VALUE) {

            *pos = url_ftell(pb) + length;

            continue;

        }

        break;

    }

    pvactx->continue_pes = 0;

    return res;

}


static ssize_t handle_aiocb_ioctl(struct qemu_paiocb *aiocb)

{

    int ret;

    ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);

    if (ret == -1)

        return -errno;

    /*

     * This looks weird, but the aio code only consideres a request

     * successful if it has written the number full number of bytes.

     *

     * Now we overload aio_nbytes as aio_ioctl_cmd for the ioctl command,

     * so in fact we return the ioctl command here to make posix_aio_read()

     * happy..

     */

    return aiocb->aio_nbytes;

}


static int filter_slice(AVFilterContext *ctx, void *arg, int job, int nb_jobs)

{

    FrameRateContext *s = ctx->priv;

    ThreadData *td = arg;

    uint16_t src1_factor = td->src1_factor;

    uint16_t src2_factor = td->src2_factor;

    int plane;

    for (plane = 0; plane < 4 && td->copy_src1->data[plane] && td->copy_src2->data[plane]; plane++) {

        int cpy_line_width = s->line_size[plane];

        uint8_t *cpy_src1_data = td->copy_src1->data[plane];

        int cpy_src1_line_size = td->copy_src1->linesize[plane];

        uint8_t *cpy_src2_data = td->copy_src2->data[plane];

        int cpy_src2_line_size = td->copy_src2->linesize[plane];

        int cpy_src_h = (plane > 0 && plane < 3) ? (td->copy_src1->height >> s->vsub) : (td->copy_src1->height);

        uint8_t *cpy_dst_data = s->work->data[plane];

        int cpy_dst_line_size = s->work->linesize[plane];

        const int start = (cpy_src_h *  job   ) / nb_jobs;

        const int end   = (cpy_src_h * (job+1)) / nb_jobs;

        cpy_src1_data += start * cpy_src1_line_size;

        cpy_src2_data += start * cpy_src2_line_size;

        cpy_dst_data += start * cpy_dst_line_size;

        s->blend(cpy_src1_data, cpy_src1_line_size,

                 cpy_src2_data, cpy_src2_line_size,

                 cpy_dst_data,  cpy_dst_line_size,

                 cpy_line_width, end - start,

                 src1_factor, src2_factor, s->max / 2, s->bitdepth);

    }

    return 0;

}


static void update_initial_timestamps(AVFormatContext *s, int stream_index,

                                      int64_t dts, int64_t pts, AVPacket *pkt)

{

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

    AVPacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;

    int64_t pts_buffer[MAX_REORDER_DELAY+1];

    int64_t shift;

    int i, delay;

    if (st->first_dts != AV_NOPTS_VALUE ||

        dts           == AV_NOPTS_VALUE ||

        st->cur_dts   == AV_NOPTS_VALUE ||

        is_relative(dts))

        return;

    delay         = st->codec->has_b_frames;

    st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE);

    st->cur_dts   = dts;

    shift         = st->first_dts - RELATIVE_TS_BASE;

    for (i = 0; i<MAX_REORDER_DELAY+1; i++)

        pts_buffer[i] = AV_NOPTS_VALUE;

    if (is_relative(pts))

        pts += shift;

    for (; pktl; pktl = get_next_pkt(s, st, pktl)) {

        if (pktl->pkt.stream_index != stream_index)

            continue;

        if (is_relative(pktl->pkt.pts))

            pktl->pkt.pts += shift;

        if (is_relative(pktl->pkt.dts))

            pktl->pkt.dts += shift;

        if (st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)

            st->start_time = pktl->pkt.pts;

        if (pktl->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) {

            pts_buffer[0] = pktl->pkt.pts;

            for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++)

                FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);

            pktl->pkt.dts = select_from_pts_buffer(st, pts_buffer, pktl->pkt.dts);

        }

    }

    if (st->start_time == AV_NOPTS_VALUE)

        st->start_time = pts;

}


static void ide_test_quit(void)

{

    qtest_end();

}


static void mcf5208evb_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    M68kCPU *cpu;

    CPUM68KState *env;

    int kernel_size;

    uint64_t elf_entry;

    hwaddr entry;

    qemu_irq *pic;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *sram = g_new(MemoryRegion, 1);

    if (!cpu_model) {

        cpu_model = "m5208";

    }

    cpu = M68K_CPU(cpu_generic_init(TYPE_M68K_CPU, cpu_model));

    if (!cpu) {

        fprintf(stderr, "Unable to find m68k CPU definition\n");

        exit(1);

    }

    env = &cpu->env;

    /* Initialize CPU registers.  */

    env->vbr = 0;

    /* TODO: Configure BARs.  */

    /* DRAM at 0x40000000 */

    memory_region_allocate_system_memory(ram, NULL, "mcf5208.ram", ram_size);

    memory_region_add_subregion(address_space_mem, 0x40000000, ram);

    /* Internal SRAM.  */

    memory_region_init_ram(sram, NULL, "mcf5208.sram", 16384, &error_fatal);

    memory_region_add_subregion(address_space_mem, 0x80000000, sram);

    /* Internal peripherals.  */

    pic = mcf_intc_init(address_space_mem, 0xfc048000, cpu);

    mcf_uart_mm_init(0xfc060000, pic[26], serial_hds[0]);

    mcf_uart_mm_init(0xfc064000, pic[27], serial_hds[1]);

    mcf_uart_mm_init(0xfc068000, pic[28], serial_hds[2]);

    mcf5208_sys_init(address_space_mem, pic);

    if (nb_nics > 1) {

        fprintf(stderr, "Too many NICs\n");

        exit(1);

    }

    if (nd_table[0].used) {

        mcf_fec_init(address_space_mem, &nd_table[0],

                     0xfc030000, pic + 36);

    }

    /*  0xfc000000 SCM.  */

    /*  0xfc004000 XBS.  */

    /*  0xfc008000 FlexBus CS.  */

    /* 0xfc030000 FEC.  */

    /*  0xfc040000 SCM + Power management.  */

    /*  0xfc044000 eDMA.  */

    /* 0xfc048000 INTC.  */

    /*  0xfc058000 I2C.  */

    /*  0xfc05c000 QSPI.  */

    /* 0xfc060000 UART0.  */

    /* 0xfc064000 UART0.  */

    /* 0xfc068000 UART0.  */

    /*  0xfc070000 DMA timers.  */

    /* 0xfc080000 PIT0.  */

    /* 0xfc084000 PIT1.  */

    /*  0xfc088000 EPORT.  */

    /*  0xfc08c000 Watchdog.  */

    /*  0xfc090000 clock module.  */

    /*  0xfc0a0000 CCM + reset.  */

    /*  0xfc0a4000 GPIO.  */

    /* 0xfc0a8000 SDRAM controller.  */

    /* Load kernel.  */

    if (!kernel_filename) {

        if (qtest_enabled()) {

            return;

        }

        fprintf(stderr, "Kernel image must be specified\n");

        exit(1);

    }

    kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,

                           NULL, NULL, 1, EM_68K, 0, 0);

    entry = elf_entry;

    if (kernel_size < 0) {

        kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL,

                                  NULL, NULL);

    }

    if (kernel_size < 0) {

        kernel_size = load_image_targphys(kernel_filename, 0x40000000,

                                          ram_size);

        entry = 0x40000000;

    }

    if (kernel_size < 0) {

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

        exit(1);

    }

    env->pc = entry;

}


static void vga_get_text_resolution(VGACommonState *s, int *pwidth, int *pheight,

                                    int *pcwidth, int *pcheight)

{

    int width, cwidth, height, cheight;

    /* total width & height */

    cheight = (s->cr[VGA_CRTC_MAX_SCAN] & 0x1f) + 1;

    cwidth = 8;

    if (!(s->sr[VGA_SEQ_CLOCK_MODE] & VGA_SR01_CHAR_CLK_8DOTS)) {

        cwidth = 9;

    }

    if (s->sr[VGA_SEQ_CLOCK_MODE] & 0x08) {

        cwidth = 16; /* NOTE: no 18 pixel wide */

    }

    width = (s->cr[VGA_CRTC_H_DISP] + 1);

    if (s->cr[VGA_CRTC_V_TOTAL] == 100) {

        /* ugly hack for CGA 160x100x16 - explain me the logic */

        height = 100;

    } else {

        height = s->cr[VGA_CRTC_V_DISP_END] |

            ((s->cr[VGA_CRTC_OVERFLOW] & 0x02) << 7) |

            ((s->cr[VGA_CRTC_OVERFLOW] & 0x40) << 3);

        height = (height + 1) / cheight;

    }

    *pwidth = width;

    *pheight = height;

    *pcwidth = cwidth;

    *pcheight = cheight;

}


int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,

                     AVFormatContext *src)

{

    AVPacket local_pkt;

    local_pkt = *pkt;

    local_pkt.stream_index = dst_stream;

    if (pkt->pts != AV_NOPTS_VALUE)

        local_pkt.pts = av_rescale_q(pkt->pts,

                                     src->streams[pkt->stream_index]->time_base,

                                     dst->streams[dst_stream]->time_base);

    if (pkt->dts != AV_NOPTS_VALUE)

        local_pkt.dts = av_rescale_q(pkt->dts,

                                     src->streams[pkt->stream_index]->time_base,

                                     dst->streams[dst_stream]->time_base);

    if (pkt->duration)

        local_pkt.duration = av_rescale_q(pkt->duration,

                                          src->streams[pkt->stream_index]->time_base,

                                          dst->streams[dst_stream]->time_base);

    return av_write_frame(dst, &local_pkt);

}


static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id, int buf_size)

{

    int i;

    int skip = 0;

    int len, toks, pos;

    TM2Codes codes;

    GetByteContext gb;

    if (buf_size < 4) {

        av_log(ctx->avctx, AV_LOG_ERROR, "not enough space for len left\n");

        return AVERROR_INVALIDDATA;

    }

    /* get stream length in dwords */

    bytestream2_init(&gb, buf, buf_size);

    len  = bytestream2_get_be32(&gb);

    skip = len * 4 + 4;

    if(len == 0)

        return 4;

    if (len >= INT_MAX/4-1 || len < 0 || skip > buf_size) {

        av_log(ctx->avctx, AV_LOG_ERROR, "invalid stream size\n");

        return AVERROR_INVALIDDATA;

    }

    toks = bytestream2_get_be32(&gb);

    if(toks & 1) {

        len = bytestream2_get_be32(&gb);

        if(len == TM2_ESCAPE) {

            len = bytestream2_get_be32(&gb);

        }

        if(len > 0) {

            pos = bytestream2_tell(&gb);

            if (skip <= pos)

                return AVERROR_INVALIDDATA;

            init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);

            if(tm2_read_deltas(ctx, stream_id) == -1)

                return AVERROR_INVALIDDATA;

            bytestream2_skip(&gb, ((get_bits_count(&ctx->gb) + 31) >> 5) << 2);

        }

    }

    /* skip unused fields */

    len = bytestream2_get_be32(&gb);

    if(len == TM2_ESCAPE) { /* some unknown length - could be escaped too */

        bytestream2_skip(&gb, 8); /* unused by decoder */

    } else {

        bytestream2_skip(&gb, 4); /* unused by decoder */

    }

    pos = bytestream2_tell(&gb);

    if (skip <= pos)

        return AVERROR_INVALIDDATA;

    init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);

    if(tm2_build_huff_table(ctx, &codes) == -1)

        return AVERROR_INVALIDDATA;

    bytestream2_skip(&gb, ((get_bits_count(&ctx->gb) + 31) >> 5) << 2);

    toks >>= 1;

    /* check if we have sane number of tokens */

    if((toks < 0) || (toks > 0xFFFFFF)){

        av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of tokens: %i\n", toks);

        tm2_free_codes(&codes);

        return AVERROR_INVALIDDATA;

    }

    ctx->tokens[stream_id] = av_realloc(ctx->tokens[stream_id], toks * sizeof(int));

    ctx->tok_lens[stream_id] = toks;

    len = bytestream2_get_be32(&gb);

    if(len > 0) {

        pos = bytestream2_tell(&gb);

        if (skip <= pos)

            return AVERROR_INVALIDDATA;

        init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);

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

            if (get_bits_left(&ctx->gb) <= 0) {

                av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of tokens: %i\n", toks);

                return AVERROR_INVALIDDATA;

            }

            ctx->tokens[stream_id][i] = tm2_get_token(&ctx->gb, &codes);

            if (stream_id <= TM2_MOT && ctx->tokens[stream_id][i] >= TM2_DELTAS) {

                av_log(ctx->avctx, AV_LOG_ERROR, "Invalid delta token index %d for type %d, n=%d\n",

                       ctx->tokens[stream_id][i], stream_id, i);

                return AVERROR_INVALIDDATA;

            }

        }

    } else {

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

            ctx->tokens[stream_id][i] = codes.recode[0];

            if (stream_id <= TM2_MOT && ctx->tokens[stream_id][i] >= TM2_DELTAS) {

                av_log(ctx->avctx, AV_LOG_ERROR, "Invalid delta token index %d for type %d, n=%d\n",

                       ctx->tokens[stream_id][i], stream_id, i);

                return AVERROR_INVALIDDATA;

            }

        }

    }

    tm2_free_codes(&codes);

    return skip;

}


static int parse_section_header(GetByteContext *gbc, int *section_size,

                                enum HapSectionType *section_type)

{

    if (bytestream2_get_bytes_left(gbc) < 4)

        return AVERROR_INVALIDDATA;

    *section_size = bytestream2_get_le24(gbc);

    *section_type = bytestream2_get_byte(gbc);

    if (*section_size == 0) {

        if (bytestream2_get_bytes_left(gbc) < 4)

            return AVERROR_INVALIDDATA;

        *section_size = bytestream2_get_le32(gbc);

    }

    if (*section_size > bytestream2_get_bytes_left(gbc))

        return AVERROR_INVALIDDATA;

    else

        return 0;

}


static int pps_range_extensions(GetBitContext *gb, AVCodecContext *avctx,

                                HEVCPPS *pps, HEVCSPS *sps) {

    int i;

    if (pps->transform_skip_enabled_flag) {

        pps->log2_max_transform_skip_block_size = get_ue_golomb_long(gb) + 2;

    }

    pps->cross_component_prediction_enabled_flag = get_bits1(gb);

    pps->chroma_qp_offset_list_enabled_flag = get_bits1(gb);

    if (pps->chroma_qp_offset_list_enabled_flag) {

        pps->diff_cu_chroma_qp_offset_depth = get_ue_golomb_long(gb);

        pps->chroma_qp_offset_list_len_minus1 = get_ue_golomb_long(gb);

        if (pps->chroma_qp_offset_list_len_minus1 && pps->chroma_qp_offset_list_len_minus1 >= 5) {

            av_log(avctx, AV_LOG_ERROR,

                   "chroma_qp_offset_list_len_minus1 shall be in the range [0, 5].\n");

            return AVERROR_INVALIDDATA;

        }

        for (i = 0; i <= pps->chroma_qp_offset_list_len_minus1; i++) {

            pps->cb_qp_offset_list[i] = get_se_golomb_long(gb);

            if (pps->cb_qp_offset_list[i]) {

                av_log(avctx, AV_LOG_WARNING,

                       "cb_qp_offset_list not tested yet.\n");

            }

            pps->cr_qp_offset_list[i] = get_se_golomb_long(gb);

            if (pps->cr_qp_offset_list[i]) {

                av_log(avctx, AV_LOG_WARNING,

                       "cb_qp_offset_list not tested yet.\n");

            }

        }

    }

    pps->log2_sao_offset_scale_luma = get_ue_golomb_long(gb);

    pps->log2_sao_offset_scale_chroma = get_ue_golomb_long(gb);

    return(0);

}


av_cold int ff_wma_init(AVCodecContext *avctx, int flags2)

{

    WMACodecContext *s = avctx->priv_data;

    int i;

    float bps1, high_freq;

    volatile float bps;

    int sample_rate1;

    int coef_vlc_table;

    if (avctx->sample_rate <= 0 || avctx->sample_rate > 50000 ||

        avctx->channels    <= 0 || avctx->channels    > 2     ||

        avctx->bit_rate    <= 0)

        return -1;

    ff_fmt_convert_init(&s->fmt_conv, avctx);

    avpriv_float_dsp_init(&s->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);

    if (avctx->codec->id == AV_CODEC_ID_WMAV1)

        s->version = 1;

    else

        s->version = 2;

    /* compute MDCT block size */

    s->frame_len_bits = ff_wma_get_frame_len_bits(avctx->sample_rate,

                                                  s->version, 0);

    s->next_block_len_bits = s->frame_len_bits;

    s->prev_block_len_bits = s->frame_len_bits;

    s->block_len_bits      = s->frame_len_bits;

    s->frame_len = 1 << s->frame_len_bits;

    if (s->use_variable_block_len) {

        int nb_max, nb;

        nb = ((flags2 >> 3) & 3) + 1;

        if ((avctx->bit_rate / avctx->channels) >= 32000)

            nb += 2;

        nb_max = s->frame_len_bits - BLOCK_MIN_BITS;

        if (nb > nb_max)

            nb = nb_max;

        s->nb_block_sizes = nb + 1;

    } else

        s->nb_block_sizes = 1;

    /* init rate dependent parameters */

    s->use_noise_coding = 1;

    high_freq           = avctx->sample_rate * 0.5;

    /* if version 2, then the rates are normalized */

    sample_rate1 = avctx->sample_rate;

    if (s->version == 2) {

        if (sample_rate1 >= 44100)

            sample_rate1 = 44100;

        else if (sample_rate1 >= 22050)

            sample_rate1 = 22050;

        else if (sample_rate1 >= 16000)

            sample_rate1 = 16000;

        else if (sample_rate1 >= 11025)

            sample_rate1 = 11025;

        else if (sample_rate1 >= 8000)

            sample_rate1 = 8000;

    }

    bps                 = (float) avctx->bit_rate /

                          (float) (avctx->channels * avctx->sample_rate);

    s->byte_offset_bits = av_log2((int) (bps * s->frame_len / 8.0 + 0.5)) + 2;

    /* compute high frequency value and choose if noise coding should

     * be activated */

    bps1 = bps;

    if (avctx->channels == 2)

        bps1 = bps * 1.6;

    if (sample_rate1 == 44100) {

        if (bps1 >= 0.61)

            s->use_noise_coding = 0;

        else

            high_freq = high_freq * 0.4;

    } else if (sample_rate1 == 22050) {

        if (bps1 >= 1.16)

            s->use_noise_coding = 0;

        else if (bps1 >= 0.72)

            high_freq = high_freq * 0.7;

        else

            high_freq = high_freq * 0.6;

    } else if (sample_rate1 == 16000) {

        if (bps > 0.5)

            high_freq = high_freq * 0.5;

        else

            high_freq = high_freq * 0.3;

    } else if (sample_rate1 == 11025)

        high_freq = high_freq * 0.7;

    else if (sample_rate1 == 8000) {

        if (bps <= 0.625)

            high_freq = high_freq * 0.5;

        else if (bps > 0.75)

            s->use_noise_coding = 0;

        else

            high_freq = high_freq * 0.65;

    } else {

        if (bps >= 0.8)

            high_freq = high_freq * 0.75;

        else if (bps >= 0.6)

            high_freq = high_freq * 0.6;

        else

            high_freq = high_freq * 0.5;

    }

    av_dlog(s->avctx, "flags2=0x%x\n", flags2);

    av_dlog(s->avctx, "version=%d channels=%d sample_rate=%d bitrate=%d block_align=%d\n",

            s->version, avctx->channels, avctx->sample_rate, avctx->bit_rate,

            avctx->block_align);

    av_dlog(s->avctx, "bps=%f bps1=%f high_freq=%f bitoffset=%d\n",

            bps, bps1, high_freq, s->byte_offset_bits);

    av_dlog(s->avctx, "use_noise_coding=%d use_exp_vlc=%d nb_block_sizes=%d\n",

            s->use_noise_coding, s->use_exp_vlc, s->nb_block_sizes);

    /* compute the scale factor band sizes for each MDCT block size */

    {

        int a, b, pos, lpos, k, block_len, i, j, n;

        const uint8_t *table;

        if (s->version == 1)

            s->coefs_start = 3;

        else

            s->coefs_start = 0;

        for (k = 0; k < s->nb_block_sizes; k++) {

            block_len = s->frame_len >> k;

            if (s->version == 1) {

                lpos = 0;

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

                    a   = ff_wma_critical_freqs[i];

                    b   = avctx->sample_rate;

                    pos = ((block_len * 2 * a) + (b >> 1)) / b;

                    if (pos > block_len)

                        pos = block_len;

                    s->exponent_bands[0][i] = pos - lpos;

                    if (pos >= block_len) {

                        i++;

                        break;

                    }

                    lpos = pos;

                }

                s->exponent_sizes[0] = i;

            } else {

                /* hardcoded tables */

                table = NULL;

                a     = s->frame_len_bits - BLOCK_MIN_BITS - k;

                if (a < 3) {

                    if (avctx->sample_rate >= 44100)

                        table = exponent_band_44100[a];

                    else if (avctx->sample_rate >= 32000)

                        table = exponent_band_32000[a];

                    else if (avctx->sample_rate >= 22050)

                        table = exponent_band_22050[a];

                }

                if (table) {

                    n = *table++;

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

                        s->exponent_bands[k][i] = table[i];

                    s->exponent_sizes[k] = n;

                } else {

                    j    = 0;

                    lpos = 0;

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

                        a     = ff_wma_critical_freqs[i];

                        b     = avctx->sample_rate;

                        pos   = ((block_len * 2 * a) + (b << 1)) / (4 * b);

                        pos <<= 2;

                        if (pos > block_len)

                            pos = block_len;

                        if (pos > lpos)

                            s->exponent_bands[k][j++] = pos - lpos;

                        if (pos >= block_len)

                            break;

                        lpos = pos;

                    }

                    s->exponent_sizes[k] = j;

                }

            }

            /* max number of coefs */

            s->coefs_end[k] = (s->frame_len - ((s->frame_len * 9) / 100)) >> k;

            /* high freq computation */

            s->high_band_start[k] = (int) ((block_len * 2 * high_freq) /

                                           avctx->sample_rate + 0.5);

            n   = s->exponent_sizes[k];

            j   = 0;

            pos = 0;

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

                int start, end;

                start = pos;

                pos  += s->exponent_bands[k][i];

                end   = pos;

                if (start < s->high_band_start[k])

                    start = s->high_band_start[k];

                if (end > s->coefs_end[k])

                    end = s->coefs_end[k];

                if (end > start)

                    s->exponent_high_bands[k][j++] = end - start;

            }

            s->exponent_high_sizes[k] = j;

#if 0

            tprintf(s->avctx, "%5d: coefs_end=%d high_band_start=%d nb_high_bands=%d: ",

                    s->frame_len >> k,

                    s->coefs_end[k],

                    s->high_band_start[k],

                    s->exponent_high_sizes[k]);

            for (j = 0; j < s->exponent_high_sizes[k]; j++)

                tprintf(s->avctx, " %d", s->exponent_high_bands[k][j]);

            tprintf(s->avctx, "\n");

#endif /* 0 */

        }

    }

#ifdef TRACE

    {

        int i, j;

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

            tprintf(s->avctx, "%5d: n=%2d:",

                    s->frame_len >> i,

                    s->exponent_sizes[i]);

            for (j = 0; j < s->exponent_sizes[i]; j++)

                tprintf(s->avctx, " %d", s->exponent_bands[i][j]);

            tprintf(s->avctx, "\n");

        }

    }

#endif /* TRACE */

    /* init MDCT windows : simple sine window */

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

        ff_init_ff_sine_windows(s->frame_len_bits - i);

        s->windows[i] = ff_sine_windows[s->frame_len_bits - i];

    }

    s->reset_block_lengths = 1;

    if (s->use_noise_coding) {

        /* init the noise generator */

        if (s->use_exp_vlc)

            s->noise_mult = 0.02;

        else

            s->noise_mult = 0.04;

#ifdef TRACE

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

            s->noise_table[i] = 1.0 * s->noise_mult;

#else

        {

            unsigned int seed;

            float norm;

            seed = 1;

            norm = (1.0 / (float) (1LL << 31)) * sqrt(3) * s->noise_mult;

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

                seed              = seed * 314159 + 1;

                s->noise_table[i] = (float) ((int) seed) * norm;

            }

        }

#endif /* TRACE */

    }

    /* choose the VLC tables for the coefficients */

    coef_vlc_table = 2;

    if (avctx->sample_rate >= 32000) {

        if (bps1 < 0.72)

            coef_vlc_table = 0;

        else if (bps1 < 1.16)

            coef_vlc_table = 1;

    }

    s->coef_vlcs[0] = &coef_vlcs[coef_vlc_table * 2];

    s->coef_vlcs[1] = &coef_vlcs[coef_vlc_table * 2 + 1];

    init_coef_vlc(&s->coef_vlc[0], &s->run_table[0], &s->level_table[0],

                  &s->int_table[0], s->coef_vlcs[0]);

    init_coef_vlc(&s->coef_vlc[1], &s->run_table[1], &s->level_table[1],

                  &s->int_table[1], s->coef_vlcs[1]);

    return 0;

}


void ff_put_h264_qpel4_mc13_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_hv_qrt_4w_msa(src + stride - 2,

                           src - (stride * 2), stride, dst, stride, 4);

}


static int flv_same_audio_codec(AVCodecContext *acodec, int flags)

{

    int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;

    int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;

    int codec_id;

    if (!acodec->codec_id && !acodec->codec_tag)

        return 1;

    if (acodec->bits_per_coded_sample != bits_per_coded_sample)

        return 0;

    switch(flv_codecid) {

        //no distinction between S16 and S8 PCM codec flags

    case FLV_CODECID_PCM:

        codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 :

#if HAVE_BIGENDIAN

                            AV_CODEC_ID_PCM_S16BE;

#else

                            AV_CODEC_ID_PCM_S16LE;

#endif

        return codec_id == acodec->codec_id;

    case FLV_CODECID_PCM_LE:

        codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_S16LE;

        return codec_id == acodec->codec_id;

    case FLV_CODECID_AAC:

        return acodec->codec_id == AV_CODEC_ID_AAC;

    case FLV_CODECID_ADPCM:

        return acodec->codec_id == AV_CODEC_ID_ADPCM_SWF;

    case FLV_CODECID_SPEEX:

        return acodec->codec_id == AV_CODEC_ID_SPEEX;

    case FLV_CODECID_MP3:

        return acodec->codec_id == AV_CODEC_ID_MP3;

    case FLV_CODECID_NELLYMOSER_8KHZ_MONO:

    case FLV_CODECID_NELLYMOSER_16KHZ_MONO:

    case FLV_CODECID_NELLYMOSER:

        return acodec->codec_id == AV_CODEC_ID_NELLYMOSER;

    case FLV_CODECID_PCM_MULAW:

        return acodec->sample_rate == 8000 &&

               acodec->codec_id == AV_CODEC_ID_PCM_MULAW;

    case FLV_CODECID_PCM_ALAW:

        return acodec->sample_rate = 8000 &&

               acodec->codec_id == AV_CODEC_ID_PCM_ALAW;

    default:

        return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);

    }

}


static inline void gen_op_clear_ieee_excp_and_FTT(void)

{

    tcg_gen_andi_tl(cpu_fsr, cpu_fsr, ~(FSR_FTT_MASK | FSR_CEXC_MASK));

}


int avpriv_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf,

                                 int bit_size, int sync_extension)

{

    GetBitContext gb;

    int specific_config_bitindex;

    if(bit_size<=0)

        return AVERROR_INVALIDDATA;

    init_get_bits(&gb, buf, bit_size);

    c->object_type = get_object_type(&gb);

    c->sample_rate = get_sample_rate(&gb, &c->sampling_index);

    c->chan_config = get_bits(&gb, 4);

    if (c->chan_config < FF_ARRAY_ELEMS(ff_mpeg4audio_channels))

        c->channels = ff_mpeg4audio_channels[c->chan_config];

    c->sbr = -1;

    c->ps  = -1;

    if (c->object_type == AOT_SBR || (c->object_type == AOT_PS &&

        // check for W6132 Annex YYYY draft MP3onMP4

        !(show_bits(&gb, 3) & 0x03 && !(show_bits(&gb, 9) & 0x3F)))) {

        if (c->object_type == AOT_PS)

            c->ps = 1;

        c->ext_object_type = AOT_SBR;

        c->sbr = 1;

        c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);

        c->object_type = get_object_type(&gb);

        if (c->object_type == AOT_ER_BSAC)

            c->ext_chan_config = get_bits(&gb, 4);

    } else {

        c->ext_object_type = AOT_NULL;

        c->ext_sample_rate = 0;

    }

    specific_config_bitindex = get_bits_count(&gb);

    if (c->object_type == AOT_ALS) {

        skip_bits(&gb, 5);

        if (show_bits_long(&gb, 24) != MKBETAG('\0','A','L','S'))

            skip_bits_long(&gb, 24);

        specific_config_bitindex = get_bits_count(&gb);

        if (parse_config_ALS(&gb, c))

            return -1;

    }

    if (c->ext_object_type != AOT_SBR && sync_extension) {

        while (get_bits_left(&gb) > 15) {

            if (show_bits(&gb, 11) == 0x2b7) { // sync extension

                get_bits(&gb, 11);

                c->ext_object_type = get_object_type(&gb);

                if (c->ext_object_type == AOT_SBR && (c->sbr = get_bits1(&gb)) == 1) {

                    c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);

                    if (c->ext_sample_rate == c->sample_rate)

                        c->sbr = -1;

                }

                if (get_bits_left(&gb) > 11 && get_bits(&gb, 11) == 0x548)

                    c->ps = get_bits1(&gb);

                break;

            } else

                get_bits1(&gb); // skip 1 bit

        }

    }

    //PS requires SBR

    if (!c->sbr)

        c->ps = 0;

    //Limit implicit PS to the HE-AACv2 Profile

    if ((c->ps == -1 && c->object_type != AOT_AAC_LC) || c->channels & ~0x01)

        c->ps = 0;

    return specific_config_bitindex;

}


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

                                     const char *name, Error **errp)

{

    Object **child = opaque;

    bool ambiguous = false;

    const char *type;

    char *path;

    type = object_property_get_type(obj, name, NULL);

    visit_type_str(v, &path, name, errp);

    if (*child) {

        object_unref(*child);

    }

    if (strcmp(path, "") != 0) {

        Object *target;

        target = object_resolve_path(path, &ambiguous);

        if (target) {

            gchar *target_type;

            target_type = g_strdup(&type[5]);

            target_type[strlen(target_type) - 2] = 0;

            if (object_dynamic_cast(target, target_type)) {

                object_ref(target);

                *child = target;

            } else {

                error_set(errp, QERR_INVALID_PARAMETER_TYPE, name, type);

            }

            g_free(target_type);

        } else {

            error_set(errp, QERR_DEVICE_NOT_FOUND, path);

        }

    } else {

        *child = NULL;

    }

    g_free(path);

}


vorbis_header (AVFormatContext * s, int idx)

{

    ogg_t *ogg = s->priv_data;

    ogg_stream_t *os = ogg->streams + idx;

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

    oggvorbis_private_t *priv;

    if (os->seq > 2)

        return 0;

    if (os->seq == 0) {

        os->private = av_mallocz(sizeof(oggvorbis_private_t));

        if (!os->private)

            return 0;

    }

    priv = os->private;

    priv->len[os->seq] = os->psize;

    priv->packet[os->seq] = av_mallocz(os->psize);

    memcpy(priv->packet[os->seq], os->buf + os->pstart, os->psize);

    if (os->buf[os->pstart] == 1) {

        uint8_t *p = os->buf + os->pstart + 11; //skip up to the audio channels

        st->codec->channels = *p++;

        st->codec->sample_rate = AV_RL32(p);

        p += 8; //skip maximum and and nominal bitrate

        st->codec->bit_rate = AV_RL32(p); //Minimum bitrate

        st->codec->codec_type = CODEC_TYPE_AUDIO;

        st->codec->codec_id = CODEC_ID_VORBIS;

        st->time_base.num = 1;

        st->time_base.den = st->codec->sample_rate;

    } else if (os->buf[os->pstart] == 3) {

        vorbis_comment (s, os->buf + os->pstart + 7, os->psize - 8);

    } else {

        st->codec->extradata_size =

            fixup_vorbis_headers(s, priv, &st->codec->extradata);

    }

    return os->seq < 3;

}


static void json_message_process_token(JSONLexer *lexer, GString *input,

                                       JSONTokenType type, int x, int y)

{

    JSONMessageParser *parser = container_of(lexer, JSONMessageParser, lexer);

    JSONToken *token;

    switch (type) {

    case JSON_LCURLY:

        parser->brace_count++;

        break;

    case JSON_RCURLY:

        parser->brace_count--;

        break;

    case JSON_LSQUARE:

        parser->bracket_count++;

        break;

    case JSON_RSQUARE:

        parser->bracket_count--;

        break;

    default:

        break;

    }

    token = g_malloc(sizeof(JSONToken) + input->len + 1);

    token->type = type;

    memcpy(token->str, input->str, input->len);

    token->str[input->len] = 0;

    token->x = x;

    token->y = y;

    parser->token_size += input->len;

    g_queue_push_tail(parser->tokens, token);

    if (type == JSON_ERROR) {

        goto out_emit_bad;

    } else if (parser->brace_count < 0 ||

        parser->bracket_count < 0 ||

        (parser->brace_count == 0 &&

         parser->bracket_count == 0)) {

        goto out_emit;

    } else if (parser->token_size > MAX_TOKEN_SIZE ||

               g_queue_get_length(parser->tokens) > MAX_TOKEN_COUNT ||

               parser->bracket_count + parser->brace_count > MAX_NESTING) {

        /* Security consideration, we limit total memory allocated per object

         * and the maximum recursion depth that a message can force.

         */

        goto out_emit_bad;

    }

    return;

out_emit_bad:

    /*

     * Clear out token list and tell the parser to emit an error

     * indication by passing it a NULL list

     */

    json_message_free_tokens(parser);

out_emit:

    /* send current list of tokens to parser and reset tokenizer */

    parser->brace_count = 0;

    parser->bracket_count = 0;

    /* parser->emit takes ownership of parser->tokens.  */

    parser->emit(parser, parser->tokens);

    parser->tokens = g_queue_new();

    parser->token_size = 0;

}


static void test_blk_write(BlockBackend *blk, long pattern, int64_t offset,

                           int64_t count, bool expect_failed)

{

    void *pattern_buf = NULL;

    QEMUIOVector qiov;

    int async_ret = NOT_DONE;

    pattern_buf = g_malloc(count);

    if (pattern) {

        memset(pattern_buf, pattern, count);

    } else {

        memset(pattern_buf, 0x00, count);

    }

    qemu_iovec_init(&qiov, 1);

    qemu_iovec_add(&qiov, pattern_buf, count);

    blk_aio_pwritev(blk, offset, &qiov, 0, blk_rw_done, &async_ret);

    while (async_ret == NOT_DONE) {

        main_loop_wait(false);

    }

    if (expect_failed) {

        g_assert(async_ret != 0);

    } else {

        g_assert(async_ret == 0);

    }

    g_free(pattern_buf);

}


void usb_packet_set_state(USBPacket *p, USBPacketState state)

{

    static const char *name[] = {

        [USB_PACKET_UNDEFINED] = "undef",

        [USB_PACKET_SETUP]     = "setup",

        [USB_PACKET_QUEUED]    = "queued",

        [USB_PACKET_ASYNC]     = "async",

        [USB_PACKET_COMPLETE]  = "complete",

        [USB_PACKET_CANCELED]  = "canceled",

    };

    USBDevice *dev = p->ep->dev;

    USBBus *bus = usb_bus_from_device(dev);

    trace_usb_packet_state_change(bus->busnr, dev->port->path, p->ep->nr,

                                  p, name[p->state], name[state]);

    p->state = state;

}


static struct URLProtocol *url_find_protocol(const char *filename)

{

    URLProtocol *up = NULL;

    char proto_str[128], proto_nested[128], *ptr;

    size_t proto_len = strspn(filename, URL_SCHEME_CHARS);

    if (filename[proto_len] != ':' &&

        (filename[proto_len] != ',' || !strchr(filename + proto_len + 1, ':')) ||

        is_dos_path(filename))

        strcpy(proto_str, "file");

    else

        av_strlcpy(proto_str, filename,

                   FFMIN(proto_len + 1, sizeof(proto_str)));

    if ((ptr = strchr(proto_str, ',')))

        *ptr = '\0';

    av_strlcpy(proto_nested, proto_str, sizeof(proto_nested));

    if ((ptr = strchr(proto_nested, '+')))

        *ptr = '\0';

    while (up = ffurl_protocol_next(up)) {

        if (!strcmp(proto_str, up->name))

            break;

        if (up->flags & URL_PROTOCOL_FLAG_NESTED_SCHEME &&

            !strcmp(proto_nested, up->name))

            break;

    }

    return up;

}


void qmp_drive_mirror(const char *device, const char *target,

                      bool has_format, const char *format,

                      enum MirrorSyncMode sync,

                      bool has_mode, enum NewImageMode mode,

                      bool has_speed, int64_t speed, Error **errp)

{

    BlockDriverInfo bdi;

    BlockDriverState *bs;

    BlockDriverState *source, *target_bs;

    BlockDriver *proto_drv;

    BlockDriver *drv = NULL;

    Error *local_err = NULL;

    int flags;

    uint64_t size;

    int ret;

    if (!has_speed) {

        speed = 0;

    }

    if (!has_mode) {

        mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;

    }

    bs = bdrv_find(device);

    if (!bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    if (!bdrv_is_inserted(bs)) {

        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        return;

    }

    if (!has_format) {

        format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;

    }

    if (format) {

        drv = bdrv_find_format(format);

        if (!drv) {

            error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);

            return;

        }

    }

    if (bdrv_in_use(bs)) {

        error_set(errp, QERR_DEVICE_IN_USE, device);

        return;

    }

    flags = bs->open_flags | BDRV_O_RDWR;

    source = bs->backing_hd;

    if (!source && sync == MIRROR_SYNC_MODE_TOP) {

        sync = MIRROR_SYNC_MODE_FULL;

    }

    proto_drv = bdrv_find_protocol(target);

    if (!proto_drv) {

        error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);

        return;

    }

    if (sync == MIRROR_SYNC_MODE_FULL && mode != NEW_IMAGE_MODE_EXISTING) {

        /* create new image w/o backing file */

        assert(format && drv);

        bdrv_get_geometry(bs, &size);

        size *= 512;

        ret = bdrv_img_create(target, format,

                              NULL, NULL, NULL, size, flags);

    } else {

        switch (mode) {

        case NEW_IMAGE_MODE_EXISTING:

            ret = 0;

            break;

        case NEW_IMAGE_MODE_ABSOLUTE_PATHS:

            /* create new image with backing file */

            ret = bdrv_img_create(target, format,

                                  source->filename,

                                  source->drv->format_name,

                                  NULL, -1, flags);

            break;

        default:

            abort();

        }

    }

    if (ret) {

        error_set(errp, QERR_OPEN_FILE_FAILED, target);

        return;

    }

    target_bs = bdrv_new("");

    ret = bdrv_open(target_bs, target, flags | BDRV_O_NO_BACKING, drv);

    if (ret < 0) {

        bdrv_delete(target_bs);

        error_set(errp, QERR_OPEN_FILE_FAILED, target);

        return;

    }

    /* We need a backing file if we will copy parts of a cluster.  */

    if (bdrv_get_info(target_bs, &bdi) >= 0 && bdi.cluster_size != 0 &&

        bdi.cluster_size >= BDRV_SECTORS_PER_DIRTY_CHUNK * 512) {

        ret = bdrv_open_backing_file(target_bs);

        if (ret < 0) {

            bdrv_delete(target_bs);

            error_set(errp, QERR_OPEN_FILE_FAILED, target);

            return;

        }

    }

    mirror_start(bs, target_bs, speed, sync, block_job_cb, bs, &local_err);

    if (local_err != NULL) {

        bdrv_delete(target_bs);

        error_propagate(errp, local_err);

        return;

    }

    /* Grab a reference so hotplug does not delete the BlockDriverState from

     * underneath us.

     */

    drive_get_ref(drive_get_by_blockdev(bs));

}


static av_cold int sonic_decode_init(AVCodecContext *avctx)

{

    SonicContext *s = avctx->priv_data;

    GetBitContext gb;

    int i;

    s->channels = avctx->channels;

    s->samplerate = avctx->sample_rate;

    if (!avctx->extradata)

    {

        av_log(avctx, AV_LOG_ERROR, "No mandatory headers present\n");

        return AVERROR_INVALIDDATA;

    }

    init_get_bits8(&gb, avctx->extradata, avctx->extradata_size);

    s->version = get_bits(&gb, 2);

    if (s->version >= 2) {

        s->version       = get_bits(&gb, 8);

        s->minor_version = get_bits(&gb, 8);

    }

    if (s->version != 2)

    {

        av_log(avctx, AV_LOG_ERROR, "Unsupported Sonic version, please report\n");

        return AVERROR_INVALIDDATA;

    }

    if (s->version >= 1)

    {

        s->channels = get_bits(&gb, 2);

        s->samplerate = samplerate_table[get_bits(&gb, 4)];

        av_log(avctx, AV_LOG_INFO, "Sonicv2 chans: %d samprate: %d\n",

            s->channels, s->samplerate);

    }

    if (s->channels > MAX_CHANNELS)

    {

        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo streams are supported by now\n");

        return AVERROR_INVALIDDATA;

    }

    s->lossless = get_bits1(&gb);

    if (!s->lossless)

        skip_bits(&gb, 3); // XXX FIXME

    s->decorrelation = get_bits(&gb, 2);

    if (s->decorrelation != 3 && s->channels != 2) {

        av_log(avctx, AV_LOG_ERROR, "invalid decorrelation %d\n", s->decorrelation);

        return AVERROR_INVALIDDATA;

    }

    s->downsampling = get_bits(&gb, 2);

    if (!s->downsampling) {

        av_log(avctx, AV_LOG_ERROR, "invalid downsampling value\n");

        return AVERROR_INVALIDDATA;

    }

    s->num_taps = (get_bits(&gb, 5)+1)<<5;

    if (get_bits1(&gb)) // XXX FIXME

        av_log(avctx, AV_LOG_INFO, "Custom quant table\n");

    s->block_align = 2048LL*s->samplerate/(44100*s->downsampling);

    s->frame_size = s->channels*s->block_align*s->downsampling;

//    avctx->frame_size = s->block_align;

    av_log(avctx, AV_LOG_INFO, "Sonic: ver: %d.%d ls: %d dr: %d taps: %d block: %d frame: %d downsamp: %d\n",

        s->version, s->minor_version, s->lossless, s->decorrelation, s->num_taps, s->block_align, s->frame_size, s->downsampling);

    // generate taps

    s->tap_quant = av_calloc(s->num_taps, sizeof(*s->tap_quant));

    if (!s->tap_quant)

        return AVERROR(ENOMEM);

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

        s->tap_quant[i] = ff_sqrt(i+1);

    s->predictor_k = av_calloc(s->num_taps, sizeof(*s->predictor_k));

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

    {

        s->predictor_state[i] = av_calloc(s->num_taps, sizeof(**s->predictor_state));

        if (!s->predictor_state[i])

            return AVERROR(ENOMEM);

    }

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

    {

        s->coded_samples[i] = av_calloc(s->block_align, sizeof(**s->coded_samples));

        if (!s->coded_samples[i])

            return AVERROR(ENOMEM);

    }

    s->int_samples = av_calloc(s->frame_size, sizeof(*s->int_samples));

    if (!s->int_samples)

        return AVERROR(ENOMEM);

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    return 0;

}


static void spapr_cpu_init(sPAPRMachineState *spapr, PowerPCCPU *cpu,

                           Error **errp)

{

    CPUPPCState *env = &cpu->env;

    CPUState *cs = CPU(cpu);

    int i;

    /* Set time-base frequency to 512 MHz */

    cpu_ppc_tb_init(env, SPAPR_TIMEBASE_FREQ);

    /* Enable PAPR mode in TCG or KVM */

    cpu_ppc_set_papr(cpu);

    if (cpu->max_compat) {

        Error *local_err = NULL;

        ppc_set_compat(cpu, cpu->max_compat, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            return;

        }

    }

    /* Set NUMA node for the added CPUs  */

    i = numa_get_node_for_cpu(cs->cpu_index);

    if (i < nb_numa_nodes) {

            cs->numa_node = i;

    }

    xics_cpu_setup(spapr->xics, cpu);

    qemu_register_reset(spapr_cpu_reset, cpu);

    spapr_cpu_reset(cpu);

}


int ppc_find_by_name (const unsigned char *name, ppc_def_t **def)

{

    int i, ret;

    ret = -1;

    *def = NULL;

    for (i = 0; strcmp(ppc_defs[i].name, "default") != 0; i++) {

        if (strcasecmp(name, ppc_defs[i].name) == 0) {

            *def = &ppc_defs[i];

            ret = 0;

            break;

        }

    }

    return ret;

}


static void spitz_gpio_setup(PXA2xxState *cpu, int slots)

{

    qemu_irq lcd_hsync;

    /*

     * Bad hack: We toggle the LCD hsync GPIO on every GPIO status

     * read to satisfy broken guests that poll-wait for hsync.

     * Simulating a real hsync event would be less practical and

     * wouldn't guarantee that a guest ever exits the loop.

     */

    spitz_hsync = 0;

    lcd_hsync = qemu_allocate_irqs(spitz_lcd_hsync_handler, cpu, 1)[0];

    pxa2xx_gpio_read_notifier(cpu->gpio, lcd_hsync);

    pxa2xx_lcd_vsync_notifier(cpu->lcd, lcd_hsync);

    /* MMC/SD host */

    pxa2xx_mmci_handlers(cpu->mmc,

                    qdev_get_gpio_in(cpu->gpio, SPITZ_GPIO_SD_WP),

                    qdev_get_gpio_in(cpu->gpio, SPITZ_GPIO_SD_DETECT));

    /* Battery lock always closed */

    qemu_irq_raise(qdev_get_gpio_in(cpu->gpio, SPITZ_GPIO_BAT_COVER));

    /* Handle reset */

    qdev_connect_gpio_out(cpu->gpio, SPITZ_GPIO_ON_RESET, cpu->reset);

    /* PCMCIA signals: card's IRQ and Card-Detect */

    if (slots >= 1)

        pxa2xx_pcmcia_set_irq_cb(cpu->pcmcia[0],

                        qdev_get_gpio_in(cpu->gpio, SPITZ_GPIO_CF1_IRQ),

                        qdev_get_gpio_in(cpu->gpio, SPITZ_GPIO_CF1_CD));

    if (slots >= 2)

        pxa2xx_pcmcia_set_irq_cb(cpu->pcmcia[1],

                        qdev_get_gpio_in(cpu->gpio, SPITZ_GPIO_CF2_IRQ),

                        qdev_get_gpio_in(cpu->gpio, SPITZ_GPIO_CF2_CD));

}


int vnc_display_pw_expire(DisplayState *ds, time_t expires)
{
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
    vs->expires = expires;
    return 0;


static int usb_hub_handle_data(USBDevice *dev, USBPacket *p)

{

    USBHubState *s = (USBHubState *)dev;

    int ret;

    switch(p->pid) {

    case USB_TOKEN_IN:

        if (p->devep == 1) {

            USBHubPort *port;

            unsigned int status;

            int i, n;

            n = (NUM_PORTS + 1 + 7) / 8;

            if (p->len == 1) { /* FreeBSD workaround */

                n = 1;

            } else if (n > p->len) {

                return USB_RET_BABBLE;

            }

            status = 0;

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

                port = &s->ports[i];

                if (port->wPortChange)

                    status |= (1 << (i + 1));

            }

            if (status != 0) {

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

                    p->data[i] = status >> (8 * i);

                }

                ret = n;

            } else {

                ret = USB_RET_NAK; /* usb11 11.13.1 */

            }

        } else {

            goto fail;

        }

        break;

    case USB_TOKEN_OUT:

    default:

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


void bdrv_drain_all(void)

{

    /* Always run first iteration so any pending completion BHs run */

    bool busy = true;

    BlockDriverState *bs;

    while (busy) {

        /* FIXME: We do not have timer support here, so this is effectively

         * a busy wait.

         */

        QTAILQ_FOREACH(bs, &bdrv_states, list) {

            if (bdrv_start_throttled_reqs(bs)) {

                busy = true;

            }

        }

        busy = bdrv_requests_pending_all();

        busy |= aio_poll(qemu_get_aio_context(), busy);

    }

}


static void do_fbranch(DisasContext *dc, int32_t offset, uint32_t insn, int cc,

                      TCGv r_cond)

{

    unsigned int cond = GET_FIELD(insn, 3, 6), a = (insn & (1 << 29));

    target_ulong target = dc->pc + offset;

    if (cond == 0x0) {

        /* unconditional not taken */

        if (a) {

            dc->pc = dc->npc + 4;

            dc->npc = dc->pc + 4;

        } else {

            dc->pc = dc->npc;

            dc->npc = dc->pc + 4;

        }

    } else if (cond == 0x8) {

        /* unconditional taken */

        if (a) {

            dc->pc = target;

            dc->npc = dc->pc + 4;

        } else {

            dc->pc = dc->npc;

            dc->npc = target;

            tcg_gen_mov_tl(cpu_pc, cpu_npc);

        }

    } else {

        flush_cond(dc, r_cond);

        gen_fcond(r_cond, cc, cond);

        if (a) {

            gen_branch_a(dc, target, dc->npc, r_cond);

            dc->is_br = 1;

        } else {

            dc->pc = dc->npc;

            dc->jump_pc[0] = target;

            dc->jump_pc[1] = dc->npc + 4;

            dc->npc = JUMP_PC;

        }

    }

}


static inline uint32_t vtd_slpt_level_shift(uint32_t level)

{

    return VTD_PAGE_SHIFT_4K + (level - 1) * VTD_SL_LEVEL_BITS;

}


static int vtd_iova_to_slpte(VTDContextEntry *ce, uint64_t iova, bool is_write,

                             uint64_t *slptep, uint32_t *slpte_level,

                             bool *reads, bool *writes)

{

    dma_addr_t addr = vtd_get_slpt_base_from_context(ce);

    uint32_t level = vtd_get_level_from_context_entry(ce);

    uint32_t offset;

    uint64_t slpte;

    uint32_t ce_agaw = vtd_get_agaw_from_context_entry(ce);

    uint64_t access_right_check;

    /* Check if @iova is above 2^X-1, where X is the minimum of MGAW

     * in CAP_REG and AW in context-entry.

     */

    if (iova & ~((1ULL << MIN(ce_agaw, VTD_MGAW)) - 1)) {

        VTD_DPRINTF(GENERAL, "error: iova 0x%"PRIx64 " exceeds limits", iova);

        return -VTD_FR_ADDR_BEYOND_MGAW;

    }

    /* FIXME: what is the Atomics request here? */

    access_right_check = is_write ? VTD_SL_W : VTD_SL_R;

    while (true) {

        offset = vtd_iova_level_offset(iova, level);

        slpte = vtd_get_slpte(addr, offset);

        if (slpte == (uint64_t)-1) {

            VTD_DPRINTF(GENERAL, "error: fail to access second-level paging "

                        "entry at level %"PRIu32 " for iova 0x%"PRIx64,

                        level, iova);

            if (level == vtd_get_level_from_context_entry(ce)) {

                /* Invalid programming of context-entry */

                return -VTD_FR_CONTEXT_ENTRY_INV;

            } else {

                return -VTD_FR_PAGING_ENTRY_INV;

            }

        }

        *reads = (*reads) && (slpte & VTD_SL_R);

        *writes = (*writes) && (slpte & VTD_SL_W);

        if (!(slpte & access_right_check)) {

            VTD_DPRINTF(GENERAL, "error: lack of %s permission for "

                        "iova 0x%"PRIx64 " slpte 0x%"PRIx64,

                        (is_write ? "write" : "read"), iova, slpte);

            return is_write ? -VTD_FR_WRITE : -VTD_FR_READ;

        }

        if (vtd_slpte_nonzero_rsvd(slpte, level)) {

            VTD_DPRINTF(GENERAL, "error: non-zero reserved field in second "

                        "level paging entry level %"PRIu32 " slpte 0x%"PRIx64,

                        level, slpte);

            return -VTD_FR_PAGING_ENTRY_RSVD;

        }

        if (vtd_is_last_slpte(slpte, level)) {

            *slptep = slpte;

            *slpte_level = level;

            return 0;

        }

        addr = vtd_get_slpte_addr(slpte);

        level--;

    }

}


PCIBus *ppce500_pci_init(qemu_irq pci_irqs[4], target_phys_addr_t registers)

{

    PPCE500PCIState *controller;

    PCIDevice *d;

    int index;

    static int ppce500_pci_id;

    controller = qemu_mallocz(sizeof(PPCE500PCIState));

    controller->pci_state.bus = pci_register_bus(NULL, "pci",

                                                 mpc85xx_pci_set_irq,

                                                 mpc85xx_pci_map_irq,

                                                 pci_irqs, 0x88, 4);

    d = pci_register_device(controller->pci_state.bus,

                            "host bridge", sizeof(PCIDevice),

                            0, NULL, NULL);

    pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_FREESCALE);

    pci_config_set_device_id(d->config, PCI_DEVICE_ID_MPC8533E);

    pci_config_set_class(d->config, PCI_CLASS_PROCESSOR_POWERPC);

    controller->pci_dev = d;

    /* CFGADDR */

    index = cpu_register_io_memory(pcie500_cfgaddr_read,

                                   pcie500_cfgaddr_write, controller);

    if (index < 0)

        goto free;

    cpu_register_physical_memory(registers + PCIE500_CFGADDR, 4, index);

    /* CFGDATA */

    index = cpu_register_io_memory(pcie500_cfgdata_read,

                                   pcie500_cfgdata_write,

                                   &controller->pci_state);

    if (index < 0)

        goto free;

    cpu_register_physical_memory(registers + PCIE500_CFGDATA, 4, index);

    index = cpu_register_io_memory(e500_pci_reg_read,

                                   e500_pci_reg_write, controller);

    if (index < 0)

        goto free;

    cpu_register_physical_memory(registers + PCIE500_REG_BASE,

                                   PCIE500_REG_SIZE, index);

    /* XXX load/save code not tested. */

    register_savevm("ppce500_pci", ppce500_pci_id++, 1,

                    ppce500_pci_save, ppce500_pci_load, controller);

    return controller->pci_state.bus;

free:

    printf("%s error\n", __func__);

    qemu_free(controller);

    return NULL;

}


int omap_validate_tipb_addr(struct omap_mpu_state_s *s,

                target_phys_addr_t addr)

{

    return addr >= 0xfffb0000 && addr < 0xffff0000;

}


static int load_bitmap_data(BlockDriverState *bs,

                            const uint64_t *bitmap_table,

                            uint32_t bitmap_table_size,

                            BdrvDirtyBitmap *bitmap)

{

    int ret = 0;

    BDRVQcow2State *s = bs->opaque;

    uint64_t sector, sbc;

    uint64_t bm_size = bdrv_dirty_bitmap_size(bitmap);

    uint64_t bm_sectors = DIV_ROUND_UP(bm_size, BDRV_SECTOR_SIZE);

    uint8_t *buf = NULL;

    uint64_t i, tab_size =

            size_to_clusters(s,

                bdrv_dirty_bitmap_serialization_size(bitmap, 0, bm_sectors));

    if (tab_size != bitmap_table_size || tab_size > BME_MAX_TABLE_SIZE) {

        return -EINVAL;

    }

    buf = g_malloc(s->cluster_size);

    sbc = sectors_covered_by_bitmap_cluster(s, bitmap);

    for (i = 0, sector = 0; i < tab_size; ++i, sector += sbc) {

        uint64_t count = MIN(bm_sectors - sector, sbc);

        uint64_t entry = bitmap_table[i];

        uint64_t offset = entry & BME_TABLE_ENTRY_OFFSET_MASK;

        assert(check_table_entry(entry, s->cluster_size) == 0);

        if (offset == 0) {

            if (entry & BME_TABLE_ENTRY_FLAG_ALL_ONES) {

                bdrv_dirty_bitmap_deserialize_ones(bitmap, sector, count,

                                                   false);

            } else {

                /* No need to deserialize zeros because the dirty bitmap is

                 * already cleared */

            }

        } else {

            ret = bdrv_pread(bs->file, offset, buf, s->cluster_size);

            if (ret < 0) {

                goto finish;

            }

            bdrv_dirty_bitmap_deserialize_part(bitmap, buf, sector, count,

                                               false);

        }

    }

    ret = 0;

    bdrv_dirty_bitmap_deserialize_finish(bitmap);

finish:

    g_free(buf);

    return ret;

}


static coroutine_fn int nbd_negotiate(NBDClientNewData *data)

{

    NBDClient *client = data->client;

    char buf[8 + 8 + 8 + 128];

    int rc;

    const int myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |

                         NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);

    bool oldStyle;

    /* Old style negotiation header without options

        [ 0 ..   7]   passwd       ("NBDMAGIC")

        [ 8 ..  15]   magic        (NBD_CLIENT_MAGIC)

        [16 ..  23]   size

        [24 ..  25]   server flags (0)

        [26 ..  27]   export flags

        [28 .. 151]   reserved     (0)

       New style negotiation header with options

        [ 0 ..   7]   passwd       ("NBDMAGIC")

        [ 8 ..  15]   magic        (NBD_OPTS_MAGIC)

        [16 ..  17]   server flags (0)

        ....options sent....

        [18 ..  25]   size

        [26 ..  27]   export flags

        [28 .. 151]   reserved     (0)

     */

    qio_channel_set_blocking(client->ioc, false, NULL);

    rc = -EINVAL;

    TRACE("Beginning negotiation.");

    memset(buf, 0, sizeof(buf));

    memcpy(buf, "NBDMAGIC", 8);

    oldStyle = client->exp != NULL && !client->tlscreds;

    if (oldStyle) {

        assert ((client->exp->nbdflags & ~65535) == 0);

        TRACE("advertising size %" PRIu64 " and flags %x",

              client->exp->size, client->exp->nbdflags | myflags);

        stq_be_p(buf + 8, NBD_CLIENT_MAGIC);

        stq_be_p(buf + 16, client->exp->size);

        stw_be_p(buf + 26, client->exp->nbdflags | myflags);

    } else {

        stq_be_p(buf + 8, NBD_OPTS_MAGIC);

        stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE);

    }

    if (oldStyle) {

        if (client->tlscreds) {

            TRACE("TLS cannot be enabled with oldstyle protocol");

            goto fail;

        }

        if (nbd_negotiate_write(client->ioc, buf, sizeof(buf)) != sizeof(buf)) {

            LOG("write failed");

            goto fail;

        }

    } else {

        if (nbd_negotiate_write(client->ioc, buf, 18) != 18) {

            LOG("write failed");

            goto fail;

        }

        rc = nbd_negotiate_options(client);

        if (rc != 0) {

            LOG("option negotiation failed");

            goto fail;

        }

        assert ((client->exp->nbdflags & ~65535) == 0);

        TRACE("advertising size %" PRIu64 " and flags %x",

              client->exp->size, client->exp->nbdflags | myflags);

        stq_be_p(buf + 18, client->exp->size);

        stw_be_p(buf + 26, client->exp->nbdflags | myflags);

        if (nbd_negotiate_write(client->ioc, buf + 18, sizeof(buf) - 18) !=

            sizeof(buf) - 18) {

            LOG("write failed");

            goto fail;

        }

    }

    TRACE("Negotiation succeeded.");

    rc = 0;

fail:

    return rc;

}


void bdrv_io_plug(BlockDriverState *bs)

{

    BlockDriver *drv = bs->drv;

    if (drv && drv->bdrv_io_plug) {

        drv->bdrv_io_plug(bs);

    } else if (bs->file) {

        bdrv_io_plug(bs->file);

    }

}


void cpu_watchpoint_remove_all(CPUState *env, int mask)

{

    CPUWatchpoint *wp, *next;

    TAILQ_FOREACH_SAFE(wp, &env->watchpoints, entry, next) {

        if (wp->flags & mask)

            cpu_watchpoint_remove_by_ref(env, wp);

    }

}


static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)

{

    AVCodecInternal *avci = avctx->internal;

    InternalBuffer *buf;

    int buf_size, ret;

    buf_size = av_samples_get_buffer_size(NULL, avctx->channels,

                                          frame->nb_samples, avctx->sample_fmt,

                                          0);

    if (buf_size < 0)

        return AVERROR(EINVAL);

    /* allocate InternalBuffer if needed */

    if (!avci->buffer) {

        avci->buffer = av_mallocz(sizeof(InternalBuffer));

        if (!avci->buffer)

            return AVERROR(ENOMEM);

    }

    buf = avci->buffer;

    /* if there is a previously-used internal buffer, check its size and

     * channel count to see if we can reuse it */

    if (buf->extended_data) {

        /* if current buffer is too small, free it */

        if (buf->extended_data[0] && buf_size > buf->audio_data_size) {

            av_free(buf->extended_data[0]);

            if (buf->extended_data != buf->data)

                av_free(buf->extended_data);

            buf->extended_data = NULL;

            buf->data[0]       = NULL;

        }

        /* if number of channels has changed, reset and/or free extended data

         * pointers but leave data buffer in buf->data[0] for reuse */

        if (buf->nb_channels != avctx->channels) {

            if (buf->extended_data != buf->data)

                av_free(buf->extended_data);

            buf->extended_data = NULL;

        }

    }

    /* if there is no previous buffer or the previous buffer cannot be used

     * as-is, allocate a new buffer and/or rearrange the channel pointers */

    if (!buf->extended_data) {

        if (!buf->data[0]) {

            if (!(buf->data[0] = av_mallocz(buf_size)))

                return AVERROR(ENOMEM);

            buf->audio_data_size = buf_size;

        }

        if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,

                                            avctx->sample_fmt, buf->data[0],

                                            buf->audio_data_size, 0)))

            return ret;

        if (frame->extended_data == frame->data)

            buf->extended_data = buf->data;

        else

            buf->extended_data = frame->extended_data;

        memcpy(buf->data, frame->data, sizeof(frame->data));

        buf->linesize[0] = frame->linesize[0];

        buf->nb_channels = avctx->channels;

    } else {

        /* copy InternalBuffer info to the AVFrame */

        frame->extended_data = buf->extended_data;

        frame->linesize[0]   = buf->linesize[0];

        memcpy(frame->data, buf->data, sizeof(frame->data));

    }

    frame->type = FF_BUFFER_TYPE_INTERNAL;

    ff_init_buffer_info(avctx, frame);

    if (avctx->debug & FF_DEBUG_BUFFERS)

        av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p, "

                                    "internal audio buffer used\n", frame);

    return 0;

}


static void tracked_request_begin(BdrvTrackedRequest *req,

                                  BlockDriverState *bs,

                                  int64_t offset,

                                  unsigned int bytes, bool is_write)

{

    *req = (BdrvTrackedRequest){

        .bs = bs,

        .offset         = offset,

        .bytes          = bytes,

        .is_write       = is_write,

        .co             = qemu_coroutine_self(),

        .serialising    = false,

        .overlap_offset = offset,

        .overlap_bytes  = bytes,

    };

    qemu_co_queue_init(&req->wait_queue);

    QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);

}


static uint64_t omap_id_read(void *opaque, hwaddr addr,

                             unsigned size)

{

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

    if (size != 4) {

        return omap_badwidth_read32(opaque, addr);

    }

    switch (addr) {

    case 0xfffe1800:	/* DIE_ID_LSB */

        return 0xc9581f0e;

    case 0xfffe1804:	/* DIE_ID_MSB */

        return 0xa8858bfa;

    case 0xfffe2000:	/* PRODUCT_ID_LSB */

        return 0x00aaaafc;

    case 0xfffe2004:	/* PRODUCT_ID_MSB */

        return 0xcafeb574;

    case 0xfffed400:	/* JTAG_ID_LSB */

        switch (s->mpu_model) {

        case omap310:

            return 0x03310315;

        case omap1510:

            return 0x03310115;

        default:

            hw_error("%s: bad mpu model\n", __FUNCTION__);

        }

        break;

    case 0xfffed404:	/* JTAG_ID_MSB */

        switch (s->mpu_model) {

        case omap310:

            return 0xfb57402f;

        case omap1510:

            return 0xfb47002f;

        default:

            hw_error("%s: bad mpu model\n", __FUNCTION__);

        }

        break;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static void pc_compat_1_7(MachineState *machine)

{

    pc_compat_2_0(machine);

    smbios_defaults = false;

    gigabyte_align = false;

    option_rom_has_mr = true;

    x86_cpu_change_kvm_default("x2apic", NULL);

}


static void v9fs_create_post_mksock(V9fsState *s, V9fsCreateState *vs,

                                                                int err)

{

    if (err) {

        err = -errno;

        goto out;

    }

    err = v9fs_do_chmod(s, &vs->fullname, vs->perm & 0777);

    v9fs_create_post_perms(s, vs, err);

    return;

out:

    v9fs_post_create(s, vs, err);

}


void qemu_peer_set_vnet_hdr_len(NetClientState *nc, int len)

{

    if (!nc->peer || !nc->peer->info->set_vnet_hdr_len) {

        return;

    }

    nc->peer->info->set_vnet_hdr_len(nc->peer, len);

}


BusState *qdev_get_child_bus(DeviceState *dev, const char *name)

{

    BusState *bus;

    LIST_FOREACH(bus, &dev->child_bus, sibling) {

        if (strcmp(name, bus->name) == 0) {

            return bus;

        }

    }

    return NULL;

}


static bool e1000_mit_state_needed(void *opaque)

{

    E1000State *s = opaque;

    return s->compat_flags & E1000_FLAG_MIT;

}


void helper_ldq_l_raw(uint64_t t0, uint64_t t1)

{

    env->lock = t1;

    ldl_raw(t1, t0);

}


void xen_pt_config_delete(XenPCIPassthroughState *s)

{

    struct XenPTRegGroup *reg_group, *next_grp;

    struct XenPTReg *reg, *next_reg;

    /* free MSI/MSI-X info table */

    if (s->msix) {

        xen_pt_msix_delete(s);

    }

    if (s->msi) {

        g_free(s->msi);

    }

    /* free all register group entry */

    QLIST_FOREACH_SAFE(reg_group, &s->reg_grps, entries, next_grp) {

        /* free all register entry */

        QLIST_FOREACH_SAFE(reg, &reg_group->reg_tbl_list, entries, next_reg) {

            QLIST_REMOVE(reg, entries);

            g_free(reg);

        }

        QLIST_REMOVE(reg_group, entries);

        g_free(reg_group);

    }

}


static void luma_mc(HEVCContext *s, int16_t *dst, ptrdiff_t dststride,

                    AVFrame *ref, const Mv *mv, int x_off, int y_off,

                    int block_w, int block_h)

{

    HEVCLocalContext *lc = &s->HEVClc;

    uint8_t *src         = ref->data[0];

    ptrdiff_t srcstride  = ref->linesize[0];

    int pic_width        = s->ps.sps->width;

    int pic_height       = s->ps.sps->height;

    int mx         = mv->x & 3;

    int my         = mv->y & 3;

    int extra_left = ff_hevc_qpel_extra_before[mx];

    int extra_top  = ff_hevc_qpel_extra_before[my];

    x_off += mv->x >> 2;

    y_off += mv->y >> 2;

    src   += y_off * srcstride + (x_off << s->ps.sps->pixel_shift);

    if (x_off < extra_left || y_off < extra_top ||

        x_off >= pic_width - block_w - ff_hevc_qpel_extra_after[mx] ||

        y_off >= pic_height - block_h - ff_hevc_qpel_extra_after[my]) {

        const int edge_emu_stride = EDGE_EMU_BUFFER_STRIDE << s->ps.sps->pixel_shift;

        int offset = extra_top * srcstride + (extra_left << s->ps.sps->pixel_shift);

        int buf_offset = extra_top *

                         edge_emu_stride + (extra_left << s->ps.sps->pixel_shift);

        s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, src - offset,

                                 edge_emu_stride, srcstride,

                                 block_w + ff_hevc_qpel_extra[mx],

                                 block_h + ff_hevc_qpel_extra[my],

                                 x_off - extra_left, y_off - extra_top,

                                 pic_width, pic_height);

        src = lc->edge_emu_buffer + buf_offset;

        srcstride = edge_emu_stride;

    }

    s->hevcdsp.put_hevc_qpel[my][mx](dst, dststride, src, srcstride, block_w,

                                     block_h, lc->mc_buffer);

}


static gboolean gd_scroll_event(GtkWidget *widget, GdkEventScroll *scroll,

                                void *opaque)

{

    VirtualConsole *vc = opaque;

    InputButton btn;

    if (scroll->direction == GDK_SCROLL_UP) {

        btn = INPUT_BUTTON_WHEEL_UP;

    } else if (scroll->direction == GDK_SCROLL_DOWN) {

        btn = INPUT_BUTTON_WHEEL_DOWN;

    } else {

        return TRUE;

    }

    qemu_input_queue_btn(vc->gfx.dcl.con, btn, true);

    qemu_input_event_sync();

    qemu_input_queue_btn(vc->gfx.dcl.con, btn, false);

    qemu_input_event_sync();

    return TRUE;

}


static int nfs_parse_uri(const char *filename, QDict *options, Error **errp)

{

    URI *uri = NULL;

    QueryParams *qp = NULL;

    int ret = -EINVAL, i;

    uri = uri_parse(filename);

    if (!uri) {

        error_setg(errp, "Invalid URI specified");

        goto out;

    }

    if (strcmp(uri->scheme, "nfs") != 0) {

        error_setg(errp, "URI scheme must be 'nfs'");

        goto out;

    }

    if (!uri->server) {

        error_setg(errp, "missing hostname in URI");

        goto out;

    }

    if (!uri->path) {

        error_setg(errp, "missing file path in URI");

        goto out;

    }

    qp = query_params_parse(uri->query);

    if (!qp) {

        error_setg(errp, "could not parse query parameters");

        goto out;

    }

    qdict_put(options, "server.host", qstring_from_str(uri->server));

    qdict_put(options, "server.type", qstring_from_str("inet"));

    qdict_put(options, "path", qstring_from_str(uri->path));

    for (i = 0; i < qp->n; i++) {

        if (!qp->p[i].value) {

            error_setg(errp, "Value for NFS parameter expected: %s",

                       qp->p[i].name);

            goto out;

        }

        if (parse_uint_full(qp->p[i].value, NULL, 0)) {

            error_setg(errp, "Illegal value for NFS parameter: %s",

                       qp->p[i].name);

            goto out;

        }

        if (!strcmp(qp->p[i].name, "uid")) {

            qdict_put(options, "user",

                      qstring_from_str(qp->p[i].value));

        } else if (!strcmp(qp->p[i].name, "gid")) {

            qdict_put(options, "group",

                      qstring_from_str(qp->p[i].value));

        } else if (!strcmp(qp->p[i].name, "tcp-syncnt")) {

            qdict_put(options, "tcp-syn-count",

                      qstring_from_str(qp->p[i].value));

        } else if (!strcmp(qp->p[i].name, "readahead")) {

            qdict_put(options, "readahead-size",

                      qstring_from_str(qp->p[i].value));

        } else if (!strcmp(qp->p[i].name, "pagecache")) {

            qdict_put(options, "page-cache-size",

                      qstring_from_str(qp->p[i].value));

        } else if (!strcmp(qp->p[i].name, "debug")) {

            qdict_put(options, "debug",

                      qstring_from_str(qp->p[i].value));

        } else {

            error_setg(errp, "Unknown NFS parameter name: %s",

                       qp->p[i].name);

            goto out;

        }

    }

    ret = 0;

out:

    if (qp) {

        query_params_free(qp);

    }

    if (uri) {

        uri_free(uri);

    }

    return ret;

}


void helper_rfi(CPUPPCState *env)

{

    do_rfi(env, env->spr[SPR_SRR0], env->spr[SPR_SRR1],

           ~((target_ulong)0x783F0000), 1);

}


QEMUFile *qemu_popen_cmd(const char *command, const char *mode)

{

    FILE *stdio_file;

    QEMUFileStdio *s;

    if (mode == NULL || (mode[0] != 'r' && mode[0] != 'w') || mode[1] != 0) {

        fprintf(stderr, "qemu_popen: Argument validity check failed\n");

        return NULL;

    }

    stdio_file = popen(command, mode);

    if (stdio_file == NULL) {

        return NULL;

    }

    s = g_malloc0(sizeof(QEMUFileStdio));

    s->stdio_file = stdio_file;

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

        s->file = qemu_fopen_ops(s, &stdio_pipe_read_ops);

    } else {

        s->file = qemu_fopen_ops(s, &stdio_pipe_write_ops);

    }

    return s->file;

}