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

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

Fix M/S encoding in ABR

  • libavcodec/aac.h

    diff --git a/libavcodec/aac.h b/libavcodec/aac.h
    index 89f463e..d7a2303 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 50a246f..a3dc19c 100644
    a b static const uint8_t *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
    6062
    6163/**
    6264 * Quantize one coefficient.
    6365 * @return absolute value of the quantized coefficient
    6466 * @see 3GPP TS26.403 5.6.2 "Scalefactor determination"
    6567 */
    66 static av_always_inline int quant(float coef, const float Q)
     68static av_always_inline int quant(float coef, const float Q, const float rounding)
    6769{
    6870    float a = coef * Q;
    69     return sqrtf(a * sqrtf(a)) + 0.4054;
     71    return sqrtf(a * sqrtf(a)) + rounding;
    7072}
    7173
    7274static void quantize_bands(int *out, const float *in, const float *scaled,
    73                            int size, float Q34, int is_signed, int maxval)
     75                           int size, float Q34, int is_signed, int maxval, const float rounding)
    7476{
    7577    int i;
    7678    double qc;
    7779    for (i = 0; i < size; i++) {
    7880        qc = scaled[i] * Q34;
    79         out[i] = (int)FFMIN(qc + 0.4054, (double)maxval);
     81        out[i] = (int)FFMIN(qc + rounding, (double)maxval);
    8082        if (is_signed && in[i] < 0.0f) {
    8183            out[i] = -out[i];
    8284        }
    static av_always_inline float quantize_and_encode_band_cost_template(  
    108110                                const float *scaled, int size, int scale_idx,
    109111                                int cb, const float lambda, const float uplim,
    110112                                int *bits, int BT_ZERO, int BT_UNSIGNED,
    111                                 int BT_PAIR, int BT_ESC)
     113                                int BT_PAIR, int BT_ESC, const float ROUNDING)
    112114{
    113115    const int q_idx = POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512;
    114116    const float Q   = ff_aac_pow2sf_tab [q_idx];
    static av_always_inline float quantize_and_encode_band_cost_template(  
    134136        abs_pow34_v(s->scoefs, in, size);
    135137        scaled = s->scoefs;
    136138    }
    137     quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, maxval);
     139    quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, maxval, ROUNDING);
    138140    if (BT_UNSIGNED) {
    139141        off = 0;
    140142    } else {
    static av_always_inline float quantize_and_encode_band_cost_template(  
    161163                        di = t - CLIPPED_ESCAPE;
    162164                        curbits += 21;
    163165                    } else {
    164                         int c = av_clip(quant(t, Q), 0, 8191);
     166                        int c = av_clip(quant(t, Q, ROUNDING), 0, 8191);
    165167                        di = t - c*cbrtf(c)*IQ;
    166168                        curbits += av_log2(c)*2 - 4 + 1;
    167169                    }
    static av_always_inline float quantize_and_encode_band_cost_template(  
    191193            if (BT_ESC) {
    192194                for (j = 0; j < 2; j++) {
    193195                    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);
     196                        int coef = av_clip(quant(fabsf(in[i+j]), Q, ROUNDING), 0, 8191);
    195197                        int len = av_log2(coef);
    196198
    197199                        put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);
    static av_always_inline float quantize_and_encode_band_cost_template(  
    207209    return cost;
    208210}
    209211
    210 #define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC) \
     212#define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, ROUNDING) \
    211213static float quantize_and_encode_band_cost_ ## NAME(                                        \
    212214                                struct AACEncContext *s,                                \
    213215                                PutBitContext *pb, const float *in,                     \
    static float quantize_and_encode_band_cost_ ## NAME(  
    217219    return quantize_and_encode_band_cost_template(                                      \
    218220                                s, pb, in, scaled, size, scale_idx,                     \
    219221                                BT_ESC ? ESC_BT : cb, lambda, uplim, bits,              \
    220                                 BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC);                 \
     222                                BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, ROUNDING);       \
    221223}
    222224
    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)
     225QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO,  1, 0, 0, 0, ROUND_STANDARD)
     226QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD, 0, 0, 0, 0, ROUND_STANDARD)
     227QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD, 0, 1, 0, 0, ROUND_STANDARD)
     228QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR, 0, 0, 1, 0, ROUND_STANDARD)
     229QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR, 0, 1, 1, 0, ROUND_STANDARD)
     230QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC,   0, 1, 1, 1, ROUND_STANDARD)
     231
     232/*QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO_RTZ,  1, 0, 0, 0, ROUND_TO_ZERO)
     233QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD_RTZ, 0, 0, 0, 0, ROUND_TO_ZERO)
     234QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD_RTZ, 0, 1, 0, 0, ROUND_TO_ZERO)
     235QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR_RTZ, 0, 0, 1, 0, ROUND_TO_ZERO)
     236QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR_RTZ, 0, 1, 1, 0, ROUND_TO_ZERO)*/
     237QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC_RTZ,   0, 1, 1, 1, ROUND_TO_ZERO)
    229238
    230239static float (*const quantize_and_encode_band_cost_arr[])(
    231240                                struct AACEncContext *s,
    static float (*const quantize_and_encode_band_cost_arr[])(  
    247256    quantize_and_encode_band_cost_ESC,
    248257};
    249258
     259static float (*const quantize_and_encode_band_cost_rtz_arr[])(
     260                                struct AACEncContext *s,
     261                                PutBitContext *pb, const float *in,
     262                                const float *scaled, int size, int scale_idx,
     263                                int cb, const float lambda, const float uplim,
     264                                int *bits) = {
     265    quantize_and_encode_band_cost_ZERO,
     266    quantize_and_encode_band_cost_SQUAD,
     267    quantize_and_encode_band_cost_SQUAD,
     268    quantize_and_encode_band_cost_UQUAD,
     269    quantize_and_encode_band_cost_UQUAD,
     270    quantize_and_encode_band_cost_SPAIR,
     271    quantize_and_encode_band_cost_SPAIR,
     272    quantize_and_encode_band_cost_UPAIR,
     273    quantize_and_encode_band_cost_UPAIR,
     274    quantize_and_encode_band_cost_UPAIR,
     275    quantize_and_encode_band_cost_UPAIR,
     276    quantize_and_encode_band_cost_ESC_RTZ,
     277};
     278
    250279#define quantize_and_encode_band_cost(                                  \
    251280                                s, pb, in, scaled, size, scale_idx, cb, \
    252                                 lambda, uplim, bits)                    \
    253     quantize_and_encode_band_cost_arr[cb](                              \
     281                                lambda, uplim, bits, rtz)               \
     282    ((rtz) ? quantize_and_encode_band_cost_rtz_arr : quantize_and_encode_band_cost_arr)[cb]( \
    254283                                s, pb, in, scaled, size, scale_idx, cb, \
    255284                                lambda, uplim, bits)
    256285
    257286static float quantize_band_cost(struct AACEncContext *s, const float *in,
    258287                                const float *scaled, int size, int scale_idx,
    259288                                int cb, const float lambda, const float uplim,
    260                                 int *bits)
     289                                int *bits, int rtz)
    261290{
    262291    return quantize_and_encode_band_cost(s, NULL, in, scaled, size, scale_idx,
    263                                          cb, lambda, uplim, bits);
     292                                         cb, lambda, uplim, bits, rtz);
    264293}
    265294
    266295static void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb,
    267296                                     const float *in, int size, int scale_idx,
    268                                      int cb, const float lambda)
     297                                     int cb, const float lambda, int rtz)
    269298{
    270299    quantize_and_encode_band_cost(s, pb, in, NULL, size, scale_idx, cb, lambda,
    271                                   INFINITY, NULL);
     300                                  INFINITY, NULL, rtz);
    272301}
    273302
    274303static 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) {  
    282311    return maxval;
    283312}
    284313
     314static av_const float sqrf(float f) {
     315    return f*f;
     316}
     317
     318static float find_form_factor(int group_len, int swb_size, float thresh, const float *scaled, float cleanup_factor) {
     319    const float iswb_size = 1.0f / swb_size;
     320    const float iswb_sizem1 = 1.0f / (swb_size - 1);
     321    const float ethresh = thresh;
     322    float form = 0.0f, weight = 0.0f;
     323    int w2, i;
     324    for (w2 = 0; w2 < group_len; w2++) {
     325        float e = 0.0f, e2 = 0.0f, var = 0.0f, maxval = 0.0f;
     326        float nzl = 0;
     327        for (i = 0; i < swb_size; i++) {
     328            float s = fabsf(scaled[w2*128+i]);
     329            maxval = FFMAX(maxval, s);
     330            e += s;
     331            e2 += s *= s;
     332            /* We really don't want a hard non-zero-line count, since
     333             * even below-threshold lines do add up towards band spectral power.
     334             * So, fall steeply towards zero, but smoothly
     335             */
     336            if (s >= ethresh)
     337                nzl += 1.0f;
     338            else if (cleanup_factor > 1.0f)
     339                nzl += powf(sqrf(s / ethresh), sqrf(FFMIN(4.0f,cleanup_factor)));
     340            else
     341                nzl += sqrf(s / ethresh);
     342        }
     343        if (e2 > thresh) {
     344            float frm;
     345            e *= iswb_size;
     346           
     347            // compute variance
     348            for (i = 0; i < swb_size; i++) {
     349                float d = fabsf(scaled[w2*128+i]) - e;
     350                var += d*d;
     351            }
     352            var = sqrtf(var * iswb_sizem1);
     353           
     354            e2 *= iswb_size;
     355            frm = e / FFMIN(e+4*var,maxval);
     356            form += e2 * sqrtf(frm) / FFMAX(0.5f,nzl);
     357            weight += e2;
     358        }
     359    }
     360    if (weight > 0)
     361        return form / weight;
     362    else
     363        return 1.0f;
     364}
     365
     366static float find_max_absval(int group_len, int swb_size, const float *scaled) {
     367    float maxval = 0.0f;
     368    int w2, i;
     369    for (w2 = 0; w2 < group_len; w2++) {
     370        for (i = 0; i < swb_size; i++) {
     371            maxval = FFMAX(maxval, fabs(scaled[w2*128+i]));
     372        }
     373    }
     374    return maxval;
     375}
     376
     377static unsigned char aac_maxval_cb[] = {
     378    0, 1, 3, 5, 5, 7, 7, 7, 9, 9, 9, 9, 9, 11
     379};
     380
    285381static int find_min_book(float maxval, int sf) {
    286382    float Q = ff_aac_pow2sf_tab[POW_SF2_ZERO - sf + SCALE_ONE_POS - SCALE_DIV_512];
    287383    float Q34 = sqrtf(Q * sqrtf(Q));
    288384    int qmaxval, cb;
    289385    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;
     386    if (qmaxval >= (sizeof(aac_maxval_cb) / sizeof(aac_maxval_cb[0])))
     387        cb = 11;
     388    else
     389        cb = aac_maxval_cb[qmaxval];
    297390    return cb;
    298391}
    299392
    static void encode_window_bands_info(AACEncContext *s, SingleChannelElement *sce  
    351444                    rd += quantize_band_cost(s, sce->coeffs + start + w*128,
    352445                                             s->scoefs + start + w*128, size,
    353446                                             sce->sf_idx[(win+w)*16+swb], cb,
    354                                              lambda / band->threshold, INFINITY, NULL);
     447                                             lambda / band->threshold, INFINITY, NULL, 0);
    355448                }
    356449                cost_stay_here = path[swb][cb].cost + rd;
    357450                cost_get_here  = minrd              + rd + run_bits + 4;
    static void codebook_trellis_rate(AACEncContext *s, SingleChannelElement *sce,  
    473566                    bits += quantize_band_cost(s, sce->coeffs + start + w*128,
    474567                                               s->scoefs + start + w*128, size,
    475568                                               sce->sf_idx[(win+w)*16+swb], cb,
    476                                                0, INFINITY, NULL);
     569                                               0, INFINITY, NULL, 0);
    477570                }
    478571                cost_stay_here = path[swb][cb].cost + bits;
    479572                cost_get_here  = minbits            + bits + run_bits + 4;
    static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,  
    655748                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    656749                        FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
    657750                        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);
     751                                                   q + q0, cb, lambda / band->threshold, INFINITY, NULL, 0);
    659752                    }
    660753                    minrd = FFMIN(minrd, dist);
    661754
    static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,  
    701794                sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
    702795}
    703796
     797#define sclip(x) av_clip(x,60,218)
     798
    704799/**
    705800 * two-loop quantizers search taken from ISO 13818-7 Appendix C
    706801 */
    707802static void search_for_quantizers_twoloop(AVCodecContext *avctx,
    708803                                          AACEncContext *s,
    709804                                          SingleChannelElement *sce,
    710                                           const float lambda)
     805                                          float lambda)
    711806{
    712807    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];
     808    int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate
     809        / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels)
     810        * (lambda / 120.f);
     811    int refbits = destbits;
     812    int toomanybits, toofewbits;
     813    char nzs[128];
     814    float dists[128] = { 0 }, uplims[128], energies[128];
    715815    float maxvals[128];
    716     int fflag, minscaler;
     816   
     817    /* rdlambda controls the maximum tolerated distortion. Twoloop
     818     * will keep iterating until it fails to lower it or it reaches
     819     * ulimit * rdlambda. Keeping it low increases quality on difficult
     820     * signals, but lower it too much, and bits will be taken from weak
     821     * signals, creating "holes". A balance is necesary.
     822     * rdmax and rdmin specify the relative deviation from rdlambda
     823     * allowed for tonality compensation
     824     */
     825    float rdlambda = av_clipf(2.0f * 120.f / lambda, 0.0625f, 16.0f);
     826    float rdmin = 0.03125f;
     827    float rdmax = 1.0f;
     828   
     829    /* sfoffs controls an offset of optmium allocation that will be
     830     * applied based on lambda. Keep it real and modest, the loop
     831     * will take care of the rest, this just accelerates convergence
     832     */
     833    float sfoffs = av_clipf(log2f(120.0f / lambda) * 4.0f, -5, 10);
     834   
     835    int fflag, minscaler, maxscaler, nminscaler, minrdsf;
    717836    int its  = 0;
     837    int maxits = 20;
    718838    int allz = 0;
    719     float minthr = INFINITY;
     839    int tbits;
     840    int cutoff = 1024;
     841    int cleanoff = 1024;
     842   
     843    /* zeroscale controls a multiplier of the threshold, if band energy
     844     * is below this, a zero is forced. Keep it lower than 1, unless
     845     * low lambda is used, because energy < threshold doesn't mean there's
     846     * no audible signal outright, it's just energy. Also make it rise
     847     * slower than rdlambda, as rdscale has due compensation with
     848     * noisy band depriorization below, whereas zeroing logic is rather dumb
     849     */
     850    float zeroscale;
     851    if (lambda > 120.f)
     852        zeroscale = av_clipf(powf(120.f / lambda, 0.25f), 0.0625f, 1.0f);
     853    else
     854        zeroscale = 1.f;
     855   
     856    if (s->psy.bitres.alloc >= 0) {
     857        // Psy granted us extra bits to use, from the reservoire
     858        // adjust for lambda except what psy already did
     859        destbits = s->psy.bitres.alloc
     860            * (lambda / (avctx->global_quality ? avctx->global_quality : 120));
     861    }
     862   
     863    if (avctx->flags & CODEC_FLAG_QSCALE) {
     864        // Constant Q-scale doesn't compensat MS coding on its own
     865        // No need to be overly precise, this only controls RD
     866        // adjustment CB limits when going overboard
     867        if (s->options.stereo_mode && s->cur_type == TYPE_CPE)
     868            destbits *= 2;
     869       
     870        // When using a constant Q-scale, don't adjust bits, just use RD
     871        // Don't let it go overboard, though... 8x psy target is enough
     872        toomanybits = 5800; //av_clip(FFMAX(refbits*3, destbits * 8), 768, 5800);
     873        toofewbits = 0;
     874       
     875        // Don't offset scalers, just RD
     876        sfoffs = sce->ics.num_windows - 1;
     877        rdlambda = sqrtf(rdlambda);
     878       
     879        // search further
     880        maxits = 40;
     881    } else {
     882        // When using ABR, be strict
     883        toomanybits = destbits + destbits/16;
     884        toofewbits = destbits - destbits/16;
     885       
     886        sfoffs = 0;
     887        rdlambda = sqrtf(rdlambda);
     888    }
     889
     890    // and zero out above cutoff frequency
     891    {
     892        int wlen = 1024 / sce->ics.num_windows;
     893        int bandwidth;
     894        int cleanwidth;
     895
     896        /* Scale, psy gives us constant quality, this LP only scales
     897         * bitrate by lambda, so we save bits on subjectively unimportant HF
     898         * rather than increase quantization noise. Adjust nominal bitrate
     899         * to effective bitrate according to encoding parameters, _AAC_CUTOFF
     900         * is calibrated for effective bitrate.
     901         */
     902        float rate_bandwidth_multiplier = 1.3f;
     903        int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE)
     904            ? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024)
     905            : (avctx->bit_rate / avctx->channels);
     906       
     907        if (avctx->cutoff > 0)
     908            bandwidth = avctx->cutoff;
     909        else
     910            bandwidth = FFMAX(3000, _AAC_CUTOFF(frame_bit_rate, 1, avctx->sample_rate));
     911        cleanwidth = FFMAX(3000, _AAC_CUTOFF(frame_bit_rate * 0.8f, 1, avctx->sample_rate));
     912
     913        cutoff = bandwidth * 2 * wlen / avctx->sample_rate;
     914        cleanoff = cleanwidth * 2 * wlen / avctx->sample_rate;
     915    }
    720916
    721917    // for values above this the decoder might end up in an endless loop
    722918    // due to always having more bits than what can be encoded.
    723919    destbits = FFMIN(destbits, 5800);
     920    toomanybits = FFMIN(toomanybits, 5800);
     921    toofewbits = FFMIN(toofewbits, 5800);
    724922    //XXX: some heuristic to determine initial quantizers will reduce search time
    725923    //determine zero bands and upper limits
    726924    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    727         for (g = 0;  g < sce->ics.num_swb; g++) {
     925        for (g = start = 0;  g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) {
    728926            int nz = 0;
    729927            float uplim = 0.0f;
     928            float energy = 0.0f;
     929           
    730930            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    731931                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) {
     932                if (start >= cutoff || band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0) {
    734933                    sce->zeroes[(w+w2)*16+g] = 1;
    735934                    continue;
    736935                }
    737936                nz = 1;
    738937            }
    739             uplims[w*16+g] = uplim *512;
     938            if (!nz) {
     939                uplim = 0.0f;
     940            } else {
     941                nz = 0;
     942                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
     943                    FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
     944                    if (band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0f)
     945                        continue;
     946                    uplim += band->threshold;
     947                    energy += band->energy;
     948                    nz++;
     949                }
     950            }
     951            uplims[w*16+g] = uplim;
     952            energies[w*16+g] = energy;
     953            nzs[w*16+g] = nz;
    740954            sce->zeroes[w*16+g] = !nz;
    741             if (nz)
    742                 minthr = FFMIN(minthr, uplim);
    743955            allz |= nz;
    744956        }
    745957    }
     958   
     959    /* Compute initial scalers */
     960    minscaler = 65535;
    746961    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    747962        for (g = 0;  g < sce->ics.num_swb; g++) {
    748963            if (sce->zeroes[w*16+g]) {
    749964                sce->sf_idx[w*16+g] = SCALE_ONE_POS;
    750965                continue;
    751966            }
    752             sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2f(uplims[w*16+g]/minthr)*4,59);
     967            /* log2f-to-distortion ratio is, technically, 2 (1.5db = 4, but it's power vs level so it's 2).
     968             * But, as offsets are applied, low-frequency signals are too sensitive to the induced distortion,
     969             * so we make scaling more conservative by choosing a lower log2f-to-distortion ratio, and thus
     970             * more robust.
     971             */
     972            sce->sf_idx[w*16+g] = av_clip(
     973                SCALE_ONE_POS
     974                    + 1.75*log2f(FFMAX(0.00125f,uplims[w*16+g]) / sce->ics.swb_sizes[g])
     975                    + sfoffs,
     976                60, SCALE_MAX_POS);
     977            //fprintf(stderr, "%02x ", sce->sf_idx[w*16+g]);
     978            minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
    753979        }
     980        //fprintf(stderr, "|\n");
    754981    }
    755 
     982    //fprintf(stderr, "\n");
     983   
     984    /* Clip */
     985    minscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512);
     986    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
     987        for (g = 0;  g < sce->ics.num_swb; g++)
     988            if (!sce->zeroes[w*16+g])
     989                sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF - 1);
     990   
    756991    if (!allz)
    757992        return;
    758993    abs_pow34_v(s->scoefs, sce->coeffs, 1024);
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    7661001        }
    7671002    }
    7681003
     1004    /* Scale uplims to match rate distortion to quality
     1005     * and apply noisy band depriorization and tonal band priorization.
     1006     * Maxval-energy ratio gives us an idea of how noisy/tonal the band is.
     1007     * If maxval^2 ~ energy, then that band is mostly noise, and we can relax
     1008     * rate distortion requirements.
     1009     */
     1010    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1011        /* psy already priorizes transients to some extent */
     1012        float de_psy_factor = (sce->ics.num_windows > 1) ? 8.0f / sce->ics.group_len[w] : 1.0f;
     1013        start = w*128;
     1014        for (g = 0;  g < sce->ics.num_swb; g++) {
     1015            if (nzs[g] > 0) {
     1016                float energy2uplim = find_form_factor(
     1017                    sce->ics.group_len[w], sce->ics.swb_sizes[g],
     1018                    uplims[w*16+g] / (nzs[g] * sce->ics.swb_sizes[w]),
     1019                    sce->coeffs + start,
     1020                    start / (float)cleanoff);
     1021                energy2uplim *= de_psy_factor;
     1022                energy2uplim = FFMAX(0.015625f, FFMIN(1.0f,energy2uplim));
     1023                //fprintf(stderr, "%.3f ", energy2uplim);
     1024                uplims[w*16+g] *= av_clipf(rdlambda * energy2uplim, rdmin, rdmax)
     1025                                  * sce->ics.group_len[w];
     1026            }
     1027            start += sce->ics.swb_sizes[g];
     1028        }
     1029        //fprintf(stderr, "|");
     1030    }
     1031    //fprintf(stderr, "\n");
     1032
    7691033    //perform two-loop search
    7701034    //outer loop - improve quality
    7711035    do {
    772         int tbits, qstep;
    773         minscaler = sce->sf_idx[0];
     1036        int qstep;
    7741037        //inner loop - quantize spectrum to fit into given number of bits
    7751038        qstep = its ? 1 : 32;
    7761039        do {
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    7901053                        start += sce->ics.swb_sizes[g];
    7911054                        continue;
    7921055                    }
    793                     minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
    7941056                    cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
    7951057                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    7961058                        int b;
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    8011063                                                   cb,
    8021064                                                   1.0f,
    8031065                                                   INFINITY,
    804                                                    &b);
     1066                                                   &b,
     1067                                                   0);
    8051068                        bits += b;
    8061069                    }
    8071070                    dists[w*16+g] = dist - bits;
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    8131076                    prev = sce->sf_idx[w*16+g];
    8141077                }
    8151078            }
    816             if (tbits > destbits) {
     1079            if (tbits > toomanybits) {
    8171080                for (i = 0; i < 128; i++)
    818                     if (sce->sf_idx[i] < 218 - qstep)
    819                         sce->sf_idx[i] += qstep;
    820             } else {
     1081                    if (sce->sf_idx[i] < (SCALE_MAX_POS - SCALE_DIV_512))
     1082                        sce->sf_idx[i] = FFMIN(SCALE_MAX_POS, sce->sf_idx[i] + qstep);
     1083            } else if (tbits < toofewbits) {
    8211084                for (i = 0; i < 128; i++)
    822                     if (sce->sf_idx[i] > 60 - qstep)
    823                         sce->sf_idx[i] -= qstep;
     1085                    if (sce->sf_idx[i] > SCALE_ONE_POS)
     1086                        sce->sf_idx[i] = FFMAX(SCALE_ONE_POS, sce->sf_idx[i] - qstep);
    8241087            }
    8251088            qstep >>= 1;
    826             if (!qstep && tbits > destbits*1.02 && sce->sf_idx[0] < 217)
     1089            if (!qstep && tbits > toomanybits && sce->sf_idx[0] < 217)
    8271090                qstep = 1;
    8281091        } while (qstep);
    8291092
     1093        minscaler = SCALE_MAX_POS;
     1094        maxscaler = 0;
     1095        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1096            for (g = 0;  g < sce->ics.num_swb; g++) {
     1097                if (!sce->zeroes[w*16+g]) {
     1098                    minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
     1099                    maxscaler = FFMAX(maxscaler, sce->sf_idx[w*16+g]);
     1100                }
     1101            }
     1102        }
     1103
     1104        //NOTE: Emulate v4 patch with n = 0, uncommenting if (mb >= ESC_BT) break,
     1105        //  and replacing minscaler-1 with minscaler
    8301106        fflag = 0;
    831         minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);
     1107        minscaler = nminscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512);
     1108        minrdsf = FFMAX3(60, minscaler-1, maxscaler - SCALE_MAX_DIFF);
    8321109        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1110            int depth = (avctx->flags & CODEC_FLAG_QSCALE) ? 4 : 2;
     1111            int mblim;
     1112            float uplmax = FFMIN(4.0f, FFMAX(1.0f, tbits / (float)FFMAX(1,destbits)));
     1113            if (tbits > (destbits*6))
     1114                mblim = 9;
     1115            else if (tbits < (destbits/3))
     1116                mblim = (ESC_BT + 1);
     1117            else
     1118                mblim = ESC_BT;
    8331119            for (g = 0; g < sce->ics.num_swb; g++) {
    8341120                int prevsc = sce->sf_idx[w*16+g];
    835                 if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60) {
    836                     if (find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1))
    837                         sce->sf_idx[w*16+g]--;
    838                     else //Try to make sure there is some energy in every band
    839                         sce->sf_idx[w*16+g]-=2;
     1121                if (!sce->zeroes[w*16+g]) {
     1122                    if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > minrdsf) {
     1123                        //Try to make sure there is some energy in every nonzero band
     1124                        //NOTE: This algorithm must be forcibly imbalanced, pushing harder
     1125                        //  on holes or more distorted bands at first, otherwise there's
     1126                        //  no net gain (since the next iteration will offset all bands
     1127                        //  on the opposite direction to compensate for extra bits)
     1128                        int n = (its > 4 && g > sce->ics.num_swb/4) ? 0 : (depth/2);
     1129                        for (i = 0; i < depth; ++i) {
     1130                            int mb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1);
     1131                            int cmb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
     1132                            if ((mb > cmb || cmb > mblim) && mb >= mblim && dists[w*16+g] <= uplims[w*16+g]*uplmax && sce->sf_idx[w*16+g] <= (minrdsf+1)) break;
     1133                            sce->sf_idx[w*16+g]--;
     1134                            dists[w*16+g] *= 0.5f;
     1135                            if (mb && (i >= n || dists[w*16+g] < uplims[w*16+g])) break;
     1136                        }
     1137                    } else if (tbits > destbits && dists[w*16+g] < (uplims[w*16+g]*0.5f) && sce->sf_idx[w*16+g] < maxscaler) {
     1138                        // Um... over target
     1139                        sce->sf_idx[w*16+g]++;
     1140                        dists[w*16+g] *= 2.0f;
     1141                    }
    8401142                }
    841                 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
    842                 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);
     1143                sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minrdsf, minscaler + SCALE_MAX_DIFF);
     1144                sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], SCALE_MAX_POS - SCALE_DIV_512);
    8431145                if (sce->sf_idx[w*16+g] != prevsc)
    8441146                    fflag = 1;
     1147                nminscaler = FFMIN(nminscaler, sce->sf_idx[w*16+g]);
    8451148                sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
    8461149            }
    8471150        }
     1151        if (nminscaler < minscaler) {
     1152            // Drecreased some scalers below minscaler. Must re-clamp.
     1153            minscaler = nminscaler;
     1154            for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
     1155                for (g = 0; g < sce->ics.num_swb; g++)
     1156                    sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
     1157        }
    8481158        its++;
    849     } while (fflag && its < 10);
     1159    } while (fflag && its < maxits);
     1160   
     1161    /* Fill implicit zeroes */
     1162    //fprintf(stderr, "its:%d %d/%d: ", its, tbits, destbits);
     1163    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1164        /* No lowly codebooks beyond cutoff zone, to clean up noisy coefs */
     1165        int scutoff = cutoff + cutoff/5;
     1166        for (g = start = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) {
     1167            int minbt = (start < scutoff) ? 0 : 3;
     1168            //fprintf(stderr, "%02x ", sce->sf_idx[w*16+g]);
     1169            if (sce->band_type[w*16+g] <= minbt) {
     1170                sce->zeroes[w*16+g] = 1;
     1171                sce->band_type[w*16+g] = 0;
     1172            }
     1173        }
     1174        //fprintf(stderr, "|");
     1175    }
     1176    //fprintf(stderr, "\n");
     1177    //fprintf(stderr, "ba:%d br:%d  \t\r", s->psy.bitres.alloc, tbits);
    8501178}
    8511179
    8521180static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
    static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,  
    9671295                                               ESC_BT,
    9681296                                               lambda,
    9691297                                               INFINITY,
    970                                                &b);
     1298                                               &b,
     1299                                               0);
    9711300                    dist -= b;
    9721301                }
    9731302                dist *= 1.0f / 512.0f / lambda;
    974                 quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512]);
     1303                quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512], ROUND_STANDARD);
    9751304                if (quant_max >= 8191) { // too much, return to the previous quantizer
    9761305                    sce->sf_idx[w*16+g] = prev_scf;
    9771306                    break;
    static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,  
    10211350                                       SingleChannelElement *sce,
    10221351                                       const float lambda)
    10231352{
    1024     int i, w, w2, g;
    1025     int minq = 255;
     1353    int w, w2, g;
     1354    float lowlambda = av_clipf(120.f / lambda, 0.85f, 1.f);
     1355    float rlambda = av_clipf(120.f / lambda, 0.75f, 10.f);
     1356    const int minq = av_clip(2 * log2f(120.f / lambda) + 150, 100, 218 - SCALE_MAX_DIFF);
     1357    const int maxq = minq + SCALE_MAX_DIFF - 1;
    10261358
    10271359    memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
    10281360    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    10291361        for (g = 0; g < sce->ics.num_swb; g++) {
    10301362            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    10311363                FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
    1032                 if (band->energy <= band->threshold) {
    1033                     sce->sf_idx[(w+w2)*16+g] = 218;
     1364                if (band->energy <= 0.05 * lowlambda * band->threshold) {
     1365                    sce->sf_idx[(w+w2)*16+g] = maxq;
    10341366                    sce->zeroes[(w+w2)*16+g] = 1;
    10351367                } else {
    1036                     sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2f(band->threshold), 80, 218);
     1368                    sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + 1.414*log2f(band->threshold * rlambda), minq, maxq);
    10371369                    sce->zeroes[(w+w2)*16+g] = 0;
    10381370                }
    1039                 minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
    10401371            }
    10411372        }
    10421373    }
    1043     for (i = 0; i < 128; i++) {
    1044         sce->sf_idx[i] = 140;
    1045         //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);
    1046     }
    10471374    //set the same quantizers inside window groups
    1048     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
    1049         for (g = 0;  g < sce->ics.num_swb; g++)
    1050             for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
    1051                 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
     1375    if (sce->ics.num_windows > 1) {
     1376        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1377            for (g = 0;  g < sce->ics.num_swb; g++) {
     1378                if (sce->ics.group_len[w] > 1) {
     1379                    int avg_sf_idx = 0;
     1380                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
     1381                        avg_sf_idx += sce->sf_idx[w*16+g];
     1382                    avg_sf_idx /= sce->ics.group_len[w];
     1383                    for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
     1384                        sce->sf_idx[(w+w2)*16+g] = avg_sf_idx;
     1385                }
     1386            }
     1387        }
     1388    }
     1389}
     1390
     1391static float bval2bmax(float b)
     1392{
     1393    /* approximates exp10f(-3.0f*(0.5f + 0.5f * cosf(FFMIN(b,15.5f) / 15.5f))) */
     1394    return 0.001f + 0.0035f * (b*b*b) / (15.5f*15.5f*15.5f);
    10521395}
    10531396
    10541397static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
    10551398                          const float lambda)
    10561399{
    1057     int start = 0, i, w, w2, g;
     1400    int start = 0, i, w, w2, g, sid_sf_boost;
    10581401    float M[128], S[128];
    10591402    float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
     1403    float mslambda = FFMIN(1.0f, lambda / 120.0f);
    10601404    SingleChannelElement *sce0 = &cpe->ch[0];
    10611405    SingleChannelElement *sce1 = &cpe->ch[1];
     1406   
    10621407    if (!cpe->common_window)
    10631408        return;
     1409   
    10641410    for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
     1411        int min_sf_idx_mid = SCALE_MAX_POS;
     1412        int min_sf_idx_side = SCALE_MAX_POS;
     1413        for (g = 0; g < sce0->ics.num_swb; g++) {
     1414            if (!sce0->zeroes[w*16+g])
     1415                min_sf_idx_mid = FFMIN(min_sf_idx_mid, sce0->sf_idx[w*16+g]);
     1416            if (!sce1->zeroes[w*16+g])
     1417                min_sf_idx_side = FFMIN(min_sf_idx_side, sce1->sf_idx[w*16+g]);
     1418        }
     1419       
    10651420        for (g = 0;  g < sce0->ics.num_swb; g++) {
     1421            float bmax = bval2bmax(g * 17.0f / sce0->ics.num_swb) / 0.0045f;
     1422            cpe->ms_mask[w*16+g] = 0;
    10661423            if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {
    1067                 float dist1 = 0.0f, dist2 = 0.0f;
     1424                float Mmax = 0.0f, Smax = 0.0f;
     1425               
     1426                /* Must compute mid/side SF and book for the whole window group */
    10681427                for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
    1069                     FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
    1070                     FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
    1071                     float minthr = FFMIN(band0->threshold, band1->threshold);
    1072                     float maxthr = FFMAX(band0->threshold, band1->threshold);
    10731428                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
    1074                         M[i] = (sce0->coeffs[start+w2*128+i]
    1075                               + sce1->coeffs[start+w2*128+i]) * 0.5;
     1429                        M[i] = (sce0->pcoeffs[start+w2*128+i]
     1430                              + sce1->pcoeffs[start+w2*128+i]) * 0.5f;
    10761431                        S[i] =  M[i]
    1077                               - sce1->coeffs[start+w2*128+i];
     1432                              - sce1->pcoeffs[start+w2*128+i];
     1433                    }
     1434                    abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);
     1435                    abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);
     1436                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++ ) {
     1437                        Mmax = FFMAX(Mmax, M34[i]);
     1438                        Smax = FFMAX(Smax, S34[i]);
     1439                    }
     1440                }
     1441               
     1442                for (sid_sf_boost = 0; sid_sf_boost < 4; sid_sf_boost++) {
     1443                    float dist1 = 0.0f, dist2 = 0.0f;
     1444                    int B0 = 0, B1 = 0;
     1445                    int minidx;
     1446                    int mididx, sididx;
     1447                    int midcb, sidcb;
     1448                   
     1449                    minidx = FFMIN(sce0->sf_idx[w*16+g], sce1->sf_idx[w*16+g]);
     1450                    mididx = av_clip(minidx, min_sf_idx_mid, min_sf_idx_mid + SCALE_MAX_DIFF);
     1451                    sididx = av_clip(minidx - sid_sf_boost * 3, min_sf_idx_side, min_sf_idx_side + SCALE_MAX_DIFF);
     1452                    midcb = find_min_book(Mmax, mididx);
     1453                    sidcb = find_min_book(Smax, sididx);
     1454                   
     1455                    if ((mididx > minidx) || (sididx > minidx)) {
     1456                        /* scalefactor range violation, bad stuff, will decrease quality unacceptably */
     1457                        continue;
     1458                    }
     1459                   
     1460                    /* No CB can be zero */
     1461                    midcb = FFMAX(1,midcb);
     1462                    sidcb = FFMAX(1,sidcb);
     1463                   
     1464                    for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
     1465                        FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
     1466                        FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
     1467                        float minthr = FFMIN(band0->threshold, band1->threshold);
     1468                        int b1,b2,b3,b4;
     1469                        for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
     1470                            M[i] = (sce0->coeffs[start+w2*128+i]
     1471                                  + sce1->coeffs[start+w2*128+i]) * 0.5;
     1472                            S[i] =  M[i]
     1473                                  - sce1->coeffs[start+w2*128+i];
     1474                        }
     1475                        abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
     1476                        abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
     1477                        abs_pow34_v(M34, M,                         sce0->ics.swb_sizes[g]);
     1478                        abs_pow34_v(S34, S,                         sce0->ics.swb_sizes[g]);
     1479                        dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,
     1480                                                    L34,
     1481                                                    sce0->ics.swb_sizes[g],
     1482                                                    sce0->sf_idx[(w+w2)*16+g],
     1483                                                    sce0->band_type[w*16+g],
     1484                                                    lambda / band0->threshold, INFINITY, &b1, 0);
     1485                        dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,
     1486                                                    R34,
     1487                                                    sce1->ics.swb_sizes[g],
     1488                                                    sce1->sf_idx[(w+w2)*16+g],
     1489                                                    sce1->band_type[w*16+g],
     1490                                                    lambda / band1->threshold, INFINITY, &b2, 0);
     1491                        dist2 += quantize_band_cost(s, M,
     1492                                                    M34,
     1493                                                    sce0->ics.swb_sizes[g],
     1494                                                    mididx,
     1495                                                    midcb,
     1496                                                    lambda / minthr, INFINITY, &b3, 0);
     1497                        dist2 += quantize_band_cost(s, S,
     1498                                                    S34,
     1499                                                    sce1->ics.swb_sizes[g],
     1500                                                    sididx,
     1501                                                    sidcb,
     1502                                                    lambda * mslambda / (minthr * bmax), INFINITY, &b4, 0);
     1503                        B0 += b1+b2;
     1504                        B1 += b3+b4;
     1505                        dist1 -= B0;
     1506                        dist2 -= B1;
     1507                    }
     1508                    cpe->ms_mask[w*16+g] = dist2 <= dist1 && B1 < B0;
     1509                    if (cpe->ms_mask[w*16+g]) {
     1510                        sce0->sf_idx[w*16+g] = mididx;
     1511                        sce1->sf_idx[w*16+g] = sididx;
     1512                        sce0->band_type[w*16+g] = midcb;
     1513                        sce1->band_type[w*16+g] = sidcb;
     1514                        break;
     1515                    } else if (B1 > B0) {
     1516                        /* More boost won't fix this */
     1517                        break;
    10781518                    }
    1079                     abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
    1080                     abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
    1081                     abs_pow34_v(M34, M,                         sce0->ics.swb_sizes[g]);
    1082                     abs_pow34_v(S34, S,                         sce0->ics.swb_sizes[g]);
    1083                     dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,
    1084                                                 L34,
    1085                                                 sce0->ics.swb_sizes[g],
    1086                                                 sce0->sf_idx[(w+w2)*16+g],
    1087                                                 sce0->band_type[(w+w2)*16+g],
    1088                                                 lambda / band0->threshold, INFINITY, NULL);
    1089                     dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,
    1090                                                 R34,
    1091                                                 sce1->ics.swb_sizes[g],
    1092                                                 sce1->sf_idx[(w+w2)*16+g],
    1093                                                 sce1->band_type[(w+w2)*16+g],
    1094                                                 lambda / band1->threshold, INFINITY, NULL);
    1095                     dist2 += quantize_band_cost(s, M,
    1096                                                 M34,
    1097                                                 sce0->ics.swb_sizes[g],
    1098                                                 sce0->sf_idx[(w+w2)*16+g],
    1099                                                 sce0->band_type[(w+w2)*16+g],
    1100                                                 lambda / maxthr, INFINITY, NULL);
    1101                     dist2 += quantize_band_cost(s, S,
    1102                                                 S34,
    1103                                                 sce1->ics.swb_sizes[g],
    1104                                                 sce1->sf_idx[(w+w2)*16+g],
    1105                                                 sce1->band_type[(w+w2)*16+g],
    1106                                                 lambda / minthr, INFINITY, NULL);
    11071519                }
    1108                 cpe->ms_mask[w*16+g] = dist2 < dist1;
    11091520            }
    11101521            start += sce0->ics.swb_sizes[g];
    11111522        }
  • libavcodec/aacenc.c

    diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c
    index 5596b4b..c1bf389 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        }
    571608        start_ch += chans;
    572609    }
    573610    if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels)) < 0)
    574611        return ret;
     612   
     613    frame_bits = 0;
     614    its = 0;
    575615    do {
    576         int frame_bits;
    577 
     616        int target_bits, too_many_bits, too_few_bits;
     617       
    578618        init_put_bits(&s->pb, avpkt->data, avpkt->size);
    579619
    580620        if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT))
    581621            put_bitstream_info(s, LIBAVCODEC_IDENT);
    582622        start_ch = 0;
     623        target_bits = 0;
    583624        memset(chan_el_counter, 0, sizeof(chan_el_counter));
    584625        for (i = 0; i < s->chan_map[0]; i++) {
    585626            FFPsyWindowInfo* wi = windows + start_ch;
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    591632            put_bits(&s->pb, 4, chan_el_counter[tag]++);
    592633            for (ch = 0; ch < chans; ch++)
    593634                coeffs[ch] = cpe->ch[ch].coeffs;
     635            s->psy.bitres.alloc = -1;
     636            s->psy.bitres.bits = avctx->frame_bits / s->channels;
    594637            s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);
     638            if (s->psy.bitres.alloc > 0) {
     639                /* Lambda unused here on purpose, we need to take psy's unscaled allocation */
     640                target_bits += s->psy.bitres.alloc;
     641                s->psy.bitres.alloc /= chans;
     642            }
     643            s->cur_type = tag;
    595644            for (ch = 0; ch < chans; ch++) {
    596645                s->cur_channel = start_ch + ch;
    597646                s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    626675                if (cpe->common_window) {
    627676                    put_ics_info(s, &cpe->ch[0].ics);
    628677                    encode_ms_info(&s->pb, cpe);
     678                    if (cpe->ms_mode) ms_mode = 1;
    629679                }
    630680            }
    631681            for (ch = 0; ch < chans; ch++) {
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    635685            start_ch += chans;
    636686        }
    637687
     688        if (avctx->flags & CODEC_FLAG_QSCALE) {
     689            // When using a constant Q-scale, don't mess with lambda
     690            break;
     691        }
     692       
     693        // rate control stuff
     694        // target either the nominal bitrate, or what psy's bit reservoir says to target
     695        // whichever is greatest
    638696        frame_bits = put_bits_count(&s->pb);
    639         if (frame_bits <= 6144 * s->channels - 3) {
    640             s->psy.bitres.bits = frame_bits / s->channels;
     697        target_bits = FFMAX(target_bits, avctx->bit_rate * 1024 / avctx->sample_rate);
     698        target_bits = FFMIN(target_bits, 6144 * s->channels - 3);
     699       
     700        // When using ABR, be strict (but only for increasing)
     701        too_many_bits = target_bits + target_bits/2;
     702        too_few_bits = target_bits - target_bits/8;
     703        //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);
     704       
     705        if (   its == 0 /* for steady-state Q-scale tracking */
     706            || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits))
     707            || frame_bits >= 6144 * s->channels - 3  )
     708        {
     709            float ratio = ((float)target_bits) / frame_bits;
     710           
     711            if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) {
     712                /*
     713                This path is for steady-state Q-scale tracking
     714                When frame bits fall within the stable range, we still need to adjust
     715                lambda to maintain it like so in a stable fashion (large jumps in lambda
     716                create artifacts and shoulda be avoided), but slowly
     717                */
     718                ratio = sqrtf(sqrtf(ratio));
     719                ratio = av_clipf(ratio, 0.9f, 1.1f);
     720            } else {
     721                /* Not so fast though */
     722                ratio = sqrtf(ratio);
     723            }
     724            s->lambda = FFMIN(s->lambda * ratio, 65536.f);
     725           
     726            // Keep iterating if we must reduce and lambda is in the sky
     727            // NOT if we did M/S coding, it's undoable
     728            if (s->lambda < 300.f || ratio > 0.9f)
     729                break;
     730            else {
     731                if (ms_mode) {
     732                    for (i = 0; i < s->chan_map[0]; i++) {
     733                        // Must restore coeffs
     734                        chans = tag == TYPE_CPE ? 2 : 1;
     735                        cpe = &s->cpe[i];
     736                        for (ch = 0; ch < chans; ch++)
     737                            memcpy(cpe->ch[ch].coeffs, cpe->ch[ch].pcoeffs, sizeof(cpe->ch[ch].coeffs));
     738                    }
     739                }
     740                its++;
     741            }
     742        } else {
    641743            break;
    642744        }
    643 
    644         s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;
    645 
    646745    } while (1);
    647746
    648747    put_bits(&s->pb, 3, TYPE_END);
    649748    flush_put_bits(&s->pb);
    650749    avctx->frame_bits = put_bits_count(&s->pb);
    651750
    652     // rate control stuff
    653     if (!(avctx->flags & CODEC_FLAG_QSCALE)) {
    654         float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits;
    655         s->lambda *= ratio;
    656         s->lambda = FFMIN(s->lambda, 65536.f);
    657     }
    658 
    659751    if (!frame)
    660752        s->last_frame++;
    661753
    static av_cold int aac_encode_init(AVCodecContext *avctx)  
    733825
    734826    s->channels = avctx->channels;
    735827
    736     ERROR_IF(i == 16,
     828    ERROR_IF(i == 16
     829                || i >= (sizeof(swb_size_1024) / sizeof(*swb_size_1024))
     830                || i >= (sizeof(swb_size_128) / sizeof(*swb_size_128)),
    737831             "Unsupported sample rate %d\n", avctx->sample_rate);
    738832    ERROR_IF(s->channels > AAC_MAX_CHANNELS,
    739833             "Unsupported number of channels: %d\n", s->channels);
    740834    ERROR_IF(avctx->profile != FF_PROFILE_UNKNOWN && avctx->profile != FF_PROFILE_AAC_LOW,
    741835             "Unsupported profile %d\n", avctx->profile);
    742     ERROR_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
    743              "Too many bits per frame requested\n");
     836    WARN_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
     837             "Too many bits per frame requested, clamping to max\n");
     838   
     839    avctx->bit_rate = (int)FFMIN(
     840        6144 * s->channels / 1024.0 * avctx->sample_rate,
     841        avctx->bit_rate);
    744842
    745843    s->samplerate_index = i;
    746844
    fail:  
    787885
    788886#define AACENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
    789887static const AVOption aacenc_options[] = {
    790     {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.i64 = 0}, -1, 1, AACENC_FLAGS, "stereo_mode"},
     888    {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AACENC_FLAGS, "stereo_mode"},
    791889        {"auto",     "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = -1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
    792890        {"ms_off",   "Disable Mid/Side coding", 0, AV_OPT_TYPE_CONST, {.i64 =  0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
    793891        {"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 ecd6811..4de3531 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 d2a782e..ddde1da 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 FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,  
    827873    int grouping     = 0;
    828874    int uselongblock = 1;
    829875    int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
     876    uint8_t clippings[AAC_NUM_BLOCKS_SHORT];
    830877    int i;
    831878    FFPsyWindowInfo wi = { { 0 } };
    832879
    static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,  
    841888
    842889        /* LAME comment: apply high pass filter of fs/4 */
    843890        psy_hp_filter(firbuf, hpfsmpl, psy_fir_coeffs);
    844 
     891       
    845892        /* Calculate the energies of each sub-shortblock */
    846893        for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) {
    847894            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,  
    916963
    917964    lame_apply_block_type(pch, &wi, uselongblock);
    918965
     966    /* Calculate input sample maximums and evaluate clipping risk */
     967    if (audio) {
     968        for (i = 0; i < AAC_NUM_BLOCKS_SHORT; i++) {
     969            const float *wbuf = audio + i * AAC_BLOCK_SIZE_SHORT;
     970            float max = 0;
     971            int j;
     972            for (j = 0; j < AAC_BLOCK_SIZE_SHORT; j++)
     973                max = FFMAX(max, fabsf(wbuf[j]));
     974            clippings[i] = (max > CLIPPING_THRESHOLD) ? 1 : 0;
     975        }
     976    } else {
     977        for (i = 0; i < 8; i++)
     978            clippings[i] = 0;
     979    }
     980
    919981    wi.window_type[1] = prev_type;
    920982    if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
     983        int clipping = 0;
     984       
    921985        wi.num_windows  = 1;
    922986        wi.grouping[0]  = 1;
    923987        if (wi.window_type[0] == LONG_START_SEQUENCE)
    924988            wi.window_shape = 0;
    925989        else
    926990            wi.window_shape = 1;
     991
     992        for (i = 0; i < 8 && !clipping; i++)
     993            clipping = clippings[i];
     994        wi.clipping[0] = clipping;
    927995    } else {
    928         int lastgrp = 0;
     996        int lastgrp = 0, anyclipped = 0;
    929997
    930998        wi.num_windows = 8;
    931999        wi.window_shape = 0;
    static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,  
    9341002                lastgrp = i;
    9351003            wi.grouping[lastgrp]++;
    9361004        }
     1005       
     1006        for (i = 0; i < 8; i += wi.grouping[i]) {
     1007            int w, clipping = 0;
     1008            for (w = 0; w < wi.grouping[i] && !clipping; w++)
     1009                clipping = clippings[i+w];
     1010            wi.clipping[i] = clipping;
     1011            if (clipping) anyclipped = 1;
     1012        }
    9371013    }
    9381014
    9391015    /* Determine grouping, based on the location of the first attack, and save for
    static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,  
    9481024            break;
    9491025        }
    9501026    }
     1027   
    9511028    pch->next_grouping = window_grouping[grouping];
    9521029
    9531030    pch->prev_attack = attacks[8];
  • libavcodec/psymodel.c

    diff --git a/libavcodec/psymodel.c b/libavcodec/psymodel.c
    index 22d2497..5e9a6fd 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 d1a126a..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