static void aarch64_any_initfn(Object *obj)

{

    ARMCPU *cpu = ARM_CPU(obj);

    set_feature(&cpu->env, ARM_FEATURE_V8);

    set_feature(&cpu->env, ARM_FEATURE_VFP4);

    set_feature(&cpu->env, ARM_FEATURE_NEON);

    set_feature(&cpu->env, ARM_FEATURE_AARCH64);

    set_feature(&cpu->env, ARM_FEATURE_V8_AES);

    set_feature(&cpu->env, ARM_FEATURE_V8_SHA1);

    set_feature(&cpu->env, ARM_FEATURE_V8_SHA256);

    set_feature(&cpu->env, ARM_FEATURE_V8_PMULL);

    set_feature(&cpu->env, ARM_FEATURE_CRC);

    cpu->ctr = 0x80030003; /* 32 byte I and D cacheline size, VIPT icache */

    cpu->dcz_blocksize = 7; /*  512 bytes */

}


static av_always_inline float quantize_and_encode_band_cost_template(

                                struct AACEncContext *s,

                                PutBitContext *pb, const float *in,

                                const float *scaled, int size, int scale_idx,

                                int cb, const float lambda, const float uplim,

                                int *bits, int BT_ZERO, int BT_UNSIGNED,

                                int BT_PAIR, int BT_ESC)

{

    const int q_idx = POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512;

    const float Q   = ff_aac_pow2sf_tab [q_idx];

    const float Q34 = ff_aac_pow34sf_tab[q_idx];

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

    const float CLIPPED_ESCAPE = 165140.0f*IQ;

    int i, j;

    float cost = 0;

    const int dim = BT_PAIR ? 2 : 4;

    int resbits = 0;

    const int range  = aac_cb_range[cb];

    const int maxval = aac_cb_maxval[cb];

    int off;

    if (BT_ZERO) {

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

            cost += in[i]*in[i];

        if (bits)

            *bits = 0;

        return cost * lambda;

    }

    if (!scaled) {

        abs_pow34_v(s->scoefs, in, size);

        scaled = s->scoefs;

    }

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

    if (BT_UNSIGNED) {

        off = 0;

    } else {

        off = maxval;

    }

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

        const float *vec;

        int *quants = s->qcoefs + i;

        int curidx = 0;

        int curbits;

        float rd = 0.0f;

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

            curidx *= range;

            curidx += quants[j] + off;

        }

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

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

        if (BT_UNSIGNED) {

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

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

                float di;

                if (BT_ESC && vec[j] == 64.0f) { //FIXME: slow

                    if (t >= CLIPPED_ESCAPE) {

                        di = t - CLIPPED_ESCAPE;

                        curbits += 21;

                    } else {

                        int c = av_clip_uintp2(quant(t, Q), 13);

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

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

                    }

                } else {

                    di = t - vec[j]*IQ;

                }

                if (vec[j] != 0.0f)

                    curbits++;

                rd += di*di;

            }

        } else {

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

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

                rd += di*di;

            }

        }

        cost    += rd * lambda + curbits;

        resbits += curbits;

        if (cost >= uplim)

            return uplim;

        if (pb) {

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

            if (BT_UNSIGNED)

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

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

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

            if (BT_ESC) {

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

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

                        int coef = av_clip_uintp2(quant(fabsf(in[i+j]), Q), 13);

                        int len = av_log2(coef);

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

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

                    }

                }

            }

        }

    }

    if (bits)

        *bits = resbits;

    return cost;

}


e1000e_set_icr(E1000ECore *core, int index, uint32_t val)

{

    if ((core->mac[ICR] & E1000_ICR_ASSERTED) &&

        (core->mac[CTRL_EXT] & E1000_CTRL_EXT_IAME)) {

        trace_e1000e_irq_icr_process_iame();

        e1000e_clear_ims_bits(core, core->mac[IAM]);

    }

    trace_e1000e_irq_icr_write(val, core->mac[ICR], core->mac[ICR] & ~val);

    core->mac[ICR] &= ~val;

    e1000e_update_interrupt_state(core);

}


MemoryRegionSection *phys_page_find(target_phys_addr_t index)

{

    PhysPageEntry lp = phys_map;

    PhysPageEntry *p;

    int i;

    uint16_t s_index = phys_section_unassigned;

    for (i = P_L2_LEVELS - 1; i >= 0 && !lp.is_leaf; i--) {

        if (lp.ptr == PHYS_MAP_NODE_NIL) {

            goto not_found;

        }

        p = phys_map_nodes[lp.ptr];

        lp = p[(index >> (i * L2_BITS)) & (L2_SIZE - 1)];

    }

    s_index = lp.ptr;

not_found:

    return &phys_sections[s_index];

}


static int encode_init(AVCodecContext * avctx){

    WMACodecContext *s = avctx->priv_data;

    int i, flags1, flags2;

    uint8_t *extradata;

    s->avctx = avctx;

    if(avctx->channels > MAX_CHANNELS) {

        av_log(avctx, AV_LOG_ERROR, "too many channels: got %i, need %i or fewer",

               avctx->channels, MAX_CHANNELS);

        return AVERROR(EINVAL);

    }

    if (avctx->sample_rate > 48000) {

        av_log(avctx, AV_LOG_ERROR, "sample rate is too high: %d > 48kHz",

               avctx->sample_rate);

        return AVERROR(EINVAL);

    }

    if(avctx->bit_rate < 24*1000) {

        av_log(avctx, AV_LOG_ERROR, "bitrate too low: got %i, need 24000 or higher\n",

               avctx->bit_rate);

        return AVERROR(EINVAL);

    }

    /* extract flag infos */

    flags1 = 0;

    flags2 = 1;

    if (avctx->codec->id == CODEC_ID_WMAV1) {

        extradata= av_malloc(4);

        avctx->extradata_size= 4;

        AV_WL16(extradata, flags1);

        AV_WL16(extradata+2, flags2);

    } else if (avctx->codec->id == CODEC_ID_WMAV2) {

        extradata= av_mallocz(10);

        avctx->extradata_size= 10;

        AV_WL32(extradata, flags1);

        AV_WL16(extradata+4, flags2);

    }else

        av_assert0(0);

    avctx->extradata= extradata;

    s->use_exp_vlc = flags2 & 0x0001;

    s->use_bit_reservoir = flags2 & 0x0002;

    s->use_variable_block_len = flags2 & 0x0004;

    if (avctx->channels == 2)

        s->ms_stereo = 1;

    ff_wma_init(avctx, flags2);

    /* init MDCT */

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

        ff_mdct_init(&s->mdct_ctx[i], s->frame_len_bits - i + 1, 0, 1.0);

    s->block_align     = avctx->bit_rate * (int64_t)s->frame_len /

                         (avctx->sample_rate * 8);

    s->block_align     = FFMIN(s->block_align, MAX_CODED_SUPERFRAME_SIZE);

    avctx->block_align = s->block_align;

    avctx->bit_rate    = avctx->block_align * 8LL * avctx->sample_rate /

                         s->frame_len;

//av_log(NULL, AV_LOG_ERROR, "%d %d %d %d\n", s->block_align, avctx->bit_rate, s->frame_len, avctx->sample_rate);

    avctx->frame_size = avctx->delay = s->frame_len;

#if FF_API_OLD_ENCODE_AUDIO

    avctx->coded_frame = &s->frame;

    avcodec_get_frame_defaults(avctx->coded_frame);

#endif

    return 0;

}


START_TEST(float_number)

{

    int i;

    struct {

        const char *encoded;

        double decoded;

        int skip;

    } test_cases[] = {

        { "32.43", 32.43 },

        { "0.222", 0.222 },

        { "-32.12313", -32.12313 },

        { "-32.20e-10", -32.20e-10, .skip = 1 },

        { },

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QFloat *qfloat;

        obj = qobject_from_json(test_cases[i].encoded);

        fail_unless(obj != NULL);

        fail_unless(qobject_type(obj) == QTYPE_QFLOAT);

        qfloat = qobject_to_qfloat(obj);

        fail_unless(qfloat_get_double(qfloat) == test_cases[i].decoded);

        if (test_cases[i].skip == 0) {

            QString *str;

            str = qobject_to_json(obj);

            fail_unless(strcmp(qstring_get_str(str), test_cases[i].encoded) == 0);

            QDECREF(str);

        }

        QDECREF(qfloat);

    }

}


static void check_watchpoint(int offset, int len_mask, int flags)

{

    CPUState *env = cpu_single_env;

    target_ulong pc, cs_base;

    TranslationBlock *tb;

    target_ulong vaddr;

    CPUWatchpoint *wp;

    int cpu_flags;

    if (env->watchpoint_hit) {

        /* We re-entered the check after replacing the TB. Now raise

         * the debug interrupt so that is will trigger after the

         * current instruction. */

        cpu_interrupt(env, CPU_INTERRUPT_DEBUG);

        return;

    }

    vaddr = (env->mem_io_vaddr & TARGET_PAGE_MASK) + offset;

    QTAILQ_FOREACH(wp, &env->watchpoints, entry) {

        if ((vaddr == (wp->vaddr & len_mask) ||

             (vaddr & wp->len_mask) == wp->vaddr) && (wp->flags & flags)) {

            wp->flags |= BP_WATCHPOINT_HIT;

            if (!env->watchpoint_hit) {

                env->watchpoint_hit = wp;

                tb = tb_find_pc(env->mem_io_pc);

                if (!tb) {

                    cpu_abort(env, "check_watchpoint: could not find TB for "

                              "pc=%p", (void *)env->mem_io_pc);

                }

                cpu_restore_state(tb, env, env->mem_io_pc);

                tb_phys_invalidate(tb, -1);

                if (wp->flags & BP_STOP_BEFORE_ACCESS) {

                    env->exception_index = EXCP_DEBUG;

                } else {

                    cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags);

                    tb_gen_code(env, pc, cs_base, cpu_flags, 1);

                }

                cpu_resume_from_signal(env, NULL);

            }

        } else {

            wp->flags &= ~BP_WATCHPOINT_HIT;

        }

    }

}


static gboolean gd_vc_in(GIOChannel *chan, GIOCondition cond, void *opaque)

{

    VirtualConsole *vc = opaque;

    uint8_t buffer[1024];

    ssize_t len;

    len = read(vc->fd, buffer, sizeof(buffer));

    if (len <= 0) {

        return FALSE;

    }

    qemu_chr_be_write(vc->chr, buffer, len);

    return TRUE;

}


void ff_aac_search_for_is(AACEncContext *s, AVCodecContext *avctx, ChannelElement *cpe)

{

    SingleChannelElement *sce0 = &cpe->ch[0];

    SingleChannelElement *sce1 = &cpe->ch[1];

    int start = 0, count = 0, w, w2, g, i, prev_sf1 = -1;

    const float freq_mult = avctx->sample_rate/(1024.0f/sce0->ics.num_windows)/2.0f;

    uint8_t nextband1[128];

    if (!cpe->common_window)

        return;

    /** Scout out next nonzero bands */

    ff_init_nextband_map(sce1, nextband1);

    for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {

        start = 0;

        for (g = 0;  g < sce0->ics.num_swb; g++) {

            if (start*freq_mult > INT_STEREO_LOW_LIMIT*(s->lambda/170.0f) &&

                cpe->ch[0].band_type[w*16+g] != NOISE_BT && !cpe->ch[0].zeroes[w*16+g] &&

                cpe->ch[1].band_type[w*16+g] != NOISE_BT && !cpe->ch[1].zeroes[w*16+g] &&

                ff_sfdelta_can_remove_band(sce1, nextband1, prev_sf1, w*16+g)) {

                float ener0 = 0.0f, ener1 = 0.0f, ener01 = 0.0f, ener01p = 0.0f;

                struct AACISError ph_err1, ph_err2, *best;

                if (sce0->band_type[w*16+g] == NOISE_BT ||

                    sce1->band_type[w*16+g] == NOISE_BT) {

                    start += sce0->ics.swb_sizes[g];

                    continue;

                }

                for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {

                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {

                        float coef0 = fabsf(sce0->coeffs[start+(w+w2)*128+i]);

                        float coef1 = fabsf(sce1->coeffs[start+(w+w2)*128+i]);

                        ener0  += coef0*coef0;

                        ener1  += coef1*coef1;

                        ener01 += (coef0 + coef1)*(coef0 + coef1);

                        ener01p += (coef0 - coef1)*(coef0 - coef1);

                    }

                }

                ph_err1 = ff_aac_is_encoding_err(s, cpe, start, w, g,

                                                 ener0, ener1, ener01p, 0, -1);

                ph_err2 = ff_aac_is_encoding_err(s, cpe, start, w, g,

                                                 ener0, ener1, ener01, 0, +1);

                best = (ph_err1.pass && ph_err1.error < ph_err2.error) ? &ph_err1 : &ph_err2;

                if (best->pass) {

                    cpe->is_mask[w*16+g] = 1;

                    cpe->ms_mask[w*16+g] = 0;

                    cpe->ch[0].is_ener[w*16+g] = sqrt(ener0 / best->ener01);

                    cpe->ch[1].is_ener[w*16+g] = ener0/ener1;

                    cpe->ch[1].band_type[w*16+g] = (best->phase > 0) ? INTENSITY_BT : INTENSITY_BT2;

                    count++;

                }

            }

            if (!sce1->zeroes[w*16+g] && sce1->band_type[w*16+g] < RESERVED_BT)

                prev_sf1 = sce1->sf_idx[w*16+g];

            start += sce0->ics.swb_sizes[g];

        }

    }

    cpe->is_mode = !!count;

}


static void vnc_write_s32(VncState *vs, int32_t value)

{

    vnc_write_u32(vs, *(uint32_t *)&value);

}


static int vnc_zlib_stop(VncState *vs)

{

    z_streamp zstream = &vs->zlib_stream;

    int previous_out;

    // switch back to normal output/zlib buffers

    vs->zlib = vs->output;

    vs->output = vs->zlib_tmp;

    // compress the zlib buffer

    // initialize the stream

    // XXX need one stream per session

    if (zstream->opaque != vs) {

        int err;

        VNC_DEBUG("VNC: initializing zlib stream\n");

        VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);

        zstream->zalloc = vnc_zlib_zalloc;

        zstream->zfree = vnc_zlib_zfree;

        err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,

                           MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);

        if (err != Z_OK) {

            fprintf(stderr, "VNC: error initializing zlib\n");

            return -1;

        }

        vs->zlib_level = vs->tight_compression;

        zstream->opaque = vs;

    }

    if (vs->tight_compression != vs->zlib_level) {

        if (deflateParams(zstream, vs->tight_compression,

                          Z_DEFAULT_STRATEGY) != Z_OK) {

            return -1;

        }

        vs->zlib_level = vs->tight_compression;

    }

    // reserve memory in output buffer

    buffer_reserve(&vs->output, vs->zlib.offset + 64);

    // set pointers

    zstream->next_in = vs->zlib.buffer;

    zstream->avail_in = vs->zlib.offset;

    zstream->next_out = vs->output.buffer + vs->output.offset;

    zstream->avail_out = vs->output.capacity - vs->output.offset;

    zstream->data_type = Z_BINARY;

    previous_out = zstream->total_out;

    // start encoding

    if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {

        fprintf(stderr, "VNC: error during zlib compression\n");

        return -1;

    }

    vs->output.offset = vs->output.capacity - zstream->avail_out;

    return zstream->total_out - previous_out;

}


static int ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band, IVITile *tile,
                             AVCodecContext *avctx)
{
    int         mbn, blk, num_blocks, num_coeffs, blk_size, scan_pos, run, val,
                pos, is_intra, mc_type = 0, mv_x, mv_y, col_mask;
    uint8_t     col_flags[8];
    int32_t     prev_dc, trvec[64];
    uint32_t    cbp, sym, lo, hi, quant, buf_offs, q;
    IVIMbInfo   *mb;
    RVMapDesc   *rvmap = band->rv_map;
    void (*mc_with_delta_func)(int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type);
    void (*mc_no_delta_func)  (int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type);
    const uint16_t  *base_tab;
    const uint8_t   *scale_tab;
    prev_dc = 0; /* init intra prediction for the DC coefficient */
    blk_size   = band->blk_size;
    col_mask   = blk_size - 1; /* column mask for tracking non-zero coeffs */
    num_blocks = (band->mb_size != blk_size) ? 4 : 1; /* number of blocks per mb */
    num_coeffs = blk_size * blk_size;
    if (blk_size == 8) {
        mc_with_delta_func = ff_ivi_mc_8x8_delta;
        mc_no_delta_func   = ff_ivi_mc_8x8_no_delta;
    } else {
        mc_with_delta_func = ff_ivi_mc_4x4_delta;
        mc_no_delta_func   = ff_ivi_mc_4x4_no_delta;
    for (mbn = 0, mb = tile->mbs; mbn < tile->num_MBs; mb++, mbn++) {
        is_intra = !mb->type;
        cbp      = mb->cbp;
        buf_offs = mb->buf_offs;
        quant = av_clip(band->glob_quant + mb->q_delta, 0, 23);
        base_tab  = is_intra ? band->intra_base  : band->inter_base;
        scale_tab = is_intra ? band->intra_scale : band->inter_scale;
        if (scale_tab)
            quant = scale_tab[quant];
        if (!is_intra) {
            mv_x = mb->mv_x;
            mv_y = mb->mv_y;
            if (band->is_halfpel) {
                mc_type = ((mv_y & 1) << 1) | (mv_x & 1);
                mv_x >>= 1;
                mv_y >>= 1; /* convert halfpel vectors into fullpel ones */
            if (mb->type) {
                int dmv_x, dmv_y, cx, cy;
                dmv_x = mb->mv_x >> band->is_halfpel;
                dmv_y = mb->mv_y >> band->is_halfpel;
                cx    = mb->mv_x &  band->is_halfpel;
                cy    = mb->mv_y &  band->is_halfpel;
                if (   mb->xpos + dmv_x < 0
                    || mb->xpos + dmv_x + band->mb_size + cx > band->pitch
                    || mb->ypos + dmv_y < 0
                    || mb->ypos + dmv_y + band->mb_size + cy > band->aheight) {
        for (blk = 0; blk < num_blocks; blk++) {
            /* adjust block position in the buffer according to its number */
            if (blk & 1) {
                buf_offs += blk_size;
            } else if (blk == 2) {
                buf_offs -= blk_size;
                buf_offs += blk_size * band->pitch;
            if (cbp & 1) { /* block coded ? */
                scan_pos = -1;
                memset(trvec, 0, num_coeffs*sizeof(trvec[0])); /* zero transform vector */
                memset(col_flags, 0, sizeof(col_flags));      /* zero column flags */
                while (scan_pos <= num_coeffs) {
                    sym = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1);
                    if (sym == rvmap->eob_sym)
                        break; /* End of block */
                    if (sym == rvmap->esc_sym) { /* Escape - run/val explicitly coded using 3 vlc codes */
                        run = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1) + 1;
                        lo  = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1);
                        hi  = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1);
                        val = IVI_TOSIGNED((hi << 6) | lo); /* merge them and convert into signed val */
                    } else {
                        if (sym >= 256U) {
                            av_log(avctx, AV_LOG_ERROR, "Invalid sym encountered: %d.\n", sym);
                            return -1;
                        run = rvmap->runtab[sym];
                        val = rvmap->valtab[sym];
                    /* de-zigzag and dequantize */
                    scan_pos += run;
                    if (scan_pos >= num_coeffs)
                        break;
                    pos = band->scan[scan_pos];
                    if (!val)
                        av_dlog(avctx, "Val = 0 encountered!\n");
                    q = (base_tab[pos] * quant) >> 9;
                    if (q > 1)
                        val = val * q + FFSIGN(val) * (((q ^ 1) - 1) >> 1);
                    trvec[pos] = val;
                    col_flags[pos & col_mask] |= !!val; /* track columns containing non-zero coeffs */
                }// while
                if (scan_pos >= num_coeffs && sym != rvmap->eob_sym)
                    return -1; /* corrupt block data */
                /* undoing DC coeff prediction for intra-blocks */
                if (is_intra && band->is_2d_trans) {
                    prev_dc      += trvec[0];
                    trvec[0]      = prev_dc;
                    col_flags[0] |= !!prev_dc;
                /* apply inverse transform */
                band->inv_transform(trvec, band->buf + buf_offs,
                                    band->pitch, col_flags);
                /* apply motion compensation */
                if (!is_intra)
                    mc_with_delta_func(band->buf + buf_offs,
                                       band->ref_buf + buf_offs + mv_y * band->pitch + mv_x,
                                       band->pitch, mc_type);
            } else {
                /* block not coded */
                /* for intra blocks apply the dc slant transform */
                /* for inter - perform the motion compensation without delta */
                if (is_intra && band->dc_transform) {
                    band->dc_transform(&prev_dc, band->buf + buf_offs,
                                       band->pitch, blk_size);
                } else
                    mc_no_delta_func(band->buf + buf_offs,
                                     band->ref_buf + buf_offs + mv_y * band->pitch + mv_x,
                                     band->pitch, mc_type);
            cbp >>= 1;
        }// for blk
    }// for mbn
    align_get_bits(gb);
    return 0;


static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)

{

    int byte_align = get_bits1(gb);

    int count = get_bits(gb, 8);

    if (count == 255)

        count += get_bits(gb, 8);

    if (byte_align)

        align_get_bits(gb);

    if (get_bits_left(gb) < 8 * count) {

        av_log(ac->avctx, AV_LOG_ERROR, overread_err);

        return -1;

    }

    skip_bits_long(gb, 8 * count);

    return 0;

}


static int filter_frame(AVFilterLink *inlink, AVFrame *inbuf)

{

    AudioPhaserContext *s = inlink->dst->priv;

    AVFilterLink *outlink = inlink->dst->outputs[0];

    AVFrame *outbuf;

    if (av_frame_is_writable(inbuf)) {

        outbuf = inbuf;

    } else {

        outbuf = ff_get_audio_buffer(inlink, inbuf->nb_samples);

        if (!outbuf)

            return AVERROR(ENOMEM);

        av_frame_copy_props(outbuf, inbuf);

    }

    s->phaser(s, inbuf->extended_data, outbuf->extended_data,

              outbuf->nb_samples, outbuf->channels);

    if (inbuf != outbuf)

        av_frame_free(&inbuf);

    return ff_filter_frame(outlink, outbuf);

}


static AVStream *find_stream(void *log, AVFormatContext *avf, const char *spec)

{

    int i, ret, already = 0, stream_id = -1;

    char type_char, dummy;

    AVStream *found = NULL;

    enum AVMediaType type;

    ret = sscanf(spec, "d%[av]%d%c", &type_char, &stream_id, &dummy);

    if (ret >= 1 && ret <= 2) {

        type = type_char == 'v' ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;

        ret = av_find_best_stream(avf, type, stream_id, -1, NULL, 0);

        if (ret < 0) {

            av_log(log, AV_LOG_ERROR, "No %s stream with index '%d' found\n",

                   av_get_media_type_string(type), stream_id);

            return NULL;

        }

        return avf->streams[ret];

    }

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

        ret = avformat_match_stream_specifier(avf, avf->streams[i], spec);

        if (ret < 0) {

            av_log(log, AV_LOG_ERROR,

                   "Invalid stream specifier \"%s\"\n", spec);

            return NULL;

        }

        if (!ret)

            continue;

        if (avf->streams[i]->discard != AVDISCARD_ALL) {

            already++;

            continue;

        }

        if (found) {

            av_log(log, AV_LOG_WARNING,

                   "Ambiguous stream specifier \"%s\", using #%d\n", spec, i);

            break;

        }

        found = avf->streams[i];

    }

    if (!found) {

        av_log(log, AV_LOG_WARNING, "Stream specifier \"%s\" %s\n", spec,

               already ? "matched only already used streams" :

                         "did not match any stream");

        return NULL;

    }

    if (found->codec->codec_type != AVMEDIA_TYPE_VIDEO &&

        found->codec->codec_type != AVMEDIA_TYPE_AUDIO) {

        av_log(log, AV_LOG_ERROR, "Stream specifier \"%s\" matched a %s stream,"

               "currently unsupported by libavfilter\n", spec,

               av_get_media_type_string(found->codec->codec_type));

        return NULL;

    }

    return found;

}


static void check_rgb2yuv(void)

{

    declare_func(void, uint8_t *dst[3], ptrdiff_t dst_stride[3],

                 int16_t *src[3], ptrdiff_t src_stride,

                 int w, int h, const int16_t coeff[3][3][8],

                 const int16_t off[8]);

    ColorSpaceDSPContext dsp;

    int odepth, fmt, n;

    LOCAL_ALIGNED_32(int16_t, src_y, [W * H * 2]);

    LOCAL_ALIGNED_32(int16_t, src_u, [W * H * 2]);

    LOCAL_ALIGNED_32(int16_t, src_v, [W * H * 2]);

    int16_t *src[3] = { src_y, src_u, src_v };

    LOCAL_ALIGNED_32(uint8_t, dst0_y, [W * H]);

    LOCAL_ALIGNED_32(uint8_t, dst0_u, [W * H]);

    LOCAL_ALIGNED_32(uint8_t, dst0_v, [W * H]);

    LOCAL_ALIGNED_32(uint8_t, dst1_y, [W * H]);

    LOCAL_ALIGNED_32(uint8_t, dst1_u, [W * H]);

    LOCAL_ALIGNED_32(uint8_t, dst1_v, [W * H]);

    uint8_t *dst0[3] = { dst0_y, dst0_u, dst0_v }, *dst1[3] = { dst1_y, dst1_u, dst1_v };

    LOCAL_ALIGNED_32(int16_t, offset, [8]);

    LOCAL_ALIGNED_32(int16_t, coeff_buf, [3 * 3 * 8]);

    int16_t (*coeff)[3][8] = (int16_t(*)[3][8]) coeff_buf;

    ff_colorspacedsp_init(&dsp);

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

        offset[n] = 16;

        // these somewhat resemble bt601/smpte170m coefficients

        coeff[0][0][n] = lrint(0.3 * (1 << 14));

        coeff[0][1][n] = lrint(0.6 * (1 << 14));

        coeff[0][2][n] = lrint(0.1 * (1 << 14));

        coeff[1][0][n] = lrint(-0.15 * (1 << 14));

        coeff[1][1][n] = lrint(-0.35 * (1 << 14));

        coeff[1][2][n] = lrint(0.5 * (1 << 14));

        coeff[2][0][n] = lrint(0.5 * (1 << 14));

        coeff[2][1][n] = lrint(-0.42 * (1 << 14));

        coeff[2][2][n] = lrint(-0.08 * (1 << 14));

    }

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

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

            if (check_func(dsp.rgb2yuv[odepth][fmt],

                           "ff_colorspacedsp_rgb2yuv_%sp%d",

                           format_string[fmt], odepth * 2 + 8)) {

                int ss_w = !!fmt, ss_h = fmt == 2;

                int y_dst_stride = W << !!odepth;

                int uv_dst_stride = y_dst_stride >> ss_w;

                randomize_buffers();

                call_ref(dst0, (ptrdiff_t[3]) { y_dst_stride, uv_dst_stride, uv_dst_stride },

                         src, W, W, H, coeff, offset);

                call_new(dst1, (ptrdiff_t[3]) { y_dst_stride, uv_dst_stride, uv_dst_stride },

                         src, W, W, H, coeff, offset);

                if (memcmp(dst0[0], dst1[0], H * y_dst_stride) ||

                    memcmp(dst0[1], dst1[1], H * uv_dst_stride >> ss_h) ||

                    memcmp(dst0[2], dst1[2], H * uv_dst_stride >> ss_h)) {

                    fail();

                }

            }

        }

    }

    report("rgb2yuv");

}


flac_header (AVFormatContext * s, int idx)

{

    struct ogg *ogg = s->priv_data;

    struct ogg_stream *os = ogg->streams + idx;

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

    GetBitContext gb;

    FLACStreaminfo si;

    int mdt;

    if (os->buf[os->pstart] == 0xff)

        return 0;

    init_get_bits(&gb, os->buf + os->pstart, os->psize*8);

    skip_bits1(&gb); /* metadata_last */

    mdt = get_bits(&gb, 7);

    if (mdt == OGG_FLAC_METADATA_TYPE_STREAMINFO) {

        uint8_t *streaminfo_start = os->buf + os->pstart + 5 + 4 + 4 + 4;

        skip_bits_long(&gb, 4*8); /* "FLAC" */

        if(get_bits(&gb, 8) != 1) /* unsupported major version */

            return -1;

        skip_bits_long(&gb, 8 + 16); /* minor version + header count */

        skip_bits_long(&gb, 4*8); /* "fLaC" */

        /* METADATA_BLOCK_HEADER */

        if (get_bits_long(&gb, 32) != FLAC_STREAMINFO_SIZE)

            return -1;

        avpriv_flac_parse_streaminfo(st->codec, &si, streaminfo_start);

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_id = AV_CODEC_ID_FLAC;

        st->need_parsing = AVSTREAM_PARSE_HEADERS;

        ff_alloc_extradata(st->codec, FLAC_STREAMINFO_SIZE);

        memcpy(st->codec->extradata, streaminfo_start, st->codec->extradata_size);

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

    } else if (mdt == FLAC_METADATA_TYPE_VORBIS_COMMENT) {

        ff_vorbis_comment (s, &st->metadata, os->buf + os->pstart + 4, os->psize - 4);

    }

    return 1;

}


void acpi_memory_plug_cb(ACPIREGS *ar, qemu_irq irq, MemHotplugState *mem_st,

                         DeviceState *dev, Error **errp)

{

    MemStatus *mdev;

    mdev = acpi_memory_slot_status(mem_st, dev, errp);

    if (!mdev) {

        return;

    }

    mdev->dimm = dev;

    mdev->is_enabled = true;

    mdev->is_inserting = true;

    /* do ACPI magic */

    acpi_send_gpe_event(ar, irq, ACPI_MEMORY_HOTPLUG_STATUS);

    return;

}


static int decode_i_picture_header(VC9Context *v)

{

  int pqindex, status = 0, ac_pred, condover;

    /* Prolog common to all frametypes should be done in caller */

    //BF = Buffer Fullness

    if (v->profile <= PROFILE_MAIN && get_bits(&v->gb, 7))

    {

        av_log(v, AV_LOG_DEBUG, "I BufferFullness not 0\n");

    }

    /* Quantizer stuff */

    pqindex = get_bits(&v->gb, 5);

    if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)

        v->pq = pquant_table[0][pqindex];

    else

    {

        v->pq = pquant_table[v->quantizer_mode-1][pqindex];

    }

    if (pqindex < 9) v->halfpq = get_bits(&v->gb, 1);

    if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)

        v->pquantizer = get_bits(&v->gb, 1);

    av_log(v->avctx, AV_LOG_DEBUG, "I frame: QP=%i (+%i/2)\n",

           v->pq, v->halfpq);

#if HAS_ADVANCED_PROFILE

    if (v->profile <= PROFILE_MAIN)

#endif

    {

        if (v->extended_mv) v->mvrange = get_prefix(&v->gb, 0, 3);

        if (v->multires) v->respic = get_bits(&v->gb, 2);

    }

#if HAS_ADVANCED_PROFILE

    else

    {

        ac_pred = get_bits(&v->gb, 1);

        if (v->postprocflag) v->postproc = get_bits(&v->gb, 1);

        /* 7.1.1.34 + 8.5.2 */

        if (v->overlap && v->pq<9)

        {

            condover = get_bits(&v->gb, 1);

            if (condover)

            {

                condover = 2+get_bits(&v->gb, 1);

                if (condover == 3)

                    status = bitplane_decoding(v->over_flags_plane,

                                                   v->width_mb, v->height_mb, v);

            }

        }

    }

#endif

    /* Epilog should be done in caller */

    return status;

}


static int vtd_page_walk(VTDContextEntry *ce, uint64_t start, uint64_t end,

                         vtd_page_walk_hook hook_fn, void *private)

{

    dma_addr_t addr = vtd_get_slpt_base_from_context(ce);

    uint32_t level = vtd_get_level_from_context_entry(ce);

    if (!vtd_iova_range_check(start, ce)) {

        return -VTD_FR_ADDR_BEYOND_MGAW;

    }

    if (!vtd_iova_range_check(end, ce)) {

        /* Fix end so that it reaches the maximum */

        end = vtd_iova_limit(ce);

    }

    return vtd_page_walk_level(addr, start, end, hook_fn, private,

                               level, true, true, false);

}


static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,

                                         int64_t sector_num, int nb_sectors,

                                         QEMUIOVector *iov)

{

    return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);

}


static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)

{

    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);

    int32_t len;

    uint8_t command;

    uint8_t *outbuf;

    int rc;

    command = buf[0];

    outbuf = (uint8_t *)r->iov.iov_base;

    DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", req->lun, req->tag, buf[0]);

    if (scsi_req_parse(&r->req, buf) != 0) {

        BADF("Unsupported command length, command %x\n", command);

        scsi_command_complete(r, CHECK_CONDITION, SENSE_CODE(INVALID_OPCODE));

        return 0;

    }

#ifdef DEBUG_SCSI

    {

        int i;

        for (i = 1; i < r->req.cmd.len; i++) {

            printf(" 0x%02x", buf[i]);

        }

        printf("\n");

    }

#endif

    if (req->lun) {

        /* Only LUN 0 supported.  */

        DPRINTF("Unimplemented LUN %d\n", req->lun);

        if (command != REQUEST_SENSE && command != INQUIRY) {

            scsi_command_complete(r, CHECK_CONDITION,

                                  SENSE_CODE(LUN_NOT_SUPPORTED));

            return 0;

        }

    }

    switch (command) {

    case TEST_UNIT_READY:

    case REQUEST_SENSE:

    case INQUIRY:

    case MODE_SENSE:

    case MODE_SENSE_10:

    case RESERVE:

    case RESERVE_10:

    case RELEASE:

    case RELEASE_10:

    case START_STOP:

    case ALLOW_MEDIUM_REMOVAL:

    case READ_CAPACITY:

    case SYNCHRONIZE_CACHE:

    case READ_TOC:

    case GET_CONFIGURATION:

    case SERVICE_ACTION_IN:

    case REPORT_LUNS:

    case VERIFY:

        rc = scsi_disk_emulate_command(r, outbuf);

        if (rc < 0) {

            return 0;

        }

        r->iov.iov_len = rc;

        break;

    case READ_6:

    case READ_10:

    case READ_12:

    case READ_16:

        len = r->req.cmd.xfer / s->qdev.blocksize;

        DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len);

        if (r->req.cmd.lba > s->max_lba)

            goto illegal_lba;

        r->sector = r->req.cmd.lba * s->cluster_size;

        r->sector_count = len * s->cluster_size;

        break;

    case WRITE_6:

    case WRITE_10:

    case WRITE_12:

    case WRITE_16:

    case WRITE_VERIFY:

    case WRITE_VERIFY_12:

    case WRITE_VERIFY_16:

        len = r->req.cmd.xfer / s->qdev.blocksize;

        DPRINTF("Write %s(sector %" PRId64 ", count %d)\n",

                (command & 0xe) == 0xe ? "And Verify " : "",

                r->req.cmd.lba, len);

        if (r->req.cmd.lba > s->max_lba)

            goto illegal_lba;

        r->sector = r->req.cmd.lba * s->cluster_size;

        r->sector_count = len * s->cluster_size;

        break;

    case MODE_SELECT:

        DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);

        /* We don't support mode parameter changes.

           Allow the mode parameter header + block descriptors only. */

        if (r->req.cmd.xfer > 12) {

            goto fail;

        }

        break;

    case MODE_SELECT_10:

        DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);

        /* We don't support mode parameter changes.

           Allow the mode parameter header + block descriptors only. */

        if (r->req.cmd.xfer > 16) {

            goto fail;

        }

        break;

    case SEEK_6:

    case SEEK_10:

        DPRINTF("Seek(%d) (sector %" PRId64 ")\n", command == SEEK_6 ? 6 : 10,

                r->req.cmd.lba);

        if (r->req.cmd.lba > s->max_lba) {

            goto illegal_lba;

        }

        break;

    case WRITE_SAME_16:

        len = r->req.cmd.xfer / s->qdev.blocksize;

        DPRINTF("WRITE SAME(16) (sector %" PRId64 ", count %d)\n",

                r->req.cmd.lba, len);

        if (r->req.cmd.lba > s->max_lba) {

            goto illegal_lba;

        }

        /*

         * We only support WRITE SAME with the unmap bit set for now.

         */

        if (!(buf[1] & 0x8)) {

            goto fail;

        }

        rc = bdrv_discard(s->bs, r->req.cmd.lba * s->cluster_size,

                          len * s->cluster_size);

        if (rc < 0) {

            /* XXX: better error code ?*/

            goto fail;

        }

        break;

    default:

        DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);

        scsi_command_complete(r, CHECK_CONDITION, SENSE_CODE(INVALID_OPCODE));

        return 0;

    fail:

        scsi_command_complete(r, CHECK_CONDITION, SENSE_CODE(INVALID_FIELD));

        return 0;

    illegal_lba:

        scsi_command_complete(r, CHECK_CONDITION, SENSE_CODE(LBA_OUT_OF_RANGE));

        return 0;

    }

    if (r->sector_count == 0 && r->iov.iov_len == 0) {

        scsi_command_complete(r, GOOD, SENSE_CODE(NO_SENSE));

    }

    len = r->sector_count * 512 + r->iov.iov_len;

    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {

        return -len;

    } else {

        if (!r->sector_count)

            r->sector_count = -1;

        return len;

    }

}


static int wav_init_out (HWVoiceOut *hw, struct audsettings *as)

{

    WAVVoiceOut *wav = (WAVVoiceOut *) hw;

    int bits16 = 0, stereo = 0;

    uint8_t hdr[] = {

        0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x41, 0x56,

        0x45, 0x66, 0x6d, 0x74, 0x20, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00,

        0x02, 0x00, 0x44, 0xac, 0x00, 0x00, 0x10, 0xb1, 0x02, 0x00, 0x04,

        0x00, 0x10, 0x00, 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00

    };

    struct audsettings wav_as = conf.settings;

    (void) as;

    stereo = wav_as.nchannels == 2;

    switch (wav_as.fmt) {

    case AUD_FMT_S8:

    case AUD_FMT_U8:

        bits16 = 0;

        break;

    case AUD_FMT_S16:

    case AUD_FMT_U16:

        bits16 = 1;

        break;

    case AUD_FMT_S32:

    case AUD_FMT_U32:

        dolog ("WAVE files can not handle 32bit formats\n");

        return -1;

    }

    hdr[34] = bits16 ? 0x10 : 0x08;

    wav_as.endianness = 0;

    audio_pcm_init_info (&hw->info, &wav_as);

    hw->samples = 1024;

    wav->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);

    if (!wav->pcm_buf) {

        dolog ("Could not allocate buffer (%d bytes)\n",

               hw->samples << hw->info.shift);

        return -1;

    }

    le_store (hdr + 22, hw->info.nchannels, 2);

    le_store (hdr + 24, hw->info.freq, 4);

    le_store (hdr + 28, hw->info.freq << (bits16 + stereo), 4);

    le_store (hdr + 32, 1 << (bits16 + stereo), 2);

    wav->f = fopen (conf.wav_path, "wb");

    if (!wav->f) {

        dolog ("Failed to open wave file `%s'\nReason: %s\n",

               conf.wav_path, strerror (errno));

        g_free (wav->pcm_buf);

        wav->pcm_buf = NULL;

        return -1;

    }

    if (fwrite (hdr, sizeof (hdr), 1, wav->f) != 1) {

        dolog ("wav_init_out: failed to write header\nReason: %s\n",

               strerror(errno));

        return -1;

    }

    return 0;

}


static char *time_value_string(char *buf, int buf_size, int64_t val, const AVRational *time_base)

{

    if (val == AV_NOPTS_VALUE) {

        snprintf(buf, buf_size, "N/A");

    } else {

        double d = val * av_q2d(*time_base);

        value_string(buf, buf_size, (struct unit_value){.val.d=d, .unit=unit_second_str});

    }

    return buf;

}


static void t_gen_cc_jmp(TCGv pc_true, TCGv pc_false)

{

	TCGv btaken;

	int l1;

	l1 = gen_new_label();

	btaken = tcg_temp_new(TCG_TYPE_TL);

	/* Conditional jmp.  */

	tcg_gen_mov_tl(btaken, env_btaken);

	tcg_gen_mov_tl(env_pc, pc_false);

	tcg_gen_brcondi_tl(TCG_COND_EQ, btaken, 0, l1);

	tcg_gen_mov_tl(env_pc, pc_true);

	gen_set_label(l1);

	tcg_temp_free(btaken);

}


NBDClient *nbd_client_new(NBDExport *exp, int csock,

                          void (*close)(NBDClient *))

{

    NBDClient *client;

    client = g_malloc0(sizeof(NBDClient));

    client->refcount = 1;

    client->exp = exp;

    client->sock = csock;

    if (nbd_send_negotiate(client)) {

        g_free(client);

        return NULL;

    }

    client->close = close;

    qemu_co_mutex_init(&client->send_lock);

    qemu_set_fd_handler2(csock, nbd_can_read, nbd_read, NULL, client);

    if (exp) {

        QTAILQ_INSERT_TAIL(&exp->clients, client, next);

        nbd_export_get(exp);

    }

    return client;

}


void helper_ljmp_protected_T0_T1(void)

{

    int new_cs, new_eip;

    uint32_t e1, e2, cpl, dpl, rpl, limit;

    new_cs = T0;

    new_eip = T1;

    if ((new_cs & 0xfffc) == 0)

        raise_exception_err(EXCP0D_GPF, 0);

    if (load_segment(&e1, &e2, new_cs) != 0)

        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

    cpl = env->hflags & HF_CPL_MASK;

    if (e2 & DESC_S_MASK) {

        if (!(e2 & DESC_CS_MASK))

            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

        dpl = (e2 >> DESC_DPL_SHIFT) & 3;

        if (e2 & DESC_CS_MASK) {

            /* conforming code segment */

            if (dpl > cpl)

                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

        } else {

            /* non conforming code segment */

            rpl = new_cs & 3;

            if (rpl > cpl)

                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

            if (dpl != cpl)

                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

        }

        if (!(e2 & DESC_P_MASK))

            raise_exception_err(EXCP0B_NOSEG, new_cs & 0xfffc);

        limit = get_seg_limit(e1, e2);

        if (new_eip > limit)

            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

        cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,

                       get_seg_base(e1, e2), limit, e2);

        EIP = new_eip;

    } else {

        cpu_abort(env, "jmp to call/task gate not supported 0x%04x:0x%08x",

                  new_cs, new_eip);

    }

}


static int read_sbr_single_channel_element(AACContext *ac,

                                            SpectralBandReplication *sbr,

                                            GetBitContext *gb)

{

    int ret;

    if (get_bits1(gb)) // bs_data_extra

        skip_bits(gb, 4); // bs_reserved

    if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))

        return -1;

    read_sbr_dtdf(sbr, gb, &sbr->data[0]);

    read_sbr_invf(sbr, gb, &sbr->data[0]);

    read_sbr_envelope(sbr, gb, &sbr->data[0], 0);

    if((ret = read_sbr_noise(ac, sbr, gb, &sbr->data[0], 0)) < 0)

        return ret;

    if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb)))

        get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]);

    return 0;

}


const char *swscale_configuration(void)

{

    return FFMPEG_CONFIGURATION;

}


static inline void RENAME(duplicate)(uint8_t src[], int stride)

{

#if TEMPLATE_PP_MMX

    __asm__ volatile(

        "movq (%0), %%mm0               \n\t"

        "add %1, %0                     \n\t"

        "movq %%mm0, (%0)               \n\t"

        "movq %%mm0, (%0, %1)           \n\t"

        "movq %%mm0, (%0, %1, 2)        \n\t"

        : "+r" (src)

        : "r" ((x86_reg)-stride)

    );

#else

    int i;

    uint8_t *p=src;

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

        p-= stride;

        memcpy(p, src, 8);

    }

#endif

}


static void RENAME(extract_even2)(const uint8_t *src, uint8_t *dst0, uint8_t *dst1, x86_reg count)

{

    dst0+=   count;

    dst1+=   count;

    src += 4*count;

    count= - count;

#if COMPILE_TEMPLATE_MMX

    if(count <= -8) {

        count += 7;

        __asm__ volatile(

            "pcmpeqw       %%mm7, %%mm7        \n\t"

            "psrlw            $8, %%mm7        \n\t"

            "1:                                \n\t"

            "movq -28(%1, %0, 4), %%mm0        \n\t"

            "movq -20(%1, %0, 4), %%mm1        \n\t"

            "movq -12(%1, %0, 4), %%mm2        \n\t"

            "movq  -4(%1, %0, 4), %%mm3        \n\t"

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

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

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

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

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

            "packuswb      %%mm3, %%mm2        \n\t"

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

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

            "psrlw            $8, %%mm0        \n\t"

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

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

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

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

            "packuswb      %%mm3, %%mm1        \n\t"

            MOVNTQ"        %%mm0,- 7(%3, %0)   \n\t"

            MOVNTQ"        %%mm1,- 7(%2, %0)   \n\t"

            "add              $8, %0           \n\t"

            " js 1b                            \n\t"

            : "+r"(count)

            : "r"(src), "r"(dst0), "r"(dst1)

        );

        count -= 7;

    }

#endif

    while(count<0) {

        dst0[count]= src[4*count+0];

        dst1[count]= src[4*count+2];

        count++;

    }

}


static void usb_xhci_exit(PCIDevice *dev)

{

    int i;

    XHCIState *xhci = XHCI(dev);

    trace_usb_xhci_exit();

    for (i = 0; i < xhci->numslots; i++) {

        xhci_disable_slot(xhci, i + 1);

    }

    if (xhci->mfwrap_timer) {

        timer_del(xhci->mfwrap_timer);

        timer_free(xhci->mfwrap_timer);

        xhci->mfwrap_timer = NULL;

    }

    memory_region_del_subregion(&xhci->mem, &xhci->mem_cap);

    memory_region_del_subregion(&xhci->mem, &xhci->mem_oper);

    memory_region_del_subregion(&xhci->mem, &xhci->mem_runtime);

    memory_region_del_subregion(&xhci->mem, &xhci->mem_doorbell);

    for (i = 0; i < xhci->numports; i++) {

        XHCIPort *port = &xhci->ports[i];

        memory_region_del_subregion(&xhci->mem, &port->mem);

    }

    /* destroy msix memory region */

    if (dev->msix_table && dev->msix_pba

        && dev->msix_entry_used) {

        memory_region_del_subregion(&xhci->mem, &dev->msix_table_mmio);

        memory_region_del_subregion(&xhci->mem, &dev->msix_pba_mmio);

    }

    usb_bus_release(&xhci->bus);

}


static void evaluate_utility_inc(elbg_data *elbg)

{

    int i, inc=0;

    for (i=0; i < elbg->numCB; i++) {

        if (elbg->numCB*elbg->utility[i] > elbg->error)

            inc += elbg->utility[i];

        elbg->utility_inc[i] = inc;

    }

}


static void init_excp_POWER7 (CPUPPCState *env)

{

#if !defined(CONFIG_USER_ONLY)

    env->excp_vectors[POWERPC_EXCP_RESET]    = 0x00000100;

    env->excp_vectors[POWERPC_EXCP_MCHECK]   = 0x00000200;

    env->excp_vectors[POWERPC_EXCP_DSI]      = 0x00000300;

    env->excp_vectors[POWERPC_EXCP_DSEG]     = 0x00000380;

    env->excp_vectors[POWERPC_EXCP_ISI]      = 0x00000400;

    env->excp_vectors[POWERPC_EXCP_ISEG]     = 0x00000480;

    env->excp_vectors[POWERPC_EXCP_EXTERNAL] = 0x00000500;

    env->excp_vectors[POWERPC_EXCP_ALIGN]    = 0x00000600;

    env->excp_vectors[POWERPC_EXCP_PROGRAM]  = 0x00000700;

    env->excp_vectors[POWERPC_EXCP_FPU]      = 0x00000800;

    env->excp_vectors[POWERPC_EXCP_DECR]     = 0x00000900;

    env->excp_vectors[POWERPC_EXCP_HDECR]    = 0x00000980;

    env->excp_vectors[POWERPC_EXCP_SYSCALL]  = 0x00000C00;

    env->excp_vectors[POWERPC_EXCP_TRACE]    = 0x00000D00;

    env->excp_vectors[POWERPC_EXCP_PERFM]    = 0x00000F00;

    env->excp_vectors[POWERPC_EXCP_VPU]      = 0x00000F20;

    env->excp_vectors[POWERPC_EXCP_VSXU]     = 0x00000F40;

    env->excp_vectors[POWERPC_EXCP_FU]       = 0x00000F60;

    env->excp_vectors[POWERPC_EXCP_IABR]     = 0x00001300;

    env->excp_vectors[POWERPC_EXCP_MAINT]    = 0x00001600;

    env->excp_vectors[POWERPC_EXCP_VPUA]     = 0x00001700;

    env->excp_vectors[POWERPC_EXCP_THERM]    = 0x00001800;

    /* Hardware reset vector */

    env->hreset_vector = 0x0000000000000100ULL;

#endif

}


static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)

{

    MpegTSContext *ts = filter->u.section_filter.opaque;

    SectionHeader h1, *h = &h1;

    const uint8_t *p, *p_end, *desc_list_end, *desc_end;

    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;

    char *name, *provider_name;

    av_dlog(ts->stream, "SDT:\n");

    hex_dump_debug(ts->stream, section, section_len);

    p_end = section + section_len - 4;

    p     = section;

    if (parse_section_header(h, &p, p_end) < 0)

        return;

    if (h->tid != SDT_TID)

        return;

    if (ts->skip_changes)

        return;

    onid = get16(&p, p_end);

    if (onid < 0)

        return;

    val = get8(&p, p_end);

    if (val < 0)

        return;

    for (;;) {

        sid = get16(&p, p_end);

        if (sid < 0)

            break;

        val = get8(&p, p_end);

        if (val < 0)

            break;

        desc_list_len = get16(&p, p_end);

        if (desc_list_len < 0)

            break;

        desc_list_len &= 0xfff;

        desc_list_end  = p + desc_list_len;

        if (desc_list_end > p_end)

            break;

        for (;;) {

            desc_tag = get8(&p, desc_list_end);

            if (desc_tag < 0)

                break;

            desc_len = get8(&p, desc_list_end);

            desc_end = p + desc_len;

            if (desc_end > desc_list_end)

                break;

            av_dlog(ts->stream, "tag: 0x%02x len=%d\n",

                    desc_tag, desc_len);

            switch (desc_tag) {

            case 0x48:

                service_type = get8(&p, p_end);

                if (service_type < 0)

                    break;

                provider_name = getstr8(&p, p_end);

                if (!provider_name)

                    break;

                name = getstr8(&p, p_end);

                if (name) {

                    AVProgram *program = av_new_program(ts->stream, sid);

                    if (program) {

                        av_dict_set(&program->metadata, "service_name", name, 0);

                        av_dict_set(&program->metadata, "service_provider",

                                    provider_name, 0);

                    }

                }

                av_free(name);

                av_free(provider_name);

                break;

            default:

                break;

            }

            p = desc_end;

        }

        p = desc_list_end;

    }

}


static int socket_get_fd(void *opaque)

{

    QEMUFileSocket *s = opaque;

    return s->fd;

}


static int nppscale_query_formats(AVFilterContext *ctx)

{

    static const enum AVPixelFormat pixel_formats[] = {

        AV_PIX_FMT_CUDA, AV_PIX_FMT_NONE,

    };

    AVFilterFormats *pix_fmts  = ff_make_format_list(pixel_formats);

    ff_set_common_formats(ctx, pix_fmts);

    return 0;

}


static void delete_next_frame(AudioFrameQueue *afq)

{

    AudioFrame *f = afq->frame_queue;

    if (f) {

        afq->frame_queue = f->next;

        f->next = NULL;

        av_freep(&f);

    }

}


int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)

{

    f->owner = avctx;

    return ff_get_buffer(avctx, f->f, flags);

}


size_t qcrypto_cipher_get_key_len(QCryptoCipherAlgorithm alg)

{

    if (alg >= G_N_ELEMENTS(alg_key_len)) {

        return 0;

    }

    return alg_key_len[alg];

}


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

{

    int c, ret = 0;

    char *options = NULL;

    QemuOptsList *create_opts = NULL;

    QemuOpts *opts = NULL;

    const char *fmt = NULL, *filename, *cache;

    int flags;

    bool quiet = false, progress = false;

    BlockBackend *blk = NULL;

    BlockDriverState *bs = NULL;

    cache = BDRV_DEFAULT_CACHE;

    for (;;) {

        c = getopt(argc, argv, "ho:f:t:pq");

        if (c == -1) {

            break;

        }

        switch (c) {

            case 'h':

            case '?':

                help();

                break;

            case 'o':

                if (!is_valid_option_list(optarg)) {

                    error_report("Invalid option list: %s", optarg);

                    ret = -1;

                    goto out;

                }

                if (!options) {

                    options = g_strdup(optarg);

                } else {

                    char *old_options = options;

                    options = g_strdup_printf("%s,%s", options, optarg);

                    g_free(old_options);

                }

                break;

            case 'f':

                fmt = optarg;

                break;

            case 't':

                cache = optarg;

                break;

            case 'p':

                progress = true;

                break;

            case 'q':

                quiet = true;

                break;

        }

    }

    if (!options) {

        error_exit("Must specify options (-o)");

    }

    if (quiet) {

        progress = false;

    }

    qemu_progress_init(progress, 1.0);

    filename = (optind == argc - 1) ? argv[argc - 1] : NULL;

    if (fmt && has_help_option(options)) {

        /* If a format is explicitly specified (and possibly no filename is

         * given), print option help here */

        ret = print_block_option_help(filename, fmt);

        goto out;

    }

    if (optind != argc - 1) {

        error_report("Expecting one image file name");

        ret = -1;

        goto out;

    }

    flags = BDRV_O_FLAGS | BDRV_O_RDWR;

    ret = bdrv_parse_cache_flags(cache, &flags);

    if (ret < 0) {

        error_report("Invalid cache option: %s", cache);

        goto out;

    }

    blk = img_open("image", filename, fmt, flags, true, quiet);

    if (!blk) {

        ret = -1;

        goto out;

    }

    bs = blk_bs(blk);

    fmt = bs->drv->format_name;

    if (has_help_option(options)) {

        /* If the format was auto-detected, print option help here */

        ret = print_block_option_help(filename, fmt);

        goto out;

    }

    if (!bs->drv->create_opts) {

        error_report("Format driver '%s' does not support any options to amend",

                     fmt);

        ret = -1;

        goto out;

    }

    create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);

    opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);

    if (options && qemu_opts_do_parse(opts, options, NULL)) {

        error_report("Invalid options for file format '%s'", fmt);

        ret = -1;

        goto out;

    }

    /* In case the driver does not call amend_status_cb() */

    qemu_progress_print(0.f, 0);

    ret = bdrv_amend_options(bs, opts, &amend_status_cb);

    qemu_progress_print(100.f, 0);

    if (ret < 0) {

        error_report("Error while amending options: %s", strerror(-ret));

        goto out;

    }

out:

    qemu_progress_end();

    blk_unref(blk);

    qemu_opts_del(opts);

    qemu_opts_free(create_opts);

    g_free(options);

    if (ret) {

        return 1;

    }

    return 0;

}


static void channel_load_g(struct fs_dma_ctrl *ctrl, int c)

{

	target_phys_addr_t addr = channel_reg(ctrl, c, RW_GROUP);

	/* Load and decode. FIXME: handle endianness.  */

	cpu_physical_memory_read (addr,

				  (void *) &ctrl->channels[c].current_g,

				  sizeof ctrl->channels[c].current_g);

}


uint32_t HELPER(rer)(CPUXtensaState *env, uint32_t addr)

{

    return address_space_ldl(env->address_space_er, addr,

                             (MemTxAttrs){0}, NULL);

}


static void sun4uv_init(MemoryRegion *address_space_mem,

                        MachineState *machine,

                        const struct hwdef *hwdef)

{

    SPARCCPU *cpu;

    Nvram *nvram;

    unsigned int i;

    uint64_t initrd_addr, initrd_size, kernel_addr, kernel_size, kernel_entry;

    PCIBus *pci_bus, *pci_bus2, *pci_bus3;

    ISABus *isa_bus;

    SysBusDevice *s;

    qemu_irq *ivec_irqs, *pbm_irqs;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    DriveInfo *fd[MAX_FD];

    FWCfgState *fw_cfg;

    /* init CPUs */

    cpu = cpu_devinit(machine->cpu_model, hwdef);

    /* set up devices */

    ram_init(0, machine->ram_size);

    prom_init(hwdef->prom_addr, bios_name);

    ivec_irqs = qemu_allocate_irqs(cpu_set_ivec_irq, cpu, IVEC_MAX);

    pci_bus = pci_apb_init(APB_SPECIAL_BASE, APB_MEM_BASE, ivec_irqs, &pci_bus2,

                           &pci_bus3, &pbm_irqs);

    pci_vga_init(pci_bus);

    // XXX Should be pci_bus3

    isa_bus = pci_ebus_init(pci_bus, -1, pbm_irqs);

    i = 0;

    if (hwdef->console_serial_base) {

        serial_mm_init(address_space_mem, hwdef->console_serial_base, 0,

                       NULL, 115200, serial_hds[i], DEVICE_BIG_ENDIAN);

        i++;

    }

    serial_hds_isa_init(isa_bus, MAX_SERIAL_PORTS);

    parallel_hds_isa_init(isa_bus, MAX_PARALLEL_PORTS);

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

        pci_nic_init_nofail(&nd_table[i], pci_bus, "ne2k_pci", NULL);

    ide_drive_get(hd, ARRAY_SIZE(hd));

    pci_cmd646_ide_init(pci_bus, hd, 1);

    isa_create_simple(isa_bus, "i8042");

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

        fd[i] = drive_get(IF_FLOPPY, 0, i);

    }

    fdctrl_init_isa(isa_bus, fd);

    /* Map NVRAM into I/O (ebus) space */

    nvram = m48t59_init(NULL, 0, 0, NVRAM_SIZE, 1968, 59);

    s = SYS_BUS_DEVICE(nvram);

    memory_region_add_subregion(get_system_io(), 0x2000,

                                sysbus_mmio_get_region(s, 0));

    initrd_size = 0;

    initrd_addr = 0;

    kernel_size = sun4u_load_kernel(machine->kernel_filename,

                                    machine->initrd_filename,

                                    ram_size, &initrd_size, &initrd_addr,

                                    &kernel_addr, &kernel_entry);

    sun4u_NVRAM_set_params(nvram, NVRAM_SIZE, "Sun4u", machine->ram_size,

                           machine->boot_order,

                           kernel_addr, kernel_size,

                           machine->kernel_cmdline,

                           initrd_addr, initrd_size,

                           /* XXX: need an option to load a NVRAM image */

                           0,

                           graphic_width, graphic_height, graphic_depth,

                           (uint8_t *)&nd_table[0].macaddr);

    fw_cfg = fw_cfg_init_io(BIOS_CFG_IOPORT);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MAX_CPUS, (uint16_t)max_cpus);

    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, hwdef->machine_id);

    fw_cfg_add_i64(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_entry);

    fw_cfg_add_i64(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);

    if (machine->kernel_cmdline) {

        fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,

                       strlen(machine->kernel_cmdline) + 1);

        fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, machine->kernel_cmdline);

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, 0);

    }

    fw_cfg_add_i64(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);

    fw_cfg_add_i64(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, machine->boot_order[0]);

    fw_cfg_add_i16(fw_cfg, FW_CFG_SPARC64_WIDTH, graphic_width);

    fw_cfg_add_i16(fw_cfg, FW_CFG_SPARC64_HEIGHT, graphic_height);

    fw_cfg_add_i16(fw_cfg, FW_CFG_SPARC64_DEPTH, graphic_depth);

    qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);

}


static void fw_cfg_data_mem_write(void *opaque, target_phys_addr_t addr,

                                  uint64_t value, unsigned size)

{

    fw_cfg_write(opaque, (uint8_t)value);

}


static void do_cpu_reset(void *opaque)

{

    ARMCPU *cpu = opaque;

    CPUARMState *env = &cpu->env;

    const struct arm_boot_info *info = env->boot_info;

    cpu_reset(CPU(cpu));

    if (info) {

        if (!info->is_linux) {

            /* Jump to the entry point.  */

            env->regs[15] = info->entry & 0xfffffffe;

            env->thumb = info->entry & 1;

        } else {

            if (CPU(cpu) == first_cpu) {

                env->regs[15] = info->loader_start;

                if (!info->dtb_filename) {

                    if (old_param) {

                        set_kernel_args_old(info);

                    } else {

                        set_kernel_args(info);

                    }

                }

            } else {

                info->secondary_cpu_reset_hook(cpu, info);

            }

        }

    }

}


void ff_msmpeg4_encode_init(MpegEncContext *s)

{

    static int init_done=0;

    int i;

    common_init(s);

    if(s->msmpeg4_version>=4){

        s->min_qcoeff= -255;

        s->max_qcoeff=  255;

    }

    if (!init_done) {

        /* init various encoding tables */

        init_done = 1;

        init_mv_table(&mv_tables[0]);

        init_mv_table(&mv_tables[1]);

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

            init_rl(&rl_table[i]);

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

            int level;

            for(level=0; level<=MAX_LEVEL; level++){

                int run;

                for(run=0; run<=MAX_RUN; run++){

                    int last;

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

                        rl_length[i][level][run][last]= get_size_of_code(s, &rl_table[  i], last, run, level, 0);

                    }

                }

            }

        }

    }

}


static int kmvc_decode_inter_8x8(KmvcContext * ctx, const uint8_t * src, int src_size, int w, int h)

{

    BitBuf bb;

    int res, val;

    int i, j;

    int bx, by;

    int l0x, l1x, l0y, l1y;

    int mx, my;

    const uint8_t *src_end = src + src_size;

    kmvc_init_getbits(bb, src);

    for (by = 0; by < h; by += 8)

        for (bx = 0; bx < w; bx += 8) {

            kmvc_getbit(bb, src, src_end, res);

            if (!res) {

                kmvc_getbit(bb, src, src_end, res);

                if (!res) {     // fill whole 8x8 block

                    if (src >= src_end) {

                        av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");

                        return AVERROR_INVALIDDATA;

                    }

                    val = *src++;

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

                        BLK(ctx->cur, bx + (i & 0x7), by + (i >> 3)) = val;

                } else {        // copy block from previous frame

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

                        BLK(ctx->cur, bx + (i & 0x7), by + (i >> 3)) =

                            BLK(ctx->prev, bx + (i & 0x7), by + (i >> 3));

                }

            } else {            // handle four 4x4 subblocks

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

                    l0x = bx + (i & 1) * 4;

                    l0y = by + (i & 2) * 2;

                    kmvc_getbit(bb, src, src_end, res);

                    if (!res) {

                        kmvc_getbit(bb, src, src_end, res);

                        if (!res) {     // fill whole 4x4 block

                            if (src >= src_end) {

                                av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");

                                return AVERROR_INVALIDDATA;

                            }

                            val = *src++;

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

                                BLK(ctx->cur, l0x + (j & 3), l0y + (j >> 2)) = val;

                        } else {        // copy block

                            if (src >= src_end) {

                                av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");

                                return AVERROR_INVALIDDATA;

                            }

                            val = *src++;

                            mx = (val & 0xF) - 8;

                            my = (val >> 4) - 8;

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

                                BLK(ctx->cur, l0x + (j & 3), l0y + (j >> 2)) =

                                    BLK(ctx->prev, l0x + (j & 3) + mx, l0y + (j >> 2) + my);

                        }

                    } else {    // descend to 2x2 sub-sub-blocks

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

                            l1x = l0x + (j & 1) * 2;

                            l1y = l0y + (j & 2);

                            kmvc_getbit(bb, src, src_end, res);

                            if (!res) {

                                kmvc_getbit(bb, src, src_end, res);

                                if (!res) {     // fill whole 2x2 block

                                    if (src >= src_end) {

                                        av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");

                                        return AVERROR_INVALIDDATA;

                                    }

                                    val = *src++;

                                    BLK(ctx->cur, l1x, l1y) = val;

                                    BLK(ctx->cur, l1x + 1, l1y) = val;

                                    BLK(ctx->cur, l1x, l1y + 1) = val;

                                    BLK(ctx->cur, l1x + 1, l1y + 1) = val;

                                } else {        // copy block

                                    if (src >= src_end) {

                                        av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");

                                        return AVERROR_INVALIDDATA;

                                    }

                                    val = *src++;

                                    mx = (val & 0xF) - 8;

                                    my = (val >> 4) - 8;

                                    BLK(ctx->cur, l1x, l1y) = BLK(ctx->prev, l1x + mx, l1y + my);

                                    BLK(ctx->cur, l1x + 1, l1y) =

                                        BLK(ctx->prev, l1x + 1 + mx, l1y + my);

                                    BLK(ctx->cur, l1x, l1y + 1) =

                                        BLK(ctx->prev, l1x + mx, l1y + 1 + my);

                                    BLK(ctx->cur, l1x + 1, l1y + 1) =

                                        BLK(ctx->prev, l1x + 1 + mx, l1y + 1 + my);

                                }

                            } else {    // read values for block

                                BLK(ctx->cur, l1x, l1y) = *src++;

                                BLK(ctx->cur, l1x + 1, l1y) = *src++;

                                BLK(ctx->cur, l1x, l1y + 1) = *src++;

                                BLK(ctx->cur, l1x + 1, l1y + 1) = *src++;

                            }

                        }

                    }

                }

            }

        }

    return 0;

}


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

                               int *data_size, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    AMRContext *s      = avctx->priv_data;

    static const uint8_t block_size[16] = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0 };

    enum Mode dec_mode;

    int packet_size;

    av_dlog(avctx, "amr_decode_frame buf=%p buf_size=%d frame_count=%d!!\n",

            buf, buf_size, avctx->frame_number);

    dec_mode    = (buf[0] >> 3) & 0x000F;

    packet_size = block_size[dec_mode] + 1;

    if (packet_size > buf_size) {

        av_log(avctx, AV_LOG_ERROR, "amr frame too short (%u, should be %u)\n",

               buf_size, packet_size);

        return AVERROR_INVALIDDATA;

    }

    av_dlog(avctx, "packet_size=%d buf= 0x%X %X %X %X\n",

              packet_size, buf[0], buf[1], buf[2], buf[3]);

    /* call decoder */

    Decoder_Interface_Decode(s->dec_state, buf, data, 0);

    *data_size = 160 * 2;

    return packet_size;

}


static void avc_h_loop_filter_chroma422_mbaff_msa(uint8_t *src,

                                                  int32_t stride,

                                                  int32_t alpha_in,

                                                  int32_t beta_in,

                                                  int8_t *tc0)

{

    int32_t col, tc_val;

    int16_t out0, out1;

    v16u8 alpha, beta, res;

    alpha = (v16u8) __msa_fill_b(alpha_in);

    beta = (v16u8) __msa_fill_b(beta_in);

    for (col = 0; col < 4; col++) {

        tc_val = (tc0[col] - 1) + 1;

        if (tc_val <= 0) {

            src += 4 * stride;

            continue;

        }

        AVC_LPF_H_2BYTE_CHROMA_422(src, stride, tc_val, alpha, beta, res);

        out0 = __msa_copy_s_h((v8i16) res, 0);

        out1 = __msa_copy_s_h((v8i16) res, 1);

        STORE_HWORD((src - 1), out0);

        src += stride;

        STORE_HWORD((src - 1), out1);

        src += stride;

    }

}


static void copy_cell(Indeo3DecodeContext *ctx, Plane *plane, Cell *cell)

{

    int     h, w, mv_x, mv_y, offset, offset_dst;

    uint8_t *src, *dst;

    /* setup output and reference pointers */

    offset_dst  = (cell->ypos << 2) * plane->pitch + (cell->xpos << 2);

    dst         = plane->pixels[ctx->buf_sel] + offset_dst;

    mv_y        = cell->mv_ptr[0];

    mv_x        = cell->mv_ptr[1];

    offset      = offset_dst + mv_y * plane->pitch + mv_x;

    src         = plane->pixels[ctx->buf_sel ^ 1] + offset;

    h = cell->height << 2;

    for (w = cell->width; w > 0;) {

        /* copy using 16xH blocks */

        if (!((cell->xpos << 2) & 15) && w >= 4) {

            for (; w >= 4; src += 16, dst += 16, w -= 4)

                ctx->dsp.put_no_rnd_pixels_tab[0][0](dst, src, plane->pitch, h);

        }

        /* copy using 8xH blocks */

        if (!((cell->xpos << 2) & 7) && w >= 2) {

            ctx->dsp.put_no_rnd_pixels_tab[1][0](dst, src, plane->pitch, h);

            w -= 2;

            src += 8;

            dst += 8;

        }

        if (w >= 1) {

            ctx->dsp.put_no_rnd_pixels_tab[2][0](dst, src, plane->pitch, h);

            w--;

            src += 4;

            dst += 4;

        }

    }

}


static int tmp105_tx(I2CSlave *i2c, uint8_t data)

{

    TMP105State *s = (TMP105State *) i2c;

    if (!s->len ++)

        s->pointer = data;

    else {

        if (s->len <= 2)

            s->buf[s->len - 1] = data;

        tmp105_write(s);

    }

    return 0;

}


static void flac_lpc_16_c(int32_t *decoded, const int coeffs[32],

                          int pred_order, int qlevel, int len)

{

    int i, j;

    for (i = pred_order; i < len - 1; i += 2, decoded += 2) {

        int c = coeffs[0];

        int d = decoded[0];

        int s0 = 0, s1 = 0;

        for (j = 1; j < pred_order; j++) {

            s0 += c*d;

            d = decoded[j];

            s1 += c*d;

            c = coeffs[j];

        }

        s0 += c*d;

        d = decoded[j] += s0 >> qlevel;

        s1 += c*d;

        decoded[j + 1] += s1 >> qlevel;

    }

    if (i < len) {

        int sum = 0;

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

            sum += coeffs[j] * decoded[j];

        decoded[j] += sum >> qlevel;

    }

}


static bool cpu_thread_is_idle(CPUState *cpu)

{

    if (cpu->stop || cpu->queued_work_first) {

        return false;

    }

    if (cpu->stopped || !runstate_is_running()) {

        return true;

    }

    if (!cpu->halted || qemu_cpu_has_work(cpu) ||

        kvm_async_interrupts_enabled()) {

        return false;

    }

    return true;

}


static inline QEMUClock *qemu_clock_ptr(QEMUClockType type)

{

    return &qemu_clocks[type];

}


int ff_h264_decode_ref_pic_marking(H264Context *h, GetBitContext *gb,

                                   int first_slice)

{

    MpegEncContext * const s = &h->s;

    int i, ret;

    MMCO mmco_temp[MAX_MMCO_COUNT], *mmco = first_slice ? h->mmco : mmco_temp;

    int mmco_index = 0;

    if (h->nal_unit_type == NAL_IDR_SLICE){ // FIXME fields

        s->broken_link = get_bits1(gb) - 1;

        if (get_bits1(gb)){

            mmco[0].opcode = MMCO_LONG;

            mmco[0].long_arg = 0;

            mmco_index = 1;

        }

    } else {

        if (get_bits1(gb)) { // adaptive_ref_pic_marking_mode_flag

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

                MMCOOpcode opcode = get_ue_golomb_31(gb);

                mmco[i].opcode = opcode;

                if (opcode == MMCO_SHORT2UNUSED || opcode == MMCO_SHORT2LONG){

                    mmco[i].short_pic_num =

                        (h->curr_pic_num - get_ue_golomb(gb) - 1) &

                            (h->max_pic_num - 1);

#if 0

                    if (mmco[i].short_pic_num >= h->short_ref_count ||

                        h->short_ref[ mmco[i].short_pic_num ] == NULL){

                        av_log(s->avctx, AV_LOG_ERROR,

                               "illegal short ref in memory management control "

                               "operation %d\n", mmco);

                        return -1;

                    }

#endif

                }

                if (opcode == MMCO_SHORT2LONG || opcode == MMCO_LONG2UNUSED ||

                    opcode == MMCO_LONG || opcode == MMCO_SET_MAX_LONG) {

                    unsigned int long_arg = get_ue_golomb_31(gb);

                    if (long_arg >= 32 ||

                        (long_arg >= 16 && !(opcode == MMCO_SET_MAX_LONG &&

                                             long_arg == 16) &&

                         !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE))){

                        av_log(h->s.avctx, AV_LOG_ERROR,

                               "illegal long ref in memory management control "

                               "operation %d\n", opcode);

                        return -1;

                    }

                    mmco[i].long_arg = long_arg;

                }

                if (opcode > (unsigned) MMCO_LONG){

                    av_log(h->s.avctx, AV_LOG_ERROR,

                           "illegal memory management control operation %d\n",

                           opcode);

                    return -1;

                }

                if (opcode == MMCO_END)

                    break;

            }

            mmco_index = i;

        } else {

            if (first_slice) {

                ret = ff_generate_sliding_window_mmcos(h, first_slice);

                if (ret < 0 && s->avctx->err_recognition & AV_EF_EXPLODE)

                    return ret;

            }

            mmco_index = -1;

        }

    }

    if (first_slice && mmco_index != -1) {

        h->mmco_index = mmco_index;

    } else if (!first_slice && mmco_index >= 0 &&

               (mmco_index != h->mmco_index ||

                (i = check_opcodes(h->mmco, mmco_temp, mmco_index)))) {

        av_log(h->s.avctx, AV_LOG_ERROR,

               "Inconsistent MMCO state between slices [%d, %d, %d]\n",

               mmco_index, h->mmco_index, i);

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


static int rprobe(AVFormatContext *s, uint8_t *enc_header, const uint8_t *r_val)

{

    OMAContext *oc = s->priv_data;

    unsigned int pos;

    struct AVDES av_des;

    if (!enc_header || !r_val)

        return -1;

    /* m_val */

    av_des_init(&av_des, r_val, 192, 1);

    av_des_crypt(&av_des, oc->m_val, &enc_header[48], 1, NULL, 1);

    /* s_val */

    av_des_init(&av_des, oc->m_val, 64, 0);

    av_des_crypt(&av_des, oc->s_val, NULL, 1, NULL, 0);

    /* sm_val */

    pos = OMA_ENC_HEADER_SIZE + oc->k_size + oc->e_size;

    av_des_init(&av_des, oc->s_val, 64, 0);

    av_des_mac(&av_des, oc->sm_val, &enc_header[pos], (oc->i_size >> 3));

    pos += oc->i_size;

    return memcmp(&enc_header[pos], oc->sm_val, 8) ? -1 : 0;

}


static int check_opcodes(MMCO *mmco1, MMCO *mmco2, int n_mmcos)

{

    int i;

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

        if (mmco1[i].opcode != mmco2[i].opcode)

            return -1;

    }

    return 0;

}


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

                                ptrdiff_t stride)

{

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

}


static VncJobQueue *vnc_queue_init(void)

{

    VncJobQueue *queue = g_malloc0(sizeof(VncJobQueue));

    qemu_cond_init(&queue->cond);

    qemu_mutex_init(&queue->mutex);

    QTAILQ_INIT(&queue->jobs);

    return queue;

}


void test_tls_write_cert_chain(const char *filename,

                               gnutls_x509_crt_t *certs,

                               size_t ncerts)

{

    size_t i;

    size_t capacity = 1024, offset = 0;

    char *buffer = g_new0(char, capacity);

    int err;

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

        size_t len = capacity - offset;

    retry:

        err = gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,

                                     buffer + offset, &len);

        if (err < 0) {

            if (err == GNUTLS_E_SHORT_MEMORY_BUFFER) {

                buffer = g_renew(char, buffer, offset + len);

                capacity = offset + len;

                goto retry;

            }

            g_critical("Failed to export certificate chain %s: %d",

                       gnutls_strerror(err), err);

            abort();

        }

        offset += len;

    }

    if (!g_file_set_contents(filename, buffer, offset, NULL)) {

        abort();

    }

}


static int tak_parse(AVCodecParserContext *s, AVCodecContext *avctx,

                     const uint8_t **poutbuf, int *poutbuf_size,

                     const uint8_t *buf, int buf_size)

{

    TAKParseContext *t = s->priv_data;

    ParseContext *pc = &t->pc;

    int next = END_NOT_FOUND;

    GetBitContext gb;

    int consumed = 0;

    int needed = buf_size ? TAK_MAX_FRAME_HEADER_BYTES : 8;

    if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {

        TAKStreamInfo ti;

        init_get_bits(&gb, buf, buf_size);

        if (!ff_tak_decode_frame_header(avctx, &gb, &ti, 127))

            s->duration = t->ti.last_frame_samples ? t->ti.last_frame_samples :

                                                     t->ti.frame_samples;

        *poutbuf      = buf;

        *poutbuf_size = buf_size;

        return buf_size;

    }

    while (buf_size || t->index + needed <= pc->index) {

        if (buf_size && t->index + TAK_MAX_FRAME_HEADER_BYTES > pc->index) {

            int tmp_buf_size = FFMIN(2 * TAK_MAX_FRAME_HEADER_BYTES, buf_size);

            const uint8_t *tmp_buf = buf;

            ff_combine_frame(pc, END_NOT_FOUND, &tmp_buf, &tmp_buf_size);

            consumed += tmp_buf_size;

            buf      += tmp_buf_size;

            buf_size -= tmp_buf_size;

        }

        for (; t->index + needed <= pc->index; t->index++) {

            if (pc->buffer[ t->index     ] == 0xFF &&

                pc->buffer[ t->index + 1 ] == 0xA0) {

                TAKStreamInfo ti;

                init_get_bits(&gb, pc->buffer + t->index,

                              8 * (pc->index - t->index));

                if (!ff_tak_decode_frame_header(avctx, &gb,

                        pc->frame_start_found ? &ti : &t->ti, 127) &&

                    !ff_tak_check_crc(pc->buffer + t->index,

                                      get_bits_count(&gb) / 8)) {

                    if (!pc->frame_start_found) {

                        pc->frame_start_found = 1;

                        s->duration = t->ti.last_frame_samples ?

                                      t->ti.last_frame_samples :

                                      t->ti.frame_samples;

                    } else {

                        pc->frame_start_found = 0;

                        next = t->index - pc->index;

                        t->index = 0;

                        goto found;

                    }

                }

            }

        }

    }

found:

    if (consumed && !buf_size && next == END_NOT_FOUND ||

        ff_combine_frame(pc, next, &buf, &buf_size) < 0) {

        *poutbuf      = NULL;

        *poutbuf_size = 0;

        return buf_size + consumed;

    }

    if (next != END_NOT_FOUND) {

        next += consumed;

        pc->overread = FFMAX(0, -next);

    }

    *poutbuf      = buf;

    *poutbuf_size = buf_size;

    return next;

}


static int gif_read_header(AVFormatContext * s1,

                           AVFormatParameters * ap)

{

    GifState *s = s1->priv_data;

    ByteIOContext *f = s1->pb;

    AVStream *st;

    s->f = f;

    if (gif_read_header1(s) < 0)

        return -1;

    /* allocate image buffer */

    s->image_linesize = s->screen_width * 3;

    s->image_buf = av_malloc(s->screen_height * s->image_linesize);

    if (!s->image_buf)

        return AVERROR(ENOMEM);

    s->pix_fmt = PIX_FMT_RGB24;

    /* now we are ready: build format streams */

    st = av_new_stream(s1, 0);

    if (!st)

        return -1;

    st->codec->codec_type = CODEC_TYPE_VIDEO;

    st->codec->codec_id = CODEC_ID_RAWVIDEO;

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

    st->codec->time_base.num = 1;

    /* XXX: check if screen size is always valid */

    st->codec->width = s->screen_width;

    st->codec->height = s->screen_height;

    st->codec->pix_fmt = PIX_FMT_RGB24;

    return 0;

}


int64_t strtosz_suffix_unit(const char *nptr, char **end,

                            const char default_suffix, int64_t unit)

{

    int64_t retval = -1;

    char *endptr;

    unsigned char c, d;

    int mul_required = 0;

    double val, mul, integral, fraction;

    errno = 0;

    val = strtod(nptr, &endptr);

    if (isnan(val) || endptr == nptr || errno != 0) {

        goto fail;

    }

    fraction = modf(val, &integral);

    if (fraction != 0) {

        mul_required = 1;

    }

    /*

     * Any whitespace character is fine for terminating the number,

     * in addition we accept ',' to handle strings where the size is

     * part of a multi token argument.

     */

    c = *endptr;

    d = c;

    if (qemu_isspace(c) || c == '\0' || c == ',') {

        c = 0;

        d = default_suffix;

    }

    switch (qemu_toupper(d)) {

    case STRTOSZ_DEFSUFFIX_B:

        mul = 1;

        if (mul_required) {

            goto fail;

        }

        break;

    case STRTOSZ_DEFSUFFIX_KB:

        mul = unit;

        break;

    case STRTOSZ_DEFSUFFIX_MB:

        mul = unit * unit;

        break;

    case STRTOSZ_DEFSUFFIX_GB:

        mul = unit * unit * unit;

        break;

    case STRTOSZ_DEFSUFFIX_TB:

        mul = unit * unit * unit * unit;

        break;

    default:

        goto fail;

    }

    /*

     * If not terminated by whitespace, ',', or \0, increment endptr

     * to point to next character, then check that we are terminated

     * by an appropriate separating character, ie. whitespace, ',', or

     * \0. If not, we are seeing trailing garbage, thus fail.

     */

    if (c != 0) {

        endptr++;

        if (!qemu_isspace(*endptr) && *endptr != ',' && *endptr != 0) {

            goto fail;

        }

    }

    if ((val * mul >= INT64_MAX) || val < 0) {

        goto fail;

    }

    retval = val * mul;

fail:

    if (end) {

        *end = endptr;

    }

    return retval;

}


static void qmp_output_push_obj(QmpOutputVisitor *qov, QObject *value,

                                void *qapi)

{

    QStackEntry *e = g_malloc0(sizeof(*e));

    assert(qov->root);

    assert(value);

    e->value = value;

    e->qapi = qapi;

    QSLIST_INSERT_HEAD(&qov->stack, e, node);

}


static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,

                               AVFrame *p, AVPacket *avpkt)

{

    AVDictionary **metadatap = NULL;

    uint32_t tag, length;

    int decode_next_dat = 0;

    int ret;

    for (;;) {

        length = bytestream2_get_bytes_left(&s->gb);

        if (length <= 0) {

            if (avctx->codec_id == AV_CODEC_ID_PNG &&

                avctx->skip_frame == AVDISCARD_ALL) {

                return 0;

            }

            if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {

                if (!(s->pic_state & PNG_IDAT))

                    return 0;

                else

                    goto exit_loop;

            }

            av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);

            if (   s->pic_state & PNG_ALLIMAGE

                && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)

                goto exit_loop;

            ret = AVERROR_INVALIDDATA;

            goto fail;

        }

        length = bytestream2_get_be32(&s->gb);

        if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {

            av_log(avctx, AV_LOG_ERROR, "chunk too big\n");

            ret = AVERROR_INVALIDDATA;

            goto fail;

        }

        tag = bytestream2_get_le32(&s->gb);

        if (avctx->debug & FF_DEBUG_STARTCODE)

            av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",

                   av_fourcc2str(tag), length);

        if (avctx->codec_id == AV_CODEC_ID_PNG &&

            avctx->skip_frame == AVDISCARD_ALL) {

            switch(tag) {

            case MKTAG('I', 'H', 'D', 'R'):

            case MKTAG('p', 'H', 'Y', 's'):

            case MKTAG('t', 'E', 'X', 't'):

            case MKTAG('I', 'D', 'A', 'T'):

            case MKTAG('t', 'R', 'N', 'S'):

                break;

            default:

                goto skip_tag;

            }

        }

        metadatap = &p->metadata;

        switch (tag) {

        case MKTAG('I', 'H', 'D', 'R'):

            if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)

                goto fail;

            break;

        case MKTAG('p', 'H', 'Y', 's'):

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

                goto fail;

            break;

        case MKTAG('f', 'c', 'T', 'L'):

            if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)

                goto skip_tag;

            if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)

                goto fail;

            decode_next_dat = 1;

            break;

        case MKTAG('f', 'd', 'A', 'T'):

            if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)

                goto skip_tag;

            if (!decode_next_dat) {

                ret = AVERROR_INVALIDDATA;

                goto fail;

            }

            bytestream2_get_be32(&s->gb);

            length -= 4;

            /* fallthrough */

        case MKTAG('I', 'D', 'A', 'T'):

            if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)

                goto skip_tag;

            if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)

                goto fail;

            break;

        case MKTAG('P', 'L', 'T', 'E'):

            if (decode_plte_chunk(avctx, s, length) < 0)

                goto skip_tag;

            break;

        case MKTAG('t', 'R', 'N', 'S'):

            if (decode_trns_chunk(avctx, s, length) < 0)

                goto skip_tag;

            break;

        case MKTAG('t', 'E', 'X', 't'):

            if (decode_text_chunk(s, length, 0, metadatap) < 0)

                av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");

            bytestream2_skip(&s->gb, length + 4);

            break;

        case MKTAG('z', 'T', 'X', 't'):

            if (decode_text_chunk(s, length, 1, metadatap) < 0)

                av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");

            bytestream2_skip(&s->gb, length + 4);

            break;

        case MKTAG('s', 'T', 'E', 'R'): {

            int mode = bytestream2_get_byte(&s->gb);

            AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);

            if (!stereo3d)

                goto fail;

            if (mode == 0 || mode == 1) {

                stereo3d->type  = AV_STEREO3D_SIDEBYSIDE;

                stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;

            } else {

                 av_log(avctx, AV_LOG_WARNING,

                        "Unknown value in sTER chunk (%d)\n", mode);

            }

            bytestream2_skip(&s->gb, 4); /* crc */

            break;

        }

        case MKTAG('i', 'C', 'C', 'P'): {

            if (decode_iccp_chunk(s, length, p) < 0)

                goto fail;

            break;

        }

        case MKTAG('I', 'E', 'N', 'D'):

            if (!(s->pic_state & PNG_ALLIMAGE))

                av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");

            if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {

                ret = AVERROR_INVALIDDATA;

                goto fail;

            }

            bytestream2_skip(&s->gb, 4); /* crc */

            goto exit_loop;

        default:

            /* skip tag */

skip_tag:

            bytestream2_skip(&s->gb, length + 4);

            break;

        }

    }

exit_loop:

    if (avctx->codec_id == AV_CODEC_ID_PNG &&

        avctx->skip_frame == AVDISCARD_ALL) {

        return 0;

    }

    if (s->bits_per_pixel <= 4)

        handle_small_bpp(s, p);

    /* apply transparency if needed */

    if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {

        size_t byte_depth = s->bit_depth > 8 ? 2 : 1;

        size_t raw_bpp = s->bpp - byte_depth;

        unsigned x, y;

        av_assert0(s->bit_depth > 1);

        for (y = 0; y < s->height; ++y) {

            uint8_t *row = &s->image_buf[s->image_linesize * y];

            /* since we're updating in-place, we have to go from right to left */

            for (x = s->width; x > 0; --x) {

                uint8_t *pixel = &row[s->bpp * (x - 1)];

                memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);

                if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {

                    memset(&pixel[raw_bpp], 0, byte_depth);

                } else {

                    memset(&pixel[raw_bpp], 0xff, byte_depth);

                }

            }

        }

    }

    /* handle P-frames only if a predecessor frame is available */

    if (s->last_picture.f->data[0]) {

        if (   !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")

            && s->last_picture.f->width == p->width

            && s->last_picture.f->height== p->height

            && s->last_picture.f->format== p->format

         ) {

            if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)

                handle_p_frame_png(s, p);

            else if (CONFIG_APNG_DECODER &&

                     avctx->codec_id == AV_CODEC_ID_APNG &&

                     (ret = handle_p_frame_apng(avctx, s, p)) < 0)

                goto fail;

        }

    }

    ff_thread_report_progress(&s->picture, INT_MAX, 0);

    ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);

    return 0;

fail:

    ff_thread_report_progress(&s->picture, INT_MAX, 0);

    ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);

    return ret;

}


static int sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){

    RMDemuxContext *rm = s->priv_data;

    ByteIOContext *pb = s->pb;

    int len, num, res, i;

    AVStream *st;

    uint32_t state=0xFFFFFFFF;

    while(!url_feof(pb)){

        *pos= url_ftell(pb) - 3;

        if(rm->remaining_len > 0){

            num= rm->current_stream;

            len= rm->remaining_len;

            *timestamp = AV_NOPTS_VALUE;

            *flags= 0;

        }else{

            state= (state<<8) + get_byte(pb);

            if(state == MKBETAG('I', 'N', 'D', 'X')){

                int n_pkts, expected_len;

                len = get_be32(pb);

                url_fskip(pb, 2);

                n_pkts = get_be32(pb);

                expected_len = 20 + n_pkts * 14;

                if (len == 20)

                    /* some files don't add index entries to chunk size... */

                    len = expected_len;

                else if (len != expected_len)

                    av_log(s, AV_LOG_WARNING,

                           "Index size %d (%d pkts) is wrong, should be %d.\n",

                           len, n_pkts, expected_len);

                len -= 14; // we already read part of the index header

                if(len<0)

                    continue;

                goto skip;

            }

            if(state > (unsigned)0xFFFF || state < 12)

                continue;

            len=state;

            state= 0xFFFFFFFF;

            num = get_be16(pb);

            *timestamp = get_be32(pb);

            res= get_byte(pb); /* reserved */

            *flags = get_byte(pb); /* flags */

            len -= 12;

        }

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

            st = s->streams[i];

            if (num == st->id)

                break;

        }

        if (i == s->nb_streams) {

skip:

            /* skip packet if unknown number */

            url_fskip(pb, len);

            rm->remaining_len = 0;

            continue;

        }

        *stream_index= i;

        return len;

    }

    return -1;

}


static int config_props(AVFilterLink *link)

{

    UnsharpContext *unsharp = link->dst->priv;

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);

    unsharp->hsub = desc->log2_chroma_w;

    unsharp->vsub = desc->log2_chroma_h;

    init_filter_param(link->dst, &unsharp->luma,   "luma",   link->w);

    init_filter_param(link->dst, &unsharp->chroma, "chroma", SHIFTUP(link->w, unsharp->hsub));

    return 0;

}


static int64_t wav_seek_tag(AVIOContext *s, int64_t offset, int whence)

{

    offset += offset < INT64_MAX && offset & 1;

    return avio_seek(s, offset, whence);

}


int qemu_global_option(const char *str)

{

    char driver[64], property[64];

    QemuOpts *opts;

    int rc, offset;

    rc = sscanf(str, "%63[^.].%63[^=]%n", driver, property, &offset);

    if (rc < 2 || str[offset] != '=') {

        error_report("can't parse: \"%s\"", str);

        return -1;

    }

    opts = qemu_opts_create(&qemu_global_opts, NULL, 0);

    qemu_opt_set(opts, "driver", driver);

    qemu_opt_set(opts, "property", property);

    qemu_opt_set(opts, "value", str+offset+1);

    return 0;

}


QEMUFile *qemu_fdopen(int fd, const char *mode)

{

    QEMUFileSocket *s;

    if (mode == NULL ||

        (mode[0] != 'r' && mode[0] != 'w') ||

        mode[1] != 'b' || mode[2] != 0) {

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

        return NULL;

    }

    s = g_malloc0(sizeof(QEMUFileSocket));

    s->fd = fd;

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

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

    } else {

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

    }

    return s->file;

}


static int vtd_interrupt_remap_msi(IntelIOMMUState *iommu,

                                   MSIMessage *origin,

                                   MSIMessage *translated)

{

    int ret = 0;

    VTD_IR_MSIAddress addr;

    uint16_t index;

    VTDIrq irq = {};

    assert(origin && translated);

    if (!iommu || !iommu->intr_enabled) {

        goto do_not_translate;

    }

    if (origin->address & VTD_MSI_ADDR_HI_MASK) {

        VTD_DPRINTF(GENERAL, "error: MSI addr high 32 bits nonzero"

                    " during interrupt remapping: 0x%"PRIx32,

                    (uint32_t)((origin->address & VTD_MSI_ADDR_HI_MASK) >> \

                    VTD_MSI_ADDR_HI_SHIFT));

        return -VTD_FR_IR_REQ_RSVD;

    }

    addr.data = origin->address & VTD_MSI_ADDR_LO_MASK;

    if (le16_to_cpu(addr.__head) != 0xfee) {

        VTD_DPRINTF(GENERAL, "error: MSI addr low 32 bits invalid: "

                    "0x%"PRIx32, addr.data);

        return -VTD_FR_IR_REQ_RSVD;

    }

    /* This is compatible mode. */

    if (addr.int_mode != VTD_IR_INT_FORMAT_REMAP) {

        goto do_not_translate;

    }

    index = addr.index_h << 15 | le16_to_cpu(addr.index_l);

#define  VTD_IR_MSI_DATA_SUBHANDLE       (0x0000ffff)

#define  VTD_IR_MSI_DATA_RESERVED        (0xffff0000)

    if (addr.sub_valid) {

        /* See VT-d spec 5.1.2.2 and 5.1.3 on subhandle */

        index += origin->data & VTD_IR_MSI_DATA_SUBHANDLE;

    }

    ret = vtd_remap_irq_get(iommu, index, &irq);

    if (ret) {

        return ret;

    }

    if (addr.sub_valid) {

        VTD_DPRINTF(IR, "received MSI interrupt");

        if (origin->data & VTD_IR_MSI_DATA_RESERVED) {

            VTD_DPRINTF(GENERAL, "error: MSI data bits non-zero for "

                        "interrupt remappable entry: 0x%"PRIx32,

                        origin->data);

            return -VTD_FR_IR_REQ_RSVD;

        }

    } else {

        uint8_t vector = origin->data & 0xff;

        VTD_DPRINTF(IR, "received IOAPIC interrupt");

        /* IOAPIC entry vector should be aligned with IRTE vector

         * (see vt-d spec 5.1.5.1). */

        if (vector != irq.vector) {

            VTD_DPRINTF(GENERAL, "IOAPIC vector inconsistent: "

                        "entry: %d, IRTE: %d, index: %d",

                        vector, irq.vector, index);

        }

    }

    /*

     * We'd better keep the last two bits, assuming that guest OS

     * might modify it. Keep it does not hurt after all.

     */

    irq.msi_addr_last_bits = addr.__not_care;

    /* Translate VTDIrq to MSI message */

    vtd_generate_msi_message(&irq, translated);

    VTD_DPRINTF(IR, "mapping MSI 0x%"PRIx64":0x%"PRIx32 " -> "

                "0x%"PRIx64":0x%"PRIx32, origin->address, origin->data,

                translated->address, translated->data);

    return 0;

do_not_translate:

    memcpy(translated, origin, sizeof(*origin));

    return 0;

}