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

File aac-improvements-wip-v7.patch, 48.2 KB (added by klaussfreire, 13 years ago)

v7 patch - mostly bugfixing on v6, but quite significant bugs - still incomplete (needs sample rate fixes and Mahler still sounds weird)

  • libavcodec/aaccoder.c

    diff --git a/libavcodec/aaccoder.c b/libavcodec/aaccoder.c
    index 50a246f..e0bd93b 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_form_factor(int group_len, int swb_size, float thresh, const float *scaled) {
     285    float form = 0.0f, iswb_size = 1.0f / swb_size, weight = 0.0f;
     286    float ethresh = thresh * sqrtf(iswb_size);
     287    int w2, i;
     288    for (w2 = 0; w2 < group_len; w2++) {
     289        float e = 0.0f, e2 = 0.0f, var = 0.0f, maxval = 0.0f;
     290        int nzl = 0;
     291        for (i = 0; i < swb_size; i++) {
     292            float s = fabsf(scaled[w2*128+i]);
     293            maxval = FFMAX(maxval, s);
     294            e += s;
     295            e2 += s *= s;
     296            if (s > ethresh)
     297                ++nzl;
     298        }
     299        e *= iswb_size;
     300        for (i = 0; i < swb_size; i++) {
     301            float d = fabsf(scaled[w2*128+i]) - e;
     302            var += d*d;
     303        }
     304        if (e2 > thresh) {
     305            var = sqrtf(var * iswb_size);
     306            e2 *= iswb_size;
     307            form += e2 * (var+maxval) / maxval;
     308            weight += e2 * (1+nzl);
     309        }
     310    }
     311    if (weight > 0)
     312        return form / weight;
     313    else
     314        return 1.0f;
     315}
     316
     317static float find_max_absval(int group_len, int swb_size, const float *scaled) {
     318    float maxval = 0.0f;
     319    int w2, i;
     320    for (w2 = 0; w2 < group_len; w2++) {
     321        for (i = 0; i < swb_size; i++) {
     322            maxval = FFMAX(maxval, fabs(scaled[w2*128+i]));
     323        }
     324    }
     325    return maxval;
     326}
     327
    285328static int find_min_book(float maxval, int sf) {
    286329    float Q = ff_aac_pow2sf_tab[POW_SF2_ZERO - sf + SCALE_ONE_POS - SCALE_DIV_512];
    287330    float Q34 = sqrtf(Q * sqrtf(Q));
    static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,  
    701744                sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
    702745}
    703746
     747#define sclip(x) av_clip(x,60,218)
     748
    704749/**
    705750 * two-loop quantizers search taken from ISO 13818-7 Appendix C
    706751 */
    707752static void search_for_quantizers_twoloop(AVCodecContext *avctx,
    708753                                          AACEncContext *s,
    709754                                          SingleChannelElement *sce,
    710                                           const float lambda)
     755                                          float lambda)
    711756{
    712757    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];
     758    int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate
     759        / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels)
     760        * (lambda / 120.f);
     761    int refbits = destbits;
     762    int toomanybits, toofewbits;
     763    char nzs[128];
     764    float dists[128] = { 0 }, uplims[128], energies[128];
    715765    float maxvals[128];
    716     int fflag, minscaler;
     766   
     767    /* rdlambda controls the maximum tolerated distortion. Twoloop
     768     * will keep iterating until it fails to lower it or it reaches
     769     * ulimit * rdlambda. Keeping it low increases quality on difficult
     770     * signals, but lower it too much, and bits will be taken from weak
     771     * signals, creating "holes". A balance is necesary.
     772     * rdmax and rdmin specify the relative deviation from rdlambda
     773     * allowed for tonality compensation
     774     */
     775    float rdlambda = av_clipf(2.0f * 120.f / lambda, 0.0625f, 16.0f);
     776    float rdmin = 0.03125f;
     777    float rdmax = 1.0f;
     778   
     779    /* sfoffs controls an offset of optmium allocation that will be
     780     * applied based on lambda. Keep it real and modest, the loop
     781     * will take care of the rest, this just accelerates convergence
     782     */
     783    float sfoffs = av_clipf(log2f(120.0f / lambda) * 4.0f, -5, 10);
     784   
     785    int fflag, minscaler, maxscaler, nminscaler, minrdsf;
    717786    int its  = 0;
     787    int maxits = 20;
    718788    int allz = 0;
    719     float minthr = INFINITY;
     789    int tbits;
     790    int cutoff = 1024;
     791   
     792    /* zeroscale controls a multiplier of the threshold, if band energy
     793     * is below this, a zero is forced. Keep it lower than 1, unless
     794     * low lambda is used, because energy < threshold doesn't mean there's
     795     * no audible signal outright, it's just energy. Also make it rise
     796     * slower than rdlambda, as rdscale has due compensation with
     797     * noisy band depriorization below, whereas zeroing logic is rather dumb
     798     */
     799    float zeroscale;
     800    if (lambda > 120.f)
     801        zeroscale = av_clipf(powf(120.f / lambda, 0.25f), 0.0625f, 1.0f);
     802    else
     803        zeroscale = 1.f;
     804   
     805    if (s->psy.bitres.alloc >= 0) {
     806        // Psy granted us extra bits to use, from the reservoire
     807        // adjust for lambda except what psy already did
     808        destbits = s->psy.bitres.alloc
     809            * (lambda / (avctx->global_quality ? avctx->global_quality : 120));
     810    }
     811   
     812    if (avctx->flags & CODEC_FLAG_QSCALE) {
     813        // When using a constant Q-scale, don't adjust bits, just use RD
     814        // Don't let it go overboard, though... 8x psy target is enough
     815        toomanybits = 5800; //av_clip(FFMAX(refbits*3, destbits * 8), 768, 5800);
     816        toofewbits = 0;
     817       
     818        // Don't offset scalers, just RD
     819        sfoffs = 0;
     820        rdlambda = sqrtf(rdlambda);
     821       
     822        // search further
     823        maxits = 40;
     824    } else {
     825        // When using ABR, be strict
     826        toomanybits = destbits + destbits/16;
     827        toofewbits = destbits - destbits/16;
     828       
     829        sfoffs = 0;
     830        rdlambda = sqrtf(rdlambda);
     831    }
     832
     833    // and zero out above cutoff frequency
     834    {
     835        int wlen = 1024 / sce->ics.num_windows;
     836        int bandwidth;
     837        if (avctx->cutoff > 0) {
     838            bandwidth = avctx->cutoff;
     839        } else {
     840            /* Scale by 2.4x, psy gives us constant quality, this LP only scales
     841             * bitrate by lambda, so we save bits on subjectively unimportant HF
     842             * rather than increase quantization noise
     843             */
     844            int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE)
     845                ? (refbits * 1.6f * avctx->sample_rate / 1024)
     846                : (avctx->bit_rate / avctx->channels);
     847           
     848            bandwidth = FFMAX(3000, _AAC_CUTOFF(frame_bit_rate, 1, avctx->sample_rate));
     849        }
     850        cutoff = bandwidth * 2 * wlen / avctx->sample_rate;
     851    }
    720852
    721853    // for values above this the decoder might end up in an endless loop
    722854    // due to always having more bits than what can be encoded.
    723855    destbits = FFMIN(destbits, 5800);
     856    toomanybits = FFMIN(toomanybits, 5800);
     857    toofewbits = FFMIN(toofewbits, 5800);
    724858    //XXX: some heuristic to determine initial quantizers will reduce search time
    725859    //determine zero bands and upper limits
    726860    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    727         for (g = 0;  g < sce->ics.num_swb; g++) {
     861        for (g = start = 0;  g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) {
    728862            int nz = 0;
    729863            float uplim = 0.0f;
     864            float energy = 0.0f;
     865           
    730866            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    731867                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) {
     868                if (start >= cutoff || band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0) {
    734869                    sce->zeroes[(w+w2)*16+g] = 1;
    735870                    continue;
    736871                }
    737872                nz = 1;
    738873            }
    739             uplims[w*16+g] = uplim *512;
     874            if (!nz) {
     875                uplim = 0.0f;
     876            } else {
     877                nz = 0;
     878                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
     879                    FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
     880                    if (band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0f)
     881                        continue;
     882                    uplim += band->threshold;
     883                    energy += band->energy;
     884                    nz++;
     885                }
     886            }
     887            uplims[w*16+g] = uplim;
     888            energies[w*16+g] = energy;
     889            nzs[w*16+g] = nz;
    740890            sce->zeroes[w*16+g] = !nz;
    741             if (nz)
    742                 minthr = FFMIN(minthr, uplim);
    743891            allz |= nz;
    744892        }
    745893    }
     894   
     895    /* Compute initial scalers */
     896    minscaler = 65535;
    746897    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    747898        for (g = 0;  g < sce->ics.num_swb; g++) {
    748899            if (sce->zeroes[w*16+g]) {
    749900                sce->sf_idx[w*16+g] = SCALE_ONE_POS;
    750901                continue;
    751902            }
    752             sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2f(uplims[w*16+g]/minthr)*4,59);
     903            /* log2f-to-distortion ratio is, technically, 2 (1.5db = 4, but it's power vs level so it's 2).
     904             * But, as offsets are applied, low-frequency signals are too sensitive to the induced distortion,
     905             * so we make scaling more conservative by choosing a lower log2f-to-distortion ratio, and thus
     906             * more robust.
     907             */
     908            sce->sf_idx[w*16+g] = av_clip(
     909                SCALE_ONE_POS
     910                    + 1.75*log2f(FFMAX(0.00125f,uplims[w*16+g]) / sce->ics.swb_sizes[g])
     911                    + sfoffs,
     912                60, SCALE_MAX_POS);
     913            //fprintf(stderr, "%02x ", sce->sf_idx[w*16+g]);
     914            minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
    753915        }
     916        //fprintf(stderr, "|\n");
    754917    }
    755 
     918    //fprintf(stderr, "\n");
     919   
     920    /* Clip */
     921    minscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512);
     922    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
     923        for (g = 0;  g < sce->ics.num_swb; g++)
     924            if (!sce->zeroes[w*16+g])
     925                sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF - 1);
     926   
    756927    if (!allz)
    757928        return;
    758929    abs_pow34_v(s->scoefs, sce->coeffs, 1024);
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    766937        }
    767938    }
    768939
     940    /* Scale uplims to match rate distortion to quality
     941     * and apply noisy band depriorization and tonal band priorization.
     942     * Maxval-energy ratio gives us an idea of how noisy/tonal the band is.
     943     * If maxval^2 ~ energy, then that band is mostly noise, and we can relax
     944     * rate distortion requirements.
     945     */
     946    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     947        start = w*128;
     948        for (g = 0;  g < sce->ics.num_swb; g++) {
     949            if (nzs[g] > 0) {
     950                /*float energy2uplim = 0.0f;
     951                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
     952                    FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
     953                    if (band->energy > (band->threshold * zeroscale) && band->threshold != 0.0f) {
     954                        float max = find_max_absval(1, sce->ics.swb_sizes[g], sce->coeffs + start + w2*128);
     955                        if (max > 0) {
     956                            float wenergy2uplim = band->energy / (max*max*sce->ics.swb_sizes[g]);
     957                            energy2uplim += wenergy2uplim;
     958                        }
     959                    }
     960                }*/
     961                float energy2uplim = find_form_factor(
     962                    sce->ics.group_len[w], sce->ics.swb_sizes[g],
     963                    uplims[w*16+g] * 0.5f / (nzs[g] * sce->ics.group_len[w]),
     964                    sce->coeffs + start);
     965                energy2uplim = FFMAX(0.015625f, FFMIN(1.0f,energy2uplim));
     966                //fprintf(stderr, "%.3f ", energy2uplim);
     967                uplims[w*16+g] *= av_clipf(rdlambda * rdlambda * energy2uplim, rdmin, rdmax);
     968                start += sce->ics.swb_sizes[g];
     969            }
     970        }
     971    }
     972    //fprintf(stderr, "\n");
     973
    769974    //perform two-loop search
    770975    //outer loop - improve quality
    771976    do {
    772         int tbits, qstep;
    773         minscaler = sce->sf_idx[0];
     977        int qstep;
    774978        //inner loop - quantize spectrum to fit into given number of bits
    775979        qstep = its ? 1 : 32;
    776980        do {
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    790994                        start += sce->ics.swb_sizes[g];
    791995                        continue;
    792996                    }
    793                     minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
    794997                    cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
    795998                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    796999                        int b;
    static void search_for_quantizers_twoloop(AVCodecContext *avctx,  
    8131016                    prev = sce->sf_idx[w*16+g];
    8141017                }
    8151018            }
    816             if (tbits > destbits) {
     1019            if (tbits > toomanybits) {
    8171020                for (i = 0; i < 128; i++)
    818                     if (sce->sf_idx[i] < 218 - qstep)
    819                         sce->sf_idx[i] += qstep;
    820             } else {
     1021                    if (sce->sf_idx[i] < (SCALE_MAX_POS - SCALE_DIV_512))
     1022                        sce->sf_idx[i] = FFMIN(SCALE_MAX_POS, sce->sf_idx[i] + qstep);
     1023            } else if (tbits < toofewbits) {
    8211024                for (i = 0; i < 128; i++)
    822                     if (sce->sf_idx[i] > 60 - qstep)
    823                         sce->sf_idx[i] -= qstep;
     1025                    if (sce->sf_idx[i] > SCALE_ONE_POS)
     1026                        sce->sf_idx[i] = FFMAX(SCALE_ONE_POS, sce->sf_idx[i] - qstep);
    8241027            }
    8251028            qstep >>= 1;
    826             if (!qstep && tbits > destbits*1.02 && sce->sf_idx[0] < 217)
     1029            if (!qstep && tbits > toomanybits && sce->sf_idx[0] < 217)
    8271030                qstep = 1;
    8281031        } while (qstep);
    8291032
     1033        minscaler = SCALE_MAX_POS;
     1034        maxscaler = 0;
     1035        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1036            for (g = 0;  g < sce->ics.num_swb; g++) {
     1037                if (!sce->zeroes[w*16+g]) {
     1038                    minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
     1039                    maxscaler = FFMAX(maxscaler, sce->sf_idx[w*16+g]);
     1040                }
     1041            }
     1042        }
     1043
     1044        //NOTE: Emulate v4 patch with n = 0, uncommenting if (mb >= ESC_BT) break,
     1045        //  and replacing minscaler-1 with minscaler
    8301046        fflag = 0;
    831         minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);
     1047        minscaler = nminscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512);
     1048        minrdsf = FFMAX(60, FFMIN(minscaler-1, maxscaler - SCALE_MAX_DIFF));
    8321049        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1050            int depth = (avctx->flags & CODEC_FLAG_QSCALE) ? 4 : 2;
    8331051            for (g = 0; g < sce->ics.num_swb; g++) {
    8341052                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))
     1053                if (!sce->zeroes[w*16+g] && dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > minrdsf) {
     1054                    //Try to make sure there is some energy in every nonzero band
     1055                    //NOTE: This algorithm must be forcibly imbalanced, pushing harder
     1056                    //  on holes or more distorted bands at first, otherwise there's
     1057                    //  no net gain (since the next iteration will offset all bands
     1058                    //  on the opposite direction to compensate for extra bits)
     1059                    int n = (its > 4 && g > sce->ics.num_swb/4) ? 0 : (depth/2);
     1060                    for (i = 0; i < depth; ++i) {
     1061                        int mb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1);
     1062                        if (mb >= ESC_BT && sce->sf_idx[w*16+g] <= (minrdsf+1)) break;
    8371063                        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;
     1064                        dists[w*16+g] *= 0.5f;
     1065                        if (mb && (i >= n || dists[w*16+g] < uplims[w*16+g])) break;
     1066                    }
    8401067                }
    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);
     1068                sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minrdsf, minscaler + SCALE_MAX_DIFF);
     1069                sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], SCALE_MAX_POS - SCALE_DIV_512);
    8431070                if (sce->sf_idx[w*16+g] != prevsc)
    8441071                    fflag = 1;
     1072                nminscaler = FFMIN(nminscaler, sce->sf_idx[w*16+g]);
    8451073                sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
    8461074            }
    8471075        }
     1076        if (nminscaler < minscaler) {
     1077            // Drecreased some scalers below minscaler. Must re-clamp.
     1078            minscaler = nminscaler;
     1079            for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
     1080                for (g = 0; g < sce->ics.num_swb; g++)
     1081                    sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
     1082        }
    8481083        its++;
    849     } while (fflag && its < 10);
     1084    } while (fflag && its < maxits);
     1085   
     1086    /* Fill implicit zeroes */
     1087    //fprintf(stderr, "its:%d %d/%d: ", its, tbits, destbits);
     1088    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1089        /* No lowly codebooks beyond cutoff zone, to clean up noisy coefs */
     1090        int scutoff = cutoff + cutoff/5;
     1091        for (g = start = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) {
     1092            int minbt = (start < scutoff) ? 0 : 3;
     1093            //fprintf(stderr, "%02x ", sce->sf_idx[w*16+g]);
     1094            if (sce->band_type[w*16+g] <= minbt) {
     1095                sce->zeroes[w*16+g] = 1;
     1096                sce->band_type[w*16+g] = 0;
     1097            }
     1098        }
     1099        //fprintf(stderr, "|");
     1100    }
     1101    //fprintf(stderr, "\n");
     1102    //fprintf(stderr, "ba:%d br:%d  \t\r", s->psy.bitres.alloc, tbits);
    8501103}
    8511104
    8521105static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
    static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,  
    10211274                                       SingleChannelElement *sce,
    10221275                                       const float lambda)
    10231276{
    1024     int i, w, w2, g;
    1025     int minq = 255;
     1277    int w, w2, g;
     1278    float lowlambda = av_clipf(120.f / lambda, 0.85f, 1.f);
     1279    float rlambda = av_clipf(120.f / lambda, 0.75f, 10.f);
     1280    const int minq = av_clip(2 * log2f(120.f / lambda) + 150, 100, 218 - SCALE_MAX_DIFF);
     1281    const int maxq = minq + SCALE_MAX_DIFF - 1;
    10261282
    10271283    memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
    10281284    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
    10291285        for (g = 0; g < sce->ics.num_swb; g++) {
    10301286            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
    10311287                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;
     1288                if (band->energy <= 0.05 * lowlambda * band->threshold) {
     1289                    sce->sf_idx[(w+w2)*16+g] = maxq;
    10341290                    sce->zeroes[(w+w2)*16+g] = 1;
    10351291                } else {
    1036                     sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2f(band->threshold), 80, 218);
     1292                    sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + 1.414*log2f(band->threshold * rlambda), minq, maxq);
    10371293                    sce->zeroes[(w+w2)*16+g] = 0;
    10381294                }
    1039                 minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
    10401295            }
    10411296        }
    10421297    }
    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     }
    10471298    //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];
     1299    if (sce->ics.num_windows > 1) {
     1300        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
     1301            for (g = 0;  g < sce->ics.num_swb; g++) {
     1302                if (sce->ics.group_len[w] > 1) {
     1303                    int avg_sf_idx = 0;
     1304                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
     1305                        avg_sf_idx += sce->sf_idx[w*16+g];
     1306                    avg_sf_idx /= sce->ics.group_len[w];
     1307                    for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
     1308                        sce->sf_idx[(w+w2)*16+g] = avg_sf_idx;
     1309                }
     1310            }
     1311        }
     1312    }
     1313}
     1314
     1315static float bval2bmax(float b)
     1316{
     1317    /* approximates exp10f(-3.0f*(0.5f + 0.5f * cosf(FFMIN(b,15.5f) / 15.5f))) */
     1318    return 0.001f + 0.0035f * (b*b*b) / (15.5f*15.5f*15.5f);
    10521319}
    10531320
    10541321static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
    static void search_for_ms(AACEncContext *s, ChannelElement *cpe,  
    10591326    float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
    10601327    SingleChannelElement *sce0 = &cpe->ch[0];
    10611328    SingleChannelElement *sce1 = &cpe->ch[1];
     1329   
    10621330    if (!cpe->common_window)
    10631331        return;
     1332   
    10641333    for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
     1334        int min_sf_idx_mid = SCALE_MAX_POS;
     1335        int min_sf_idx_side = SCALE_MAX_POS;
     1336        for (g = 0; g < sce0->ics.num_swb; g++) {
     1337            if (!sce0->zeroes[w*16+g])
     1338                min_sf_idx_mid = FFMIN(min_sf_idx_mid, sce0->sf_idx[w*16+g]);
     1339            if (!sce1->zeroes[w*16+g])
     1340                min_sf_idx_side = FFMIN(min_sf_idx_side, sce1->sf_idx[w*16+g]);
     1341        }
     1342       
    10651343        for (g = 0;  g < sce0->ics.num_swb; g++) {
     1344            float bmax = bval2bmax(g * 17.0f / sce0->ics.num_swb) / 0.0045f;
    10661345            if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {
    10671346                float dist1 = 0.0f, dist2 = 0.0f;
     1347                int B0 = 0, B1 = 0;
     1348                int minidx;
     1349                int mididx, sididx;
     1350                float Mmax = 0.0f, Smax = 0.0f;
     1351                int midcb, sidcb;
     1352               
     1353                /* Must compute mid/side SF and book for the whole window group */
     1354                minidx = FFMIN(sce0->sf_idx[w*16+g], sce1->sf_idx[w*16+g]);
     1355                for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
     1356                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
     1357                        M[i] = (sce0->coeffs[start+w2*128+i]
     1358                              + sce1->coeffs[start+w2*128+i]) * 0.5;
     1359                        S[i] =  M[i]
     1360                              - sce1->coeffs[start+w2*128+i];
     1361                    }
     1362                    abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);
     1363                    abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);
     1364                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++ ) {
     1365                        Mmax = FFMAX(Mmax, M34[i]);
     1366                        Smax = FFMAX(Smax, S34[i]);
     1367                    }
     1368                }
     1369                mididx = av_clip(minidx, min_sf_idx_mid, min_sf_idx_mid + SCALE_MAX_DIFF);
     1370                sididx = av_clip(minidx, min_sf_idx_side, min_sf_idx_side + SCALE_MAX_DIFF);
     1371                midcb = find_min_book(Mmax, mididx);
     1372                sidcb = find_min_book(Smax, sididx);
     1373               
    10681374                for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
    10691375                    FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
    10701376                    FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
    10711377                    float minthr = FFMIN(band0->threshold, band1->threshold);
    1072                     float maxthr = FFMAX(band0->threshold, band1->threshold);
     1378                    int b1,b2,b3,b4;
    10731379                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
    10741380                        M[i] = (sce0->coeffs[start+w2*128+i]
    10751381                              + sce1->coeffs[start+w2*128+i]) * 0.5;
    static void search_for_ms(AACEncContext *s, ChannelElement *cpe,  
    10851391                                                sce0->ics.swb_sizes[g],
    10861392                                                sce0->sf_idx[(w+w2)*16+g],
    10871393                                                sce0->band_type[(w+w2)*16+g],
    1088                                                 lambda / band0->threshold, INFINITY, NULL);
     1394                                                lambda / band0->threshold, INFINITY, &b1);
    10891395                    dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,
    10901396                                                R34,
    10911397                                                sce1->ics.swb_sizes[g],
    10921398                                                sce1->sf_idx[(w+w2)*16+g],
    10931399                                                sce1->band_type[(w+w2)*16+g],
    1094                                                 lambda / band1->threshold, INFINITY, NULL);
     1400                                                lambda / band1->threshold, INFINITY, &b2);
    10951401                    dist2 += quantize_band_cost(s, M,
    10961402                                                M34,
    10971403                                                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);
     1404                                                mididx,
     1405                                                midcb,
     1406                                                lambda / minthr, INFINITY, &b3);
    11011407                    dist2 += quantize_band_cost(s, S,
    11021408                                                S34,
    11031409                                                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);
     1410                                                sididx,
     1411                                                sidcb,
     1412                                                lambda * (lambda / 120.0f) / (minthr * bmax), INFINITY, &b4);
     1413                    B0 += b1+b2;
     1414                    B1 += b3+b4;
     1415                    dist1 -= B0;
     1416                    dist2 -= B1;
    11071417                }
    1108                 cpe->ms_mask[w*16+g] = dist2 < dist1;
     1418                cpe->ms_mask[w*16+g] = dist2 <= dist1 && B1 < B0;
     1419                if (cpe->ms_mask[w*16+g]) {
     1420                    for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
     1421                        sce0->sf_idx[(w+w2)*16+g] = mididx;
     1422                        sce0->band_type[(w+w2)*16+g] = midcb;
     1423                        sce1->sf_idx[(w+w2)*16+g] = sididx;
     1424                        sce1->band_type[(w+w2)*16+g] = sidcb;
     1425                    }
     1426                }
     1427            } else {
     1428                cpe->ms_mask[w*16+g] = 0;
    11091429            }
    11101430            start += sce0->ics.swb_sizes[g];
    11111431        }
  • libavcodec/aacenc.c

    diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c
    index 5596b4b..48d3d3f 100644
    a b  
    5353        return AVERROR(EINVAL); \
    5454    }
    5555
     56#define WARN_IF(cond, ...) \
     57    if (cond) { \
     58        av_log(avctx, AV_LOG_WARNING, __VA_ARGS__); \
     59    }
     60
    5661float ff_aac_pow34sf_tab[428];
    5762
    5863static const uint8_t swb_size_1024_96[] = {
    static void adjust_frame_information(ChannelElement *cpe, int chans)  
    317322                if (cpe->common_window && !ch && cpe->ms_mask[w + g]) {
    318323                    for (i = 0; i < ics->swb_sizes[g]; i++) {
    319324                        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];
     325                        cpe->ch[1].coeffs[start+i] = cpe->ch[0].coeffs[start+i] - cpe->ch[1].coeffs[start+i];
    321326                    }
    322327                }
    323328                start += ics->swb_sizes[g];
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    507512    AACEncContext *s = avctx->priv_data;
    508513    float **samples = s->planar_samples, *samples2, *la, *overlap;
    509514    ChannelElement *cpe;
    510     int i, ch, w, g, chans, tag, start_ch, ret;
     515    int i, ch, w, g, chans, tag, start_ch, ret, frame_bits, its;
    511516    int chan_el_counter[4];
    512517    FFPsyWindowInfo windows[AAC_MAX_CHANNELS];
    513518
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    572577    }
    573578    if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels)) < 0)
    574579        return ret;
     580   
     581    frame_bits = 0;
     582    its = 0;
    575583    do {
    576         int frame_bits;
    577 
     584        int target_bits, too_many_bits, too_few_bits;
     585       
    578586        init_put_bits(&s->pb, avpkt->data, avpkt->size);
    579587
    580588        if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT))
    581589            put_bitstream_info(s, LIBAVCODEC_IDENT);
    582590        start_ch = 0;
     591        target_bits = 0;
    583592        memset(chan_el_counter, 0, sizeof(chan_el_counter));
    584593        for (i = 0; i < s->chan_map[0]; i++) {
    585594            FFPsyWindowInfo* wi = windows + start_ch;
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    591600            put_bits(&s->pb, 4, chan_el_counter[tag]++);
    592601            for (ch = 0; ch < chans; ch++)
    593602                coeffs[ch] = cpe->ch[ch].coeffs;
     603            s->psy.bitres.alloc = -1;
     604            s->psy.bitres.bits = avctx->frame_bits / s->channels;
    594605            s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);
     606            if (s->psy.bitres.alloc > 0) {
     607                /* Lambda unused here on purpose, we need to take psy's unscaled allocation */
     608                target_bits += s->psy.bitres.alloc;
     609                s->psy.bitres.alloc /= chans;
     610            }
    595611            for (ch = 0; ch < chans; ch++) {
    596612                s->cur_channel = start_ch + ch;
    597613                s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);
    static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,  
    635651            start_ch += chans;
    636652        }
    637653
     654        if (avctx->flags & CODEC_FLAG_QSCALE) {
     655            // When using a constant Q-scale, don't mess with lambda
     656            break;
     657        }
     658       
     659        // rate control stuff
     660        // target either the nominal bitrate, or what psy's bit reservoir says to target
     661        // whichever is greatest
    638662        frame_bits = put_bits_count(&s->pb);
    639         if (frame_bits <= 6144 * s->channels - 3) {
    640             s->psy.bitres.bits = frame_bits / s->channels;
     663        target_bits = FFMAX(target_bits, avctx->bit_rate * 1024 / avctx->sample_rate);
     664        target_bits = FFMIN(target_bits, 6144 * s->channels - 3);
     665       
     666        // When using ABR, be strict (but only for increasing)
     667        too_many_bits = target_bits + target_bits/2;
     668        too_few_bits = target_bits - target_bits/8;
     669        //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);
     670       
     671        if (   its == 0 /* for steady-state Q-scale tracking */
     672            || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits))
     673            || frame_bits >= 6144 * s->channels - 3  )
     674        {
     675            float ratio = ((float)target_bits) / frame_bits;
     676           
     677            if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) {
     678                /*
     679                This path is for steady-state Q-scale tracking
     680                When frame bits fall within the stable range, we still need to adjust
     681                lambda to maintain it like so in a stable fashion (large jumps in lambda
     682                create artifacts and shoulda be avoided), but slowly
     683                */
     684                ratio = sqrtf(sqrtf(ratio));
     685                ratio = av_clipf(ratio, 0.9f, 1.1f);
     686            } else {
     687                /* Not so fast though */
     688                ratio = sqrtf(ratio);
     689            }
     690            s->lambda = FFMIN(s->lambda * ratio, 65536.f);
     691           
     692            // Keep iterating if we must reduce and lambda is in the sky
     693            if (s->lambda < 300.f || ratio > 0.9f)
     694                break;
     695            else
     696                its++;
     697        } else {
    641698            break;
    642699        }
    643 
    644         s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;
    645 
    646700    } while (1);
    647701
    648702    put_bits(&s->pb, 3, TYPE_END);
    649703    flush_put_bits(&s->pb);
    650704    avctx->frame_bits = put_bits_count(&s->pb);
    651705
    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 
    659706    if (!frame)
    660707        s->last_frame++;
    661708
    static av_cold int aac_encode_init(AVCodecContext *avctx)  
    739786             "Unsupported number of channels: %d\n", s->channels);
    740787    ERROR_IF(avctx->profile != FF_PROFILE_UNKNOWN && avctx->profile != FF_PROFILE_AAC_LOW,
    741788             "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");
     789    WARN_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
     790             "Too many bits per frame requested, clamping to max\n");
     791   
     792    avctx->bit_rate = (int)FFMIN(
     793        6144 * s->channels / 1024.0 * avctx->sample_rate,
     794        avctx->bit_rate);
    744795
    745796    s->samplerate_index = i;
    746797
    static const AVOption aacenc_options[] = {  
    791842        {"auto",     "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = -1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
    792843        {"ms_off",   "Disable Mid/Side coding", 0, AV_OPT_TYPE_CONST, {.i64 =  0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
    793844        {"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"},
    794     {"aac_coder", "", offsetof(AACEncContext, options.aac_coder), AV_OPT_TYPE_INT, {.i64 = AAC_CODER_TWOLOOP}, 0, AAC_CODER_NB-1, AACENC_FLAGS, "aac_coder"},
    795         {"faac",     "FAAC-inspired method",      0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_FAAC},    INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
    796         {"anmr",     "ANMR method",               0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_ANMR},    INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
    797         {"twoloop",  "Two loop searching method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_TWOLOOP}, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
    798         {"fast",     "Constant quantizer",        0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_FAST},    INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
     845    {"aac_coder", "", offsetof(AACEncContext, options.aac_coder), AV_OPT_TYPE_INT, {.i64 = 2}, 0, AAC_CODER_NB-1, AACENC_FLAGS},
    799846    {NULL}
    800847};
    801848
  • libavcodec/aacpsy.c

    diff --git a/libavcodec/aacpsy.c b/libavcodec/aacpsy.c
    index d2a782e..d5212f0 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
    typedef struct AacPsyContext{  
    157158    } pe;
    158159    AacPsyCoeffs psy_coef[2][64];
    159160    AacPsyChannel *ch;
     161    float global_quality; ///< normalized global quality taken from avctx
    160162}AacPsyContext;
    161163
    162164/**
    static float lame_calc_attack_threshold(int bitrate)  
    255257/**
    256258 * LAME psy model specific initialization
    257259 */
    258 static av_cold void lame_window_init(AacPsyContext *ctx, AVCodecContext *avctx)
    259 {
     260static void lame_window_init(AacPsyContext *ctx, AVCodecContext *avctx) {
    260261    int i, j;
    261262
    262263    for (i = 0; i < avctx->channels; i++) {
    static av_cold int psy_3gpp_init(FFPsyContext *ctx) {  
    299300    float bark;
    300301    int i, j, g, start;
    301302    float prev, minscale, minath, minsnr, pe_min;
    302     const int chan_bitrate = ctx->avctx->bit_rate / ctx->avctx->channels;
     303    int chan_bitrate = ctx->avctx->bit_rate / ((ctx->avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : ctx->avctx->channels);
    303304    const int bandwidth    = ctx->avctx->cutoff ? ctx->avctx->cutoff : AAC_CUTOFF(ctx->avctx);
    304305    const float num_bark   = calc_bark((float)bandwidth);
    305306
    306307    ctx->model_priv_data = av_mallocz(sizeof(AacPsyContext));
    307308    pctx = (AacPsyContext*) ctx->model_priv_data;
     309    pctx->global_quality = (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) * 0.01f;
    308310
     311    if (ctx->avctx->flags & CODEC_FLAG_QSCALE) {
     312        /* Use the target average bitrate to compute spread parameters */
     313        chan_bitrate = (int)(chan_bitrate / 120.0 * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120));
     314    }
     315   
    309316    pctx->chan_bitrate = chan_bitrate;
    310     pctx->frame_bits   = chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate;
     317    pctx->frame_bits   = FFMIN(2560, chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate);
    311318    pctx->pe.min       =  8.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
    312319    pctx->pe.max       = 12.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
    313320    ctx->bitres.size   = 6144 - pctx->frame_bits;
    314321    ctx->bitres.size  -= ctx->bitres.size % 8;
    315322    pctx->fill_level   = ctx->bitres.size;
    316323    minath = ath(3410, ATH_ADD);
     324   
    317325    for (j = 0; j < 2; j++) {
    318326        AacPsyCoeffs *coeffs = pctx->psy_coef[j];
    319327        const uint8_t *band_sizes = ctx->bands[j];
    static av_unused FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,  
    391399                                                 int channel, int prev_type)
    392400{
    393401    int i, j;
    394     int br               = ctx->avctx->bit_rate / ctx->avctx->channels;
     402    int br               = ((AacPsyContext*)ctx->model_priv_data)->chan_bitrate;
    395403    int attack_ratio     = br <= 16000 ? 18 : 10;
    396404    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
    397405    AacPsyChannel *pch  = &pctx->ch[channel];
    static int calc_bit_demand(AacPsyContext *ctx, float pe, int bits, int size,  
    501509    ctx->pe.max = FFMAX(pe, ctx->pe.max);
    502510    ctx->pe.min = FFMIN(pe, ctx->pe.min);
    503511
    504     return FFMIN(ctx->frame_bits * bit_factor, ctx->frame_bits + size - bits);
     512    /* NOTE: allocate a minimum of 1/8th average frame bits, to avoid
     513     *   reservoir starvation from producing zero-bit frames
     514     */
     515    return FFMIN(
     516        ctx->frame_bits * bit_factor,
     517        FFMAX(ctx->frame_bits + size - bits, ctx->frame_bits / 8));
    505518}
    506519
    507520static float calc_pe_3gpp(AacPsyBand *band)
    static float calc_reduced_thr_3gpp(AacPsyBand *band, float min_snr,  
    566579    return thr;
    567580}
    568581
     582static av_always_inline float sqrf(float f)
     583{
     584    return f*f;
     585}
     586
    569587#ifndef calc_thr_3gpp
    570588static void calc_thr_3gpp(const FFPsyWindowInfo *wi, const int num_bands, AacPsyChannel *pch,
    571                           const uint8_t *band_sizes, const float *coefs)
     589                          const uint8_t *band_sizes, const float *coefs, float q)
    572590{
    573591    int i, w, g;
    574     int start = 0;
     592    int start = 0, wstart = 0, end = 1024 / wi->num_windows;
     593    float iq2 = sqrf(1.0f / FFMAX(0.125f, q));
    575594    for (w = 0; w < wi->num_windows*16; w += 16) {
     595        wstart = start;
    576596        for (g = 0; g < num_bands; g++) {
    577597            AacPsyBand *band = &pch->band[w+g];
    578598
    579599            float form_factor = 0.0f;
    580             float Temp;
     600            float Temp, absthr;
    581601            band->energy = 0.0f;
    582602            for (i = 0; i < band_sizes[g]; i++) {
    583603                band->energy += coefs[start+i] * coefs[start+i];
    584604                form_factor  += sqrtf(fabs(coefs[start+i]));
    585605            }
     606            // Absolute threshold of hearing approx taking the low point
     607            // to be 16-bit quantization noise, scaled up to improve vbr
     608            absthr = sqrf(sqrf(FFMAX(1.0f, (abs(start - wstart - end/16) - end/64) / end * 6.5f)) * end) * 3.0517578125e-5;
     609            absthr *= band_sizes[g];
    586610            Temp = band->energy > 0 ? sqrtf((float)band_sizes[g] / band->energy) : 0;
    587             band->thr      = band->energy * 0.001258925f;
     611            band->thr      = FFMAX(absthr * iq2, band->energy * 0.001258925f);
    588612            band->nz_lines = form_factor * sqrtf(Temp);
    589613
    590614            start += band_sizes[g];
    static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,  
    628652    const uint8_t *band_sizes  = ctx->bands[wi->num_windows == 8];
    629653    AacPsyCoeffs  *coeffs      = pctx->psy_coef[wi->num_windows == 8];
    630654    const float avoid_hole_thr = wi->num_windows == 8 ? PSY_3GPP_AH_THR_SHORT : PSY_3GPP_AH_THR_LONG;
    631 
     655   
    632656    //calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation"
    633     calc_thr_3gpp(wi, num_bands, pch, band_sizes, coefs);
     657    calc_thr_3gpp(wi, num_bands, pch, band_sizes, coefs, pctx->global_quality);
    634658
    635659    //modify thresholds and energies - spread, threshold in quiet, pre-echo control
    636660    for (w = 0; w < wi->num_windows*16; w += 16) {
    static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,  
    671695
    672696    /* 5.6.1.3.2 "Calculation of the desired perceptual entropy" */
    673697    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);
     698    if (ctx->avctx->flags & CODEC_FLAG_QSCALE) {
     699        /* (2.5 * 120) achieves almost transparent rate, and we want to give
     700         * ample room downwards, so we make that equivalent to QSCALE=2.4
     701         */
     702        desired_pe = pe * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) / (2 * 2.5f * 120.0f);
     703        desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe));
     704        desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping
     705       
     706        /* PE slope smoothing */
     707        if (ctx->bitres.bits > 0) {
     708            desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe));
     709            desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping
     710        }
     711       
     712        pctx->pe.max = FFMAX(pe, pctx->pe.max);
     713        pctx->pe.min = FFMIN(pe, pctx->pe.min);
     714    } else {
     715        desired_bits = calc_bit_demand(pctx, pe, ctx->bitres.bits, ctx->bitres.size, wi->num_windows == 8);
     716        desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits);
     717       
     718        /* NOTE: PE correction is kept simple. During initial testing it had very
     719         *       little effect on the final bitrate. Probably a good idea to come
     720         *       back and do more testing later.
     721         */
     722        if (ctx->bitres.bits > 0)
     723            desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits),
     724                                   0.85f, 1.15f);
     725    }
    683726    pctx->pe.previous = PSY_3GPP_BITS_TO_PE(desired_bits);
    684 
     727    ctx->bitres.alloc = desired_bits;
     728   
    685729    if (desired_pe < pe) {
    686730        /* 5.6.1.3.4 "First Estimation of the reduction value" */
    687731        for (w = 0; w < wi->num_windows*16; w += 16) {
    static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,  
    717761            }
    718762            desired_pe_no_ah = FFMAX(desired_pe - (pe - pe_no_ah), 0.0f);
    719763            if (active_lines > 0.0f)
    720                 reduction += calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);
     764                reduction = calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);
    721765
    722766            pe = 0.0f;
    723767            for (w = 0; w < wi->num_windows*16; w += 16) {
  • libavcodec/psymodel.c

    diff --git a/libavcodec/psymodel.c b/libavcodec/psymodel.c
    index bfc85b3..cc25fca 100644
    a b 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(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..5ebd44f 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 FFPsyContext {  
    88101    struct {
    89102        int size;                     ///< size of the bitresevoir in bits
    90103        int bits;                     ///< number of bits used in the bitresevoir
     104        int alloc;                    ///< number of bits allocated by the psy, or -1 if no allocation was done
    91105    } bitres;
    92106
    93107    void* model_priv_data;            ///< psychoacoustic model implementation private data