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

{

    MP3Context  *mp3 = s->priv_data;

    if (pkt->data && pkt->size >= 4) {

        MPADecodeHeader c;

        int av_unused base;

        avpriv_mpegaudio_decode_header(&c, AV_RB32(pkt->data));

        if (!mp3->initial_bitrate)

            mp3->initial_bitrate = c.bit_rate;

        if ((c.bit_rate == 0) || (mp3->initial_bitrate != c.bit_rate))

            mp3->has_variable_bitrate = 1;

#ifdef FILTER_VBR_HEADERS

        /* filter out XING and INFO headers. */

        base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1];

        if (base + 4 <= pkt->size) {

            uint32_t v = AV_RB32(pkt->data + base);

            if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)

                return 0;

        }

        /* filter out VBRI headers. */

        base = 4 + 32;

        if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))

            return 0;

#endif

        if (mp3->xing_offset)

            mp3_xing_add_frame(mp3, pkt);

    }

    return ff_raw_write_packet(s, pkt);

}


static int handle_instruction(CPUState *env, struct kvm_run *run)

{

    unsigned int ipa0 = (run->s390_sieic.ipa & 0xff00);

    uint8_t ipa1 = run->s390_sieic.ipa & 0x00ff;

    int ipb_code = (run->s390_sieic.ipb & 0x0fff0000) >> 16;

    int r = -1;

    dprintf("handle_instruction 0x%x 0x%x\n", run->s390_sieic.ipa, run->s390_sieic.ipb);

    switch (ipa0) {

        case IPA0_PRIV:

            r = handle_priv(env, run, ipa1);

            break;

        case IPA0_DIAG:

            r = handle_diag(env, run, ipb_code);

            break;

        case IPA0_SIGP:

            r = handle_sigp(env, run, ipa1);

            break;

    }

    if (r < 0) {

        enter_pgmcheck(env, 0x0001);

    }

    return r;

}


static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)

{

    NvencContext *ctx = avctx->priv_data;

    NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;

    NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;

    uint32_t slice_mode_data;

    uint32_t *slice_offsets;

    NV_ENC_LOCK_BITSTREAM lock_params = { 0 };

    NVENCSTATUS nv_status;

    int res = 0;

    enum AVPictureType pict_type;

    switch (avctx->codec->id) {

    case AV_CODEC_ID_H264:

      slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;

      break;

    case AV_CODEC_ID_H265:

      slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;

      break;

    default:

      av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");

      res = AVERROR(EINVAL);

      goto error;

    }

    slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));

    if (!slice_offsets)

        goto error;

    lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;

    lock_params.doNotWait = 0;

    lock_params.outputBitstream = tmpoutsurf->output_surface;

    lock_params.sliceOffsets = slice_offsets;

    nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);

    if (nv_status != NV_ENC_SUCCESS) {

        res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");

        goto error;

    }

    if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {

        p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);

        goto error;

    }

    memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);

    nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);

    if (nv_status != NV_ENC_SUCCESS)

        nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");

    if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {

        p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);

        av_frame_unref(tmpoutsurf->in_ref);

        ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;

        tmpoutsurf->input_surface = NULL;

    }

    switch (lock_params.pictureType) {

    case NV_ENC_PIC_TYPE_IDR:

        pkt->flags |= AV_PKT_FLAG_KEY;

    case NV_ENC_PIC_TYPE_I:

        pict_type = AV_PICTURE_TYPE_I;

        break;

    case NV_ENC_PIC_TYPE_P:

        pict_type = AV_PICTURE_TYPE_P;

        break;

    case NV_ENC_PIC_TYPE_B:

        pict_type = AV_PICTURE_TYPE_B;

        break;

    case NV_ENC_PIC_TYPE_BI:

        pict_type = AV_PICTURE_TYPE_BI;

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");

        av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");

        res = AVERROR_EXTERNAL;

        goto error;

    }

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    avctx->coded_frame->pict_type = pict_type;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    ff_side_data_set_encoder_stats(pkt,

        (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);

    res = nvenc_set_timestamp(avctx, &lock_params, pkt);

    if (res < 0)

        goto error2;

    av_free(slice_offsets);

    return 0;

error:

    timestamp_queue_dequeue(ctx->timestamp_list);

error2:

    av_free(slice_offsets);

    return res;

}


yuv2422_1_c_template(SwsContext *c, const int16_t *buf0,
                     const int16_t *ubuf[2], const int16_t *vbuf[2],
                     const int16_t *abuf0, uint8_t *dest, int dstW,
                     int uvalpha, int y, enum PixelFormat target)
{
    const int16_t *ubuf0 = ubuf[0], *vbuf0 = vbuf[0];
    int i;
    if (uvalpha < 2048) {
        for (i = 0; i < (dstW >> 1); i++) {
            int Y1 = buf0[i * 2]     >> 7;
            int Y2 = buf0[i * 2 + 1] >> 7;
            int U  = ubuf0[i]        >> 7;
            int V  = vbuf0[i]        >> 7;
            output_pixels(i * 4, Y1, U, Y2, V);
        }
    } else {
        const int16_t *ubuf1 = ubuf[1], *vbuf1 = vbuf[1];
        for (i = 0; i < (dstW >> 1); i++) {
            int Y1 =  buf0[i * 2]          >> 7;
            int Y2 =  buf0[i * 2 + 1]      >> 7;
            int U  = (ubuf0[i] + ubuf1[i]) >> 8;
            int V  = (vbuf0[i] + vbuf1[i]) >> 8;
            output_pixels(i * 4, Y1, U, Y2, V);
        }
    }
}


static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,

                                       int64_t sector_num, int nb_sectors,

                                       QEMUIOVector *iov)

{

    IscsiLun *iscsilun = bs->opaque;

    struct IscsiTask iTask;

    uint64_t lba;

    uint32_t num_sectors;

    if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {

        return -EINVAL;

    }

    if (bs->bl.max_transfer_length && nb_sectors > bs->bl.max_transfer_length) {

        error_report("iSCSI Error: Read of %d sectors exceeds max_xfer_len "

                     "of %d sectors", nb_sectors, bs->bl.max_transfer_length);

        return -EINVAL;

    }

    if (iscsilun->lbprz && nb_sectors >= ISCSI_CHECKALLOC_THRES &&

        !iscsi_allocationmap_is_allocated(iscsilun, sector_num, nb_sectors)) {

        int64_t ret;

        int pnum;

        BlockDriverState *file;

        ret = iscsi_co_get_block_status(bs, sector_num, INT_MAX, &pnum, &file);

        if (ret < 0) {

            return ret;

        }

        if (ret & BDRV_BLOCK_ZERO && pnum >= nb_sectors) {

            qemu_iovec_memset(iov, 0, 0x00, iov->size);

            return 0;

        }

    }

    lba = sector_qemu2lun(sector_num, iscsilun);

    num_sectors = sector_qemu2lun(nb_sectors, iscsilun);

    iscsi_co_init_iscsitask(iscsilun, &iTask);

retry:

    if (iscsilun->use_16_for_rw) {

        iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,

                                       num_sectors * iscsilun->block_size,

                                       iscsilun->block_size, 0, 0, 0, 0, 0,

                                       iscsi_co_generic_cb, &iTask);

    } else {

        iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,

                                       num_sectors * iscsilun->block_size,

                                       iscsilun->block_size,

                                       0, 0, 0, 0, 0,

                                       iscsi_co_generic_cb, &iTask);

    }

    if (iTask.task == NULL) {

        return -ENOMEM;

    }

    scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);

    while (!iTask.complete) {

        iscsi_set_events(iscsilun);

        qemu_coroutine_yield();

    }

    if (iTask.task != NULL) {

        scsi_free_scsi_task(iTask.task);

        iTask.task = NULL;

    }

    if (iTask.do_retry) {

        iTask.complete = 0;

        goto retry;

    }

    if (iTask.status != SCSI_STATUS_GOOD) {

        return iTask.err_code;

    }

    return 0;

}


static void spapr_numa_cpu(const void *data)

{

    char *cli;

    QDict *resp;

    QList *cpus;

    const QObject *e;

    cli = make_cli(data, "-smp 4,cores=4 "

        "-numa node,nodeid=0 -numa node,nodeid=1 "

        "-numa cpu,node-id=0,core-id=0 "

        "-numa cpu,node-id=0,core-id=1 "

        "-numa cpu,node-id=0,core-id=2 "

        "-numa cpu,node-id=1,core-id=3");

    qtest_start(cli);

    cpus = get_cpus(&resp);

    g_assert(cpus);

    while ((e = qlist_pop(cpus))) {

        QDict *cpu, *props;

        int64_t core, node;

        cpu = qobject_to_qdict(e);

        g_assert(qdict_haskey(cpu, "props"));

        props = qdict_get_qdict(cpu, "props");

        g_assert(qdict_haskey(props, "node-id"));

        node = qdict_get_int(props, "node-id");

        g_assert(qdict_haskey(props, "core-id"));

        core = qdict_get_int(props, "core-id");

        if (core >= 0 && core < 3) {

            g_assert_cmpint(node, ==, 0);

        } else if (core == 3) {

            g_assert_cmpint(node, ==, 1);

        } else {

            g_assert(false);

        }

    }

    QDECREF(resp);

    qtest_end();

    g_free(cli);

}


ssize_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)

{

    ssize_t ret;

#ifdef CONFIG_VNC_TLS

    if (vs->tls.session) {

        ret = vnc_client_read_tls(&vs->tls.session, data, datalen);

    } else {

#endif /* CONFIG_VNC_TLS */

        ret = qemu_recv(vs->csock, data, datalen, 0);

#ifdef CONFIG_VNC_TLS

    }

#endif /* CONFIG_VNC_TLS */

    VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);

    return vnc_client_io_error(vs, ret, socket_error());

}


void qemu_put_be64(QEMUFile *f, uint64_t v)

{

    qemu_put_be32(f, v >> 32);

    qemu_put_be32(f, v);

}


void lance_init(NICInfo *nd, int irq, uint32_t leaddr, uint32_t ledaddr)

{

    LANCEState *s;

    int lance_io_memory, ledma_io_memory;

    s = qemu_mallocz(sizeof(LANCEState));

    if (!s)

        return;

    s->irq = irq;

    lance_io_memory = cpu_register_io_memory(0, lance_mem_read, lance_mem_write, s);

    cpu_register_physical_memory(leaddr, 4, lance_io_memory);

    ledma_io_memory = cpu_register_io_memory(0, ledma_mem_read, ledma_mem_write, s);

    cpu_register_physical_memory(ledaddr, 16, ledma_io_memory);

    memcpy(s->macaddr, nd->macaddr, 6);

    lance_reset(s);

    s->vc = qemu_new_vlan_client(nd->vlan, lance_receive, s);

    snprintf(s->vc->info_str, sizeof(s->vc->info_str),

             "lance macaddr=%02x:%02x:%02x:%02x:%02x:%02x",

             s->macaddr[0],

             s->macaddr[1],

             s->macaddr[2],

             s->macaddr[3],

             s->macaddr[4],

             s->macaddr[5]);

    register_savevm("lance", leaddr, 1, lance_save, lance_load, s);

    qemu_register_reset(lance_reset, s);

}


static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb, int channel, int *last)

{

    int t, t2;

    int sign, base, add, ret;

    WvChannel *c = &ctx->ch[channel];

    *last = 0;

    if((ctx->ch[0].median[0] < 2U) && (ctx->ch[1].median[0] < 2U) && !ctx->zero && !ctx->one){

        if(ctx->zeroes){

            ctx->zeroes--;

            if(ctx->zeroes){

                c->slow_level -= LEVEL_DECAY(c->slow_level);

                return 0;

            }

        }else{

            t = get_unary_0_33(gb);

            if(t >= 2) t = get_bits(gb, t - 1) | (1 << (t-1));

            ctx->zeroes = t;

            if(ctx->zeroes){

                memset(ctx->ch[0].median, 0, sizeof(ctx->ch[0].median));

                memset(ctx->ch[1].median, 0, sizeof(ctx->ch[1].median));

                c->slow_level -= LEVEL_DECAY(c->slow_level);

                return 0;

            }

        }

    }

    if(get_bits_count(gb) >= ctx->data_size){

        *last = 1;

        return 0;

    }

    if(ctx->zero){

        t = 0;

        ctx->zero = 0;

    }else{

        t = get_unary_0_33(gb);

        if(get_bits_count(gb) >= ctx->data_size){

            *last = 1;

            return 0;

        }

        if(t == 16) {

            t2 = get_unary_0_33(gb);

            if(t2 < 2) t += t2;

            else t += get_bits(gb, t2 - 1) | (1 << (t2 - 1));

        }

        if(ctx->one){

            ctx->one = t&1;

            t = (t>>1) + 1;

        }else{

            ctx->one = t&1;

            t >>= 1;

        }

        ctx->zero = !ctx->one;

    }

    if(ctx->hybrid && !channel)

        update_error_limit(ctx);

    if(!t){

        base = 0;

        add = GET_MED(0) - 1;

        DEC_MED(0);

    }else if(t == 1){

        base = GET_MED(0);

        add = GET_MED(1) - 1;

        INC_MED(0);

        DEC_MED(1);

    }else if(t == 2){

        base = GET_MED(0) + GET_MED(1);

        add = GET_MED(2) - 1;

        INC_MED(0);

        INC_MED(1);

        DEC_MED(2);

    }else{

        base = GET_MED(0) + GET_MED(1) + GET_MED(2) * (t - 2);

        add = GET_MED(2) - 1;

        INC_MED(0);

        INC_MED(1);

        INC_MED(2);

    }

    if(!c->error_limit){

        ret = base + get_tail(gb, add);

    }else{

        int mid = (base*2 + add + 1) >> 1;

        while(add > c->error_limit){

            if(get_bits1(gb)){

                add -= (mid - base);

                base = mid;

            }else

                add = mid - base - 1;

            mid = (base*2 + add + 1) >> 1;

        }

        ret = mid;

    }

    sign = get_bits1(gb);

    if(ctx->hybrid_bitrate)

        c->slow_level += wp_log2(ret) - LEVEL_DECAY(c->slow_level);

    return sign ? ~ret : ret;

}


static int block_save_setup(QEMUFile *f, void *opaque)

{

    int ret;

    DPRINTF("Enter save live setup submitted %d transferred %d\n",

            block_mig_state.submitted, block_mig_state.transferred);

    qemu_mutex_lock_iothread();

    init_blk_migration(f);

    /* start track dirty blocks */

    set_dirty_tracking();

    qemu_mutex_unlock_iothread();

    ret = flush_blks(f);

    blk_mig_reset_dirty_cursor();

    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

    return ret;

}


static void test_dynamic_globalprop(void)

{

    MyType *mt;

    static GlobalProperty props[] = {

        { TYPE_DYNAMIC_PROPS, "prop1", "101" },

        { TYPE_DYNAMIC_PROPS, "prop2", "102" },

        { TYPE_DYNAMIC_PROPS"-bad", "prop3", "103", true },

        {}

    };

    int all_used;

    qdev_prop_register_global_list(props);

    mt = DYNAMIC_TYPE(object_new(TYPE_DYNAMIC_PROPS));

    qdev_init_nofail(DEVICE(mt));

    g_assert_cmpuint(mt->prop1, ==, 101);

    g_assert_cmpuint(mt->prop2, ==, 102);

}


void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)

{

    if (min_size < *size)

        return ptr;

    min_size = FFMAX(min_size + min_size / 16 + 32, min_size);

    ptr = av_realloc(ptr, min_size);

    /* we could set this to the unmodified min_size but this is safer

     * if the user lost the ptr and uses NULL now

     */

    if (!ptr)

        min_size = 0;

    *size = min_size;

    return ptr;

}


static inline int decode_residual_inter(AVSContext *h)

{

    int block;

    /* get coded block pattern */

    int cbp = get_ue_golomb(&h->gb);

    if (cbp > 63) {

        av_log(h->avctx, AV_LOG_ERROR, "illegal inter cbp\n");

        return AVERROR_INVALIDDATA;

    }

    h->cbp = cbp_tab[cbp][1];

    /* get quantizer */

    if (h->cbp && !h->qp_fixed)

        h->qp = (h->qp + get_se_golomb(&h->gb)) & 63;

    for (block = 0; block < 4; block++)

        if (h->cbp & (1 << block))

            decode_residual_block(h, &h->gb, inter_dec, 0, h->qp,

                                  h->cy + h->luma_scan[block], h->l_stride);

    decode_residual_chroma(h);

    return 0;

}


static int decode_pulses(Pulse *pulse, GetBitContext *gb,

                         const uint16_t *swb_offset, int num_swb)

{

    int i, pulse_swb;

    pulse->num_pulse = get_bits(gb, 2) + 1;

    pulse_swb        = get_bits(gb, 6);

    if (pulse_swb >= num_swb)

        return -1;

    pulse->pos[0]    = swb_offset[pulse_swb];

    pulse->pos[0]   += get_bits(gb, 5);

    if (pulse->pos[0] > 1023)

        return -1;

    pulse->amp[0]    = get_bits(gb, 4);

    for (i = 1; i < pulse->num_pulse; i++) {

        pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];

        if (pulse->pos[i] > 1023)

            return -1;

        pulse->amp[i] = get_bits(gb, 4);

    }

    return 0;

}


static int aiff_probe(AVProbeData *p)

{

    /* check file header */

    if (p->buf_size < 16)

        return 0;

    if (p->buf[0] == 'F' && p->buf[1] == 'O' &&

        p->buf[2] == 'R' && p->buf[3] == 'M' &&

        p->buf[8] == 'A' && p->buf[9] == 'I' &&

        p->buf[10] == 'F' && (p->buf[11] == 'F' || p->buf[11] == 'C'))

        return AVPROBE_SCORE_MAX;

    else

        return 0;

}


static int encode_residual(FlacEncodeContext *ctx, int ch)

{

    int i, n;

    int min_order, max_order, opt_order, precision, omethod;

    int min_porder, max_porder;

    FlacFrame *frame;

    FlacSubframe *sub;

    int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];

    int shift[MAX_LPC_ORDER];

    int32_t *res, *smp;

    frame = &ctx->frame;

    sub = &frame->subframes[ch];

    res = sub->residual;

    smp = sub->samples;

    n = frame->blocksize;

    /* CONSTANT */

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

        if(smp[i] != smp[0]) break;

    }

    if(i == n) {

        sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;

        res[0] = smp[0];

        return sub->obits;

    }

    /* VERBATIM */

    if(n < 5) {

        sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;

        encode_residual_verbatim(res, smp, n);

        return sub->obits * n;

    }

    min_order = ctx->options.min_prediction_order;

    max_order = ctx->options.max_prediction_order;

    min_porder = ctx->options.min_partition_order;

    max_porder = ctx->options.max_partition_order;

    precision = ctx->options.lpc_coeff_precision;

    omethod = ctx->options.prediction_order_method;

    /* FIXED */

    if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {

        uint32_t bits[MAX_FIXED_ORDER+1];

        if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;

        opt_order = 0;

        bits[0] = UINT32_MAX;

        for(i=min_order; i<=max_order; i++) {

            encode_residual_fixed(res, smp, n, i);

            bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,

                                             n, i, sub->obits);

            if(bits[i] < bits[opt_order]) {

                opt_order = i;

            }

        }

        sub->order = opt_order;

        sub->type = FLAC_SUBFRAME_FIXED;

        sub->type_code = sub->type | sub->order;

        if(sub->order != max_order) {

            encode_residual_fixed(res, smp, n, sub->order);

            return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,

                                          sub->order, sub->obits);

        }

        return bits[sub->order];

    }

    /* LPC */

    opt_order = ff_lpc_calc_coefs(&ctx->dsp, smp, n, max_order, precision, coefs,

                               shift, ctx->options.use_lpc, omethod, MAX_LPC_SHIFT, 0);

    if(omethod == ORDER_METHOD_2LEVEL ||

       omethod == ORDER_METHOD_4LEVEL ||

       omethod == ORDER_METHOD_8LEVEL) {

        int levels = 1 << omethod;

        uint32_t bits[levels];

        int order;

        int opt_index = levels-1;

        opt_order = max_order-1;

        bits[opt_index] = UINT32_MAX;

        for(i=levels-1; i>=0; i--) {

            order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;

            if(order < 0) order = 0;

            encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);

            bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,

                                           res, n, order+1, sub->obits, precision);

            if(bits[i] < bits[opt_index]) {

                opt_index = i;

                opt_order = order;

            }

        }

        opt_order++;

    } else if(omethod == ORDER_METHOD_SEARCH) {

        // brute-force optimal order search

        uint32_t bits[MAX_LPC_ORDER];

        opt_order = 0;

        bits[0] = UINT32_MAX;

        for(i=min_order-1; i<max_order; i++) {

            encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);

            bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,

                                           res, n, i+1, sub->obits, precision);

            if(bits[i] < bits[opt_order]) {

                opt_order = i;

            }

        }

        opt_order++;

    } else if(omethod == ORDER_METHOD_LOG) {

        uint32_t bits[MAX_LPC_ORDER];

        int step;

        opt_order= min_order - 1 + (max_order-min_order)/3;

        memset(bits, -1, sizeof(bits));

        for(step=16 ;step; step>>=1){

            int last= opt_order;

            for(i=last-step; i<=last+step; i+= step){

                if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)

                    continue;

                encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);

                bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,

                                            res, n, i+1, sub->obits, precision);

                if(bits[i] < bits[opt_order])

                    opt_order= i;

            }

        }

        opt_order++;

    }

    sub->order = opt_order;

    sub->type = FLAC_SUBFRAME_LPC;

    sub->type_code = sub->type | (sub->order-1);

    sub->shift = shift[sub->order-1];

    for(i=0; i<sub->order; i++) {

        sub->coefs[i] = coefs[sub->order-1][i];

    }

    encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);

    return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,

                                sub->obits, precision);

}


static int decode_stream_header(NUTContext *nut){

    AVFormatContext *s= nut->avf;

    ByteIOContext *bc = &s->pb;

    StreamContext *stc;

    int class, nom, denom, stream_id;

    uint64_t tmp, end;

    AVStream *st;

    end= get_packetheader(nut, bc, 1);

    end += url_ftell(bc) - 4;

    GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base.num);

    stc= &nut->stream[stream_id];

    st = s->streams[stream_id];

    if (!st)

        return AVERROR_NOMEM;

    class = get_v(bc);

    tmp = get_fourcc(bc);

    st->codec->codec_tag= tmp;

    switch(class)

    {

        case 0:

            st->codec->codec_type = CODEC_TYPE_VIDEO;

            st->codec->codec_id = codec_get_bmp_id(tmp);

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

                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");

            break;

        case 1:

            st->codec->codec_type = CODEC_TYPE_AUDIO;

            st->codec->codec_id = codec_get_wav_id(tmp);

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

                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");

            break;

        case 2:

//            st->codec->codec_type = CODEC_TYPE_TEXT;

//            break;

        case 3:

            st->codec->codec_type = CODEC_TYPE_DATA;

            break;

        default:

            av_log(s, AV_LOG_ERROR, "Unknown stream class (%d)\n", class);

            return -1;

    }

    GET_V(stc->time_base_id    , tmp < nut->time_base_count);

    GET_V(stc->msb_pts_shift   , tmp < 16);

    stc->max_pts_distance= get_v(bc);

    GET_V(stc->decode_delay    , tmp < 1000); //sanity limit, raise this if moors law is true

    st->codec->has_b_frames= stc->decode_delay;

    get_v(bc); //stream flags

    GET_V(st->codec->extradata_size, tmp < (1<<30));

    if(st->codec->extradata_size){

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

        get_buffer(bc, st->codec->extradata, st->codec->extradata_size);

    }

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

        GET_V(st->codec->width , tmp > 0)

        GET_V(st->codec->height, tmp > 0)

        st->codec->sample_aspect_ratio.num= get_v(bc);

        st->codec->sample_aspect_ratio.den= get_v(bc);

        if((!st->codec->sample_aspect_ratio.num) != (!st->codec->sample_aspect_ratio.den)){

            av_log(s, AV_LOG_ERROR, "invalid aspect ratio\n");

            return -1;

        }

        get_v(bc); /* csp type */

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

        GET_V(st->codec->sample_rate , tmp > 0)

        tmp= get_v(bc); // samplerate_den

        if(tmp > st->codec->sample_rate){

            av_log(s, AV_LOG_ERROR, "bleh, libnut muxed this ;)\n");

            st->codec->sample_rate= tmp;

        }

        GET_V(st->codec->channels, tmp > 0)

    }

    if(skip_reserved(bc, end) || check_checksum(bc)){

        av_log(s, AV_LOG_ERROR, "Stream header %d checksum mismatch\n", stream_id);

        return -1;

    }

    stc->time_base= nut->time_base[stc->time_base_id];

    av_set_pts_info(s->streams[stream_id], 63, stc->time_base.num, stc->time_base.den);

    return 0;

}


void avformat_close_input(AVFormatContext **ps)

{

    AVFormatContext *s = *ps;

    AVIOContext *pb = (s->iformat->flags & AVFMT_NOFILE) || (s->flags & AVFMT_FLAG_CUSTOM_IO) ?

                       NULL : s->pb;

    flush_packet_queue(s);

    if (s->iformat->read_close)

        s->iformat->read_close(s);

    avformat_free_context(s);

    *ps = NULL;

    avio_close(pb);

}


static void cris_alu(DisasContext *dc, int op,

			       TCGv d, TCGv op_a, TCGv op_b, int size)

{

	TCGv tmp;

	int writeback;

	writeback = 1;

	if (op == CC_OP_BOUND || op == CC_OP_BTST)

		tmp = tcg_temp_local_new(TCG_TYPE_TL);

	else

		tmp = tcg_temp_new(TCG_TYPE_TL);

	if (op == CC_OP_CMP) {

		writeback = 0;

	} else if (size == 4) {

		tmp = d;

		writeback = 0;

	}

	cris_pre_alu_update_cc(dc, op, op_a, op_b, size);

	cris_alu_op_exec(dc, op, tmp, op_a, op_b, size);

	cris_update_result(dc, tmp);

	/* Writeback.  */

	if (writeback) {

		if (size == 1)

			tcg_gen_andi_tl(d, d, ~0xff);

		else

			tcg_gen_andi_tl(d, d, ~0xffff);

		tcg_gen_or_tl(d, d, tmp);

	}

	if (tmp != d)

		tcg_temp_free(tmp);

}


int avresample_set_matrix(AVAudioResampleContext *avr, const double *matrix,

                          int stride)

{

    int in_channels, out_channels, i, o;

    in_channels  = av_get_channel_layout_nb_channels(avr->in_channel_layout);

    out_channels = av_get_channel_layout_nb_channels(avr->out_channel_layout);

    if ( in_channels < 0 ||  in_channels > AVRESAMPLE_MAX_CHANNELS ||

        out_channels < 0 || out_channels > AVRESAMPLE_MAX_CHANNELS) {

        av_log(avr, AV_LOG_ERROR, "Invalid channel layouts\n");

        return AVERROR(EINVAL);

    }

    if (avr->am->matrix)

        av_freep(avr->am->matrix);

#define CONVERT_MATRIX(type, expr)                                          \

    avr->am->matrix_## type[0] = av_mallocz(out_channels * in_channels *    \

                                            sizeof(*avr->am->matrix_## type[0])); \

    if (!avr->am->matrix_## type[0])                                        \

        return AVERROR(ENOMEM);                                             \

    for (o = 0; o < out_channels; o++) {                                    \

        if (o > 0)                                                          \

            avr->am->matrix_## type[o] = avr->am->matrix_## type[o - 1] +   \

                                         in_channels;                       \

        for (i = 0; i < in_channels; i++) {                                 \

            double v = matrix[o * stride + i];                              \

            avr->am->matrix_## type[o][i] = expr;                           \

        }                                                                   \

    }                                                                       \

    avr->am->matrix = (void **)avr->am->matrix_## type;

    switch (avr->mix_coeff_type) {

    case AV_MIX_COEFF_TYPE_Q8:

        CONVERT_MATRIX(q8, av_clip_int16(lrint(256.0 * v)))

        break;

    case AV_MIX_COEFF_TYPE_Q15:

        CONVERT_MATRIX(q15, av_clipl_int32(llrint(32768.0 * v)))

        break;

    case AV_MIX_COEFF_TYPE_FLT:

        CONVERT_MATRIX(flt, v)

        break;

    default:

        av_log(avr, AV_LOG_ERROR, "Invalid mix coeff type\n");

        return AVERROR(EINVAL);

    }

    /* TODO: detect situations where we can just swap around pointers

             instead of doing matrix multiplications with 0.0 and 1.0 */

    return 0;

}


av_cold void ff_vp9dsp_init(VP9DSPContext *dsp, int bpp, int bitexact)

{

    if (bpp == 8) {

        ff_vp9dsp_init_8(dsp);

    } else if (bpp == 10) {

        ff_vp9dsp_init_10(dsp);

    } else {

        av_assert0(bpp == 12);

        ff_vp9dsp_init_12(dsp);

    }

    if (ARCH_X86) ff_vp9dsp_init_x86(dsp, bpp, bitexact);

    if (ARCH_MIPS) ff_vp9dsp_init_mips(dsp, bpp);

}


FFAMediaCodec* ff_AMediaCodec_createCodecByName(const char *name)

{

    JNIEnv *env = NULL;

    FFAMediaCodec *codec = NULL;

    jstring codec_name = NULL;

    codec = av_mallocz(sizeof(FFAMediaCodec));

    if (!codec) {

        return NULL;

    }

    codec->class = &amediacodec_class;

    env = ff_jni_get_env(codec);

    if (!env) {

        av_freep(&codec);

        return NULL;

    }

    if (ff_jni_init_jfields(env, &codec->jfields, jni_amediacodec_mapping, 1, codec) < 0) {

        goto fail;

    }

    codec_name = ff_jni_utf_chars_to_jstring(env, name, codec);

    if (!codec_name) {

        goto fail;

    }

    codec->object = (*env)->CallStaticObjectMethod(env, codec->jfields.mediacodec_class, codec->jfields.create_by_codec_name_id, codec_name);

    if (ff_jni_exception_check(env, 1, codec) < 0) {

        goto fail;

    }

    codec->object = (*env)->NewGlobalRef(env, codec->object);

    if (!codec->object) {

        goto fail;

    }

    if (codec_init_static_fields(codec) < 0) {

        goto fail;

    }

    if (codec->jfields.get_input_buffer_id && codec->jfields.get_output_buffer_id) {

        codec->has_get_i_o_buffer = 1;

    }

    return codec;

fail:

    ff_jni_reset_jfields(env, &codec->jfields, jni_amediacodec_mapping, 1, codec);

    if (codec_name) {

        (*env)->DeleteLocalRef(env, codec_name);

    }

    av_freep(&codec);

    return NULL;

}


void ide_drive_get(DriveInfo **hd, int max_bus)

{

    int i;

    if (drive_get_max_bus(IF_IDE) >= max_bus) {

        fprintf(stderr, "qemu: too many IDE bus: %d\n", max_bus);

        exit(1);

    }

    for(i = 0; i < max_bus * MAX_IDE_DEVS; i++) {

        hd[i] = drive_get(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);

    }

}


static void release_keys(void *opaque)

{

    int i;

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

        if (keycodes[i] & 0x80) {

            kbd_put_keycode(0xe0);

        }

        kbd_put_keycode(keycodes[i]| 0x80);

    }

    free_keycodes();

}


static int mace6_decode_frame(AVCodecContext *avctx,

                              void *data, int *data_size,

                              const uint8_t *buf, int buf_size)

{

    int16_t *samples = data;

    MACEContext *ctx = avctx->priv_data;

    int i, j;

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

        int16_t *output = samples + i;

        for (j = 0; j < buf_size / avctx->channels; j++) {

            uint8_t pkt = buf[i + j*avctx->channels];

            chomp6(&ctx->chd[i], output, pkt >> 5     , MACEtab1, MACEtab2,

                   8, avctx->channels);

            output += avctx->channels << 1;

            chomp6(&ctx->chd[i], output,(pkt >> 3) & 3, MACEtab3, MACEtab4,

                   4, avctx->channels);

            output += avctx->channels << 1;

            chomp6(&ctx->chd[i], output, pkt       & 7, MACEtab1, MACEtab2,

                   8, avctx->channels);

            output += avctx->channels << 1;

        }

    }

    *data_size = 2 * 6 * buf_size;

    return buf_size;

}


static void new_video_stream(AVFormatContext *oc)

{

    AVStream *st;

    AVCodecContext *video_enc;

    enum CodecID codec_id;

    AVCodec *codec= NULL;

    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);

    if (!st) {

        fprintf(stderr, "Could not alloc stream\n");

        ffmpeg_exit(1);

    }

    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);

    if(!video_stream_copy){

        if (video_codec_name) {

            codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1,

                                         avcodec_opts[AVMEDIA_TYPE_VIDEO]->strict_std_compliance);

            codec = avcodec_find_encoder_by_name(video_codec_name);

            output_codecs[nb_output_codecs-1] = codec;

        } else {

            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);

            codec = avcodec_find_encoder(codec_id);

        }

    }

    avcodec_get_context_defaults3(st->codec, codec);

    bitstream_filters[nb_output_files] =

        grow_array(bitstream_filters[nb_output_files],

                   sizeof(*bitstream_filters[nb_output_files]),

                   &nb_bitstream_filters[nb_output_files], oc->nb_streams);

    bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;

    video_bitstream_filters= NULL;

    avcodec_thread_init(st->codec, thread_count);

    video_enc = st->codec;

    if(video_codec_tag)

        video_enc->codec_tag= video_codec_tag;

    if(   (video_global_header&1)

       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){

        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;

        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;

    }

    if(video_global_header&2){

        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;

        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags2|= CODEC_FLAG2_LOCAL_HEADER;

    }

    if (video_stream_copy) {

        st->stream_copy = 1;

        video_enc->codec_type = AVMEDIA_TYPE_VIDEO;

        video_enc->sample_aspect_ratio =

        st->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);

    } else {

        const char *p;

        int i;

        AVRational fps= frame_rate.num ? frame_rate : (AVRational){25,1};

        video_enc->codec_id = codec_id;

        set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);

        if (codec && codec->supported_framerates && !force_fps)

            fps = codec->supported_framerates[av_find_nearest_q_idx(fps, codec->supported_framerates)];

        video_enc->time_base.den = fps.num;

        video_enc->time_base.num = fps.den;

        video_enc->width = frame_width;

        video_enc->height = frame_height;

        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);

        video_enc->pix_fmt = frame_pix_fmt;

        st->sample_aspect_ratio = video_enc->sample_aspect_ratio;

        choose_pixel_fmt(st, codec);

        if (intra_only)

            video_enc->gop_size = 0;

        if (video_qscale || same_quality) {

            video_enc->flags |= CODEC_FLAG_QSCALE;

            video_enc->global_quality=

                st->quality = FF_QP2LAMBDA * video_qscale;

        }

        if(intra_matrix)

            video_enc->intra_matrix = intra_matrix;

        if(inter_matrix)

            video_enc->inter_matrix = inter_matrix;

        p= video_rc_override_string;

        for(i=0; p; i++){

            int start, end, q;

            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);

            if(e!=3){

                fprintf(stderr, "error parsing rc_override\n");

                ffmpeg_exit(1);

            }

            video_enc->rc_override=

                av_realloc(video_enc->rc_override,

                           sizeof(RcOverride)*(i+1));

            video_enc->rc_override[i].start_frame= start;

            video_enc->rc_override[i].end_frame  = end;

            if(q>0){

                video_enc->rc_override[i].qscale= q;

                video_enc->rc_override[i].quality_factor= 1.0;

            }

            else{

                video_enc->rc_override[i].qscale= 0;

                video_enc->rc_override[i].quality_factor= -q/100.0;

            }

            p= strchr(p, '/');

            if(p) p++;

        }

        video_enc->rc_override_count=i;

        if (!video_enc->rc_initial_buffer_occupancy)

            video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;

        video_enc->me_threshold= me_threshold;

        video_enc->intra_dc_precision= intra_dc_precision - 8;

        if (do_psnr)

            video_enc->flags|= CODEC_FLAG_PSNR;

        /* two pass mode */

        if (do_pass) {

            if (do_pass == 1) {

                video_enc->flags |= CODEC_FLAG_PASS1;

            } else {

                video_enc->flags |= CODEC_FLAG_PASS2;

            }

        }

    }

    if (video_language) {

        av_metadata_set2(&st->metadata, "language", video_language, 0);

        av_freep(&video_language);

    }

    /* reset some key parameters */

    video_disable = 0;

    av_freep(&video_codec_name);

    video_stream_copy = 0;

    frame_pix_fmt = PIX_FMT_NONE;

}


void visit_start_implicit_struct(Visitor *v, void **obj, size_t size,

                                 Error **errp)

{

    if (!error_is_set(errp) && v->start_implicit_struct) {

        v->start_implicit_struct(v, obj, size, errp);

    }

}


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

{

    struct timeval t1, t2;

    int Cflag = 0, qflag = 0;

    int c, cnt;

    char **buf;

    int64_t offset, first_offset = 0;

    /* Some compilers get confused and warn if this is not initialized.  */

    int total = 0;

    int nr_iov;

    int nr_reqs;

    int pattern = 0xcd;

    QEMUIOVector *qiovs;

    int i;

    BlockRequest *reqs;

    while ((c = getopt(argc, argv, "CqP:")) != EOF) {

        switch (c) {

        case 'C':

            Cflag = 1;

            break;

        case 'q':

            qflag = 1;

            break;

        case 'P':

            pattern = parse_pattern(optarg);

            if (pattern < 0) {

                return 0;

            }

            break;

        default:

            return command_usage(&writev_cmd);

        }

    }

    if (optind > argc - 2) {

        return command_usage(&writev_cmd);

    }

    nr_reqs = 1;

    for (i = optind; i < argc; i++) {

        if (!strcmp(argv[i], ";")) {

            nr_reqs++;

        }

    }

    reqs = g_malloc0(nr_reqs * sizeof(*reqs));

    buf = g_malloc0(nr_reqs * sizeof(*buf));

    qiovs = g_malloc(nr_reqs * sizeof(*qiovs));

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

        int j;

        /* Read the offset of the request */

        offset = cvtnum(argv[optind]);

        if (offset < 0) {

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

            return 0;

        }

        optind++;

        if (offset & 0x1ff) {

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

                   (long long)offset);

            return 0;

        }

        if (i == 0) {

            first_offset = offset;

        }

        /* Read lengths for qiov entries */

        for (j = optind; j < argc; j++) {

            if (!strcmp(argv[j], ";")) {

                break;

            }

        }

        nr_iov = j - optind;

        /* Build request */

        buf[i] = create_iovec(&qiovs[i], &argv[optind], nr_iov, pattern);

        if (buf[i] == NULL) {

            goto out;

        }

        reqs[i].qiov = &qiovs[i];

        reqs[i].sector = offset >> 9;

        reqs[i].nb_sectors = reqs[i].qiov->size >> 9;

        optind = j + 1;

        pattern++;

    }

    gettimeofday(&t1, NULL);

    cnt = do_aio_multiwrite(reqs, nr_reqs, &total);

    gettimeofday(&t2, NULL);

    if (cnt < 0) {

        printf("aio_multiwrite failed: %s\n", strerror(-cnt));

        goto out;

    }

    if (qflag) {

        goto out;

    }

    /* Finally, report back -- -C gives a parsable format */

    t2 = tsub(t2, t1);

    print_report("wrote", &t2, first_offset, total, total, cnt, Cflag);

out:

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

        qemu_io_free(buf[i]);

        if (reqs[i].qiov != NULL) {

            qemu_iovec_destroy(&qiovs[i]);

        }

    }

    g_free(buf);

    g_free(reqs);

    g_free(qiovs);

    return 0;

}


static void vaapi_encode_h264_write_sps(PutBitContext *pbc,

                                        VAAPIEncodeContext *ctx)

{

    VAEncSequenceParameterBufferH264  *vseq = ctx->codec_sequence_params;

    VAAPIEncodeH264Context            *priv = ctx->priv_data;

    VAAPIEncodeH264MiscSequenceParams *mseq = &priv->misc_sequence_params;

    int i;

    vaapi_encode_h264_write_nal_header(pbc, NAL_SPS, 3);

    u(8, mseq_var(profile_idc));

    u(1, mseq_var(constraint_set0_flag));

    u(1, mseq_var(constraint_set1_flag));

    u(1, mseq_var(constraint_set2_flag));

    u(1, mseq_var(constraint_set3_flag));

    u(1, mseq_var(constraint_set4_flag));

    u(1, mseq_var(constraint_set5_flag));

    u(2, 0, reserved_zero_2bits);

    u(8, vseq_var(level_idc));

    ue(vseq_var(seq_parameter_set_id));

    if (mseq->profile_idc == 100 || mseq->profile_idc == 110 ||

        mseq->profile_idc == 122 || mseq->profile_idc == 244 ||

        mseq->profile_idc ==  44 || mseq->profile_idc ==  83 ||

        mseq->profile_idc ==  86 || mseq->profile_idc == 118 ||

        mseq->profile_idc == 128 || mseq->profile_idc == 138) {

        ue(vseq_field(chroma_format_idc));

        if (vseq->seq_fields.bits.chroma_format_idc == 3)

            u(1, mseq_var(separate_colour_plane_flag));

        ue(vseq_var(bit_depth_luma_minus8));

        ue(vseq_var(bit_depth_chroma_minus8));

        u(1, mseq_var(qpprime_y_zero_transform_bypass_flag));

        u(1, vseq_field(seq_scaling_matrix_present_flag));

        if (vseq->seq_fields.bits.seq_scaling_matrix_present_flag) {

            av_assert0(0 && "scaling matrices not supported");

        }

    }

    ue(vseq_field(log2_max_frame_num_minus4));

    ue(vseq_field(pic_order_cnt_type));

    if (vseq->seq_fields.bits.pic_order_cnt_type == 0) {

        ue(vseq_field(log2_max_pic_order_cnt_lsb_minus4));

    } else if (vseq->seq_fields.bits.pic_order_cnt_type == 1) {

        u(1, mseq_var(delta_pic_order_always_zero_flag));

        se(vseq_var(offset_for_non_ref_pic));

        se(vseq_var(offset_for_top_to_bottom_field));

        ue(vseq_var(num_ref_frames_in_pic_order_cnt_cycle));

        for (i = 0; i < vseq->num_ref_frames_in_pic_order_cnt_cycle; i++)

            se(vseq_var(offset_for_ref_frame[i]));

    }

    ue(vseq_var(max_num_ref_frames));

    u(1, mseq_var(gaps_in_frame_num_allowed_flag));

    ue(vseq->picture_width_in_mbs  - 1, pic_width_in_mbs_minus1);

    ue(vseq->picture_height_in_mbs - 1, pic_height_in_mbs_minus1);

    u(1, vseq_field(frame_mbs_only_flag));

    if (!vseq->seq_fields.bits.frame_mbs_only_flag)

        u(1, vseq_field(mb_adaptive_frame_field_flag));

    u(1, vseq_field(direct_8x8_inference_flag));

    u(1, vseq_var(frame_cropping_flag));

    if (vseq->frame_cropping_flag) {

        ue(vseq_var(frame_crop_left_offset));

        ue(vseq_var(frame_crop_right_offset));

        ue(vseq_var(frame_crop_top_offset));

        ue(vseq_var(frame_crop_bottom_offset));

    }

    u(1, vseq_var(vui_parameters_present_flag));

    if (vseq->vui_parameters_present_flag)

        vaapi_encode_h264_write_vui(pbc, ctx);

    vaapi_encode_h264_write_trailing_rbsp(pbc);

}


static void restore_median(uint8_t *src, int step, int stride,

                           int width, int height, int slices, int rmode)

{

    int i, j, slice;

    int A, B, C;

    uint8_t *bsrc;

    int slice_start, slice_height;

    const int cmask = ~rmode;

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

        slice_start  = ((slice * height) / slices) & cmask;

        slice_height = ((((slice + 1) * height) / slices) & cmask) -

                       slice_start;

        bsrc = src + slice_start * stride;

        // first line - left neighbour prediction

        bsrc[0] += 0x80;

        A = bsrc[0];

        for (i = step; i < width * step; i += step) {

            bsrc[i] += A;

            A        = bsrc[i];

        }

        bsrc += stride;

        if (slice_height == 1)

            continue;

        // second line - first element has top prediction, the rest uses median

        C        = bsrc[-stride];

        bsrc[0] += C;

        A        = bsrc[0];

        for (i = step; i < width * step; i += step) {

            B        = bsrc[i - stride];

            bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));

            C        = B;

            A        = bsrc[i];

        }

        bsrc += stride;

        // the rest of lines use continuous median prediction

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

            for (i = 0; i < width * step; i += step) {

                B        = bsrc[i - stride];

                bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));

                C        = B;

                A        = bsrc[i];

            }

            bsrc += stride;

        }

    }

}


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

                             int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    SVQ1Context     *s = avctx->priv_data;

    AVFrame       *cur = s->cur;

    uint8_t *current;

    int result, i, x, y, width, height;

    svq1_pmv *pmv;

    if (cur->data[0])

        avctx->release_buffer(avctx, cur);

    /* initialize bit buffer */

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

    /* decode frame header */

    s->frame_code = get_bits(&s->gb, 22);

    if ((s->frame_code & ~0x70) || !(s->frame_code & 0x60))

        return AVERROR_INVALIDDATA;

    /* swap some header bytes (why?) */

    if (s->frame_code != 0x20) {

        uint32_t *src = (uint32_t *)(buf + 4);

        if (buf_size < 36)

            return AVERROR_INVALIDDATA;

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

            src[i] = ((src[i] << 16) | (src[i] >> 16)) ^ src[7 - i];

    }

    result = svq1_decode_frame_header(avctx, cur);

    if (result != 0) {

        av_dlog(avctx, "Error in svq1_decode_frame_header %i\n", result);

        return result;

    }

    avcodec_set_dimensions(avctx, s->width, s->height);

    if ((avctx->skip_frame >= AVDISCARD_NONREF && s->nonref) ||

        (avctx->skip_frame >= AVDISCARD_NONKEY &&

         cur->pict_type != AV_PICTURE_TYPE_I) ||

        avctx->skip_frame >= AVDISCARD_ALL)

        return buf_size;

    result = ff_get_buffer(avctx, cur);

    if (result < 0)

        return result;

    pmv = av_malloc((FFALIGN(s->width, 16) / 8 + 3) * sizeof(*pmv));

    if (!pmv)

        return AVERROR(ENOMEM);

    /* decode y, u and v components */

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

        int linesize = cur->linesize[i];

        if (i == 0) {

            width    = FFALIGN(s->width,  16);

            height   = FFALIGN(s->height, 16);

        } else {

            if (avctx->flags & CODEC_FLAG_GRAY)

                break;

            width    = FFALIGN(s->width  / 4, 16);

            height   = FFALIGN(s->height / 4, 16);

        }

        current = cur->data[i];

        if (cur->pict_type == AV_PICTURE_TYPE_I) {

            /* keyframe */

            for (y = 0; y < height; y += 16) {

                for (x = 0; x < width; x += 16) {

                    result = svq1_decode_block_intra(&s->gb, &current[x],

                                                     linesize);

                    if (result) {

                        av_log(avctx, AV_LOG_ERROR,

                               "Error in svq1_decode_block %i (keyframe)\n",

                               result);

                        goto err;

                    }

                }

                current += 16 * linesize;

            }

        } else {

            /* delta frame */

            uint8_t *previous = s->prev->data[i];

            if (!previous) {

                av_log(avctx, AV_LOG_ERROR, "Missing reference frame.\n");

                result = AVERROR_INVALIDDATA;

                goto err;

            }

            memset(pmv, 0, ((width / 8) + 3) * sizeof(svq1_pmv));

            for (y = 0; y < height; y += 16) {

                for (x = 0; x < width; x += 16) {

                    result = svq1_decode_delta_block(avctx, &s->dsp,

                                                     &s->gb, &current[x],

                                                     previous, linesize,

                                                     pmv, x, y);

                    if (result) {

                        av_dlog(avctx,

                                "Error in svq1_decode_delta_block %i\n",

                                result);

                        goto err;

                    }

                }

                pmv[0].x     =

                    pmv[0].y = 0;

                current += 16 * linesize;

            }

        }

    }

    *(AVFrame*)data = *cur;

    cur->qscale_table = NULL;

    if (!s->nonref)

        FFSWAP(AVFrame*, s->cur, s->prev);

    *got_frame = 1;

    result     = buf_size;

err:

    av_free(pmv);

    return result;

}


static int init_context_frame(MpegEncContext *s)

{

    int y_size, c_size, yc_size, i, mb_array_size, mv_table_size, x, y;

    s->mb_width   = (s->width + 15) / 16;

    s->mb_stride  = s->mb_width + 1;

    s->b8_stride  = s->mb_width * 2 + 1;

    s->b4_stride  = s->mb_width * 4 + 1;

    mb_array_size = s->mb_height * s->mb_stride;

    mv_table_size = (s->mb_height + 2) * s->mb_stride + 1;

    /* set default edge pos, will be overriden

     * in decode_header if needed */

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

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

    s->mb_num     = s->mb_width * s->mb_height;

    s->block_wrap[0] =

    s->block_wrap[1] =

    s->block_wrap[2] =

    s->block_wrap[3] = s->b8_stride;

    s->block_wrap[4] =

    s->block_wrap[5] = s->mb_stride;

    y_size  = s->b8_stride * (2 * s->mb_height + 1);

    c_size  = s->mb_stride * (s->mb_height + 1);

    yc_size = y_size + 2   * c_size;

    if (s->mb_height & 1)

        yc_size += 2*s->b8_stride + 2*s->mb_stride;

    FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_index2xy, (s->mb_num + 1) * sizeof(int), fail); // error ressilience code looks cleaner with this

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

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

            s->mb_index2xy[x + y * s->mb_width] = x + y * s->mb_stride;

    s->mb_index2xy[s->mb_height * s->mb_width] = (s->mb_height - 1) * s->mb_stride + s->mb_width; // FIXME really needed?

    if (s->encoding) {

        /* Allocate MV tables */

        FF_ALLOCZ_OR_GOTO(s->avctx, s->p_mv_table_base,                 mv_table_size * 2 * sizeof(int16_t), fail)

        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_forw_mv_table_base,            mv_table_size * 2 * sizeof(int16_t), fail)

        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_back_mv_table_base,            mv_table_size * 2 * sizeof(int16_t), fail)

        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_forw_mv_table_base,      mv_table_size * 2 * sizeof(int16_t), fail)

        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_back_mv_table_base,      mv_table_size * 2 * sizeof(int16_t), fail)

        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_direct_mv_table_base,          mv_table_size * 2 * sizeof(int16_t), fail)

        s->p_mv_table            = s->p_mv_table_base + s->mb_stride + 1;

        s->b_forw_mv_table       = s->b_forw_mv_table_base + s->mb_stride + 1;

        s->b_back_mv_table       = s->b_back_mv_table_base + s->mb_stride + 1;

        s->b_bidir_forw_mv_table = s->b_bidir_forw_mv_table_base + s->mb_stride + 1;

        s->b_bidir_back_mv_table = s->b_bidir_back_mv_table_base + s->mb_stride + 1;

        s->b_direct_mv_table     = s->b_direct_mv_table_base + s->mb_stride + 1;

        /* Allocate MB type table */

        FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_type, mb_array_size * sizeof(uint16_t), fail) // needed for encoding

        FF_ALLOCZ_OR_GOTO(s->avctx, s->lambda_table, mb_array_size * sizeof(int), fail)

        FF_ALLOC_OR_GOTO(s->avctx, s->cplx_tab,

                         mb_array_size * sizeof(float), fail);

        FF_ALLOC_OR_GOTO(s->avctx, s->bits_tab,

                         mb_array_size * sizeof(float), fail);

    }

    if (s->codec_id == AV_CODEC_ID_MPEG4 ||

        (s->flags & CODEC_FLAG_INTERLACED_ME)) {

        /* interlaced direct mode decoding tables */

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

            int j, k;

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

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

                    FF_ALLOCZ_OR_GOTO(s->avctx,

                                      s->b_field_mv_table_base[i][j][k],

                                      mv_table_size * 2 * sizeof(int16_t),

                                      fail);

                    s->b_field_mv_table[i][j][k] = s->b_field_mv_table_base[i][j][k] +

                                                   s->mb_stride + 1;

                }

                FF_ALLOCZ_OR_GOTO(s->avctx, s->b_field_select_table [i][j], mb_array_size * 2 * sizeof(uint8_t), fail)

                FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_mv_table_base[i][j], mv_table_size * 2 * sizeof(int16_t), fail)

                s->p_field_mv_table[i][j] = s->p_field_mv_table_base[i][j] + s->mb_stride + 1;

            }

            FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_select_table[i], mb_array_size * 2 * sizeof(uint8_t), fail)

        }

    }

    if (s->out_format == FMT_H263) {

        /* cbp values */

        FF_ALLOCZ_OR_GOTO(s->avctx, s->coded_block_base, y_size + (s->mb_height&1)*2*s->b8_stride, fail);

        s->coded_block = s->coded_block_base + s->b8_stride + 1;

        /* cbp, ac_pred, pred_dir */

        FF_ALLOCZ_OR_GOTO(s->avctx, s->cbp_table     , mb_array_size * sizeof(uint8_t), fail);

        FF_ALLOCZ_OR_GOTO(s->avctx, s->pred_dir_table, mb_array_size * sizeof(uint8_t), fail);

    }

    if (s->h263_pred || s->h263_plus || !s->encoding) {

        /* dc values */

        // MN: we need these for  error resilience of intra-frames

        FF_ALLOCZ_OR_GOTO(s->avctx, s->dc_val_base, yc_size * sizeof(int16_t), fail);

        s->dc_val[0] = s->dc_val_base + s->b8_stride + 1;

        s->dc_val[1] = s->dc_val_base + y_size + s->mb_stride + 1;

        s->dc_val[2] = s->dc_val[1] + c_size;

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

            s->dc_val_base[i] = 1024;

    }

    /* which mb is a intra block */

    FF_ALLOCZ_OR_GOTO(s->avctx, s->mbintra_table, mb_array_size, fail);

    memset(s->mbintra_table, 1, mb_array_size);

    /* init macroblock skip table */

    FF_ALLOCZ_OR_GOTO(s->avctx, s->mbskip_table, mb_array_size + 2, fail);

    // Note the + 1 is for  a quicker mpeg4 slice_end detection

    return init_er(s);

fail:

    return AVERROR(ENOMEM);

}


static void mpeg4_encode_gop_header(MpegEncContext * s){

    int hours, minutes, seconds;

    int64_t time;

    put_bits(&s->pb, 16, 0);

    put_bits(&s->pb, 16, GOP_STARTCODE);

    time= s->current_picture_ptr->pts;

    if(s->reordered_input_picture[1])

        time= FFMIN(time, s->reordered_input_picture[1]->pts);

    time= time*s->avctx->time_base.num;

    seconds= time/s->avctx->time_base.den;

    minutes= seconds/60; seconds %= 60;

    hours= minutes/60; minutes %= 60;

    hours%=24;

    put_bits(&s->pb, 5, hours);

    put_bits(&s->pb, 6, minutes);

    put_bits(&s->pb, 1, 1);

    put_bits(&s->pb, 6, seconds);

    put_bits(&s->pb, 1, !!(s->flags&CODEC_FLAG_CLOSED_GOP));

    put_bits(&s->pb, 1, 0); //broken link == NO

    s->last_time_base= time / s->avctx->time_base.den;

    ff_mpeg4_stuffing(&s->pb);

}


static int ws_snd_decode_frame(AVCodecContext *avctx,

                void *data, int *data_size,

                AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

//    WSSNDContext *c = avctx->priv_data;

    int in_size, out_size;

    int sample = 128;

    int i;

    uint8_t *samples = data;

    uint8_t *samples_end;

    if (!buf_size)

        return 0;

    if (buf_size < 4) {

        av_log(avctx, AV_LOG_ERROR, "packet is too small\n");

        return AVERROR(EINVAL);

    }

    out_size = AV_RL16(&buf[0]);

    in_size = AV_RL16(&buf[2]);

    buf += 4;

    if (out_size > *data_size) {

        av_log(avctx, AV_LOG_ERROR, "Frame is too large to fit in buffer\n");

        return -1;

    }

    if (in_size > buf_size) {

        av_log(avctx, AV_LOG_ERROR, "Frame data is larger than input buffer\n");

        return -1;

    }

    samples_end = samples + out_size;

    if (in_size == out_size) {

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

            *samples++ = *buf++;

        *data_size = out_size;

        return buf_size;

    }

    while (samples < samples_end && buf - avpkt->data < buf_size) {

        int code, smp, size;

        uint8_t count;

        code = (*buf) >> 6;

        count = (*buf) & 0x3F;

        buf++;

        /* make sure we don't write past the output buffer */

        switch (code) {

        case 0:  smp = 4;                              break;

        case 1:  smp = 2;                              break;

        case 2:  smp = (count & 0x20) ? 1 : count + 1; break;

        default: smp = count + 1;                      break;

        }

        if (samples_end - samples < smp)

            break;

        /* make sure we don't read past the input buffer */

        size = ((code == 2 && (count & 0x20)) || code == 3) ? 0 : count + 1;

        if ((buf - avpkt->data) + size > buf_size)

            break;

        switch(code) {

        case 0: /* ADPCM 2-bit */

            for (count++; count > 0; count--) {

                code = *buf++;

                sample += ws_adpcm_2bit[code & 0x3];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

                sample += ws_adpcm_2bit[(code >> 2) & 0x3];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

                sample += ws_adpcm_2bit[(code >> 4) & 0x3];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

                sample += ws_adpcm_2bit[(code >> 6) & 0x3];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

            }

            break;

        case 1: /* ADPCM 4-bit */

            for (count++; count > 0; count--) {

                code = *buf++;

                sample += ws_adpcm_4bit[code & 0xF];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

                sample += ws_adpcm_4bit[code >> 4];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

            }

            break;

        case 2: /* no compression */

            if (count & 0x20) { /* big delta */

                int8_t t;

                t = count;

                t <<= 3;

                sample += t >> 3;

                sample = av_clip_uint8(sample);

                *samples++ = sample;

            } else { /* copy */

                for (count++; count > 0; count--) {

                    *samples++ = *buf++;

                }

                sample = buf[-1];

            }

            break;

        default: /* run */

            for(count++; count > 0; count--) {

                *samples++ = sample;

            }

        }

    }

    *data_size = samples - (uint8_t *)data;

    return buf_size;

}


static int doTest(uint8_t *ref[3], int refStride[3], int w, int h, int srcFormat, int dstFormat,

                   int srcW, int srcH, int dstW, int dstH, int flags){

	uint8_t *src[3];

	uint8_t *dst[3];

	uint8_t *out[3];

	int srcStride[3], dstStride[3];

	int i;

	uint64_t ssdY, ssdU, ssdV;

	struct SwsContext *srcContext, *dstContext, *outContext;

	int res;

	res = 0;

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

		// avoid stride % bpp != 0

		if(srcFormat==PIX_FMT_RGB24 || srcFormat==PIX_FMT_BGR24)

			srcStride[i]= srcW*3;

		else

			srcStride[i]= srcW*4;

		if(dstFormat==PIX_FMT_RGB24 || dstFormat==PIX_FMT_BGR24)

			dstStride[i]= dstW*3;

		else

			dstStride[i]= dstW*4;

		src[i]= (uint8_t*) malloc(srcStride[i]*srcH);

		dst[i]= (uint8_t*) malloc(dstStride[i]*dstH);

		out[i]= (uint8_t*) malloc(refStride[i]*h);

		if ((src[i] == NULL) || (dst[i] == NULL) || (out[i] == NULL)) {

			perror("Malloc");

			res = -1;

			goto end;

		}

	}

	dstContext = outContext = NULL;

	srcContext= sws_getContext(w, h, PIX_FMT_YUV420P, srcW, srcH, srcFormat, flags, NULL, NULL, NULL);

	if (srcContext == NULL) {

		fprintf(stderr, "Failed to get %s ---> %s\n",

				sws_format_name(PIX_FMT_YUV420P),

				sws_format_name(srcFormat));

		res = -1;

		goto end;

	}

	dstContext= sws_getContext(srcW, srcH, srcFormat, dstW, dstH, dstFormat, flags, NULL, NULL, NULL);

	if (dstContext == NULL) {

		fprintf(stderr, "Failed to get %s ---> %s\n",

				sws_format_name(srcFormat),

				sws_format_name(dstFormat));

		res = -1;

		goto end;

	}

	outContext= sws_getContext(dstW, dstH, dstFormat, w, h, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);

	if (outContext == NULL) {

		fprintf(stderr, "Failed to get %s ---> %s\n",

				sws_format_name(dstFormat),

				sws_format_name(PIX_FMT_YUV420P));

		res = -1;

		goto end;

	}

//	printf("test %X %X %X -> %X %X %X\n", (int)ref[0], (int)ref[1], (int)ref[2],

//		(int)src[0], (int)src[1], (int)src[2]);

	sws_scale(srcContext, ref, refStride, 0, h   , src, srcStride);

	sws_scale(dstContext, src, srcStride, 0, srcH, dst, dstStride);

	sws_scale(outContext, dst, dstStride, 0, dstH, out, refStride);

#if defined(ARCH_X86)

	asm volatile ("emms\n\t");

#endif

	ssdY= getSSD(ref[0], out[0], refStride[0], refStride[0], w, h);

	ssdU= getSSD(ref[1], out[1], refStride[1], refStride[1], (w+1)>>1, (h+1)>>1);

	ssdV= getSSD(ref[2], out[2], refStride[2], refStride[2], (w+1)>>1, (h+1)>>1);

	if(srcFormat == PIX_FMT_GRAY8 || dstFormat==PIX_FMT_GRAY8) ssdU=ssdV=0; //FIXME check that output is really gray

	ssdY/= w*h;

	ssdU/= w*h/4;

	ssdV/= w*h/4;

	if(ssdY>100 || ssdU>100 || ssdV>100){

		printf(" %s %dx%d -> %s %4dx%4d flags=%2d SSD=%5lld,%5lld,%5lld\n",

			sws_format_name(srcFormat), srcW, srcH,

			sws_format_name(dstFormat), dstW, dstH,

			flags,

			ssdY, ssdU, ssdV);

	}

	end:

	sws_freeContext(srcContext);

	sws_freeContext(dstContext);

	sws_freeContext(outContext);

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

		free(src[i]);

		free(dst[i]);

		free(out[i]);

	}

	return res;

}


static int local_mknod(FsContext *fs_ctx, const char *path, FsCred *credp)

{

    int err = -1;

    int serrno = 0;

    /* Determine the security model */

    if (fs_ctx->fs_sm == SM_MAPPED) {

        err = mknod(rpath(fs_ctx, path), SM_LOCAL_MODE_BITS|S_IFREG, 0);

        if (err == -1) {

            return err;

        }

        local_set_xattr(rpath(fs_ctx, path), credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    } else if (fs_ctx->fs_sm == SM_PASSTHROUGH) {

        err = mknod(rpath(fs_ctx, path), credp->fc_mode, credp->fc_rdev);

        if (err == -1) {

            return err;

        }

        err = local_post_create_passthrough(fs_ctx, path, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    }

    return err;

err_end:

    remove(rpath(fs_ctx, path));

    errno = serrno;

    return err;

}


uint32_t ff_celt_encode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,

                             float *X, float *Y, int N, int b, uint32_t blocks,

                             float *lowband, int duration, float *lowband_out, int level,

                             float gain, float *lowband_scratch, int fill)

{

    const uint8_t *cache;

    int dualstereo, split;

    int imid = 0, iside = 0;

    //uint32_t N0 = N;

    int N_B;

    //int N_B0;

    int B0 = blocks;

    int time_divide = 0;

    int recombine = 0;

    int inv = 0;

    float mid = 0, side = 0;

    int longblocks = (B0 == 1);

    uint32_t cm = 0;

    //N_B0 = N_B = N / blocks;

    split = dualstereo = (Y != NULL);

    if (N == 1) {

        /* special case for one sample - the decoder's output will be +- 1.0f!!! */

        int i;

        float *x = X;

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

            if (f->remaining2 >= 1<<3) {

                ff_opus_rc_put_raw(rc, x[0] < 0, 1);

                f->remaining2 -= 1 << 3;

                b             -= 1 << 3;

            }

            x = Y;

        }

        if (lowband_out)

            lowband_out[0] = X[0];

        return 1;

    }

    if (!dualstereo && level == 0) {

        int tf_change = f->tf_change[band];

        int k;

        if (tf_change > 0)

            recombine = tf_change;

        /* Band recombining to increase frequency resolution */

        if (lowband &&

            (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {

            int j;

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

                lowband_scratch[j] = lowband[j];

            lowband = lowband_scratch;

        }

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

            celt_haar1(X, N >> k, 1 << k);

            fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;

        }

        blocks >>= recombine;

        N_B <<= recombine;

        /* Increasing the time resolution */

        while ((N_B & 1) == 0 && tf_change < 0) {

            celt_haar1(X, N_B, blocks);

            fill |= fill << blocks;

            blocks <<= 1;

            N_B >>= 1;

            time_divide++;

            tf_change++;

        }

        B0 = blocks;

        //N_B0 = N_B;

        /* Reorganize the samples in time order instead of frequency order */

        if (B0 > 1)

            celt_deinterleave_hadamard(f->scratch, X, N_B >> recombine,

                                       B0 << recombine, longblocks);

    }

    /* If we need 1.5 more bit than we can produce, split the band in two. */

    cache = ff_celt_cache_bits +

            ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];

    if (!dualstereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {

        N >>= 1;

        Y = X + N;

        split = 1;

        duration -= 1;

        if (blocks == 1)

            fill = (fill & 1) | (fill << 1);

        blocks = (blocks + 1) >> 1;

    }

    if (split) {

        int qn;

        int itheta = celt_calc_theta(X, Y, dualstereo, N);

        int mbits, sbits, delta;

        int qalloc;

        int pulse_cap;

        int offset;

        int orig_fill;

        int tell;

        /* Decide on the resolution to give to the split parameter theta */

        pulse_cap = ff_celt_log_freq_range[band] + duration * 8;

        offset = (pulse_cap >> 1) - (dualstereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :

                                                          CELT_QTHETA_OFFSET);

        qn = (dualstereo && band >= f->intensity_stereo) ? 1 :

             celt_compute_qn(N, b, offset, pulse_cap, dualstereo);

        tell = opus_rc_tell_frac(rc);

        if (qn != 1) {

            itheta = (itheta*qn + 8192) >> 14;

            /* Entropy coding of the angle. We use a uniform pdf for the

             * time split, a step for stereo, and a triangular one for the rest. */

            if (dualstereo && N > 2)

                ff_opus_rc_enc_uint_step(rc, itheta, qn / 2);

            else if (dualstereo || B0 > 1)

                ff_opus_rc_enc_uint(rc, itheta, qn + 1);

            else

                ff_opus_rc_enc_uint_tri(rc, itheta, qn);

            itheta = itheta * 16384 / qn;

            if (dualstereo) {

                if (itheta == 0)

                    celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band], f->block[1].lin_energy[band], N);

                else

                    celt_stereo_ms_decouple(X, Y, N);

            }

        } else if (dualstereo) {

             inv = itheta > 8192;

             if (inv)

             {

                int j;

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

                   Y[j] = -Y[j];

             }

             celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band], f->block[1].lin_energy[band], N);

            if (b > 2 << 3 && f->remaining2 > 2 << 3) {

                ff_opus_rc_enc_log(rc, inv, 2);

            } else {

                inv = 0;

            }

            itheta = 0;

        }

        qalloc = opus_rc_tell_frac(rc) - tell;

        b -= qalloc;

        orig_fill = fill;

        if (itheta == 0) {

            imid = 32767;

            iside = 0;

            fill = av_mod_uintp2(fill, blocks);

            delta = -16384;

        } else if (itheta == 16384) {

            imid = 0;

            iside = 32767;

            fill &= ((1 << blocks) - 1) << blocks;

            delta = 16384;

        } else {

            imid = celt_cos(itheta);

            iside = celt_cos(16384-itheta);

            /* This is the mid vs side allocation that minimizes squared error

            in that band. */

            delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));

        }

        mid  = imid  / 32768.0f;

        side = iside / 32768.0f;

        /* This is a special case for N=2 that only works for stereo and takes

        advantage of the fact that mid and side are orthogonal to encode

        the side with just one bit. */

        if (N == 2 && dualstereo) {

            int c;

            int sign = 0;

            float tmp;

            float *x2, *y2;

            mbits = b;

            /* Only need one bit for the side */

            sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;

            mbits -= sbits;

            c = (itheta > 8192);

            f->remaining2 -= qalloc+sbits;

            x2 = c ? Y : X;

            y2 = c ? X : Y;

            if (sbits) {

                sign = x2[0]*y2[1] - x2[1]*y2[0] < 0;

                ff_opus_rc_put_raw(rc, sign, 1);

            }

            sign = 1 - 2 * sign;

            /* We use orig_fill here because we want to fold the side, but if

            itheta==16384, we'll have cleared the low bits of fill. */

            cm = ff_celt_encode_band(f, rc, band, x2, NULL, N, mbits, blocks,

                                     lowband, duration, lowband_out, level, gain,

                                     lowband_scratch, orig_fill);

            /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),

            and there's no need to worry about mixing with the other channel. */

            y2[0] = -sign * x2[1];

            y2[1] =  sign * x2[0];

            X[0] *= mid;

            X[1] *= mid;

            Y[0] *= side;

            Y[1] *= side;

            tmp = X[0];

            X[0] = tmp - Y[0];

            Y[0] = tmp + Y[0];

            tmp = X[1];

            X[1] = tmp - Y[1];

            Y[1] = tmp + Y[1];

        } else {

            /* "Normal" split code */

            float *next_lowband2     = NULL;

            float *next_lowband_out1 = NULL;

            int next_level = 0;

            int rebalance;

            /* Give more bits to low-energy MDCTs than they would

             * otherwise deserve */

            if (B0 > 1 && !dualstereo && (itheta & 0x3fff)) {

                if (itheta > 8192)

                    /* Rough approximation for pre-echo masking */

                    delta -= delta >> (4 - duration);

                else

                    /* Corresponds to a forward-masking slope of

                     * 1.5 dB per 10 ms */

                    delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));

            }

            mbits = av_clip((b - delta) / 2, 0, b);

            sbits = b - mbits;

            f->remaining2 -= qalloc;

            if (lowband && !dualstereo)

                next_lowband2 = lowband + N; /* >32-bit split case */

            /* Only stereo needs to pass on lowband_out.

             * Otherwise, it's handled at the end */

            if (dualstereo)

                next_lowband_out1 = lowband_out;

            else

                next_level = level + 1;

            rebalance = f->remaining2;

            if (mbits >= sbits) {

                /* In stereo mode, we do not apply a scaling to the mid

                 * because we need the normalized mid for folding later */

                cm = ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,

                                         lowband, duration, next_lowband_out1,

                                         next_level, dualstereo ? 1.0f : (gain * mid),

                                         lowband_scratch, fill);

                rebalance = mbits - (rebalance - f->remaining2);

                if (rebalance > 3 << 3 && itheta != 0)

                    sbits += rebalance - (3 << 3);

                /* For a stereo split, the high bits of fill are always zero,

                 * so no folding will be done to the side. */

                cm |= ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,

                                          next_lowband2, duration, NULL,

                                          next_level, gain * side, NULL,

                                          fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));

            } else {

                /* For a stereo split, the high bits of fill are always zero,

                 * so no folding will be done to the side. */

                cm = ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,

                                         next_lowband2, duration, NULL,

                                         next_level, gain * side, NULL,

                                         fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));

                rebalance = sbits - (rebalance - f->remaining2);

                if (rebalance > 3 << 3 && itheta != 16384)

                    mbits += rebalance - (3 << 3);

                /* In stereo mode, we do not apply a scaling to the mid because

                 * we need the normalized mid for folding later */

                cm |= ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,

                                          lowband, duration, next_lowband_out1,

                                          next_level, dualstereo ? 1.0f : (gain * mid),

                                          lowband_scratch, fill);

            }

        }

    } else {

        /* This is the basic no-split case */

        uint32_t q         = celt_bits2pulses(cache, b);

        uint32_t curr_bits = celt_pulses2bits(cache, q);

        f->remaining2 -= curr_bits;

        /* Ensures we can never bust the budget */

        while (f->remaining2 < 0 && q > 0) {

            f->remaining2 += curr_bits;

            curr_bits      = celt_pulses2bits(cache, --q);

            f->remaining2 -= curr_bits;

        }

        if (q != 0) {

            /* Finally do the actual quantization */

            cm = celt_alg_quant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),

                                f->spread, blocks, gain);

        }

    }

    return cm;

}


static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,

                                 uint64_t value)

{

    env->cp15.c5_data = extended_mpu_ap_bits(value);

}


static int mv_read_packet(AVFormatContext *avctx, AVPacket *pkt)

{

    MvContext *mv = avctx->priv_data;

    AVIOContext *pb = avctx->pb;

    AVStream *st = avctx->streams[mv->stream_index];

    const AVIndexEntry *index;

    int frame = mv->frame[mv->stream_index];

    int ret;

    uint64_t pos;

    if (frame  < st->nb_frames) {

        index = &st->index_entries[frame];

        pos = avio_tell(pb);

        if (index->pos > pos)

            avio_skip(pb, index->pos - pos);

        else if (index->pos < pos) {

            if (!pb->seekable)

                return AVERROR(EIO);

            ret = avio_seek(pb, index->pos, SEEK_SET);

            if (ret < 0)

                return ret;

        }

        ret = av_get_packet(pb, pkt, index->size);

        if (ret < 0)

            return ret;

        pkt->stream_index = mv->stream_index;

        pkt->pts = index->timestamp;

        pkt->flags |= AV_PKT_FLAG_KEY;

        mv->frame[mv->stream_index]++;

        mv->eof_count = 0;

    } else {

        mv->eof_count++;

        if (mv->eof_count >= avctx->nb_streams)

            return AVERROR_EOF;

    }

    mv->stream_index++;

    if (mv->stream_index >= avctx->nb_streams)

        mv->stream_index = 0;

    return 0;

}


static int adx_parse(AVCodecParserContext *s1,

                           AVCodecContext *avctx,

                           const uint8_t **poutbuf, int *poutbuf_size,

                           const uint8_t *buf, int buf_size)

{

    ADXParseContext *s = s1->priv_data;

    ParseContext *pc = &s->pc;

    int next = END_NOT_FOUND;

    if (!avctx->extradata_size) {

        int ret;

        ff_combine_frame(pc, END_NOT_FOUND, &buf, &buf_size);

        if (!s->header_size && pc->index >= MIN_HEADER_SIZE) {

            if (ret = avpriv_adx_decode_header(avctx, pc->buffer, pc->index,

                                               &s->header_size, NULL))

                return AVERROR_INVALIDDATA;

            s->block_size = BLOCK_SIZE * avctx->channels;

        }

        if (s->header_size && s->header_size <= pc->index) {

            avctx->extradata = av_mallocz(s->header_size + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!avctx->extradata)

                return AVERROR(ENOMEM);

            avctx->extradata_size = s->header_size;

            memcpy(avctx->extradata, pc->buffer, s->header_size);

            memmove(pc->buffer, pc->buffer + s->header_size, s->header_size);

            pc->index -= s->header_size;

        }

        *poutbuf      = NULL;

        *poutbuf_size = 0;

        return buf_size;

    }

    if (pc->index - s->buf_pos >= s->block_size) {

        *poutbuf      = &pc->buffer[s->buf_pos];

        *poutbuf_size = s->block_size;

        s->buf_pos   += s->block_size;

        return 0;

    }

    if (pc->index && s->buf_pos) {

        memmove(pc->buffer, &pc->buffer[s->buf_pos], pc->index - s->buf_pos);

        pc->index -= s->buf_pos;

        s->buf_pos = 0;

    }

    if (buf_size + pc->index >= s->block_size)

        next = s->block_size - pc->index;

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

        *poutbuf      = NULL;

        *poutbuf_size = 0;

        return buf_size;

    }

    *poutbuf = buf;

    *poutbuf_size = buf_size;

    return next;

}


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

                                ptrdiff_t stride)

{

    avc_luma_hz_qrt_8w_msa(src - 2, stride, dst, stride, 8, 0);

}


static int decode_dvd_subtitles(AVSubtitle *sub_header,

                                const uint8_t *buf, int buf_size)

{

    int cmd_pos, pos, cmd, x1, y1, x2, y2, offset1, offset2, next_cmd_pos;

    int big_offsets, offset_size, is_8bit = 0;

    const uint8_t *yuv_palette = 0;

    uint8_t colormap[4], alpha[256];

    int date;

    int i;

    int is_menu = 0;

    if (buf_size < 10)

        return -1;

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

    if (AV_RB16(buf) == 0) {   /* HD subpicture with 4-byte offsets */

        big_offsets = 1;

        offset_size = 4;

        cmd_pos = 6;

    } else {

        big_offsets = 0;

        offset_size = 2;

        cmd_pos = 2;

    }

    cmd_pos = READ_OFFSET(buf + cmd_pos);

    while (cmd_pos > 0 && cmd_pos < buf_size - 2 - offset_size) {

        date = AV_RB16(buf + cmd_pos);

        next_cmd_pos = READ_OFFSET(buf + cmd_pos + 2);

        av_dlog(NULL, "cmd_pos=0x%04x next=0x%04x date=%d\n",

                cmd_pos, next_cmd_pos, date);

        pos = cmd_pos + 2 + offset_size;

        offset1 = -1;

        offset2 = -1;

        x1 = y1 = x2 = y2 = 0;

        while (pos < buf_size) {

            cmd = buf[pos++];

            av_dlog(NULL, "cmd=%02x\n", cmd);

            switch(cmd) {

            case 0x00:

                /* menu subpicture */

                is_menu = 1;

                break;

            case 0x01:

                /* set start date */

                sub_header->start_display_time = (date << 10) / 90;

                break;

            case 0x02:

                /* set end date */

                sub_header->end_display_time = (date << 10) / 90;

                break;

            case 0x03:

                /* set colormap */

                if ((buf_size - pos) < 2)

                    goto fail;

                colormap[3] = buf[pos] >> 4;

                colormap[2] = buf[pos] & 0x0f;

                colormap[1] = buf[pos + 1] >> 4;

                colormap[0] = buf[pos + 1] & 0x0f;

                pos += 2;

                break;

            case 0x04:

                /* set alpha */

                if ((buf_size - pos) < 2)

                    goto fail;

                alpha[3] = buf[pos] >> 4;

                alpha[2] = buf[pos] & 0x0f;

                alpha[1] = buf[pos + 1] >> 4;

                alpha[0] = buf[pos + 1] & 0x0f;

                pos += 2;

            av_dlog(NULL, "alpha=%x%x%x%x\n", alpha[0],alpha[1],alpha[2],alpha[3]);

                break;

            case 0x05:

            case 0x85:

                if ((buf_size - pos) < 6)

                    goto fail;

                x1 = (buf[pos] << 4) | (buf[pos + 1] >> 4);

                x2 = ((buf[pos + 1] & 0x0f) << 8) | buf[pos + 2];

                y1 = (buf[pos + 3] << 4) | (buf[pos + 4] >> 4);

                y2 = ((buf[pos + 4] & 0x0f) << 8) | buf[pos + 5];

                if (cmd & 0x80)

                    is_8bit = 1;

                av_dlog(NULL, "x1=%d x2=%d y1=%d y2=%d\n", x1, x2, y1, y2);

                pos += 6;

                break;

            case 0x06:

                if ((buf_size - pos) < 4)

                    goto fail;

                offset1 = AV_RB16(buf + pos);

                offset2 = AV_RB16(buf + pos + 2);

                av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);

                pos += 4;

                break;

            case 0x86:

                if ((buf_size - pos) < 8)

                    goto fail;

                offset1 = AV_RB32(buf + pos);

                offset2 = AV_RB32(buf + pos + 4);

                av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);

                pos += 8;

                break;

            case 0x83:

                /* HD set palette */

                if ((buf_size - pos) < 768)

                    goto fail;

                yuv_palette = buf + pos;

                pos += 768;

                break;

            case 0x84:

                /* HD set contrast (alpha) */

                if ((buf_size - pos) < 256)

                    goto fail;

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

                    alpha[i] = 0xFF - buf[pos+i];

                pos += 256;

                break;

            case 0xff:

                goto the_end;

            default:

                av_dlog(NULL, "unrecognised subpicture command 0x%x\n", cmd);

                goto the_end;

            }

        }

    the_end:

        if (offset1 >= 0) {

            int w, h;

            uint8_t *bitmap;

            /* decode the bitmap */

            w = x2 - x1 + 1;

            if (w < 0)

                w = 0;

            h = y2 - y1;

            if (h < 0)

                h = 0;

            if (w > 0 && h > 0) {

                if (sub_header->rects != NULL) {

                    for (i = 0; i < sub_header->num_rects; i++) {

                        av_freep(&sub_header->rects[i]->pict.data[0]);

                        av_freep(&sub_header->rects[i]->pict.data[1]);

                        av_freep(&sub_header->rects[i]);

                    }

                    av_freep(&sub_header->rects);

                    sub_header->num_rects = 0;

                }

                bitmap = av_malloc(w * h);

                sub_header->rects = av_mallocz(sizeof(*sub_header->rects));

                sub_header->rects[0] = av_mallocz(sizeof(AVSubtitleRect));

                sub_header->num_rects = 1;

                sub_header->rects[0]->pict.data[0] = bitmap;

                decode_rle(bitmap, w * 2, w, (h + 1) / 2,

                           buf, offset1, buf_size, is_8bit);

                decode_rle(bitmap + w, w * 2, w, h / 2,

                           buf, offset2, buf_size, is_8bit);

                sub_header->rects[0]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);

                if (is_8bit) {

                    if (yuv_palette == 0)

                        goto fail;

                    sub_header->rects[0]->nb_colors = 256;

                    yuv_a_to_rgba(yuv_palette, alpha, (uint32_t*)sub_header->rects[0]->pict.data[1], 256);

                } else {

                    sub_header->rects[0]->nb_colors = 4;

                    guess_palette((uint32_t*)sub_header->rects[0]->pict.data[1],

                                  colormap, alpha, 0xffff00);

                }

                sub_header->rects[0]->x = x1;

                sub_header->rects[0]->y = y1;

                sub_header->rects[0]->w = w;

                sub_header->rects[0]->h = h;

                sub_header->rects[0]->type = SUBTITLE_BITMAP;

                sub_header->rects[0]->pict.linesize[0] = w;

            }

        }

        if (next_cmd_pos == cmd_pos)

            break;

        cmd_pos = next_cmd_pos;

    }

    if (sub_header->num_rects > 0)

        return is_menu;

 fail:

    if (sub_header->rects != NULL) {

        for (i = 0; i < sub_header->num_rects; i++) {

            av_freep(&sub_header->rects[i]->pict.data[0]);

            av_freep(&sub_header->rects[i]->pict.data[1]);

            av_freep(&sub_header->rects[i]);

        }

        av_freep(&sub_header->rects);

        sub_header->num_rects = 0;

    }

    return -1;

}


static AVFrame *apply_palette(AVFilterLink *inlink, AVFrame *in)

{

    int x, y, w, h;

    AVFilterContext *ctx = inlink->dst;

    PaletteUseContext *s = ctx->priv;

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

    AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);

    if (!out) {

        av_frame_free(&in);

        return NULL;

    }

    av_frame_copy_props(out, in);

    set_processing_window(s->diff_mode, s->last_in, in,

                          s->last_out, out, &x, &y, &w, &h);

    av_frame_free(&s->last_in);

    av_frame_free(&s->last_out);

    s->last_in  = av_frame_clone(in);

    s->last_out = av_frame_clone(out);

    if (!s->last_in || !s->last_out ||

        av_frame_make_writable(s->last_in) < 0) {

        av_frame_free(&in);

        av_frame_free(&out);

        return NULL;

    }

    ff_dlog(ctx, "%dx%d rect: (%d;%d) -> (%d,%d) [area:%dx%d]\n",

            w, h, x, y, x+w, y+h, in->width, in->height);

    if (s->set_frame(s, out, in, x, y, w, h) < 0) {

        av_frame_free(&out);

        return NULL;

    }

    memcpy(out->data[1], s->palette, AVPALETTE_SIZE);

    if (s->calc_mean_err)

        debug_mean_error(s, in, out, inlink->frame_count_out);

    av_frame_free(&in);

    return out;

}


static av_cold int flic_decode_init(AVCodecContext *avctx)

{

    FlicDecodeContext *s = avctx->priv_data;

    unsigned char *fli_header = (unsigned char *)avctx->extradata;

    int depth;

    if (avctx->extradata_size != 0 &&

        avctx->extradata_size != 12 &&

        avctx->extradata_size != 128 &&

        avctx->extradata_size != 1024) {

        av_log(avctx, AV_LOG_ERROR, "Expected extradata of 12, 128 or 1024 bytes\n");

        return AVERROR_INVALIDDATA;

    }

    s->avctx = avctx;

    if (s->avctx->extradata_size == 12) {

        /* special case for magic carpet FLIs */

        s->fli_type = FLC_MAGIC_CARPET_SYNTHETIC_TYPE_CODE;

        depth = 8;

    } else if (avctx->extradata_size == 1024) {

        uint8_t *ptr = avctx->extradata;

        int i;

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

            s->palette[i] = AV_RL32(ptr);

            ptr += 4;

        }

        depth = 8;

    } else if (avctx->extradata_size == 0) {

        /* FLI in MOV, see e.g. FFmpeg trac issue #626 */

        s->fli_type = FLI_TYPE_CODE;

        depth = 8;

    } else {

        s->fli_type = AV_RL16(&fli_header[4]);

        depth = AV_RL16(&fli_header[12]);

    }

    if (depth == 0) {

        depth = 8; /* Some FLC generators set depth to zero, when they mean 8Bpp. Fix up here */

    }

    if ((s->fli_type == FLC_FLX_TYPE_CODE) && (depth == 16)) {

        depth = 15; /* Original Autodesk FLX's say the depth is 16Bpp when it is really 15Bpp */

    }

    switch (depth) {

        case 8  : avctx->pix_fmt = PIX_FMT_PAL8; break;

        case 15 : avctx->pix_fmt = PIX_FMT_RGB555; break;

        case 16 : avctx->pix_fmt = PIX_FMT_RGB565; break;

        case 24 : avctx->pix_fmt = PIX_FMT_BGR24; /* Supposedly BGR, but havent any files to test with */

                  av_log(avctx, AV_LOG_ERROR, "24Bpp FLC/FLX is unsupported due to no test files.\n");

                  return -1;

        default :

                  av_log(avctx, AV_LOG_ERROR, "Unknown FLC/FLX depth of %d Bpp is unsupported.\n",depth);

                  return -1;

    }

    avcodec_get_frame_defaults(&s->frame);

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

    s->new_palette = 0;

    return 0;

}


static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis)

{

    PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);

    uint64_t remote_hps, remote_tps;

    trace_loadvm_postcopy_handle_advise();

    if (ps != POSTCOPY_INCOMING_NONE) {

        error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);

        return -1;

    }

    if (!postcopy_ram_supported_by_host()) {

        postcopy_state_set(POSTCOPY_INCOMING_NONE);

        return -1;

    }

    remote_hps = qemu_get_be64(mis->from_src_file);

    if (remote_hps != getpagesize())  {

        /*

         * Some combinations of mismatch are probably possible but it gets

         * a bit more complicated.  In particular we need to place whole

         * host pages on the dest at once, and we need to ensure that we

         * handle dirtying to make sure we never end up sending part of

         * a hostpage on it's own.

         */

        error_report("Postcopy needs matching host page sizes (s=%d d=%d)",

                     (int)remote_hps, getpagesize());

        return -1;

    }

    remote_tps = qemu_get_be64(mis->from_src_file);

    if (remote_tps != (1ul << qemu_target_page_bits())) {

        /*

         * Again, some differences could be dealt with, but for now keep it

         * simple.

         */

        error_report("Postcopy needs matching target page sizes (s=%d d=%d)",

                     (int)remote_tps, 1 << qemu_target_page_bits());

        return -1;

    }

    if (ram_postcopy_incoming_init(mis)) {

        return -1;

    }

    postcopy_state_set(POSTCOPY_INCOMING_ADVISE);

    return 0;

}


static void search_for_quantizers_twoloop(AVCodecContext *avctx,

                                          AACEncContext *s,

                                          SingleChannelElement *sce,

                                          const float lambda)

{

    int start = 0, i, w, w2, g;

    int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate / avctx->channels * (lambda / 120.f);

    float dists[128] = { 0 }, uplims[128] = { 0 };

    float maxvals[128];

    int fflag, minscaler;

    int its  = 0;

    int allz = 0;

    float minthr = INFINITY;

    // for values above this the decoder might end up in an endless loop

    // due to always having more bits than what can be encoded.

    destbits = FFMIN(destbits, 5800);

    //XXX: some heuristic to determine initial quantizers will reduce search time

    //determine zero bands and upper limits

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

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

            int nz = 0;

            float uplim = 0.0f, energy = 0.0f;

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

                FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];

                uplim  += band->threshold;

                energy += band->energy;

                if (band->energy <= band->threshold || band->threshold == 0.0f) {

                    sce->zeroes[(w+w2)*16+g] = 1;

                    continue;

                }

                nz = 1;

            }

            uplims[w*16+g] = uplim *512;

            sce->zeroes[w*16+g] = !nz;

            if (nz)

                minthr = FFMIN(minthr, uplim);

            allz |= nz;

        }

    }

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

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

            if (sce->zeroes[w*16+g]) {

                sce->sf_idx[w*16+g] = SCALE_ONE_POS;

                continue;

            }

            sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2f(uplims[w*16+g]/minthr)*4,59);

        }

    }

    if (!allz)

        return;

    abs_pow34_v(s->scoefs, sce->coeffs, 1024);

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

        start = w*128;

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

            const float *scaled = s->scoefs + start;

            maxvals[w*16+g] = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], scaled);

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

        }

    }

    //perform two-loop search

    //outer loop - improve quality

    do {

        int tbits, qstep;

        minscaler = sce->sf_idx[0];

        //inner loop - quantize spectrum to fit into given number of bits

        qstep = its ? 1 : 32;

        do {

            int prev = -1;

            tbits = 0;

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

                start = w*128;

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

                    const float *coefs = sce->coeffs + start;

                    const float *scaled = s->scoefs + start;

                    int bits = 0;

                    int cb;

                    float dist = 0.0f;

                    if (sce->zeroes[w*16+g] || sce->sf_idx[w*16+g] >= 218) {

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

                        continue;

                    }

                    minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);

                    cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);

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

                        int b;

                        dist += quantize_band_cost(s, coefs + w2*128,

                                                   scaled + w2*128,

                                                   sce->ics.swb_sizes[g],

                                                   sce->sf_idx[w*16+g],

                                                   cb,

                                                   1.0f,

                                                   INFINITY,

                                                   &b,

                                                   0);

                        bits += b;

                    }

                    dists[w*16+g] = dist - bits;

                    if (prev != -1) {

                        bits += ff_aac_scalefactor_bits[sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO];

                    }

                    tbits += bits;

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

                    prev = sce->sf_idx[w*16+g];

                }

            }

            if (tbits > destbits) {

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

                    if (sce->sf_idx[i] < 218 - qstep)

                        sce->sf_idx[i] += qstep;

            } else {

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

                    if (sce->sf_idx[i] > 60 - qstep)

                        sce->sf_idx[i] -= qstep;

            }

            qstep >>= 1;

            if (!qstep && tbits > destbits*1.02 && sce->sf_idx[0] < 217)

                qstep = 1;

        } while (qstep);

        fflag = 0;

        minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);

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

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

                int prevsc = sce->sf_idx[w*16+g];

                if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60) {

                    if (find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1))

                        sce->sf_idx[w*16+g]--;

                    else //Try to make sure there is some energy in every band

                        sce->sf_idx[w*16+g]-=2;

                }

                sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);

                sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);

                if (sce->sf_idx[w*16+g] != prevsc)

                    fflag = 1;

                sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);

            }

        }

        its++;

    } while (fflag && its < 10);

}