Ticket #2686: aac-improvements-wip-v9b.patch

File aac-improvements-wip-v9b.patch, 98.6 KB (added by klaussfreire, 12 years ago)

v9b version, based on v9, matched behavior against v7

  • libavcodec/aac.h

    diff --git a/libavcodec/aac.h b/libavcodec/aac.h
    index a151737..32f5ad3 100644
    a b typedef struct LongTermPrediction {  
    157157typedef struct IndividualChannelStream {
    158158    uint8_t max_sfb;            ///< number of scalefactor bands per group
    159159    enum WindowSequence window_sequence[2];
    160     uint8_t use_kb_window[2];   ///< If set, use Kaiser-Bessel window, otherwise use a sine window.
     160    uint8_t use_kb_window[2];   ///< If set, use Kaiser-Bessel window, otherwise use a sinus window.
    161161    int num_window_groups;
    162162    uint8_t group_len[8];
    163163    LongTermPrediction ltp;
    typedef struct IndividualChannelStream {  
    170170    int predictor_initialized;
    171171    int predictor_reset_group;
    172172    uint8_t prediction_used[41];
     173    uint8_t window_clipping[8]; ///< set if a certain window is near clipping
    173174} IndividualChannelStream;
    174175
    175176/**
    typedef struct SingleChannelElement {  
    233234    float sf[120];                                  ///< scalefactors
    234235    int sf_idx[128];                                ///< scalefactor indices (used by encoder)
    235236    uint8_t zeroes[128];                            ///< band is not coded (used by encoder)
    236     DECLARE_ALIGNED(32, float,   coeffs)[1024];     ///< coefficients for IMDCT
    237     DECLARE_ALIGNED(32, float,   saved)[1536];      ///< overlap
     237    DECLARE_ALIGNED(32, float,   pcoeffs)[1024];    ///< coefficients for IMDCT, pristine
     238    DECLARE_ALIGNED(32, float,   coeffs)[1024];     ///< coefficients for IMDCT, maybe processed
     239    DECLARE_ALIGNED(32, float,   saved)[1024];      ///< overlap
    238240    DECLARE_ALIGNED(32, float,   ret_buf)[2048];    ///< PCM output buffer
    239241    DECLARE_ALIGNED(16, float,   ltp_state)[3072];  ///< time signal for LTP
    240242    PredictorState predictor_state[MAX_PREDICTORS];
  • libavcodec/aaccoder.c

    diff --git a/libavcodec/aaccoder.c b/libavcodec/aaccoder.c
    index 5bf6a9c..9768f18 100644
    a b static const uint8_t * const run_value_bits[2] = {  
    5757    run_value_bits_long, run_value_bits_short
    5858};
    5959
     60#define ROUND_STANDARD 0.4054f
     61#define ROUND_TO_ZERO 0.1054f
     62
     63/**
     64 * approximates exp10f(-3.0f*(0.5f + 0.5f * cosf(FFMIN(b,15.5f) / 15.5f)))
     65 */
     66static av_always_inline float bval2bmax(float b)
     67{
     68    return 0.001f + 0.0035f * (b*b*b) / (15.5f*15.5f*15.5f);
     69}
    6070
    6171/**
    6272 * Quantize one coefficient.
    6373 * @return absolute value of the quantized coefficient
    6474 * @see 3GPP TS26.403 5.6.2 "Scalefactor determination"
    6575 */
    66 static av_always_inline int quant(float coef, const float Q)
     76static av_always_inline int quant(float coef, const float Q, const float rounding)
    6777{
    6878    float a = coef * Q;
    69     return sqrtf(a * sqrtf(a)) + 0.4054;
     79    return sqrtf(a * sqrtf(a)) + rounding;
    7080}
    7181
    7282static void quantize_bands(int *out, const float *in, const float *scaled,
    73                            int size, float Q34, int is_signed, int maxval)
     83                           int size, float Q34, int is_signed, int maxval, const float rounding)
    7484{
    7585    int i;
    7686    double qc;
    7787    for (i = 0; i < size; i++) {
    7888        qc = scaled[i] * Q34;
    79         out[i] = (int)FFMIN(qc + 0.4054, (double)maxval);
     89        out[i] = (int)FFMIN(qc + rounding, (double)maxval);
    8090        if (is_signed && in[i] < 0.0f) {
    8191            out[i] = -out[i];
    8292        }
    static av_always_inline float quantize_and_encode_band_cost_template(  
    108118                                const float *scaled, int size, int scale_idx,
    109119                                int cb, const float lambda, const float uplim,
    110120                                int *bits, int BT_ZERO, int BT_UNSIGNED,
    111                                 int BT_PAIR, int BT_ESC)
     121                                int BT_PAIR, int BT_ESC, const float ROUNDING)
    112122{
    113123    const int q_idx = POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512;
    114124    const float Q   = ff_aac_pow2sf_tab [q_idx];
    static av_always_inline float quantize_and_encode_band_cost_template(  
    134144        abs_pow34_v(s->scoefs, in, size);
    135145        scaled = s->scoefs;
    136146    }
    137     quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, maxval);
     147    quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, maxval, ROUNDING);
    138148    if (BT_UNSIGNED) {
    139149        off = 0;
    140150    } else {
    static av_always_inline float quantize_and_encode_band_cost_template(  
    161171                        di = t - CLIPPED_ESCAPE;
    162172                        curbits += 21;
    163173                    } else {
    164                         int c = av_clip(quant(t, Q), 0, 8191);
     174                        int c = av_clip(quant(t, Q, ROUNDING), 0, 8191);
    165175                        di = t - c*cbrtf(c)*IQ;
    166176                        curbits += av_log2(c)*2 - 4 + 1;
    167177                    }
    static av_always_inline float quantize_and_encode_band_cost_template(  
    191201            if (BT_ESC) {
    192202                for (j = 0; j < 2; j++) {
    193203                    if (ff_aac_codebook_vectors[cb-1][curidx*2+j] == 64.0f) {
    194                         int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191);
     204                        int coef = av_clip(quant(fabsf(in[i+j]), Q, ROUNDING), 0, 8191);
    195205                        int len = av_log2(coef);
    196206
    197207                        put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);
    static av_always_inline float quantize_and_encode_band_cost_template(  
    207217    return cost;
    208218}
    209219
    210 #define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC) \
     220#define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, ROUNDING) \
    211221static float quantize_and_encode_band_cost_ ## NAME(                                        \
    212222                                struct AACEncContext *s,                                \
    213223                                PutBitContext *pb, const float *in,                     \
    static float quantize_and_encode_band_cost_ ## NAME(  
    217227    return quantize_and_encode_band_cost_template(                                      \
    218228                                s, pb, in, scaled, size, scale_idx,                     \
    219229                                BT_ESC ? ESC_BT : cb, lambda, uplim, bits,              \
    220                                 BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC);                 \
     230                                BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, ROUNDING);       \
    221231}
    222232
    223 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO,  1, 0, 0, 0)
    224 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD, 0, 0, 0, 0)
    225 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD, 0, 1, 0, 0)
    226 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR, 0, 0, 1, 0)
    227 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR, 0, 1, 1, 0)
    228 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC,   0, 1, 1, 1)
     233QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO,  1, 0, 0, 0, ROUND_STANDARD)
     234QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD, 0, 0, 0, 0, ROUND_STANDARD)
     235QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD, 0, 1, 0, 0, ROUND_STANDARD)
     236QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR, 0, 0, 1, 0, ROUND_STANDARD)
     237QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR, 0, 1, 1, 0, ROUND_STANDARD)
     238QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC,   0, 1, 1, 1, ROUND_STANDARD)
     239
     240/*QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO_RTZ,  1, 0, 0, 0, ROUND_TO_ZERO)
     241QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD_RTZ, 0, 0, 0, 0, ROUND_TO_ZERO)
     242QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD_RTZ, 0, 1, 0, 0, ROUND_TO_ZERO)
     243QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR_RTZ, 0, 0, 1, 0, ROUND_TO_ZERO)
     244QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR_RTZ, 0, 1, 1, 0, ROUND_TO_ZERO)*/
     245QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC_RTZ,   0, 1, 1, 1, ROUND_TO_ZERO)
    229246
    230247static float (*const quantize_and_encode_band_cost_arr[])(
    231248                                struct AACEncContext *s,
    static float (*const quantize_and_encode_band_cost_arr[])(  
    247264    quantize_and_encode_band_cost_ESC,
    248265};
    249266
     267static float (*const quantize_and_encode_band_cost_rtz_arr[])(
     268                                struct AACEncContext *s,
     269                                PutBitContext *pb, const float *in,
     270                                const float *scaled, int size, int scale_idx,
     271                                int cb, const float lambda, const float uplim,
     272                                int *bits) = {
     273    quantize_and_encode_band_cost_ZERO,
     274    quantize_and_encode_band_cost_SQUAD,
     275    quantize_and_encode_band_cost_SQUAD,
     276    quantize_and_encode_band_cost_UQUAD,
     277    quantize_and_encode_band_cost_UQUAD,
     278    quantize_and_encode_band_cost_SPAIR,
     279    quantize_and_encode_band_cost_SPAIR,
     280    quantize_and_encode_band_cost_UPAIR,
     281    quantize_and_encode_band_cost_UPAIR,
     282    quantize_and_encode_band_cost_UPAIR,
     283    quantize_and_encode_band_cost_UPAIR,
     284    quantize_and_encode_band_cost_ESC_RTZ,
     285};
     286
    250287#define quantize_and_encode_band_cost(                                  \
    251288                                s, pb, in, scaled, size, scale_idx, cb, \
    252                                 lambda, uplim, bits)                    \
    253     quantize_and_encode_band_cost_arr[cb](                              \
     289                                lambda, uplim, bits, rtz)               \
     290    ((rtz) ? quantize_and_encode_band_cost_rtz_arr : quantize_and_encode_band_cost_arr)[cb]( \
    254291                                s, pb, in, scaled, size, scale_idx, cb, \
    255292                                lambda, uplim, bits)
    256293
    257294static float quantize_band_cost(struct AACEncContext *s, const float *in,
    258295                                const float *scaled, int size, int scale_idx,
    259296                                int cb, const float lambda, const float uplim,
    260                                 int *bits)
     297                                int *bits, int rtz)
    261298{
    262299    return quantize_and_encode_band_cost(s, NULL, in, scaled, size, scale_idx,
    263                                          cb, lambda, uplim, bits);
     300                                         cb, lambda, uplim, bits, rtz);
    264301}
    265302
    266303static void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb,
    267304                                     const float *in, int size, int scale_idx,
    268                                      int cb, const float lambda)
     305                                     int cb, const float lambda, int rtz)
    269306{
    270307    quantize_and_encode_band_cost(s, pb, in, NULL, size, scale_idx, cb, lambda,
    271                                   INFINITY, NULL);
     308                                  INFINITY, NULL, rtz);
    272309}
    273310
    274311static float find_max_val(int group_len, int swb_size, const float *scaled) {
    static float find_max_val(int group_len, int swb_size, const float *scaled) {  
    282319    return maxval;
    283320}
    284321
     322static av_const float sqrf(float f) {
     323    return f*f;
     324}
     325
     326static float find_form_factor(int group_len, int swb_size, float thresh, const float *scaled, float cleanup_factor) {
     327    const float iswb_size = 1.0f / swb_size;
     328    const float iswb_sizem1 = 1.0f / (swb_size - 1);
     329    const float ethresh = thresh;
     330    float form = 0.0f, weight = 0.0f;
     331    int w2, i;
     332    for (w2 = 0; w2 < group_len; w2++) {
     333        float e = 0.0f, e2 = 0.0f, var = 0.0f, maxval = 0.0f;
     334        float nzl = 0;
     335        for (i = 0; i < swb_size; i++) {
     336            float s = fabsf(scaled[w2*128+i]);
     337            maxval = FFMAX(maxval, s);
     338            e += s;
     339            e2 += s *= s;
     340            /* We really don't want a hard non-zero-line count, since
     341             * even below-threshold lines do add up towards band spectral power.
     342             * So, fall steeply towards zero, but smoothly
     343             */
     344            if (s >= ethresh)
     345                nzl += 1.0f;
     346            else if (cleanup_factor > 1.0f)
     347                nzl += powf(sqrf(s / ethresh), sqrf(FFMIN(4.0f,cleanup_factor)));
     348            else
     349                nzl += sqrf(s / ethresh);
     350        }
     351        if (e2 > thresh) {
     352            float frm;
     353            e *= iswb_size;
     354           
     355            // compute variance
     356            for (i = 0; i < swb_size; i++) {
     357                float d = fabsf(scaled[w2*128+i]) - e;
     358                var += d*d;
     359            }
     360            var = sqrtf(var * iswb_sizem1);
     361           
     362            e2 *= iswb_size;
     363            frm = e / FFMIN(e+4*var,maxval);
     364            form += e2 * sqrtf(frm) / FFMAX(0.5f,nzl);
     365            weight += e2;
     366        }
     367    }
     368    if (weight > 0)
     369        return form / weight;
     370    else
     371        return 1.0f;
     372}
     373
     374static float find_max_absval(int group_len, int swb_size, const float *scaled) {
     375    float maxval = 0.0f;
     376    int w2, i;
     377    for (w2 = 0; w2 < group_len; w2++) {
     378        for (i = 0; i < swb_size; i++) {
     379            maxval = FFMAX(maxval, fabs(scaled[w2*128+i]));
     380        }
     381    }
     382    return maxval;
     383}
     384
     385static unsigned char aac_maxval_cb[] = {
     386    0, 1, 3, 5, 5, 7, 7, 7, 9, 9, 9, 9, 9, 11
     387};
     388
    285389static int find_min_book(float maxval, int sf) {
    286390    float Q = ff_aac_pow2sf_tab[POW_SF2_ZERO - sf + SCALE_ONE_POS - SCALE_DIV_512];
    287391    float Q34 = sqrtf(Q * sqrtf(Q));
    288392    int qmaxval, cb;
    289393    qmaxval = maxval * Q34 + 0.4054f;
    290     if      (qmaxval ==  0) cb = 0;
    291     else if (qmaxval ==  1) cb = 1;
    292     else if (qmaxval ==  2) cb = 3;
    293     else if (qmaxval <=  4) cb = 5;
    294     else if (qmaxval <=  7) cb = 7;
    295     else if (qmaxval <= 12) cb = 9;
    296     else                    cb = 11;
     394    if (qmaxval >= (sizeof(aac_maxval_cb) / sizeof(aac_maxval_cb[0])))
     395        cb = 11;
     396    else
     397        cb = aac_maxval_cb[qmaxval];
    297398    return cb;
    298399}
    299400
    static void encode_window_bands_info(AACEncContext *s, SingleChannelElement *sce  
    341442        } else {
    342443            float minrd = next_minrd;
    343444            int mincb = next_mincb;
     445            float maxval = find_max_val(group_len, size, s->scoefs + start + w*128);
     446            int startcb = find_min_book(maxval, sce->sf_idx[win*16+swb]);
    344447            next_minrd = INFINITY;
    345448            next_mincb = 0;
    346             for (cb = 0; cb < 12; cb++) {
     449            for (cb = 0; cb < startcb; cb++) {
     450                path[swb+1][cb].cost = INFINITY;
     451                path[swb+1][cb].prev_idx = -1;
     452                path[swb+1][cb].run = 0;
     453            }
     454            for (cb = startcb; cb < 12; cb++) {
    347455                float cost_stay_here, cost_get_here;
    348456                float rd = 0.0f;
    349457                for (w = 0; w < group_len; w++) {
    350458                    FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(win+w)*16+swb];
    351459                    rd += quantize_band_cost(s, sce->coeffs + start + w*128,
    352460                                             s->scoefs + start + w*128, size,
    353                                              sce->sf_idx[(win+w)*16+swb], cb,
    354                                              lambda / band->threshold, INFINITY, NULL);
     461                                             sce->sf_idx[win*16+swb], cb,
     462                                             lambda / band->threshold, INFINITY, NULL, 0);
    355463                }
    356464                cost_stay_here = path[swb][cb].cost + rd;
    357465                cost_get_here  = minrd              + rd + run_bits + 4;
    static void codebook_trellis_rate(AACEncContext *s, SingleChannelElement *sce,  
    472580                for (w = 0; w < group_len; w++) {
    473581                    bits += quantize_band_cost(s, sce->coeffs + start + w*128,
    474582                                               s->scoefs + start + w*128, size,
    475                                                sce->sf_idx[(win+w)*16+swb], cb,
    476                                                0, INFINITY, NULL);
     583                                               sce->sf_idx[win*16+swb], cb,
     584                                               0, INFINITY, NULL, 0);
    477585                }
    478586                cost_stay_here = path[swb][cb].cost + bits;
    479587                cost_get_here  = minbits            + bits + run_bits + 4;
    static av_always_inline uint8_t coef2maxsf(float coef) {  
    545653
    546654typedef struct TrellisPath {
    547655    float cost;
     656    int bits;
    548657    int prev;
     658    int cb;
    549659} TrellisPath;
    550660
    551661#define TRELLIS_STAGES 121
    552 #define TRELLIS_STATES (SCALE_MAX_DIFF+1)
     662#define TRELLIS_STATES 255
    553663
    554664static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,
    555665                                       SingleChannelElement *sce,
    556666                                       const float lambda)
    557667{
    558     int q, w, w2, g, start = 0;
     668    int q, w, w2, g, start = 0, wstart = 0;
    559669    int i, j;
    560670    int idx;
    561671    TrellisPath paths[TRELLIS_STAGES][TRELLIS_STATES];
    562672    int bandaddr[TRELLIS_STAGES];
    563673    int minq;
    564674    float mincost;
     675    const float sqlambda = (float)sqrtf(lambda / 100.f) * 100.f;
     676    const float rdlambda = sqrtf(av_clipf(2.0f * 120.f / lambda, 0.0625f, 16.0f));
     677    const float rdmin = 0.03125f;
     678    const float rdmax = 1.0f;
    565679    float q0f = FLT_MAX, q1f = 0.0f, qnrgf = 0.0f;
    566680    int q0, q1, qcnt = 0;
     681    int toomanybits;
     682    int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate
     683        / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels)
     684        * (lambda / 120.f);
     685    int refbits = destbits;
     686    int cutoff = 1024;
     687    int psy_bits_max;
     688    int g_to_toomanybits[TRELLIS_STAGES];
     689
     690    if (s->psy.bitres.alloc >= 0) {
     691        // Psy granted us extra bits to use, from the reservoire
     692        // adjust for lambda except what psy already did
     693        destbits = s->psy.bitres.alloc
     694            * (lambda / (avctx->global_quality ? avctx->global_quality : 120));
     695    }
     696
     697    // Compute band-to-bit-allocation table to properly cost by cumulative bit expenditure
     698   
     699    if (avctx->flags & CODEC_FLAG_QSCALE) {
     700        // Constant Q-scale doesn't compensate MS coding on its own
     701        // No need to be overly precise, this only controls cutoff frequency
     702        if (s->options.stereo_mode && s->cur_type == TYPE_CPE)
     703            destbits *= 2;
     704       
     705        toomanybits = 5800;
     706    } else {
     707        toomanybits = FFMIN(destbits + destbits/8, 5800);
     708    }
     709   
     710    // and zero out above cutoff frequency
     711    {
     712        int wlen = 1024 / sce->ics.num_windows;
     713        int bandwidth;
     714
     715        /* Scale, psy gives us constant quality, this LP only scales
     716         * bitrate by lambda, so we save bits on subjectively unimportant HF
     717         * rather than increase quantization noise. Adjust nominal bitrate
     718         * to effective bitrate according to encoding parameters, _AAC_CUTOFF
     719         * is calibrated for effective bitrate.
     720         */
     721        float rate_bandwidth_multiplier = 1.3f;
     722        int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE)
     723            ? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024)
     724            : (avctx->bit_rate / avctx->channels);
     725       
     726        if (avctx->cutoff > 0)
     727            bandwidth = avctx->cutoff;
     728        else
     729            bandwidth = FFMAX(3000, _AAC_CUTOFF(frame_bit_rate, 1, avctx->sample_rate));
    567730
     731        cutoff = bandwidth * 2 * wlen / avctx->sample_rate;
     732    }
     733
     734    for (w = 0, idx = 1; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     735        for (g = wstart = 0; g < sce->ics.num_swb; g++, wstart += sce->ics.swb_sizes[g]) {
     736            int nz = 0, bits = 0, curbits;
     737           
     738            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
     739                FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
     740                bits += band->bits;
     741                if (!(wstart >= cutoff || band->energy <= band->threshold || band->threshold == 0.0f))
     742                    nz = 1;
     743            }
     744           
     745            curbits = g_to_toomanybits[idx-1];
     746            if (nz) {
     747                curbits += 3+bits;
     748            } else {
     749                curbits += 1;
     750            }
     751            if (g == 0)
     752                curbits += destbits / (8 * sce->ics.num_windows);
     753            g_to_toomanybits[idx] = curbits;
     754            idx++;
     755        }
     756    }
     757    j = idx;
     758    psy_bits_max = g_to_toomanybits[idx-1];
     759    if (psy_bits_max) {
     760        for (idx = 0; idx < j; idx++) {
     761            g_to_toomanybits[idx] = g_to_toomanybits[idx] * toomanybits / psy_bits_max;
     762        }
     763    }
     764
     765    // Initialize trellis state
     766   
    568767    for (i = 0; i < 1024; i++) {
    569768        float t = fabsf(sce->coeffs[i]);
    570769        if (t > 0.0f) {
    static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,  
    585784    q0 = coef2minsf(q0f);
    586785    //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
    587786    q1 = coef2maxsf(q1f);
    588     if (q1 - q0 > 60) {
     787    if (q1 - q0 > TRELLIS_STATES) {
    589788        int q0low  = q0;
    590789        int q1high = q1;
    591790        //minimum scalefactor index is when maximum nonzero coefficient after quantizing is not clipped
    592791        int qnrg = av_clip_uint8(log2f(sqrtf(qnrgf/qcnt))*4 - 31 + SCALE_ONE_POS - SCALE_DIV_512);
    593         q1 = qnrg + 30;
    594         q0 = qnrg - 30;
     792        q1 = qnrg + TRELLIS_STATES/2;
     793        q0 = qnrg - TRELLIS_STATES/2;
    595794        if (q0 < q0low) {
    596795            q1 += q0low - q0;
    597796            q0  = q0low;
    static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,  
    603802
    604803    for (i = 0; i < TRELLIS_STATES; i++) {
    605804        paths[0][i].cost    = 0.0f;
     805        paths[0][i].bits    = 0;
    606806        paths[0][i].prev    = -1;
     807        paths[0][i].cb      = 0;
    607808    }
    608809    for (j = 1; j < TRELLIS_STAGES; j++) {
    609810        for (i = 0; i < TRELLIS_STATES; i++) {
    610811            paths[j][i].cost    = INFINITY;
     812            paths[j][i].bits    = 0;
    611813            paths[j][i].prev    = -2;
     814            paths[j][i].cb      = 0;
    612815        }
    613816    }
    614817    idx = 1;
    615818    abs_pow34_v(s->scoefs, sce->coeffs, 1024);
    616819    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     820        const float de_psy_factor = (sce->ics.num_windows > 1) ? 8.0f / sce->ics.group_len[w] : 1.0f;
    617821        start = w*128;
    618         for (g = 0; g < sce->ics.num_swb; g++) {
     822        for (g = wstart = 0; g < sce->ics.num_swb; g++, wstart += sce->ics.swb_sizes[g]) {
    619823            const float *coefs = sce->coeffs + start;
     824            const float *scoefs = s->scoefs + start;
    620825            float qmin, qmax;
    621826            int nz = 0;
    622827
    623828            bandaddr[idx] = w * 16 + g;
    624             qmin = INT_MAX;
     829            qmin = FLT_MAX;
    625830            qmax = 0.0f;
    626831            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    627832                FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
    628                 if (band->energy <= band->threshold || band->threshold == 0.0f) {
    629                     sce->zeroes[(w+w2)*16+g] = 1;
     833                if (wstart >= cutoff || band->energy <= band->threshold || band->threshold == 0.0f) {
    630834                    continue;
    631835                }
    632                 sce->zeroes[(w+w2)*16+g] = 0;
    633836                nz = 1;
    634837                for (i = 0; i < sce->ics.swb_sizes[g]; i++) {
    635838                    float t = fabsf(coefs[w2*128+i]);
    static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,  
    639842                }
    640843            }
    641844            if (nz) {
    642                 int minscale, maxscale;
     845                int minscale, maxscale, qstep;
    643846                float minrd = INFINITY;
    644847                float maxval;
     848                float bmax = bval2bmax(g * 17.0f / sce->ics.num_swb) / 0.0045f;
     849                int btoomanybits = FFMIN(5800, toomanybits * (0.25f + 0.75f * bmax));
    645850                //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
    646851                minscale = coef2minsf(qmin);
    647852                //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
    static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,  
    649854                minscale = av_clip(minscale - q0, 0, TRELLIS_STATES - 1);
    650855                maxscale = av_clip(maxscale - q0, 0, TRELLIS_STATES);
    651856                maxval = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], s->scoefs+start);
    652                 for (q = minscale; q < maxscale; q++) {
    653                     float dist = 0;
    654                     int cb = find_min_book(maxval, sce->sf_idx[w*16+g]);
    655                     for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    656                         FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
    657                         dist += quantize_band_cost(s, coefs + w2*128, s->scoefs + start + w2*128, sce->ics.swb_sizes[g],
    658                                                    q + q0, cb, lambda / band->threshold, INFINITY, NULL);
    659                     }
    660                     minrd = FFMIN(minrd, dist);
    661 
    662                     for (i = 0; i < q1 - q0; i++) {
    663                         float cost;
    664                         cost = paths[idx - 1][i].cost + dist
    665                                + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
    666                         if (cost < paths[idx][q].cost) {
    667                             paths[idx][q].cost    = cost;
    668                             paths[idx][q].prev    = i;
     857                qstep = av_clip((maxscale - minscale + SCALE_MAX_DIFF/2) / SCALE_MAX_DIFF, 1, 3);
     858
     859                for (q = minscale; q < maxscale; q += qstep) {
     860                    // we don't want holes - ie: codebook 0
     861                    int cb = find_min_book(maxval, q + q0);
     862                    if (cb > 0) {
     863                        // Check viability (ie: that there is a path starting at this q that respects SCALE_MAX_DIFF)
     864                        int viable = 0, qdiff = FFMIN(q + SCALE_MAX_DIFF, q1 - q0);
     865                        for (i = FFMAX(0, q - SCALE_MAX_DIFF); !viable && i < qdiff; i++) {
     866                            viable = paths[idx - 1][i].prev != -2;
     867                        }
     868                        if (viable) {
     869                            float dist = 0;
     870                            int bits = 0;
     871                            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
     872                                FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
     873                                int b;
     874                                float formfactor = find_form_factor(
     875                                    1, sce->ics.swb_sizes[g],
     876                                    band->threshold / sce->ics.swb_sizes[w],
     877                                    coefs + w2*128,
     878                                    start / (cutoff * 1.25f));
     879                                formfactor *= de_psy_factor;
     880                                formfactor = av_clipf(sqrtf(formfactor), 0.015625f, 1.0f);
     881                                formfactor = av_clipf(rdlambda * formfactor, rdmin, rdmax);
     882                                dist += quantize_band_cost(s, coefs + w2*128, scoefs + w2*128, sce->ics.swb_sizes[g],
     883                                                           q + q0, cb, sqlambda / (band->threshold * formfactor), INFINITY, &b, 0);
     884                                bits += b;
     885                            }
     886                            minrd = FFMIN(minrd, dist);
     887
     888                            for (i = FFMAX(0, q - SCALE_MAX_DIFF); i < qdiff; i++) {
     889                                if (paths[idx - 1][i].prev != -2) {
     890                                    int tbits = paths[idx - 1][i].bits + bits
     891                                           + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
     892                                    float cost = paths[idx - 1][i].cost + dist
     893                                           + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO]
     894                                           + sqrf(FFMAX(0, tbits - g_to_toomanybits[idx]));
     895                                    if (cost < paths[idx][q].cost) {
     896                                        paths[idx][q].cost    = cost;
     897                                        paths[idx][q].bits    = tbits;
     898                                        paths[idx][q].prev    = i;
     899                                        paths[idx][q].cb      = cb;
     900                                    }
     901                                }
     902                            }
    669903                        }
    670904                    }
    671905                }
    672906            } else {
    673907                for (q = 0; q < q1 - q0; q++) {
    674                     paths[idx][q].cost = paths[idx - 1][q].cost + 1;
    675                     paths[idx][q].prev = q;
     908                    if (paths[idx-1][q].prev != -2) {
     909                        paths[idx][q].cost = paths[idx - 1][q].cost + 1;
     910                        paths[idx][q].bits = paths[idx - 1][q].bits + 1;
     911                        paths[idx][q].prev = q;
     912                        paths[idx][q].cb   = 0;
     913                    }
    676914                }
    677915            }
    678916            sce->zeroes[w*16+g] = !nz;
    static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,  
    691929    }
    692930    while (idx) {
    693931        sce->sf_idx[bandaddr[idx]] = minq + q0;
     932        sce->band_type[bandaddr[idx]] = paths[idx][minq].cb;
    694933        minq = paths[idx][minq].prev;
    695934        idx--;
    696935    }
    697936    //set the same quantizers inside window groups
    698     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
    699         for (g = 0;  g < sce->ics.num_swb; g++)
    700             for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
     937    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     938        for (g = 0;  g < sce->ics.num_swb; g++) {
     939            for (w2 = 1; w2 < sce->ics.group_len[w]; w2++) {
    701940                sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
     941                sce->zeroes[(w+w2)*16+g] = sce->zeroes[w*16+g];
     942                sce->band_type[(w+w2)*16+g] = sce->band_type[w*16+g];
     943            }
     944        }
     945    }
    702946}
    703947
     948#define sclip(x) av_clip(x,60,218)
     949
    704950/**
    705951 * two-loop quantizers search taken from ISO 13818-7 Appendix C
    706952 */
    707953static void search_for_quantizers_twoloop(AVCodecContext *avctx,
    708954                                          AACEncContext *s,
    709955                                          SingleChannelElement *sce,
    710                                           const float lambda)
     956                                          float lambda)
    711957{
    712     int start = 0, i, w, w2, g;
    713     int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate / avctx->channels * (lambda / 120.f);
    714     float dists[128] = { 0 }, uplims[128];
     958    int start = 0, i, w, w2, g, recomprd;
     959    int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate
     960        / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels)
     961        * (lambda / 120.f);
     962    int refbits = destbits;
     963    int toomanybits, toofewbits;
     964    char nzs[128];
     965    int maxsf[128];
     966    float dists[128] = { 0 }, uplims[128], euplims[128];
    715967    float maxvals[128];
    716     int fflag, minscaler;
     968   
     969    /* rdlambda controls the maximum tolerated distortion. Twoloop
     970     * will keep iterating until it fails to lower it or it reaches
     971     * ulimit * rdlambda. Keeping it low increases quality on difficult
     972     * signals, but lower it too much, and bits will be taken from weak
     973     * signals, creating "holes". A balance is necesary.
     974     * rdmax and rdmin specify the relative deviation from rdlambda
     975     * allowed for tonality compensation
     976     */
     977    float rdlambda = av_clipf(2.0f * 120.f / lambda, 0.0625f, 16.0f);
     978    float rdmin = 0.03125f;
     979    float rdmax = 1.0f;
     980   
     981    /* sfoffs controls an offset of optmium allocation that will be
     982     * applied based on lambda. Keep it real and modest, the loop
     983     * will take care of the rest, this just accelerates convergence
     984     */
     985    float sfoffs = av_clipf(log2f(120.0f / lambda) * 4.0f, -5, 10);
     986   
     987    int fflag, minscaler, maxscaler, nminscaler, minrdsf;
    717988    int its  = 0;
     989    int maxits = 30;
    718990    int allz = 0;
    719     float minthr = INFINITY;
     991    int tbits;
     992    int cutoff = 1024;
     993    int cleanoff = 1024;
     994   
     995    /* zeroscale controls a multiplier of the threshold, if band energy
     996     * is below this, a zero is forced. Keep it lower than 1, unless
     997     * low lambda is used, because energy < threshold doesn't mean there's
     998     * no audible signal outright, it's just energy. Also make it rise
     999     * slower than rdlambda, as rdscale has due compensation with
     1000     * noisy band depriorization below, whereas zeroing logic is rather dumb
     1001     */
     1002    float zeroscale;
     1003    if (lambda > 120.f)
     1004        zeroscale = av_clipf(powf(120.f / lambda, 0.25f), 0.0625f, 1.0f);
     1005    else
     1006        zeroscale = 1.f;
     1007   
     1008    if (s->psy.bitres.alloc >= 0) {
     1009        // Psy granted us extra bits to use, from the reservoire
     1010        // adjust for lambda except what psy already did
     1011        destbits = s->psy.bitres.alloc
     1012            * (lambda / (avctx->global_quality ? avctx->global_quality : 120));
     1013    }
     1014   
     1015    if (avctx->flags & CODEC_FLAG_QSCALE) {
     1016        // Constant Q-scale doesn't compensate MS coding on its own
     1017        // No need to be overly precise, this only controls RD
     1018        // adjustment CB limits when going overboard
     1019        if (s->options.stereo_mode && s->cur_type == TYPE_CPE)
     1020            destbits *= 2;
     1021       
     1022        // When using a constant Q-scale, don't adjust bits, just use RD
     1023        // Don't let it go overboard, though... 8x psy target is enough
     1024        toomanybits = 5800; //av_clip(FFMAX(refbits*3, destbits * 8), 768, 5800);
     1025        toofewbits = destbits / 16;
     1026       
     1027        // Don't offset scalers, just RD
     1028        sfoffs = sce->ics.num_windows - 1;
     1029        rdlambda = sqrtf(rdlambda);
     1030       
     1031        // search further
     1032        maxits *= 2;
     1033    } else {
     1034        // When using ABR, be strict
     1035        toomanybits = destbits + destbits/16;
     1036        toofewbits = destbits - destbits/4;
     1037       
     1038        sfoffs = 0;
     1039        rdlambda = sqrtf(rdlambda);
     1040    }
     1041
     1042    // and zero out above cutoff frequency
     1043    {
     1044        int wlen = 1024 / sce->ics.num_windows;
     1045        int bandwidth;
     1046        int cleanwidth;
     1047
     1048        /* Scale, psy gives us constant quality, this LP only scales
     1049         * bitrate by lambda, so we save bits on subjectively unimportant HF
     1050         * rather than increase quantization noise. Adjust nominal bitrate
     1051         * to effective bitrate according to encoding parameters, _AAC_CUTOFF
     1052         * is calibrated for effective bitrate.
     1053         */
     1054        float rate_bandwidth_multiplier = 1.3f;
     1055        int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE)
     1056            ? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024)
     1057            : (avctx->bit_rate / avctx->channels);
     1058       
     1059        if (avctx->cutoff > 0)
     1060            bandwidth = avctx->cutoff;
     1061        else
     1062            bandwidth = FFMAX(3000, _AAC_CUTOFF(frame_bit_rate, 1, avctx->sample_rate));
     1063        cleanwidth = FFMAX(3000, _AAC_CUTOFF(frame_bit_rate * 0.8f, 1, avctx->sample_rate));
     1064
     1065        cutoff = bandwidth * 2 * wlen / avctx->sample_rate;
     1066        cleanoff = cleanwidth * 2 * wlen / avctx->sample_rate;
     1067    }
    7201068
    7211069    // for values above this the decoder might end up in an endless loop
    7221070    // due to always having more bits than what can be encoded.
    7231071    destbits = FFMIN(destbits, 5800);
     1072    toomanybits = FFMIN(toomanybits, 5800);
     1073    toofewbits = FFMIN(toofewbits, 5800);
    7241074    //XXX: some heuristic to determine initial quantizers will reduce search time
    7251075    //determine zero bands and upper limits
    7261076    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    727         for (g = 0;  g < sce->ics.num_swb; g++) {
     1077        for (g = start = 0;  g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) {
    7281078            int nz = 0;
    7291079            float uplim = 0.0f;
     1080            float energy = 0.0f;
     1081           
    7301082            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    7311083                FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
    732                 uplim += band->threshold;
    733                 if (band->energy <= band->threshold || band->threshold == 0.0f) {
     1084                if (start >= cutoff || band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0) {
    7341085                    sce->zeroes[(w+w2)*16+g] = 1;
    7351086                    continue;
    7361087                }
    7371088                nz = 1;
    7381089            }
    739             uplims[w*16+g] = uplim *512;
     1090            if (!nz) {
     1091                uplim = 0.0f;
     1092            } else {
     1093                nz = 0;
     1094                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
     1095                    FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
     1096                    if (band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0f)
     1097                        continue;
     1098                    uplim += band->threshold;
     1099                    energy += band->energy;
     1100                    nz++;
     1101                }
     1102            }
     1103            uplims[w*16+g] = uplim;
     1104            nzs[w*16+g] = nz;
    7401105            sce->zeroes[w*16+g] = !nz;
    741             if (nz)
    742                 minthr = FFMIN(minthr, uplim);
    7431106            allz |= nz;
    7441107        }
    7451108    }
     1109   
     1110    /* Compute initial scalers */
     1111    minscaler = 65535;
    7461112    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    7471113        for (g = 0;  g < sce->ics.num_swb; g++) {
    7481114            if (sce->zeroes[w*16+g]) {
    7491115                sce->sf_idx[w*16+g] = SCALE_ONE_POS;
    7501116                continue;
    7511117            }
    752             sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2f(uplims[w*16+g]/minthr)*4,59);
     1118            /* log2f-to-distortion ratio is, technically, 2 (1.5db = 4, but it's power vs level so it's 2).
     1119             * But, as offsets are applied, low-frequency signals are too sensitive to the induced distortion,
     1120             * so we make scaling more conservative by choosing a lower log2f-to-distortion ratio, and thus
     1121             * more robust.
     1122             */
     1123            sce->sf_idx[w*16+g] = av_clip(
     1124                SCALE_ONE_POS
     1125                    + 1.75*log2f(FFMAX(0.00125f,uplims[w*16+g]) / sce->ics.swb_sizes[g])
     1126                    + sfoffs,
     1127                60, SCALE_MAX_POS);
     1128            //fprintf(stderr, "%02x ", sce->sf_idx[w*16+g]);
     1129            minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
    7531130        }
     1131        //fprintf(stderr, "|\n");
    7541132    }
    755 
     1133    //fprintf(stderr, "\n");
     1134   
     1135    /* Clip */
     1136    minscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512);
     1137    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
     1138        for (g = 0;  g < sce->ics.num_swb; g++)
     1139            if (!sce->zeroes[w*16+g])
     1140                sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF - 1);
     1141   
    7561142    if (!allz)
    7571143        return;
    7581144    abs_pow34_v(s->scoefs, sce->coeffs, 1024);
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    7661152        }
    7671153    }
    7681154
     1155    /* Scale uplims to match rate distortion to quality
     1156     * and apply noisy band depriorization and tonal band priorization.
     1157     * Maxval-energy ratio gives us an idea of how noisy/tonal the band is.
     1158     * If maxval^2 ~ energy, then that band is mostly noise, and we can relax
     1159     * rate distortion requirements.
     1160     */
     1161    memcpy(euplims, uplims, sizeof(euplims));
     1162    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1163        /* psy already priorizes transients to some extent */
     1164        float de_psy_factor = (sce->ics.num_windows > 1) ? 8.0f / sce->ics.group_len[w] : 1.0f;
     1165        start = w*128;
     1166        for (g = 0;  g < sce->ics.num_swb; g++) {
     1167            if (nzs[g] > 0) {
     1168                float energy2uplim = find_form_factor(
     1169                    sce->ics.group_len[w], sce->ics.swb_sizes[g],
     1170                    uplims[w*16+g] / (nzs[g] * sce->ics.swb_sizes[w]),
     1171                    sce->coeffs + start,
     1172                    start / (float)cleanoff);
     1173                energy2uplim *= de_psy_factor;
     1174                if (!(avctx->flags & CODEC_FLAG_QSCALE)) {
     1175                    // In ABR, we need to priorize less and let rate control do its thing
     1176                    energy2uplim = sqrtf(energy2uplim);
     1177                }
     1178                energy2uplim = FFMAX(0.015625f, FFMIN(1.0f, energy2uplim));
     1179                //fprintf(stderr, "%.3f ", energy2uplim);
     1180                uplims[w*16+g] *= av_clipf(rdlambda * energy2uplim, rdmin, rdmax)
     1181                                  * sce->ics.group_len[w];
     1182               
     1183                // For energy uplims, don't cleanoff
     1184                energy2uplim = find_form_factor(
     1185                    sce->ics.group_len[w], sce->ics.swb_sizes[g],
     1186                    uplims[w*16+g] / (nzs[g] * sce->ics.swb_sizes[w]),
     1187                    sce->coeffs + start, 0);
     1188                energy2uplim *= de_psy_factor;
     1189                if (!(avctx->flags & CODEC_FLAG_QSCALE)) {
     1190                    // In ABR, we need to priorize less and let rate control do its thing
     1191                    energy2uplim = sqrtf(energy2uplim);
     1192                }
     1193                energy2uplim = FFMAX(0.015625f, FFMIN(1.0f, energy2uplim));
     1194                euplims[w*16+g] *= av_clipf(rdlambda * energy2uplim * sce->ics.group_len[w],
     1195                    0.5f, 1.0f);
     1196            }
     1197            start += sce->ics.swb_sizes[g];
     1198        }
     1199        //fprintf(stderr, "|");
     1200    }
     1201    //fprintf(stderr, "\n");
     1202
     1203    for (i = 0; i < sizeof(maxsf) / sizeof(maxsf[0]); ++i)
     1204        maxsf[i] = SCALE_MAX_POS;
     1205   
    7691206    //perform two-loop search
    7701207    //outer loop - improve quality
    7711208    do {
    772         int tbits, qstep;
    773         minscaler = sce->sf_idx[0];
     1209        int qstep;
    7741210        //inner loop - quantize spectrum to fit into given number of bits
    7751211        qstep = its ? 1 : 32;
    7761212        do {
    7771213            int prev = -1;
     1214            int changed = 0;
    7781215            tbits = 0;
     1216            recomprd = 0;
    7791217            for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    7801218                start = w*128;
    7811219                for (g = 0;  g < sce->ics.num_swb; g++) {
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    7891227                        start += sce->ics.swb_sizes[g];
    7901228                        continue;
    7911229                    }
    792                     minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
    7931230                    cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
    7941231                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    7951232                        int b;
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    8001237                                                   cb,
    8011238                                                   1.0f,
    8021239                                                   INFINITY,
    803                                                    &b);
     1240                                                   &b,
     1241                                                   0);
    8041242                        bits += b;
    8051243                    }
    8061244                    dists[w*16+g] = dist - bits;
    8071245                    if (prev != -1) {
    808                         bits += ff_aac_scalefactor_bits[sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO];
     1246                        int sfdiff = sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO;
     1247                        av_assert1(sfdiff >= 0 && sfdiff <= 2*SCALE_MAX_DIFF);
     1248                        bits += ff_aac_scalefactor_bits[sfdiff];
    8091249                    }
    8101250                    tbits += bits;
    8111251                    start += sce->ics.swb_sizes[g];
    8121252                    prev = sce->sf_idx[w*16+g];
    8131253                }
    8141254            }
    815             if (tbits > destbits) {
    816                 for (i = 0; i < 128; i++)
    817                     if (sce->sf_idx[i] < 218 - qstep)
    818                         sce->sf_idx[i] += qstep;
    819             } else {
    820                 for (i = 0; i < 128; i++)
    821                     if (sce->sf_idx[i] > 60 - qstep)
    822                         sce->sf_idx[i] -= qstep;
     1255            if (tbits > toomanybits) {
     1256                recomprd = 1;
     1257                for (i = 0; i < 128; i++) {
     1258                    if (sce->sf_idx[i] < (SCALE_MAX_POS - SCALE_DIV_512)) {
     1259                        int maxsf_i = (tbits > 5800) ? SCALE_MAX_POS : maxsf[i];
     1260                        int new_sf = FFMIN(maxsf_i, sce->sf_idx[i] + qstep);
     1261                        if (new_sf != sce->sf_idx[i]) {
     1262                            sce->sf_idx[i] = new_sf;
     1263                            changed = 1;
     1264                        }
     1265                    }
     1266                }
     1267            } else if (tbits < toofewbits) {
     1268                recomprd = 1;
     1269                for (i = 0; i < 128; i++) {
     1270                    if (sce->sf_idx[i] > SCALE_ONE_POS) {
     1271                        int new_sf = FFMAX(SCALE_ONE_POS, sce->sf_idx[i] - qstep);
     1272                        if (new_sf != sce->sf_idx[i]) {
     1273                            sce->sf_idx[i] = new_sf;
     1274                            changed = 1;
     1275                        }
     1276                    }
     1277                }
    8231278            }
    8241279            qstep >>= 1;
    825             if (!qstep && tbits > destbits*1.02 && sce->sf_idx[0] < 217)
     1280            if (!qstep && tbits > toomanybits && sce->sf_idx[0] < 217 && changed)
    8261281                qstep = 1;
    8271282        } while (qstep);
     1283        if (recomprd) {
     1284            // Must recompute distortion
     1285            int prev = -1;
     1286            tbits = 0;
     1287            for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1288                start = w*128;
     1289                for (g = 0;  g < sce->ics.num_swb; g++) {
     1290                    const float *coefs = sce->coeffs + start;
     1291                    const float *scaled = s->scoefs + start;
     1292                    int bits = 0;
     1293                    int cb;
     1294                    float dist = 0.0f;
     1295
     1296                    if (sce->zeroes[w*16+g] || sce->sf_idx[w*16+g] >= 218) {
     1297                        start += sce->ics.swb_sizes[g];
     1298                        continue;
     1299                    }
     1300                    cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
     1301                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
     1302                        int b;
     1303                        dist += quantize_band_cost(s, coefs + w2*128,
     1304                                                scaled + w2*128,
     1305                                                sce->ics.swb_sizes[g],
     1306                                                sce->sf_idx[w*16+g],
     1307                                                cb,
     1308                                                1.0f,
     1309                                                INFINITY,
     1310                                                &b,
     1311                                                0);
     1312                        bits += b;
     1313                    }
     1314                    dists[w*16+g] = dist - bits;
     1315                    if (prev != -1) {
     1316                        int sfdiff = sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO;
     1317                        av_assert1(sfdiff >= 0 && sfdiff <= 2*SCALE_MAX_DIFF);
     1318                        bits += ff_aac_scalefactor_bits[sfdiff];
     1319                    }
     1320                    tbits += bits;
     1321                    start += sce->ics.swb_sizes[g];
     1322                    prev = sce->sf_idx[w*16+g];
     1323                }
     1324            }
     1325        }
     1326
     1327        minscaler = SCALE_MAX_POS;
     1328        maxscaler = 0;
     1329        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1330            for (g = 0;  g < sce->ics.num_swb; g++) {
     1331                if (!sce->zeroes[w*16+g]) {
     1332                    minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
     1333                    maxscaler = FFMAX(maxscaler, sce->sf_idx[w*16+g]);
     1334                }
     1335            }
     1336        }
    8281337
    8291338        fflag = 0;
    830         minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);
     1339        minscaler = nminscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512);
     1340        minrdsf = FFMAX3(60, minscaler - 1, maxscaler - SCALE_MAX_DIFF - 1);
    8311341        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1342            // Start with big steps, end up fine-tunning
     1343            int depth = (its > maxits/2) ? ((its > maxits*2/3) ? 1 : 3) : 10;
     1344            int edepth = depth+2;
     1345            float uplmax = its / (maxits*0.25f) + 1.0f;
     1346            uplmax *= (tbits > destbits) ? FFMIN(2.0f, tbits / (float)FFMAX(1,destbits)) : 1.0f;
     1347            start = w * 128;
    8321348            for (g = 0; g < sce->ics.num_swb; g++) {
    8331349                int prevsc = sce->sf_idx[w*16+g];
    834                 if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60) {
    835                     if (find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1))
    836                         sce->sf_idx[w*16+g]--;
    837                     else //Try to make sure there is some energy in every band
    838                         sce->sf_idx[w*16+g]-=2;
     1350                if (!sce->zeroes[w*16+g]) {
     1351                    const float *coefs = sce->coeffs + start;
     1352                    const float *scaled = s->scoefs + start;
     1353                    int cmb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
     1354                    if ((!cmb || dists[w*16+g] > uplims[w*16+g]) && sce->sf_idx[w*16+g] > minrdsf) {
     1355                        //Try to make sure there is some energy in every nonzero band
     1356                        //NOTE: This algorithm must be forcibly imbalanced, pushing harder
     1357                        //  on holes or more distorted bands at first, otherwise there's
     1358                        //  no net gain (since the next iteration will offset all bands
     1359                        //  on the opposite direction to compensate for extra bits)
     1360                        for (i = 0; i < edepth; ++i) {
     1361                            int cb, bits;
     1362                            float dist;
     1363                            int mb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1);
     1364                            cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
     1365                            dist = 0.f;
     1366                            bits = 0;
     1367                            if (!cb) {
     1368                                maxsf[w*16+g] = FFMIN(sce->sf_idx[w*16+g], maxsf[w*16+g]);
     1369                            } else if (i >= depth && dists[w*16+g] < euplims[w*16+g]) {
     1370                                break;
     1371                            }
     1372                            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
     1373                                int b;
     1374                                dist += quantize_band_cost(s, coefs + w2*128,
     1375                                                        scaled + w2*128,
     1376                                                        sce->ics.swb_sizes[g],
     1377                                                        sce->sf_idx[w*16+g]-1,
     1378                                                        cb,
     1379                                                        1.0f,
     1380                                                        INFINITY,
     1381                                                        &b,
     1382                                                        0);
     1383                                bits += b;
     1384                            }
     1385                            sce->sf_idx[w*16+g]--;
     1386                            dists[w*16+g] = dist - bits;
     1387                            if (mb && (sce->sf_idx[w*16+g] < minrdsf || dists[w*16+g] < FFMIN(uplmax*uplims[w*16+g], euplims[w*16+g])))
     1388                                break;
     1389                        }
     1390                    } else if (tbits > toofewbits && dists[w*16+g] < uplims[w*16+g] && sce->sf_idx[w*16+g] < maxscaler) {
     1391                        // Um... over target
     1392                        for (i = 0; i < depth; ++i) {
     1393                            int cb, bits;
     1394                            float dist;
     1395                            cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]+1);
     1396                            if (cb > 0) {
     1397                                dist = 0.f;
     1398                                bits = 0;
     1399                                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
     1400                                    int b;
     1401                                    dist += quantize_band_cost(s, coefs + w2*128,
     1402                                                            scaled + w2*128,
     1403                                                            sce->ics.swb_sizes[g],
     1404                                                            sce->sf_idx[w*16+g]+1,
     1405                                                            cb,
     1406                                                            1.0f,
     1407                                                            INFINITY,
     1408                                                            &b,
     1409                                                            0);
     1410                                    bits += b;
     1411                                }
     1412                                dist -= bits;
     1413                                if (dist < uplims[w*16+g]) {
     1414                                    sce->sf_idx[w*16+g]++;
     1415                                    dists[w*16+g] = dist;
     1416                                } else {
     1417                                    break;
     1418                                }
     1419                            }
     1420                        }
     1421                    }
    8391422                }
    840                 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
    841                 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);
     1423                sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minrdsf, minscaler + SCALE_MAX_DIFF);
     1424                sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], SCALE_MAX_POS - SCALE_DIV_512);
    8421425                if (sce->sf_idx[w*16+g] != prevsc)
    8431426                    fflag = 1;
     1427                nminscaler = FFMIN(nminscaler, sce->sf_idx[w*16+g]);
    8441428                sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
     1429                start += sce->ics.swb_sizes[g];
     1430            }
     1431        }
     1432        if (nminscaler < minscaler) {
     1433            // Drecreased some scalers below minscaler. Must re-clamp.
     1434            minscaler = nminscaler;
     1435            for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1436                for (g = 0; g < sce->ics.num_swb; g++) {
     1437                    sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
     1438                    sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
     1439                }
    8451440            }
    8461441        }
    8471442        its++;
    848     } while (fflag && its < 10);
     1443    } while (fflag && its < maxits);
     1444   
     1445    /* Fill implicit zeroes */
     1446    //fprintf(stderr, "its:%d %d/%d: ", its, tbits, destbits);
     1447    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1448        /* No lowly codebooks beyond cutoff zone, to clean up noisy coefs */
     1449        int scutoff = cutoff + cutoff/5;
     1450        for (g = start = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) {
     1451            int minbt = (start < scutoff) ? 0 : 3;
     1452            //fprintf(stderr, "%02x ", sce->sf_idx[w*16+g]);
     1453            if (sce->band_type[w*16+g] <= minbt) {
     1454                sce->zeroes[w*16+g] = 1;
     1455                sce->band_type[w*16+g] = 0;
     1456            }
     1457        }
     1458        //fprintf(stderr, "|");
     1459    }
     1460    //fprintf(stderr, "\n");
     1461    //fprintf(stderr, "ba:%d br:%d (%d-%d) %.2f  \t\r\n", s->psy.bitres.alloc, tbits, toofewbits, toomanybits);
    8491462}
    8501463
    8511464static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
    static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,  
    9651578                                               ESC_BT,
    9661579                                               lambda,
    9671580                                               INFINITY,
    968                                                &b);
     1581                                               &b,
     1582                                               0);
    9691583                    dist -= b;
    9701584                }
    9711585                dist *= 1.0f / 512.0f / lambda;
    972                 quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512]);
     1586                quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512], ROUND_STANDARD);
    9731587                if (quant_max >= 8191) { // too much, return to the previous quantizer
    9741588                    sce->sf_idx[w*16+g] = prev_scf;
    9751589                    break;
    static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,  
    10191633                                       SingleChannelElement *sce,
    10201634                                       const float lambda)
    10211635{
    1022     int i, w, w2, g;
    1023     int minq = 255;
     1636    int w, w2, g;
     1637    float lowlambda = av_clipf(120.f / lambda, 0.85f, 1.f);
     1638    float rlambda = av_clipf(120.f / lambda, 0.75f, 10.f);
     1639    const int minq = av_clip(2 * log2f(120.f / lambda) + 150, 100, 218 - SCALE_MAX_DIFF);
     1640    const int maxq = minq + SCALE_MAX_DIFF - 1;
    10241641
    10251642    memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
    10261643    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    10271644        for (g = 0; g < sce->ics.num_swb; g++) {
    10281645            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    10291646                FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
    1030                 if (band->energy <= band->threshold) {
    1031                     sce->sf_idx[(w+w2)*16+g] = 218;
     1647                if (band->energy <= 0.05 * lowlambda * band->threshold) {
     1648                    sce->sf_idx[(w+w2)*16+g] = maxq;
    10321649                    sce->zeroes[(w+w2)*16+g] = 1;
    10331650                } else {
    1034                     sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2f(band->threshold), 80, 218);
     1651                    sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + 1.414*log2f(band->threshold * rlambda), minq, maxq);
    10351652                    sce->zeroes[(w+w2)*16+g] = 0;
    10361653                }
    1037                 minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
    10381654            }
    10391655        }
    10401656    }
    1041     for (i = 0; i < 128; i++) {
    1042         sce->sf_idx[i] = 140;
    1043         //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);
    1044     }
    10451657    //set the same quantizers inside window groups
    1046     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
    1047         for (g = 0;  g < sce->ics.num_swb; g++)
    1048             for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
    1049                 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
     1658    if (sce->ics.num_windows > 1) {
     1659        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1660            for (g = 0;  g < sce->ics.num_swb; g++) {
     1661                if (sce->ics.group_len[w] > 1) {
     1662                    int avg_sf_idx = 0;
     1663                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
     1664                        avg_sf_idx += sce->sf_idx[w*16+g];
     1665                    avg_sf_idx /= sce->ics.group_len[w];
     1666                    for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
     1667                        sce->sf_idx[(w+w2)*16+g] = avg_sf_idx;
     1668                }
     1669            }
     1670        }
     1671    }
    10501672}
    10511673
    10521674static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
    10531675                          const float lambda)
    10541676{
    1055     int start = 0, i, w, w2, g;
     1677    int start = 0, i, w, w2, g, sid_sf_boost;
    10561678    float M[128], S[128];
    10571679    float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
     1680    float mslambda = FFMIN(1.0f, lambda / 120.0f);
    10581681    SingleChannelElement *sce0 = &cpe->ch[0];
    10591682    SingleChannelElement *sce1 = &cpe->ch[1];
     1683   
    10601684    if (!cpe->common_window)
    10611685        return;
     1686   
    10621687    for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
     1688        int min_sf_idx_mid = SCALE_MAX_POS;
     1689        int min_sf_idx_side = SCALE_MAX_POS;
     1690        for (g = 0; g < sce0->ics.num_swb; g++) {
     1691            if (!sce0->zeroes[w*16+g])
     1692                min_sf_idx_mid = FFMIN(min_sf_idx_mid, sce0->sf_idx[w*16+g]);
     1693            if (!sce1->zeroes[w*16+g])
     1694                min_sf_idx_side = FFMIN(min_sf_idx_side, sce1->sf_idx[w*16+g]);
     1695        }
     1696       
    10631697        for (g = 0;  g < sce0->ics.num_swb; g++) {
     1698            float bmax = bval2bmax(g * 17.0f / sce0->ics.num_swb) / 0.0045f;
     1699            cpe->ms_mask[w*16+g] = 0;
    10641700            if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {
    1065                 float dist1 = 0.0f, dist2 = 0.0f;
     1701                float Mmax = 0.0f, Smax = 0.0f;
     1702               
     1703                /* Must compute mid/side SF and book for the whole window group */
    10661704                for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
    1067                     FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
    1068                     FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
    1069                     float minthr = FFMIN(band0->threshold, band1->threshold);
    1070                     float maxthr = FFMAX(band0->threshold, band1->threshold);
    10711705                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
    1072                         M[i] = (sce0->coeffs[start+w2*128+i]
    1073                               + sce1->coeffs[start+w2*128+i]) * 0.5;
     1706                        M[i] = (sce0->pcoeffs[start+w2*128+i]
     1707                              + sce1->pcoeffs[start+w2*128+i]) * 0.5f;
    10741708                        S[i] =  M[i]
    1075                               - sce1->coeffs[start+w2*128+i];
     1709                              - sce1->pcoeffs[start+w2*128+i];
     1710                    }
     1711                    abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);
     1712                    abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);
     1713                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++ ) {
     1714                        Mmax = FFMAX(Mmax, M34[i]);
     1715                        Smax = FFMAX(Smax, S34[i]);
     1716                    }
     1717                }
     1718               
     1719                for (sid_sf_boost = 0; sid_sf_boost < 4; sid_sf_boost++) {
     1720                    float dist1 = 0.0f, dist2 = 0.0f;
     1721                    int B0 = 0, B1 = 0;
     1722                    int minidx;
     1723                    int mididx, sididx;
     1724                    int midcb, sidcb;
     1725                   
     1726                    minidx = FFMIN(sce0->sf_idx[w*16+g], sce1->sf_idx[w*16+g]);
     1727                    mididx = av_clip(minidx, min_sf_idx_mid, min_sf_idx_mid + SCALE_MAX_DIFF);
     1728                    sididx = av_clip(minidx - sid_sf_boost * 3, min_sf_idx_side, min_sf_idx_side + SCALE_MAX_DIFF);
     1729                    midcb = find_min_book(Mmax, mididx);
     1730                    sidcb = find_min_book(Smax, sididx);
     1731                   
     1732                    if ((mididx > minidx) || (sididx > minidx)) {
     1733                        /* scalefactor range violation, bad stuff, will decrease quality unacceptably */
     1734                        continue;
     1735                    }
     1736                   
     1737                    /* No CB can be zero */
     1738                    midcb = FFMAX(1,midcb);
     1739                    sidcb = FFMAX(1,sidcb);
     1740                   
     1741                    for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
     1742                        FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
     1743                        FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
     1744                        float minthr = FFMIN(band0->threshold, band1->threshold);
     1745                        int b1,b2,b3,b4;
     1746                        for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
     1747                            M[i] = (sce0->coeffs[start+w2*128+i]
     1748                                  + sce1->coeffs[start+w2*128+i]) * 0.5;
     1749                            S[i] =  M[i]
     1750                                  - sce1->coeffs[start+w2*128+i];
     1751                        }
     1752                        abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
     1753                        abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
     1754                        abs_pow34_v(M34, M,                         sce0->ics.swb_sizes[g]);
     1755                        abs_pow34_v(S34, S,                         sce0->ics.swb_sizes[g]);
     1756                        dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,
     1757                                                    L34,
     1758                                                    sce0->ics.swb_sizes[g],
     1759                                                    sce0->sf_idx[(w+w2)*16+g],
     1760                                                    sce0->band_type[w*16+g],
     1761                                                    lambda / band0->threshold, INFINITY, &b1, 0);
     1762                        dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,
     1763                                                    R34,
     1764                                                    sce1->ics.swb_sizes[g],
     1765                                                    sce1->sf_idx[(w+w2)*16+g],
     1766                                                    sce1->band_type[w*16+g],
     1767                                                    lambda / band1->threshold, INFINITY, &b2, 0);
     1768                        dist2 += quantize_band_cost(s, M,
     1769                                                    M34,
     1770                                                    sce0->ics.swb_sizes[g],
     1771                                                    mididx,
     1772                                                    midcb,
     1773                                                    lambda / minthr, INFINITY, &b3, 0);
     1774                        dist2 += quantize_band_cost(s, S,
     1775                                                    S34,
     1776                                                    sce1->ics.swb_sizes[g],
     1777                                                    sididx,
     1778                                                    sidcb,
     1779                                                    lambda * mslambda / (minthr * bmax), INFINITY, &b4, 0);
     1780                        B0 += b1+b2;
     1781                        B1 += b3+b4;
     1782                        dist1 -= B0;
     1783                        dist2 -= B1;
     1784                    }
     1785                    cpe->ms_mask[w*16+g] = dist2 <= dist1 && B1 < B0;
     1786                    if (cpe->ms_mask[w*16+g]) {
     1787                        sce0->sf_idx[w*16+g] = mididx;
     1788                        sce1->sf_idx[w*16+g] = sididx;
     1789                        sce0->band_type[w*16+g] = midcb;
     1790                        sce1->band_type[w*16+g] = sidcb;
     1791                        break;
     1792                    } else if (B1 > B0) {
     1793                        /* More boost won't fix this */
     1794                        break;
    10761795                    }
    1077                     abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
    1078                     abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
    1079                     abs_pow34_v(M34, M,                         sce0->ics.swb_sizes[g]);
    1080                     abs_pow34_v(S34, S,                         sce0->ics.swb_sizes[g]);
    1081                     dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,
    1082                                                 L34,
    1083                                                 sce0->ics.swb_sizes[g],
    1084                                                 sce0->sf_idx[(w+w2)*16+g],
    1085                                                 sce0->band_type[(w+w2)*16+g],
    1086                                                 lambda / band0->threshold, INFINITY, NULL);
    1087                     dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,
    1088                                                 R34,
    1089                                                 sce1->ics.swb_sizes[g],
    1090                                                 sce1->sf_idx[(w+w2)*16+g],
    1091                                                 sce1->band_type[(w+w2)*16+g],
    1092                                                 lambda / band1->threshold, INFINITY, NULL);
    1093                     dist2 += quantize_band_cost(s, M,
    1094                                                 M34,
    1095                                                 sce0->ics.swb_sizes[g],
    1096                                                 sce0->sf_idx[(w+w2)*16+g],
    1097                                                 sce0->band_type[(w+w2)*16+g],
    1098                                                 lambda / maxthr, INFINITY, NULL);
    1099                     dist2 += quantize_band_cost(s, S,
    1100                                                 S34,
    1101                                                 sce1->ics.swb_sizes[g],
    1102                                                 sce1->sf_idx[(w+w2)*16+g],
    1103                                                 sce1->band_type[(w+w2)*16+g],
    1104                                                 lambda / minthr, INFINITY, NULL);
    11051796                }
    1106                 cpe->ms_mask[w*16+g] = dist2 < dist1;
    11071797            }
    11081798            start += sce0->ics.swb_sizes[g];
    11091799        }
    AACCoefficientsEncoder ff_aac_coders[AAC_CODER_NB] = {  
    11191809    },
    11201810    [AAC_CODER_ANMR] = {
    11211811        search_for_quantizers_anmr,
    1122         encode_window_bands_info,
     1812        codebook_trellis_rate,
    11231813        quantize_and_encode_band,
    11241814        search_for_ms,
    11251815    },
  • libavcodec/aacenc.c

    diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c
    index d9c7215..dc3bab6 100644
    a b  
    4646#include "psymodel.h"
    4747
    4848#define AAC_MAX_CHANNELS 6
     49#define CLIP_AVOIDANCE_FACTOR 0.95f
    4950
    5051#define ERROR_IF(cond, ...) \
    5152    if (cond) { \
     
    5354        return AVERROR(EINVAL); \
    5455    }
    5556
     57#define WARN_IF(cond, ...) \
     58    if (cond) { \
     59        av_log(avctx, AV_LOG_WARNING, __VA_ARGS__); \
     60    }
     61
    5662float ff_aac_pow34sf_tab[428];
    5763
    5864static const uint8_t swb_size_1024_96[] = {
    static const uint8_t *swb_size_1024[] = {  
    102108    swb_size_1024_96, swb_size_1024_96, swb_size_1024_64,
    103109    swb_size_1024_48, swb_size_1024_48, swb_size_1024_32,
    104110    swb_size_1024_24, swb_size_1024_24, swb_size_1024_16,
    105     swb_size_1024_16, swb_size_1024_16, swb_size_1024_8
     111    swb_size_1024_16, swb_size_1024_16, swb_size_1024_8,
     112    swb_size_1024_8
    106113};
    107114
    108115static const uint8_t swb_size_128_96[] = {
    static const uint8_t *swb_size_128[] = {  
    131138    swb_size_128_96, swb_size_128_96, swb_size_128_96,
    132139    swb_size_128_48, swb_size_128_48, swb_size_128_48,
    133140    swb_size_128_24, swb_size_128_24, swb_size_128_16,
    134     swb_size_128_16, swb_size_128_16, swb_size_128_8
     141    swb_size_128_16, swb_size_128_16, swb_size_128_8,
     142    swb_size_128_8
    135143};
    136144
    137145/** default channel configurations */
    static void apply_window_and_mdct(AACEncContext *s, SingleChannelElement *sce,  
    260268        for (i = 0; i < 1024; i += 128)
    261269            s->mdct128.mdct_calc(&s->mdct128, sce->coeffs + i, output + i*2);
    262270    memcpy(audio, audio + 1024, sizeof(audio[0]) * 1024);
     271    memcpy(sce->pcoeffs, sce->coeffs, sizeof(sce->pcoeffs));
    263272}
    264273
    265274/**
    static void adjust_frame_information(ChannelElement *cpe, int chans)  
    311320        start = 0;
    312321        maxsfb = 0;
    313322        cpe->ch[ch].pulse.num_pulse = 0;
    314         for (w = 0; w < ics->num_windows*16; w += 16) {
    315             for (g = 0; g < ics->num_swb; g++) {
    316                 //apply M/S
    317                 if (cpe->common_window && !ch && cpe->ms_mask[w + g]) {
    318                     for (i = 0; i < ics->swb_sizes[g]; i++) {
    319                         cpe->ch[0].coeffs[start+i] = (cpe->ch[0].coeffs[start+i] + cpe->ch[1].coeffs[start+i]) / 2.0;
    320                         cpe->ch[1].coeffs[start+i] =  cpe->ch[0].coeffs[start+i] - cpe->ch[1].coeffs[start+i];
     323        for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
     324            for (w2 = 0; w2 < ics->group_len[w]; w2++) {
     325                start = (w+w2) * 128;
     326                for (g = 0; g < ics->num_swb; g++) {
     327                    //apply M/S
     328                    if (cpe->common_window && !ch && cpe->ms_mask[w*16 + g]) {
     329                        for (i = 0; i < ics->swb_sizes[g]; i++) {
     330                            cpe->ch[0].coeffs[start+i] = (cpe->ch[0].pcoeffs[start+i] + cpe->ch[1].pcoeffs[start+i]) * 0.5f;
     331                            cpe->ch[1].coeffs[start+i] = cpe->ch[0].coeffs[start+i] - cpe->ch[1].pcoeffs[start+i];
     332                        }
    321333                    }
     334                    start += ics->swb_sizes[g];
    322335                }
    323                 start += ics->swb_sizes[g];
     336                for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w*16+cmaxsfb-1]; cmaxsfb--)
     337                    ;
     338                maxsfb = FFMAX(maxsfb, cmaxsfb);
    324339            }
    325             for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w+cmaxsfb-1]; cmaxsfb--)
    326                 ;
    327             maxsfb = FFMAX(maxsfb, cmaxsfb);
    328340        }
    329341        ics->max_sfb = maxsfb;
    330342
    static void encode_spectral_coeffs(AACEncContext *s, SingleChannelElement *sce)  
    430442                                                   sce->ics.swb_sizes[i],
    431443                                                   sce->sf_idx[w*16 + i],
    432444                                                   sce->band_type[w*16 + i],
    433                                                    s->lambda);
     445                                                   s->lambda, sce->ics.window_clipping[w]);
     446            start += sce->ics.swb_sizes[i];
     447        }
     448    }
     449}
     450
     451/**
     452 * Downscale spectral coefficients for near-clipping windows to avoid artifacts
     453 */
     454static void avoid_clipping(AACEncContext *s, SingleChannelElement *sce)
     455{
     456    int start, i, j, w, w2;
     457
     458    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     459        start = 0;
     460        for (i = 0; i < sce->ics.max_sfb; i++) {
     461            if (sce->ics.window_clipping[w]) {
     462                for (w2 = w; w2 < w + sce->ics.group_len[w]; w2++) {
     463                    float *swb_coeffs = sce->coeffs + start + w2*128;
     464                    for (j = 0; j < sce->ics.swb_sizes[i]; j++)
     465                        swb_coeffs[j] *= CLIP_AVOIDANCE_FACTOR;
     466                }
     467            }
    434468            start += sce->ics.swb_sizes[i];
    435469        }
    436470    }
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    507541    AACEncContext *s = avctx->priv_data;
    508542    float **samples = s->planar_samples, *samples2, *la, *overlap;
    509543    ChannelElement *cpe;
    510     int i, ch, w, g, chans, tag, start_ch, ret;
     544    int i, ch, w, g, chans, tag, start_ch, ret, frame_bits, its, ms_mode = 0;
    511545    int chan_el_counter[4];
    512546    FFPsyWindowInfo windows[AAC_MAX_CHANNELS];
    513547
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    565599            ics->num_swb            = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8];
    566600            for (w = 0; w < ics->num_windows; w++)
    567601                ics->group_len[w] = wi[ch].grouping[w];
     602            for (w = 0; w < ics->num_windows; w++)
     603                ics->window_clipping[w] = wi[ch].clipping[w];
    568604
    569605            apply_window_and_mdct(s, &cpe->ch[ch], overlap);
     606            avoid_clipping(s, &cpe->ch[ch]);
    570607            if (isnan(cpe->ch->coeffs[0])) {
    571608                av_log(avctx, AV_LOG_ERROR, "Input contains NaN\n");
    572609                return AVERROR(EINVAL);
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    576613    }
    577614    if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels)) < 0)
    578615        return ret;
     616   
     617    frame_bits = 0;
     618    its = 0;
    579619    do {
    580         int frame_bits;
    581 
     620        int target_bits, too_many_bits, too_few_bits;
     621       
    582622        init_put_bits(&s->pb, avpkt->data, avpkt->size);
    583623
    584624        if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT))
    585625            put_bitstream_info(s, LIBAVCODEC_IDENT);
    586626        start_ch = 0;
     627        target_bits = 0;
    587628        memset(chan_el_counter, 0, sizeof(chan_el_counter));
    588629        for (i = 0; i < s->chan_map[0]; i++) {
    589630            FFPsyWindowInfo* wi = windows + start_ch;
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    595636            put_bits(&s->pb, 4, chan_el_counter[tag]++);
    596637            for (ch = 0; ch < chans; ch++)
    597638                coeffs[ch] = cpe->ch[ch].coeffs;
     639            s->psy.bitres.alloc = -1;
     640            s->psy.bitres.bits = avctx->frame_bits / s->channels;
    598641            s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);
     642            if (s->psy.bitres.alloc > 0) {
     643                /* Lambda unused here on purpose, we need to take psy's unscaled allocation */
     644                target_bits += s->psy.bitres.alloc;
     645                s->psy.bitres.alloc /= chans;
     646            }
     647            s->cur_type = tag;
    599648            for (ch = 0; ch < chans; ch++) {
    600649                s->cur_channel = start_ch + ch;
    601650                s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    630679                if (cpe->common_window) {
    631680                    put_ics_info(s, &cpe->ch[0].ics);
    632681                    encode_ms_info(&s->pb, cpe);
     682                    if (cpe->ms_mode) ms_mode = 1;
    633683                }
    634684            }
    635685            for (ch = 0; ch < chans; ch++) {
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    639689            start_ch += chans;
    640690        }
    641691
     692        if (avctx->flags & CODEC_FLAG_QSCALE) {
     693            // When using a constant Q-scale, don't mess with lambda
     694            break;
     695        }
     696       
     697        // rate control stuff
     698        // target either the nominal bitrate, or what psy's bit reservoir says to target
     699        // whichever is greatest
    642700        frame_bits = put_bits_count(&s->pb);
    643         if (frame_bits <= 6144 * s->channels - 3) {
    644             s->psy.bitres.bits = frame_bits / s->channels;
     701        target_bits = FFMAX(target_bits, avctx->bit_rate * 1024 / avctx->sample_rate);
     702        target_bits = FFMIN(target_bits, 6144 * s->channels - 3);
     703       
     704        // When using ABR, be strict (but only for increasing)
     705        too_many_bits = target_bits + target_bits/2;
     706        too_few_bits = target_bits - target_bits/8;
     707        //fprintf(stderr, "l:%f\t%d\t%d\t%d\t%d\n", s->lambda, too_few_bits, frame_bits, target_bits, too_many_bits);
     708       
     709        if (   its == 0 /* for steady-state Q-scale tracking */
     710            || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits))
     711            || frame_bits >= 6144 * s->channels - 3  )
     712        {
     713            float ratio = ((float)target_bits) / frame_bits;
     714           
     715            if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) {
     716                /*
     717                This path is for steady-state Q-scale tracking
     718                When frame bits fall within the stable range, we still need to adjust
     719                lambda to maintain it like so in a stable fashion (large jumps in lambda
     720                create artifacts and shoulda be avoided), but slowly
     721                */
     722                ratio = sqrtf(sqrtf(ratio));
     723                ratio = av_clipf(ratio, 0.9f, 1.1f);
     724            } else {
     725                /* Not so fast though */
     726                ratio = sqrtf(ratio);
     727            }
     728            s->lambda = FFMIN(s->lambda * ratio, 65536.f);
     729           
     730            // Keep iterating if we must reduce and lambda is in the sky
     731            if (s->lambda < 300.f || ratio > 0.9f) {
     732                break;
     733            } else {
     734                if (ms_mode) {
     735                    for (i = 0; i < s->chan_map[0]; i++) {
     736                        // Must restore coeffs
     737                        chans = tag == TYPE_CPE ? 2 : 1;
     738                        cpe = &s->cpe[i];
     739                        for (ch = 0; ch < chans; ch++)
     740                            memcpy(cpe->ch[ch].coeffs, cpe->ch[ch].pcoeffs, sizeof(cpe->ch[ch].coeffs));
     741                    }
     742                }
     743                its++;
     744            }
     745        } else {
    645746            break;
    646747        }
    647 
    648         s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;
    649 
    650748    } while (1);
    651749
    652750    put_bits(&s->pb, 3, TYPE_END);
    653751    flush_put_bits(&s->pb);
    654752    avctx->frame_bits = put_bits_count(&s->pb);
    655753
    656     // rate control stuff
    657     if (!(avctx->flags & CODEC_FLAG_QSCALE)) {
    658         float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits;
    659         s->lambda *= ratio;
    660         s->lambda = FFMIN(s->lambda, 65536.f);
    661     }
    662 
    663754    if (!frame)
    664755        s->last_frame++;
    665756
    static av_cold int aac_encode_init(AVCodecContext *avctx)  
    740831
    741832    s->channels = avctx->channels;
    742833
    743     ERROR_IF(i == 16,
     834    ERROR_IF(i == 16
     835                || i >= (sizeof(swb_size_1024) / sizeof(*swb_size_1024))
     836                || i >= (sizeof(swb_size_128) / sizeof(*swb_size_128)),
    744837             "Unsupported sample rate %d\n", avctx->sample_rate);
    745838    ERROR_IF(s->channels > AAC_MAX_CHANNELS,
    746839             "Unsupported number of channels: %d\n", s->channels);
    747840    ERROR_IF(avctx->profile != FF_PROFILE_UNKNOWN && avctx->profile != FF_PROFILE_AAC_LOW,
    748841             "Unsupported profile %d\n", avctx->profile);
    749     ERROR_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
    750              "Too many bits per frame requested\n");
     842    WARN_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
     843             "Too many bits per frame requested, clamping to max\n");
     844   
     845    avctx->bit_rate = (int)FFMIN(
     846        6144 * s->channels / 1024.0 * avctx->sample_rate,
     847        avctx->bit_rate);
    751848
    752849    s->samplerate_index = i;
    753850
    fail:  
    794891
    795892#define AACENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
    796893static const AVOption aacenc_options[] = {
    797     {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.i64 = 0}, -1, 1, AACENC_FLAGS, "stereo_mode"},
     894    {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AACENC_FLAGS, "stereo_mode"},
    798895        {"auto",     "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = -1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
    799896        {"ms_off",   "Disable Mid/Side coding", 0, AV_OPT_TYPE_CONST, {.i64 =  0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
    800897        {"ms_force", "Force Mid/Side for the whole frame if possible", 0, AV_OPT_TYPE_CONST, {.i64 =  1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
  • libavcodec/aacenc.h

    diff --git a/libavcodec/aacenc.h b/libavcodec/aacenc.h
    index 0decb1d..3e040ed 100644
    a b typedef struct AACCoefficientsEncoder {  
    5252    void (*encode_window_bands_info)(struct AACEncContext *s, SingleChannelElement *sce,
    5353                                     int win, int group_len, const float lambda);
    5454    void (*quantize_and_encode_band)(struct AACEncContext *s, PutBitContext *pb, const float *in, int size,
    55                                      int scale_idx, int cb, const float lambda);
     55                                     int scale_idx, int cb, const float lambda, int rtz);
    5656    void (*search_for_ms)(struct AACEncContext *s, ChannelElement *cpe, const float lambda);
    5757} AACCoefficientsEncoder;
    5858
    typedef struct AACEncContext {  
    7878    FFPsyContext psy;
    7979    struct FFPsyPreprocessContext* psypp;
    8080    AACCoefficientsEncoder *coder;
    81     int cur_channel;
     81    int cur_channel;                             ///< current channel for coder context
    8282    int last_frame;
    8383    float lambda;
     84    enum RawDataBlockType cur_type;              ///< channel group type cur_channel belongs to
     85   
    8486    AudioFrameQueue afq;
    8587    DECLARE_ALIGNED(16, int,   qcoefs)[96];      ///< quantized coefficients
    8688    DECLARE_ALIGNED(32, float, scoefs)[1024];    ///< scaled coefficients
  • libavcodec/aacpsy.c

    diff --git a/libavcodec/aacpsy.c b/libavcodec/aacpsy.c
    index 9eeb836..c3e72a0 100644
    a b enum {  
    8787};
    8888
    8989#define PSY_3GPP_BITS_TO_PE(bits) ((bits) * 1.18f)
     90#define PSY_3GPP_PE_TO_BITS(bits) ((bits) / 1.18f)
    9091
    9192/* LAME psy model constants */
    9293#define PSY_LAME_FIR_LEN 21         ///< LAME psy model FIR order
    enum {  
    9596#define AAC_NUM_BLOCKS_SHORT 8      ///< number of blocks in a short sequence
    9697#define PSY_LAME_NUM_SUBBLOCKS 3    ///< Number of sub-blocks in each short block
    9798
     99#define CLIPPING_THRESHOLD 0.98f
     100
    98101/**
    99102 * @}
    100103 */
    typedef struct AacPsyContext{  
    157160    } pe;
    158161    AacPsyCoeffs psy_coef[2][64];
    159162    AacPsyChannel *ch;
     163    float global_quality; ///< normalized global quality taken from avctx
    160164}AacPsyContext;
    161165
    162166/**
    static float lame_calc_attack_threshold(int bitrate)  
    255259/**
    256260 * LAME psy model specific initialization
    257261 */
    258 static av_cold void lame_window_init(AacPsyContext *ctx, AVCodecContext *avctx)
    259 {
     262static void lame_window_init(AacPsyContext *ctx, AVCodecContext *avctx) {
    260263    int i, j;
    261264
    262265    for (i = 0; i < avctx->channels; i++) {
    static av_cold int psy_3gpp_init(FFPsyContext *ctx) {  
    299302    float bark;
    300303    int i, j, g, start;
    301304    float prev, minscale, minath, minsnr, pe_min;
    302     const int chan_bitrate = ctx->avctx->bit_rate / ctx->avctx->channels;
     305    int chan_bitrate = ctx->avctx->bit_rate / ((ctx->avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : ctx->avctx->channels);
    303306    const int bandwidth    = ctx->avctx->cutoff ? ctx->avctx->cutoff : AAC_CUTOFF(ctx->avctx);
    304307    const float num_bark   = calc_bark((float)bandwidth);
    305308
    306309    ctx->model_priv_data = av_mallocz(sizeof(AacPsyContext));
    307310    pctx = (AacPsyContext*) ctx->model_priv_data;
     311    pctx->global_quality = (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) * 0.01f;
    308312
     313    if (ctx->avctx->flags & CODEC_FLAG_QSCALE) {
     314        /* Use the target average bitrate to compute spread parameters */
     315        chan_bitrate = (int)(chan_bitrate / 120.0 * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120));
     316    }
     317   
    309318    pctx->chan_bitrate = chan_bitrate;
    310     pctx->frame_bits   = chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate;
     319    pctx->frame_bits   = FFMIN(2560, chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate);
    311320    pctx->pe.min       =  8.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
    312321    pctx->pe.max       = 12.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
    313322    ctx->bitres.size   = 6144 - pctx->frame_bits;
    314323    ctx->bitres.size  -= ctx->bitres.size % 8;
    315324    pctx->fill_level   = ctx->bitres.size;
    316325    minath = ath(3410, ATH_ADD);
     326   
    317327    for (j = 0; j < 2; j++) {
    318328        AacPsyCoeffs *coeffs = pctx->psy_coef[j];
    319329        const uint8_t *band_sizes = ctx->bands[j];
    static av_unused FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,  
    391401                                                 int channel, int prev_type)
    392402{
    393403    int i, j;
    394     int br               = ctx->avctx->bit_rate / ctx->avctx->channels;
     404    int br               = ((AacPsyContext*)ctx->model_priv_data)->chan_bitrate;
    395405    int attack_ratio     = br <= 16000 ? 18 : 10;
    396406    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
    397407    AacPsyChannel *pch  = &pctx->ch[channel];
    static int calc_bit_demand(AacPsyContext *ctx, float pe, int bits, int size,  
    501511    ctx->pe.max = FFMAX(pe, ctx->pe.max);
    502512    ctx->pe.min = FFMIN(pe, ctx->pe.min);
    503513
    504     return FFMIN(ctx->frame_bits * bit_factor, ctx->frame_bits + size - bits);
     514    /* NOTE: allocate a minimum of 1/8th average frame bits, to avoid
     515     *   reservoir starvation from producing zero-bit frames
     516     */
     517    return FFMIN(
     518        ctx->frame_bits * bit_factor,
     519        FFMAX(ctx->frame_bits + size - bits, ctx->frame_bits / 8));
    505520}
    506521
    507522static float calc_pe_3gpp(AacPsyBand *band)
    static float calc_reduced_thr_3gpp(AacPsyBand *band, float min_snr,  
    566581    return thr;
    567582}
    568583
     584static av_always_inline float sqrf(float f)
     585{
     586    return f*f;
     587}
     588
    569589#ifndef calc_thr_3gpp
    570590static void calc_thr_3gpp(const FFPsyWindowInfo *wi, const int num_bands, AacPsyChannel *pch,
    571                           const uint8_t *band_sizes, const float *coefs)
     591                          const uint8_t *band_sizes, const float *coefs, float q)
    572592{
    573593    int i, w, g;
    574     int start = 0;
     594    int start = 0, wstart = 0, end = 1024 / wi->num_windows;
     595    float iq2 = sqrf(1.0f / FFMAX(0.125f, q));
    575596    for (w = 0; w < wi->num_windows*16; w += 16) {
     597        wstart = start;
    576598        for (g = 0; g < num_bands; g++) {
    577599            AacPsyBand *band = &pch->band[w+g];
    578600
    579601            float form_factor = 0.0f;
    580             float Temp;
     602            float Temp, absthr;
    581603            band->energy = 0.0f;
    582604            for (i = 0; i < band_sizes[g]; i++) {
    583605                band->energy += coefs[start+i] * coefs[start+i];
    584606                form_factor  += sqrtf(fabs(coefs[start+i]));
    585607            }
     608            // Absolute threshold of hearing approx taking the low point
     609            // to be 16-bit quantization noise, scaled up to improve vbr
     610            absthr = sqrf(sqrf(FFMAX(1.0f, (abs(start - wstart - end/16) - end/64) / end * 6.5f)) * end) * 3.0517578125e-5;
     611            absthr *= band_sizes[g];
    586612            Temp = band->energy > 0 ? sqrtf((float)band_sizes[g] / band->energy) : 0;
    587             band->thr      = band->energy * 0.001258925f;
     613            band->thr      = FFMAX(absthr * iq2, band->energy * 0.001258925f);
    588614            band->nz_lines = form_factor * sqrtf(Temp);
    589615
    590616            start += band_sizes[g];
    static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,  
    628654    const uint8_t *band_sizes  = ctx->bands[wi->num_windows == 8];
    629655    AacPsyCoeffs  *coeffs      = pctx->psy_coef[wi->num_windows == 8];
    630656    const float avoid_hole_thr = wi->num_windows == 8 ? PSY_3GPP_AH_THR_SHORT : PSY_3GPP_AH_THR_LONG;
    631 
     657   
    632658    //calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation"
    633     calc_thr_3gpp(wi, num_bands, pch, band_sizes, coefs);
     659    calc_thr_3gpp(wi, num_bands, pch, band_sizes, coefs, pctx->global_quality);
    634660
    635661    //modify thresholds and energies - spread, threshold in quiet, pre-echo control
    636662    for (w = 0; w < wi->num_windows*16; w += 16) {
    static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,  
    671697
    672698    /* 5.6.1.3.2 "Calculation of the desired perceptual entropy" */
    673699    ctx->ch[channel].entropy = pe;
    674     desired_bits = calc_bit_demand(pctx, pe, ctx->bitres.bits, ctx->bitres.size, wi->num_windows == 8);
    675     desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits);
    676     /* NOTE: PE correction is kept simple. During initial testing it had very
    677      *       little effect on the final bitrate. Probably a good idea to come
    678      *       back and do more testing later.
    679      */
    680     if (ctx->bitres.bits > 0)
    681         desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits),
    682                                0.85f, 1.15f);
     700    if (ctx->avctx->flags & CODEC_FLAG_QSCALE) {
     701        /* (2.5 * 120) achieves almost transparent rate, and we want to give
     702         * ample room downwards, so we make that equivalent to QSCALE=2.4
     703         */
     704        desired_pe = pe * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) / (2 * 2.5f * 120.0f);
     705        desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe));
     706        desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping
     707       
     708        /* PE slope smoothing */
     709        if (ctx->bitres.bits > 0) {
     710            desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe));
     711            desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping
     712        }
     713       
     714        pctx->pe.max = FFMAX(pe, pctx->pe.max);
     715        pctx->pe.min = FFMIN(pe, pctx->pe.min);
     716    } else {
     717        desired_bits = calc_bit_demand(pctx, pe, ctx->bitres.bits, ctx->bitres.size, wi->num_windows == 8);
     718        desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits);
     719       
     720        /* NOTE: PE correction is kept simple. During initial testing it had very
     721         *       little effect on the final bitrate. Probably a good idea to come
     722         *       back and do more testing later.
     723         */
     724        if (ctx->bitres.bits > 0)
     725            desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits),
     726                                   0.85f, 1.15f);
     727    }
    683728    pctx->pe.previous = PSY_3GPP_BITS_TO_PE(desired_bits);
    684 
     729    ctx->bitres.alloc = desired_bits;
     730   
    685731    if (desired_pe < pe) {
    686732        /* 5.6.1.3.4 "First Estimation of the reduction value" */
    687733        for (w = 0; w < wi->num_windows*16; w += 16) {
    static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,  
    717763            }
    718764            desired_pe_no_ah = FFMAX(desired_pe - (pe - pe_no_ah), 0.0f);
    719765            if (active_lines > 0.0f)
    720                 reduction += calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);
     766                reduction = calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);
    721767
    722768            pe = 0.0f;
    723769            for (w = 0; w < wi->num_windows*16; w += 16) {
    static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,  
    778824
    779825            psy_band->threshold = band->thr;
    780826            psy_band->energy    = band->energy;
     827            psy_band->perceptual_weight = band->pe;
     828            psy_band->bits      = PSY_3GPP_PE_TO_BITS(band->pe);
    781829        }
    782830    }
    783831
    static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,  
    827875    int grouping     = 0;
    828876    int uselongblock = 1;
    829877    int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
     878    uint8_t clippings[AAC_NUM_BLOCKS_SHORT];
    830879    int i;
    831880    FFPsyWindowInfo wi = { { 0 } };
    832881
    static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,  
    841890
    842891        /* LAME comment: apply high pass filter of fs/4 */
    843892        psy_hp_filter(firbuf, hpfsmpl, psy_fir_coeffs);
    844 
     893       
    845894        /* Calculate the energies of each sub-shortblock */
    846895        for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) {
    847896            energy_subshort[i] = pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS)];
    static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,  
    916965
    917966    lame_apply_block_type(pch, &wi, uselongblock);
    918967
     968    /* Calculate input sample maximums and evaluate clipping risk */
     969    if (audio) {
     970        for (i = 0; i < AAC_NUM_BLOCKS_SHORT; i++) {
     971            const float *wbuf = audio + i * AAC_BLOCK_SIZE_SHORT;
     972            float max = 0;
     973            int j;
     974            for (j = 0; j < AAC_BLOCK_SIZE_SHORT; j++)
     975                max = FFMAX(max, fabsf(wbuf[j]));
     976            clippings[i] = (max > CLIPPING_THRESHOLD) ? 1 : 0;
     977        }
     978    } else {
     979        for (i = 0; i < 8; i++)
     980            clippings[i] = 0;
     981    }
     982
    919983    wi.window_type[1] = prev_type;
    920984    if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
     985        int clipping = 0;
     986       
    921987        wi.num_windows  = 1;
    922988        wi.grouping[0]  = 1;
    923989        if (wi.window_type[0] == LONG_START_SEQUENCE)
    924990            wi.window_shape = 0;
    925991        else
    926992            wi.window_shape = 1;
     993
     994        for (i = 0; i < 8 && !clipping; i++)
     995            clipping = clippings[i];
     996        wi.clipping[0] = clipping;
    927997    } else {
    928         int lastgrp = 0;
     998        int lastgrp = 0, anyclipped = 0;
    929999
    9301000        wi.num_windows = 8;
    9311001        wi.window_shape = 0;
    static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,  
    9341004                lastgrp = i;
    9351005            wi.grouping[lastgrp]++;
    9361006        }
     1007       
     1008        for (i = 0; i < 8; i += wi.grouping[i]) {
     1009            int w, clipping = 0;
     1010            for (w = 0; w < wi.grouping[i] && !clipping; w++)
     1011                clipping = clippings[i+w];
     1012            wi.clipping[i] = clipping;
     1013            if (clipping) anyclipped = 1;
     1014        }
    9371015    }
    9381016
    9391017    /* Determine grouping, based on the location of the first attack, and save for
    static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,  
    9481026            break;
    9491027        }
    9501028    }
     1029   
    9511030    pch->next_grouping = window_grouping[grouping];
    9521031
    9531032    pch->prev_attack = attacks[8];
  • libavcodec/psymodel.c

    diff --git a/libavcodec/psymodel.c b/libavcodec/psymodel.c
    index 059cbef..7f92b9d 100644
    a b FFPsyChannelGroup *ff_psy_find_group(FFPsyContext *ctx, int channel)  
    7575
    7676av_cold void ff_psy_end(FFPsyContext *ctx)
    7777{
    78     if (ctx->model && ctx->model->end)
     78    if (ctx->model->end)
    7979        ctx->model->end(ctx);
    8080    av_freep(&ctx->bands);
    8181    av_freep(&ctx->num_bands);
    av_cold struct FFPsyPreprocessContext* ff_psy_preprocess_init(AVCodecContext *av  
    101101    ctx        = av_mallocz(sizeof(FFPsyPreprocessContext));
    102102    ctx->avctx = avctx;
    103103
    104     if (avctx->cutoff > 0)
    105         cutoff_coeff = 2.0 * avctx->cutoff / avctx->sample_rate;
    106 
    107     if (!cutoff_coeff && avctx->codec_id == AV_CODEC_ID_AAC)
    108         cutoff_coeff = 2.0 * AAC_CUTOFF(avctx) / avctx->sample_rate;
    109 
    110     if (cutoff_coeff && cutoff_coeff < 0.98)
    111     ctx->fcoeffs = ff_iir_filter_init_coeffs(avctx, FF_FILTER_TYPE_BUTTERWORTH,
    112                                              FF_FILTER_MODE_LOWPASS, FILT_ORDER,
    113                                              cutoff_coeff, 0.0, 0.0);
    114     if (ctx->fcoeffs) {
    115         ctx->fstate = av_mallocz_array(sizeof(ctx->fstate[0]), avctx->channels);
    116         for (i = 0; i < avctx->channels; i++)
    117             ctx->fstate[i] = ff_iir_filter_init_state(FILT_ORDER);
     104    /* AAC has its own LP method */
     105    if (avctx->codec_id != AV_CODEC_ID_AAC) {
     106        if (avctx->cutoff > 0)
     107            cutoff_coeff = 2.0 * avctx->cutoff / avctx->sample_rate;
     108
     109        if (cutoff_coeff && cutoff_coeff < 0.98)
     110        ctx->fcoeffs = ff_iir_filter_init_coeffs(avctx, FF_FILTER_TYPE_BUTTERWORTH,
     111                                                 FF_FILTER_MODE_LOWPASS, FILT_ORDER,
     112                                                 cutoff_coeff, 0.0, 0.0);
     113        if (ctx->fcoeffs) {
     114            ctx->fstate = av_mallocz(sizeof(ctx->fstate[0]) * avctx->channels);
     115            for (i = 0; i < avctx->channels; i++)
     116                ctx->fstate[i] = ff_iir_filter_init_state(FILT_ORDER);
     117        }
    118118    }
    119119
    120120    ff_iir_filter_init(&ctx->fiir);
  • libavcodec/psymodel.h

    diff --git a/libavcodec/psymodel.h b/libavcodec/psymodel.h
    index 75261ba..d0e1294 100644
    a b  
    2727/** maximum possible number of bands */
    2828#define PSY_MAX_BANDS 128
    2929/** maximum number of channels */
    30 #define PSY_MAX_CHANS 20
     30#define PSY_MAX_CHANS 24
    3131
    32 #define AAC_CUTOFF(s) ((s)->bit_rate ? FFMIN3(4000 + (s)->bit_rate/8, 12000 + (s)->bit_rate/32, (s)->sample_rate / 2) : ((s)->sample_rate / 2))
     32/* cutoff for VBR is purposedly increased, since LP filtering actually
     33 * hinders VBR performance rather than the opposite
     34 */
     35#define _AAC_CUTOFF(bit_rate,channels,sample_rate) (bit_rate ? FFMIN3(FFMIN3( \
     36    bit_rate/channels/2, \
     37    3000 + bit_rate/channels/4, \
     38    12000 + bit_rate/channels/16), \
     39    20000, \
     40    sample_rate / 2): (sample_rate / 2))
     41#define AAC_CUTOFF(s) ( \
     42    (s->flags & CODEC_FLAG_QSCALE) \
     43    ? /*_AAC_CUTOFF(((int)(480000.0f*(s->global_quality ? s->global_quality/120.0f : 1.0f))), 1, s->sample_rate)*/s->sample_rate / 2 \
     44    : _AAC_CUTOFF(s->bit_rate, s->channels, s->sample_rate) \
     45)
    3346
    3447/**
    3548 * single band psychoacoustic information
    typedef struct FFPsyWindowInfo {  
    6780    int window_shape;                 ///< window shape (sine/KBD/whatever)
    6881    int num_windows;                  ///< number of windows in a frame
    6982    int grouping[8];                  ///< window grouping (for e.g. AAC)
     83    uint8_t clipping[8];              ///< set if a window group's samples are near clipping (for e.g. AAC)
    7084    int *window_sizes;                ///< sequence of window sizes inside one frame (for eg. WMA)
    7185} FFPsyWindowInfo;
    7286
    typedef struct FFPsyContext {  
    88102    struct {
    89103        int size;                     ///< size of the bitresevoir in bits
    90104        int bits;                     ///< number of bits used in the bitresevoir
     105        int alloc;                    ///< number of bits allocated by the psy, or -1 if no allocation was done
    91106    } bitres;
    92107
    93108    void* model_priv_data;            ///< psychoacoustic model implementation private data