Ticket #2686: aac-improvements-wip-v2-rclookahead.patch

File aac-improvements-wip-v2-rclookahead.patch, 30.5 KB (added by klaussfreire, 13 years ago)

Second version of AAC improvements, with improvements on rate control, hopefully gets rid of all remaining "collapsations on high bit rates". Tested various music tracks on 64k, 128k, 256k and 384k.

  • libavcodec/aaccoder.c

    diff --git a/libavcodec/aaccoder.c b/libavcodec/aaccoder.c
    index e0285bb..7ffa300 100644
    a b static const uint8_t *run_value_bits[2] = {  
    5757    run_value_bits_long, run_value_bits_short
    5858};
    5959
    60 
    6160/**
    6261 * Quantize one coefficient.
    6362 * @return absolute value of the quantized coefficient
    static const uint8_t *run_value_bits[2] = {  
    6665static av_always_inline int quant(float coef, const float Q)
    6766{
    6867    float a = coef * Q;
    69     return sqrtf(a * sqrtf(a)) + 0.4054;
     68    return sqrtf(a * sqrtf(a)) + 0.4054f;
    7069}
    7170
    7271static void quantize_bands(int *out, const float *in, const float *scaled,
    static void quantize_bands(int *out, const float *in, const float *scaled,  
    7675    double qc;
    7776    for (i = 0; i < size; i++) {
    7877        qc = scaled[i] * Q34;
    79         out[i] = (int)FFMIN(qc + 0.4054, (double)maxval);
     78        out[i] = (int)FFMIN(qc + 0.4054f, (double)maxval);
    8079        if (is_signed && in[i] < 0.0f) {
    8180            out[i] = -out[i];
    8281        }
    static float find_max_val(int group_len, int swb_size, const float *scaled) {  
    282281    return maxval;
    283282}
    284283
     284static float find_max_absval(int group_len, int swb_size, const float *scaled) {
     285    float maxval = 0.0f;
     286    int w2, i;
     287    for (w2 = 0; w2 < group_len; w2++) {
     288        for (i = 0; i < swb_size; i++) {
     289            maxval = FFMAX(maxval, fabs(scaled[w2*128+i]));
     290        }
     291    }
     292    return maxval;
     293}
     294
    285295static int find_min_book(float maxval, int sf) {
    286296    float Q = ff_aac_pow2sf_tab[POW_SF2_ZERO - sf + SCALE_ONE_POS - SCALE_DIV_512];
    287297    float Q34 = sqrtf(Q * sqrtf(Q));
    static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,  
    701711                sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
    702712}
    703713
     714#define sclip(x) av_clip(x,60,218)
     715
    704716/**
    705717 * two-loop quantizers search taken from ISO 13818-7 Appendix C
    706718 */
    707719static void search_for_quantizers_twoloop(AVCodecContext *avctx,
    708720                                          AACEncContext *s,
    709721                                          SingleChannelElement *sce,
    710                                           const float lambda)
     722                                          float lambda)
    711723{
    712724    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];
     725    int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate
     726        / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels)
     727        * (lambda / 120.f);
     728    int toomanybits, toofewbits;
     729    float dists[128] = { 0 }, uplims[128], energies[128];
    715730    float maxvals[128];
    716     int fflag, minscaler;
     731   
     732    /* rdlambda controls the maximum tolerated distortion. Twoloop
     733     * will keep iterating until it fails to lower it or it reaches
     734     * ulimit * rdlambda. Keeping it low increases quality on difficult
     735     * signals, but lower it too much, and bits will be taken from weak
     736     * signals, creating "holes". A balance is necesary.
     737     */
     738    float rdlambda = av_clipf(2 * 120.f / lambda, 0.0625f, 16.0f);
     739    float rdmax = (avctx->flags & CODEC_FLAG_QSCALE) ? 4.0f : 1.0f;
     740   
     741    /* sfoffs controls an offset of optmium allocation that will be
     742     * applied based on lambda. Keep it real and modest, the loop
     743     * will take care of the rest, this just accelerates convergence
     744     */
     745    float sfoffs = av_clipf((120.0f - lambda) * 0.1f, -5, 10);
     746   
     747    int fflag, minscaler, nminscaler, minrdsf;
    717748    int its  = 0;
    718749    int allz = 0;
    719     float minthr = INFINITY, maxthr = 0.0f;
    720     float iminthr, ilogmaxthr;
     750    int tbits;
     751   
     752    /* zeroscale controls a multiplier of the threshold, if band energy
     753     * is below this, a zero is forced. Keep it lower than 1, unless
     754     * low lambda is used, because energy < threshold doesn't mean there's
     755     * no audible signal outright, it's just energy. Also make it rise
     756     * slower than rdlambda, as rdscale has due compensation with
     757     * noisy band depriorization below, whereas zeroing logic is rather dumb
     758     */
     759    float zeroscale;
     760    if (lambda > 120.f)
     761        zeroscale = av_clipf(powf(120.f / lambda, 0.25f), 0.0625f, 1.0f);
     762    else if (lambda < 80.f)
     763        zeroscale = av_clipf(powf(80.f / lambda, 0.25f), 1.0f, 2.0f);
     764    else
     765        zeroscale = 1.f;
     766   
     767    if (s->psy.bitres.alloc >= 0) {
     768        // Psy granted us extra bits to use, from the reservoire
     769        destbits = s->psy.bitres.alloc * (lambda / 120.f);
     770    }
     771   
     772    if (avctx->flags & CODEC_FLAG_QSCALE) {
     773        // When using a constant Q-scale, be lenient on bit over/underflow
     774        toomanybits = destbits * 3;
     775        toofewbits = destbits / 2;
     776    } else {
     777        // When using ABR, be strict
     778        toomanybits = destbits + destbits/16;
     779        toofewbits = destbits - destbits/16;
     780    }
    721781
    722782    // for values above this the decoder might end up in an endless loop
    723783    // due to always having more bits than what can be encoded.
    724784    destbits = FFMIN(destbits, 5800);
     785    toomanybits = FFMIN(toomanybits, 5800);
     786    toofewbits = FFMIN(toofewbits, 5800);
    725787    //XXX: some heuristic to determine initial quantizers will reduce search time
    726788    //determine zero bands and upper limits
    727789    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    728790        for (g = 0;  g < sce->ics.num_swb; g++) {
    729791            int nz = 0;
    730             float uplim = 0.0f;
     792            float uplim = INFINITY;
     793            float energy = 0.0f;
    731794            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    732795                FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
    733                 uplim += band->threshold;
    734                 if (band->energy <= band->threshold || band->threshold == 0.0f) {
     796                if (band->energy <= band->threshold * zeroscale || band->threshold == 0.0f) {
    735797                    sce->zeroes[(w+w2)*16+g] = 1;
    736798                    continue;
    737799                }
     800                if (uplim > band->threshold) {
     801                    uplim = band->threshold;
     802                    energy = band->energy;
     803                }
    738804                nz = 1;
    739805            }
    740             uplims[w*16+g] = uplim *512;
     806            if (!nz)
     807                uplim = 0.0f;
     808            uplims[w*16+g] = uplim;
     809            energies[w*16+g] = energy;
    741810            sce->zeroes[w*16+g] = !nz;
    742             if (nz) {
    743                 minthr = FFMIN(minthr, uplim);
    744                 maxthr = FFMAX(maxthr, uplim);
    745             }
    746811            allz |= nz;
    747812        }
    748813    }
    749     iminthr = 1.0f / minthr;
    750     ilogmaxthr = 12.0f / log2f(FFMAX(2.0f,maxthr*512*iminthr));
     814   
     815    /* Compute initial scalers */
     816    minscaler = 65535;
    751817    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    752818        for (g = 0;  g < sce->ics.num_swb; g++) {
    753819            if (sce->zeroes[w*16+g]) {
    754820                sce->sf_idx[w*16+g] = SCALE_ONE_POS;
    755821                continue;
    756822            }
    757             sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2f(uplims[w*16+g]*iminthr)*ilogmaxthr+59-12-1,59);
     823            /* log2f-to-distortion ratio is, technically, 2 (1.5db = 4, but it's power vs level so it's 2).
     824             * But, as offsets are applied, low-frequency signals are too sensitive to the induced distortion,
     825             * so we make scaling more conservative by choosing a lower log2f-to-distortion ratio, and thus
     826             * more robust.
     827             */
     828            sce->sf_idx[w*16+g] = SCALE_ONE_POS + 1.75*log2f(FFMAX(0.125f,uplims[w*16+g])) + sfoffs;
     829            minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
    758830        }
    759831    }
    760 
     832   
     833    /* Clip */
     834    minscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512);
     835    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
     836        for (g = 0;  g < sce->ics.num_swb; g++)
     837            if (!sce->zeroes[w*16+g])
     838                sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF - 1);
     839   
    761840    if (!allz)
    762841        return;
    763842    abs_pow34_v(s->scoefs, sce->coeffs, 1024);
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    771850        }
    772851    }
    773852
     853    /* Scale uplims to match rate distortion to quality
     854     * and apply noisy band depriorization.
     855     * Maxval-energy ratio gives us an idea of how noisy the band is.
     856     * If maxval^2 ~ energy, then that band is mostly noise, and we can relax
     857     * rate distortion requirements.
     858     */
     859    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     860        start = w*128;
     861        for (g = 0;  g < sce->ics.num_swb; g++) {
     862            float max = find_max_absval(sce->ics.group_len[w], sce->ics.swb_sizes[g], sce->coeffs + start);
     863            if (max > 0) {
     864                float energy2uplim = energies[w*16+g] / (max*max*sce->ics.swb_sizes[g]);
     865                energy2uplim = FFMAX(0.0625f, FFMIN(1.0f,energy2uplim));
     866                uplims[w*16+g] *= av_clipf(rdlambda * rdlambda * energy2uplim, 0.0625f, rdmax);
     867                start += sce->ics.swb_sizes[g];
     868            }
     869        }
     870    }
     871
    774872    //perform two-loop search
    775873    //outer loop - improve quality
    776874    do {
    777         int tbits, qstep;
    778         minscaler = sce->sf_idx[0];
     875        int qstep;
    779876        //inner loop - quantize spectrum to fit into given number of bits
    780877        qstep = its ? 1 : 32;
    781878        do {
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    795892                        start += sce->ics.swb_sizes[g];
    796893                        continue;
    797894                    }
    798                     minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
    799895                    cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
    800896                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    801897                        int b;
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    818914                    prev = sce->sf_idx[w*16+g];
    819915                }
    820916            }
    821             if (tbits > destbits) {
    822                 for (i = 0; i < 128; i++) 
    823                     if (sce->sf_idx[i] < 218 - qstep)
    824                         sce->sf_idx[i] += qstep;
    825             } else if (tbits < destbits) {
    826                 for (i = 0; i < 128; i++) 
    827                     if (sce->sf_idx[i] > 60 + qstep)
    828                         sce->sf_idx[i] -= qstep;
     917            if (tbits > toomanybits) {
     918                for (i = 0; i < 128; i++)
     919                    if (sce->sf_idx[i] < (SCALE_MAX_POS - SCALE_DIV_512))
     920                        sce->sf_idx[i] = FFMIN(SCALE_MAX_POS, sce->sf_idx[i] + qstep);
     921            } else if (tbits < toofewbits) {
     922                for (i = 0; i < 128; i++)
     923                    if (sce->sf_idx[i] > SCALE_ONE_POS)
     924                        sce->sf_idx[i] = FFMAX(SCALE_ONE_POS, sce->sf_idx[i] - qstep);
    829925            }
    830926            qstep >>= 1;
    831             if (!qstep && tbits > destbits*1.02 && sce->sf_idx[0] < 217)
     927            if (!qstep && tbits > toomanybits && sce->sf_idx[0] < 217)
    832928                qstep = 1;
    833929        } while (qstep);
    834930
     931        minscaler = SCALE_MAX_POS;
     932        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
     933            for (g = 0;  g < sce->ics.num_swb; g++)
     934                if (!sce->zeroes[w*16+g])
     935                    minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
     936
    835937        fflag = 0;
    836         minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);
     938        minscaler = nminscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512);
     939        minrdsf = (avctx->flags & CODEC_FLAG_QSCALE) ? 60 : minscaler;
    837940        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    838941            for (g = 0; g < sce->ics.num_swb; g++) {
    839942                int prevsc = sce->sf_idx[w*16+g];
    840                 if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60) {
     943                if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > minrdsf) {
    841944                    if (find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1))
    842945                        sce->sf_idx[w*16+g]--;
    843946                    else //Try to make sure there is some energy in every band
    844947                        sce->sf_idx[w*16+g]-=2;
    845948                }
    846                 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
    847                 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);
     949                sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minrdsf, minscaler + SCALE_MAX_DIFF);
     950                sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], SCALE_MAX_POS - SCALE_DIV_512);
    848951                if (sce->sf_idx[w*16+g] != prevsc)
    849952                    fflag = 1;
     953                nminscaler = FFMIN(nminscaler, sce->sf_idx[w*16+g]);
    850954                sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
    851955            }
    852956        }
     957        if (nminscaler < minscaler) {
     958            // Drecreased some scalers below minscaler. Must re-clamp.
     959            minscaler = nminscaler;
     960            for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
     961                for (g = 0; g < sce->ics.num_swb; g++)
     962                    sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
     963        }
    853964        its++;
    854     } while (fflag && its < 10);
     965    } while (fflag && its < 20);
     966   
     967    /* Fill implicit zeroes */
     968    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
     969        for (g = 0; g < sce->ics.num_swb; g++)
     970            if (sce->band_type[w*16+g] == 0)
     971                sce->zeroes[w*16+g] = 1;
    855972}
    856973
    857974static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
    static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,  
    10281145{
    10291146    int w, w2, g;
    10301147    float lowlambda = av_clipf(120.f / lambda, 0.85f, 1.f);
    1031     float rlambda = av_clipf(120.f / lambda, 0.75f, 2.f);
     1148    float rlambda = av_clipf(120.f / lambda, 0.75f, 10.f);
    10321149    const int minq = av_clip(2 * log2f(120.f / lambda) + 150, 100, 218 - SCALE_MAX_DIFF);
    10331150    const int maxq = minq + SCALE_MAX_DIFF - 1;
    10341151
    static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,  
    10411158                    sce->sf_idx[(w+w2)*16+g] = maxq;
    10421159                    sce->zeroes[(w+w2)*16+g] = 1;
    10431160                } else {
    1044                     sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2f(band->threshold * rlambda), minq, maxq);
     1161                    sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + 1.414*log2f(band->threshold * rlambda), minq, maxq);
    10451162                    sce->zeroes[(w+w2)*16+g] = 0;
    10461163                }
    10471164            }
    10481165        }
    10491166    }
    10501167    //set the same quantizers inside window groups
    1051     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
    1052         for (g = 0;  g < sce->ics.num_swb; g++)
    1053             for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
    1054                 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
     1168    if (sce->ics.num_windows > 1) {
     1169        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1170            for (g = 0;  g < sce->ics.num_swb; g++) {
     1171                if (sce->ics.group_len[w] > 1) {
     1172                    int avg_sf_idx = 0;
     1173                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
     1174                        avg_sf_idx += sce->sf_idx[w*16+g];
     1175                    avg_sf_idx /= sce->ics.group_len[w];
     1176                    for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
     1177                        sce->sf_idx[(w+w2)*16+g] = avg_sf_idx;
     1178                }
     1179            }
     1180        }
     1181    }
     1182}
     1183
     1184static float bval2bmax(float b)
     1185{
     1186    /* approximates exp10f(-3.0f*(0.5f + 0.5f * cosf(FFMIN(b,15.5f) / 15.5f))) */
     1187    return 0.001f + 0.0035f * (b*b*b) / (15.5f*15.5f*15.5f);
    10551188}
    10561189
    10571190static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
    static void search_for_ms(AACEncContext *s, ChannelElement *cpe,  
    10621195    float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
    10631196    SingleChannelElement *sce0 = &cpe->ch[0];
    10641197    SingleChannelElement *sce1 = &cpe->ch[1];
     1198   
    10651199    if (!cpe->common_window)
    10661200        return;
     1201   
    10671202    for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
     1203        int min_sf_idx_mid = SCALE_MAX_POS;
     1204        int min_sf_idx_side = SCALE_MAX_POS;
     1205        for (g = 0; g < sce0->ics.num_swb; g++) {
     1206            if (!sce0->zeroes[w*16+g])
     1207                min_sf_idx_mid = FFMIN(min_sf_idx_mid, sce0->sf_idx[w*16+g]);
     1208            if (!sce1->zeroes[w*16+g])
     1209                min_sf_idx_side = FFMIN(min_sf_idx_side, sce1->sf_idx[w*16+g]);
     1210        }
     1211       
    10681212        for (g = 0;  g < sce0->ics.num_swb; g++) {
     1213            float bmax = bval2bmax(g * 17.0f / sce0->ics.num_swb) / 0.0045f;
    10691214            if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {
    10701215                float dist1 = 0.0f, dist2 = 0.0f;
     1216                int B0 = 0, B1 = 0;
     1217                int minidx;
     1218                int mididx, sididx;
     1219                float Mmax = 0.0f, Smax = 0.0f;
     1220                int midcb, sidcb;
     1221               
     1222                /* Must compute mid/side SF and book for the whole window group */
     1223                minidx = FFMIN(sce0->sf_idx[w*16+g], sce1->sf_idx[w*16+g]);
     1224                for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
     1225                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
     1226                        M[i] = (sce0->coeffs[start+w2*128+i]
     1227                              + sce1->coeffs[start+w2*128+i]) * 0.5;
     1228                        S[i] =  M[i]
     1229                              - sce1->coeffs[start+w2*128+i];
     1230                    }
     1231                    abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);
     1232                    abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);
     1233                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++ ) {
     1234                        Mmax = FFMAX(Mmax, M34[i]);
     1235                        Smax = FFMAX(Smax, S34[i]);
     1236                    }
     1237                }
     1238                mididx = av_clip(minidx, min_sf_idx_mid, min_sf_idx_mid + SCALE_MAX_DIFF);
     1239                sididx = av_clip(minidx, min_sf_idx_side, min_sf_idx_side + SCALE_MAX_DIFF);
     1240                midcb = find_min_book(Mmax, mididx);
     1241                sidcb = find_min_book(Smax, sididx);
     1242               
    10711243                for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
    10721244                    FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
    10731245                    FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
    10741246                    float minthr = FFMIN(band0->threshold, band1->threshold);
    1075                     float avgthr = 0.5f*(band0->threshold + band1->threshold);
     1247                    int b1,b2,b3,b4;
    10761248                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
    10771249                        M[i] = (sce0->coeffs[start+w2*128+i]
    10781250                              + sce1->coeffs[start+w2*128+i]) * 0.5;
    static void search_for_ms(AACEncContext *s, ChannelElement *cpe,  
    10881260                                                sce0->ics.swb_sizes[g],
    10891261                                                sce0->sf_idx[(w+w2)*16+g],
    10901262                                                sce0->band_type[(w+w2)*16+g],
    1091                                                 lambda / band0->threshold, INFINITY, NULL);
     1263                                                lambda / band0->threshold, INFINITY, &b1);
    10921264                    dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,
    10931265                                                R34,
    10941266                                                sce1->ics.swb_sizes[g],
    10951267                                                sce1->sf_idx[(w+w2)*16+g],
    10961268                                                sce1->band_type[(w+w2)*16+g],
    1097                                                 lambda / band1->threshold, INFINITY, NULL);
     1269                                                lambda / band1->threshold, INFINITY, &b2);
    10981270                    dist2 += quantize_band_cost(s, M,
    10991271                                                M34,
    11001272                                                sce0->ics.swb_sizes[g],
    1101                                                 sce0->sf_idx[(w+w2)*16+g],
    1102                                                 sce0->band_type[(w+w2)*16+g],
    1103                                                 lambda / avgthr, INFINITY, NULL);
     1273                                                mididx,
     1274                                                midcb,
     1275                                                lambda / minthr, INFINITY, &b3);
    11041276                    dist2 += quantize_band_cost(s, S,
    11051277                                                S34,
    11061278                                                sce1->ics.swb_sizes[g],
    1107                                                 sce1->sf_idx[(w+w2)*16+g],
    1108                                                 sce1->band_type[(w+w2)*16+g],
    1109                                                 lambda / minthr, INFINITY, NULL);
     1279                                                sididx,
     1280                                                sidcb,
     1281                                                lambda * (lambda / 120.0f) / (minthr * bmax), INFINITY, &b4);
     1282                    B0 += b1+b2;
     1283                    B1 += b3+b4;
     1284                    dist1 -= B0;
     1285                    dist2 -= B1;
    11101286                }
    1111                 cpe->ms_mask[w*16+g] = dist2 < dist1;
     1287                cpe->ms_mask[w*16+g] = dist2 <= dist1 && B1 < B0;
     1288                if (cpe->ms_mask[w*16+g]) {
     1289                    for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
     1290                        sce0->sf_idx[(w+w2)*16+g] = mididx;
     1291                        sce0->band_type[(w+w2)*16+g] = midcb;
     1292                        sce1->sf_idx[(w+w2)*16+g] = sididx;
     1293                        sce1->band_type[(w+w2)*16+g] = sidcb;
     1294                    }
     1295                }
     1296            } else {
     1297                cpe->ms_mask[w*16+g] = 0;
    11121298            }
    11131299            start += sce0->ics.swb_sizes[g];
    11141300        }
  • libavcodec/aacenc.c

    diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c
    index aa93c90..eebdab1 100644
    a b static void adjust_frame_information(ChannelElement *cpe, int chans)  
    317317                if (cpe->common_window && !ch && cpe->ms_mask[w + g]) {
    318318                    for (i = 0; i < ics->swb_sizes[g]; i++) {
    319319                        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];
     320                        cpe->ch[1].coeffs[start+i] = cpe->ch[0].coeffs[start+i] - cpe->ch[1].coeffs[start+i];
    321321                    }
    322322                }
    323323                start += ics->swb_sizes[g];
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    507507    AACEncContext *s = avctx->priv_data;
    508508    float **samples = s->planar_samples, *samples2, *la, *overlap;
    509509    ChannelElement *cpe;
    510     int i, ch, w, g, chans, tag, start_ch, ret;
     510    int i, ch, w, g, chans, tag, start_ch, ret, frame_bits, its;
    511511    int chan_el_counter[4];
    512512    FFPsyWindowInfo windows[AAC_MAX_CHANNELS];
    513513
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    572572    }
    573573    if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels)) < 0)
    574574        return ret;
     575   
     576    frame_bits = 0;
     577    its = 0;
    575578    do {
    576         int frame_bits;
    577 
     579        int target_bits, too_many_bits, too_few_bits;
     580       
    578581        init_put_bits(&s->pb, avpkt->data, avpkt->size);
    579582
    580583        if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT))
    581584            put_bitstream_info(s, LIBAVCODEC_IDENT);
    582585        start_ch = 0;
     586        target_bits = 0;
    583587        memset(chan_el_counter, 0, sizeof(chan_el_counter));
    584588        for (i = 0; i < s->chan_map[0]; i++) {
    585589            FFPsyWindowInfo* wi = windows + start_ch;
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    591595            put_bits(&s->pb, 4, chan_el_counter[tag]++);
    592596            for (ch = 0; ch < chans; ch++)
    593597                coeffs[ch] = cpe->ch[ch].coeffs;
     598            s->psy.bitres.alloc = -1;
    594599            s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);
     600            target_bits += s->psy.bitres.alloc * (120.f / s->lambda);
    595601            for (ch = 0; ch < chans; ch++) {
    596                 s->cur_channel = start_ch * 2 + ch;
     602                s->cur_channel = start_ch + ch;
    597603                s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);
    598604            }
    599605            cpe->common_window = 0;
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    609615                    }
    610616                }
    611617            }
    612             s->cur_channel = start_ch * 2;
     618            s->cur_channel = start_ch;
    613619            if (s->options.stereo_mode && cpe->common_window) {
    614620                if (s->options.stereo_mode > 0) {
    615621                    IndividualChannelStream *ics = &cpe->ch[0].ics;
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    621627                }
    622628            }
    623629            adjust_frame_information(cpe, chans);
    624             if (cpe->ms_mode) {
    625                 /* Re-evaluate psy model and quantization selection based on
    626                    MS-transformed channels */
    627                 s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);
    628                 for (ch = 0; ch < chans; ch++) {
    629                     s->cur_channel = start_ch * 2 + ch;
    630                     s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);
    631                 }
    632             }
    633630            if (chans == 2) {
    634631                put_bits(&s->pb, 1, cpe->common_window);
    635632                if (cpe->common_window) {
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    644641            start_ch += chans;
    645642        }
    646643
     644        if (avctx->flags & CODEC_FLAG_QSCALE) {
     645            // When using a constant Q-scale, don't mess with lambda
     646            break;
     647        }
     648       
     649        // rate control stuff
     650        // target either the nominal bitrate, or what psy's bit reservoir says to target
     651        // whichever is greatest
    647652        frame_bits = put_bits_count(&s->pb);
    648         if (frame_bits <= 6144 * s->channels - 3) {
    649             s->psy.bitres.bits = frame_bits / s->channels;
     653        target_bits = FFMAX(target_bits, avctx->bit_rate * 1024 / avctx->sample_rate);
     654        target_bits = FFMIN(target_bits, 6144 * s->channels - 3);
     655       
     656        // When using ABR, be strict (but only for increasing)
     657        too_many_bits = target_bits + target_bits/2;
     658        too_few_bits = target_bits - target_bits/8;
     659       
     660        if (   its == 0 /* for steady-state Q-scale tracking */
     661            || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits))
     662            || frame_bits >= 6144 * s->channels - 3  )
     663        {
     664            float prev_lambda = s->lambda;
     665            float ratio = ((float)target_bits) / frame_bits;
     666            s->lambda = FFMIN(s->lambda * ratio, 65536.f);
     667           
     668            if (prev_lambda == s->lambda)
     669                break;
     670           
     671            // Keep iterating if we must reduce and lambda is in the sky
     672            if (ratio > 0.9f || s->lambda <= 300.f)
     673                its++;
     674           
     675            if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) {
     676                /*
     677                This path is for steady-state Q-scale tracking
     678                When frame bits fall within the stable range, we still need to adjust
     679                lambda to maintain it like so in a stable fashion (large jumps in lambda
     680                create artifacts and shoulda be avoided)
     681                */
     682                break;
     683            }
     684        } else {
    650685            break;
    651686        }
    652 
    653         s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;
    654 
    655687    } while (1);
    656688
    657689    put_bits(&s->pb, 3, TYPE_END);
    658690    flush_put_bits(&s->pb);
    659691    avctx->frame_bits = put_bits_count(&s->pb);
    660 
    661     // rate control stuff
    662     if (!(avctx->flags & CODEC_FLAG_QSCALE)) {
    663         float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits;
    664         s->lambda *= ratio;
    665         s->lambda = FFMIN(s->lambda, 65536.f);
    666     }
     692    s->psy.bitres.bits = avctx->frame_bits / s->channels;
    667693
    668694    if (!frame)
    669695        s->last_frame++;
  • libavcodec/aacpsy.c

    diff --git a/libavcodec/aacpsy.c b/libavcodec/aacpsy.c
    index 51c669a..98af667 100644
    a b static av_cold int psy_3gpp_init(FFPsyContext *ctx) {  
    297297    float bark;
    298298    int i, j, g, start;
    299299    float prev, minscale, minath, minsnr, pe_min;
    300     const int chan_bitrate = ctx->avctx->bit_rate / ctx->avctx->channels;
     300    const int chan_bitrate = ctx->avctx->bit_rate / ((ctx->avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : ctx->avctx->channels);
    301301    const int bandwidth    = ctx->avctx->cutoff ? ctx->avctx->cutoff : AAC_CUTOFF(ctx->avctx);
    302302    const float num_bark   = calc_bark((float)bandwidth);
    303303
    static av_unused FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,  
    389389                                                 int channel, int prev_type)
    390390{
    391391    int i, j;
    392     int br               = ctx->avctx->bit_rate / ctx->avctx->channels;
     392    int br               = ((AacPsyContext*)ctx->model_priv_data)->chan_bitrate;
    393393    int attack_ratio     = br <= 16000 ? 18 : 10;
    394394    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
    395395    AacPsyChannel *pch  = &pctx->ch[channel];
    static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,  
    679679        desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits),
    680680                               0.85f, 1.15f);
    681681    pctx->pe.previous = PSY_3GPP_BITS_TO_PE(desired_bits);
     682    ctx->bitres.alloc = desired_bits;
    682683
    683684    if (desired_pe < pe) {
    684685        /* 5.6.1.3.4 "First Estimation of the reduction value" */
  • libavcodec/psymodel.h

    diff --git a/libavcodec/psymodel.h b/libavcodec/psymodel.h
    index d1a126a..c446ceb 100644
    a b typedef struct FFPsyContext {  
    8888    struct {
    8989        int size;                     ///< size of the bitresevoir in bits
    9090        int bits;                     ///< number of bits used in the bitresevoir
     91        int alloc;                    ///< number of bits allocated by the psy, or -1 if no allocation was done
    9192    } bitres;
    9293
    9394    void* model_priv_data;            ///< psychoacoustic model implementation private data