2 * AAC coefficients encoder
3 * Copyright (C) 2008-2009 Konstantin Shishkov
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * AAC coefficients encoder
27 /***********************************
29 * speedup quantizer selection
30 * add sane pulse detection
31 ***********************************/
33 #include "libavutil/libm.h" // brought forward to work around cygwin header breakage
37 #include "libavutil/mathematics.h"
44 #include "aacenctab.h"
45 #include "aacenc_utils.h"
46 #include "aacenc_quantization.h"
47 #include "aac_tablegen_decl.h"
49 #include "aacenc_is.h"
50 #include "aacenc_tns.h"
51 #include "aacenc_ltp.h"
52 #include "aacenc_pred.h"
54 #include "libavcodec/aaccoder_twoloop.h"
56 /* Parameter of f(x) = a*(lambda/100), defines the maximum fourier spread
57 * beyond which no PNS is used (since the SFBs contain tone rather than noise) */
58 #define NOISE_SPREAD_THRESHOLD 0.5073f
60 /* Parameter of f(x) = a*(100/lambda), defines how much PNS is allowed to
61 * replace low energy non zero bands */
62 #define NOISE_LAMBDA_REPLACE 1.948f
64 #include "libavcodec/aaccoder_trellis.h"
67 * structure used in optimal codebook search
69 typedef struct BandCodingPath {
70 int prev_idx; ///< pointer to the previous path point
71 float cost; ///< path cost
76 * Encode band info for single window group bands.
78 static void encode_window_bands_info(AACEncContext *s, SingleChannelElement *sce,
79 int win, int group_len, const float lambda)
81 BandCodingPath path[120][CB_TOT_ALL];
82 int w, swb, cb, start, size;
84 const int max_sfb = sce->ics.max_sfb;
85 const int run_bits = sce->ics.num_windows == 1 ? 5 : 3;
86 const int run_esc = (1 << run_bits) - 1;
88 int stackrun[120], stackcb[120], stack_len;
89 float next_minrd = INFINITY;
92 abs_pow34_v(s->scoefs, sce->coeffs, 1024);
94 for (cb = 0; cb < CB_TOT_ALL; cb++) {
95 path[0][cb].cost = 0.0f;
96 path[0][cb].prev_idx = -1;
99 for (swb = 0; swb < max_sfb; swb++) {
100 size = sce->ics.swb_sizes[swb];
101 if (sce->zeroes[win*16 + swb]) {
102 for (cb = 0; cb < CB_TOT_ALL; cb++) {
103 path[swb+1][cb].prev_idx = cb;
104 path[swb+1][cb].cost = path[swb][cb].cost;
105 path[swb+1][cb].run = path[swb][cb].run + 1;
108 float minrd = next_minrd;
109 int mincb = next_mincb;
110 next_minrd = INFINITY;
112 for (cb = 0; cb < CB_TOT_ALL; cb++) {
113 float cost_stay_here, cost_get_here;
115 if (cb >= 12 && sce->band_type[win*16+swb] < aac_cb_out_map[cb] ||
116 cb < aac_cb_in_map[sce->band_type[win*16+swb]] && sce->band_type[win*16+swb] > aac_cb_out_map[cb]) {
117 path[swb+1][cb].prev_idx = -1;
118 path[swb+1][cb].cost = INFINITY;
119 path[swb+1][cb].run = path[swb][cb].run + 1;
122 for (w = 0; w < group_len; w++) {
123 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(win+w)*16+swb];
124 rd += quantize_band_cost(s, &sce->coeffs[start + w*128],
125 &s->scoefs[start + w*128], size,
126 sce->sf_idx[(win+w)*16+swb], aac_cb_out_map[cb],
127 lambda / band->threshold, INFINITY, NULL, NULL, 0);
129 cost_stay_here = path[swb][cb].cost + rd;
130 cost_get_here = minrd + rd + run_bits + 4;
131 if ( run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run]
132 != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1])
133 cost_stay_here += run_bits;
134 if (cost_get_here < cost_stay_here) {
135 path[swb+1][cb].prev_idx = mincb;
136 path[swb+1][cb].cost = cost_get_here;
137 path[swb+1][cb].run = 1;
139 path[swb+1][cb].prev_idx = cb;
140 path[swb+1][cb].cost = cost_stay_here;
141 path[swb+1][cb].run = path[swb][cb].run + 1;
143 if (path[swb+1][cb].cost < next_minrd) {
144 next_minrd = path[swb+1][cb].cost;
149 start += sce->ics.swb_sizes[swb];
152 //convert resulting path from backward-linked list
155 for (cb = 1; cb < CB_TOT_ALL; cb++)
156 if (path[max_sfb][cb].cost < path[max_sfb][idx].cost)
160 av_assert1(idx >= 0);
162 stackrun[stack_len] = path[ppos][cb].run;
163 stackcb [stack_len] = cb;
164 idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx;
165 ppos -= path[ppos][cb].run;
168 //perform actual band info encoding
170 for (i = stack_len - 1; i >= 0; i--) {
171 cb = aac_cb_out_map[stackcb[i]];
172 put_bits(&s->pb, 4, cb);
174 memset(sce->zeroes + win*16 + start, !cb, count);
175 //XXX: memset when band_type is also uint8_t
176 for (j = 0; j < count; j++) {
177 sce->band_type[win*16 + start] = cb;
180 while (count >= run_esc) {
181 put_bits(&s->pb, run_bits, run_esc);
184 put_bits(&s->pb, run_bits, count);
189 typedef struct TrellisPath {
194 #define TRELLIS_STAGES 121
195 #define TRELLIS_STATES (SCALE_MAX_DIFF+1)
197 static void set_special_band_scalefactors(AACEncContext *s, SingleChannelElement *sce)
200 int minscaler_n = sce->sf_idx[0], minscaler_i = sce->sf_idx[0];
203 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
205 for (g = 0; g < sce->ics.num_swb; g++) {
206 if (sce->band_type[w*16+g] == INTENSITY_BT || sce->band_type[w*16+g] == INTENSITY_BT2) {
207 sce->sf_idx[w*16+g] = av_clip(roundf(log2f(sce->is_ener[w*16+g])*2), -155, 100);
208 minscaler_i = FFMIN(minscaler_i, sce->sf_idx[w*16+g]);
210 } else if (sce->band_type[w*16+g] == NOISE_BT) {
211 sce->sf_idx[w*16+g] = av_clip(3+ceilf(log2f(sce->pns_ener[w*16+g])*2), -100, 155);
212 minscaler_n = FFMIN(minscaler_n, sce->sf_idx[w*16+g]);
215 start += sce->ics.swb_sizes[g];
222 /* Clip the scalefactor indices */
223 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
224 for (g = 0; g < sce->ics.num_swb; g++) {
225 if (sce->band_type[w*16+g] == INTENSITY_BT || sce->band_type[w*16+g] == INTENSITY_BT2) {
226 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler_i, minscaler_i + SCALE_MAX_DIFF);
227 } else if (sce->band_type[w*16+g] == NOISE_BT) {
228 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler_n, minscaler_n + SCALE_MAX_DIFF);
234 static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,
235 SingleChannelElement *sce,
238 int q, w, w2, g, start = 0;
241 TrellisPath paths[TRELLIS_STAGES][TRELLIS_STATES];
242 int bandaddr[TRELLIS_STAGES];
245 float q0f = FLT_MAX, q1f = 0.0f, qnrgf = 0.0f;
246 int q0, q1, qcnt = 0;
248 for (i = 0; i < 1024; i++) {
249 float t = fabsf(sce->coeffs[i]);
259 memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
260 memset(sce->zeroes, 1, sizeof(sce->zeroes));
264 //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
265 q0 = coef2minsf(q0f);
266 //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
267 q1 = coef2maxsf(q1f);
271 //minimum scalefactor index is when maximum nonzero coefficient after quantizing is not clipped
272 int qnrg = av_clip_uint8(log2f(sqrtf(qnrgf/qcnt))*4 - 31 + SCALE_ONE_POS - SCALE_DIV_512);
278 } else if (q1 > q1high) {
284 for (i = 0; i < TRELLIS_STATES; i++) {
285 paths[0][i].cost = 0.0f;
286 paths[0][i].prev = -1;
288 for (j = 1; j < TRELLIS_STAGES; j++) {
289 for (i = 0; i < TRELLIS_STATES; i++) {
290 paths[j][i].cost = INFINITY;
291 paths[j][i].prev = -2;
295 abs_pow34_v(s->scoefs, sce->coeffs, 1024);
296 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
298 for (g = 0; g < sce->ics.num_swb; g++) {
299 const float *coefs = &sce->coeffs[start];
303 bandaddr[idx] = w * 16 + g;
306 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
307 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
308 if (band->energy <= band->threshold || band->threshold == 0.0f) {
309 sce->zeroes[(w+w2)*16+g] = 1;
312 sce->zeroes[(w+w2)*16+g] = 0;
314 for (i = 0; i < sce->ics.swb_sizes[g]; i++) {
315 float t = fabsf(coefs[w2*128+i]);
317 qmin = FFMIN(qmin, t);
318 qmax = FFMAX(qmax, t);
322 int minscale, maxscale;
323 float minrd = INFINITY;
325 //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
326 minscale = coef2minsf(qmin);
327 //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
328 maxscale = coef2maxsf(qmax);
329 minscale = av_clip(minscale - q0, 0, TRELLIS_STATES - 1);
330 maxscale = av_clip(maxscale - q0, 0, TRELLIS_STATES);
331 maxval = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], s->scoefs+start);
332 for (q = minscale; q < maxscale; q++) {
334 int cb = find_min_book(maxval, sce->sf_idx[w*16+g]);
335 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
336 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
337 dist += quantize_band_cost(s, coefs + w2*128, s->scoefs + start + w2*128, sce->ics.swb_sizes[g],
338 q + q0, cb, lambda / band->threshold, INFINITY, NULL, NULL, 0);
340 minrd = FFMIN(minrd, dist);
342 for (i = 0; i < q1 - q0; i++) {
344 cost = paths[idx - 1][i].cost + dist
345 + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
346 if (cost < paths[idx][q].cost) {
347 paths[idx][q].cost = cost;
348 paths[idx][q].prev = i;
353 for (q = 0; q < q1 - q0; q++) {
354 paths[idx][q].cost = paths[idx - 1][q].cost + 1;
355 paths[idx][q].prev = q;
358 sce->zeroes[w*16+g] = !nz;
359 start += sce->ics.swb_sizes[g];
364 mincost = paths[idx][0].cost;
366 for (i = 1; i < TRELLIS_STATES; i++) {
367 if (paths[idx][i].cost < mincost) {
368 mincost = paths[idx][i].cost;
373 sce->sf_idx[bandaddr[idx]] = minq + q0;
374 minq = paths[idx][minq].prev;
377 //set the same quantizers inside window groups
378 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
379 for (g = 0; g < sce->ics.num_swb; g++)
380 for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
381 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
385 static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
386 SingleChannelElement *sce,
389 int start = 0, i, w, w2, g;
390 float uplim[128], maxq[128];
392 float distfact = ((sce->ics.num_windows > 1) ? 85.80 : 147.84) / lambda;
393 int last = 0, lastband = 0, curband = 0;
394 float avg_energy = 0.0;
395 if (sce->ics.num_windows == 1) {
397 for (i = 0; i < 1024; i++) {
398 if (i - start >= sce->ics.swb_sizes[curband]) {
399 start += sce->ics.swb_sizes[curband];
402 if (sce->coeffs[i]) {
403 avg_energy += sce->coeffs[i] * sce->coeffs[i];
409 for (w = 0; w < 8; w++) {
410 const float *coeffs = &sce->coeffs[w*128];
412 for (i = 0; i < 128; i++) {
413 if (i - start >= sce->ics.swb_sizes[curband]) {
414 start += sce->ics.swb_sizes[curband];
418 avg_energy += coeffs[i] * coeffs[i];
419 last = FFMAX(last, i);
420 lastband = FFMAX(lastband, curband);
427 if (avg_energy == 0.0f) {
428 for (i = 0; i < FF_ARRAY_ELEMS(sce->sf_idx); i++)
429 sce->sf_idx[i] = SCALE_ONE_POS;
432 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
434 for (g = 0; g < sce->ics.num_swb; g++) {
435 float *coefs = &sce->coeffs[start];
436 const int size = sce->ics.swb_sizes[g];
437 int start2 = start, end2 = start + size, peakpos = start;
438 float maxval = -1, thr = 0.0f, t;
443 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
444 memset(coefs + w2*128, 0, sizeof(coefs[0])*size);
447 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
448 for (i = 0; i < size; i++) {
449 float t = coefs[w2*128+i]*coefs[w2*128+i];
450 maxq[w*16+g] = FFMAX(maxq[w*16+g], fabsf(coefs[w2*128 + i]));
452 if (sce->ics.num_windows == 1 && maxval < t) {
458 if (sce->ics.num_windows == 1) {
459 start2 = FFMAX(peakpos - 2, start2);
460 end2 = FFMIN(peakpos + 3, end2);
466 thr = pow(thr / (avg_energy * (end2 - start2)), 0.3 + 0.1*(lastband - g) / lastband);
467 t = 1.0 - (1.0 * start2 / last);
468 uplim[w*16+g] = distfact / (1.4 * thr + t*t*t + 0.075);
471 memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
472 abs_pow34_v(s->scoefs, sce->coeffs, 1024);
473 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
475 for (g = 0; g < sce->ics.num_swb; g++) {
476 const float *coefs = &sce->coeffs[start];
477 const float *scaled = &s->scoefs[start];
478 const int size = sce->ics.swb_sizes[g];
479 int scf, prev_scf, step;
480 int min_scf = -1, max_scf = 256;
482 if (maxq[w*16+g] < 21.544) {
483 sce->zeroes[w*16+g] = 1;
487 sce->zeroes[w*16+g] = 0;
488 scf = prev_scf = av_clip(SCALE_ONE_POS - SCALE_DIV_512 - log2f(1/maxq[w*16+g])*16/3, 60, 218);
493 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
495 dist += quantize_band_cost(s, coefs + w2*128,
497 sce->ics.swb_sizes[g],
506 dist *= 1.0f / 512.0f / lambda;
507 quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512], ROUND_STANDARD);
508 if (quant_max >= 8191) { // too much, return to the previous quantizer
509 sce->sf_idx[w*16+g] = prev_scf;
513 curdiff = fabsf(dist - uplim[w*16+g]);
517 step = log2f(curdiff);
518 if (dist > uplim[w*16+g])
521 scf = av_clip_uint8(scf);
522 step = scf - prev_scf;
523 if (FFABS(step) <= 1 || (step > 0 && scf >= max_scf) || (step < 0 && scf <= min_scf)) {
524 sce->sf_idx[w*16+g] = av_clip(scf, min_scf, max_scf);
535 minq = sce->sf_idx[0] ? sce->sf_idx[0] : INT_MAX;
536 for (i = 1; i < 128; i++) {
538 sce->sf_idx[i] = sce->sf_idx[i-1];
540 minq = FFMIN(minq, sce->sf_idx[i]);
544 minq = FFMIN(minq, SCALE_MAX_POS);
545 maxsf = FFMIN(minq + SCALE_MAX_DIFF, SCALE_MAX_POS);
546 for (i = 126; i >= 0; i--) {
548 sce->sf_idx[i] = sce->sf_idx[i+1];
549 sce->sf_idx[i] = av_clip(sce->sf_idx[i], minq, maxsf);
553 static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,
554 SingleChannelElement *sce,
560 memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
561 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
562 for (g = 0; g < sce->ics.num_swb; g++) {
563 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
564 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
565 if (band->energy <= band->threshold) {
566 sce->sf_idx[(w+w2)*16+g] = 218;
567 sce->zeroes[(w+w2)*16+g] = 1;
569 sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2f(band->threshold), 80, 218);
570 sce->zeroes[(w+w2)*16+g] = 0;
572 minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
576 for (i = 0; i < 128; i++) {
577 sce->sf_idx[i] = 140;
578 //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);
580 //set the same quantizers inside window groups
581 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
582 for (g = 0; g < sce->ics.num_swb; g++)
583 for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
584 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
587 static void search_for_pns(AACEncContext *s, AVCodecContext *avctx, SingleChannelElement *sce)
591 int wlen = 1024 / sce->ics.num_windows;
592 int bandwidth, cutoff;
593 float *PNS = &s->scoefs[0*128], *PNS34 = &s->scoefs[1*128];
594 float *NOR34 = &s->scoefs[3*128];
595 const float lambda = s->lambda;
596 const float freq_mult = avctx->sample_rate*0.5f/wlen;
597 const float thr_mult = NOISE_LAMBDA_REPLACE*(100.0f/lambda);
598 const float spread_threshold = FFMIN(0.75f, NOISE_SPREAD_THRESHOLD*FFMAX(0.5f, lambda/100.f));
599 const float dist_bias = av_clipf(4.f * 120 / lambda, 0.25f, 4.0f);
600 const float pns_transient_energy_r = FFMIN(0.7f, lambda / 140.f);
602 int refbits = avctx->bit_rate * 1024.0 / avctx->sample_rate
603 / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels)
606 /** Keep this in sync with twoloop's cutoff selection */
607 float rate_bandwidth_multiplier = 1.5f;
608 int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE)
609 ? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024)
610 : (avctx->bit_rate / avctx->channels);
612 frame_bit_rate *= 1.15f;
614 if (avctx->cutoff > 0) {
615 bandwidth = avctx->cutoff;
617 bandwidth = FFMAX(3000, AAC_CUTOFF_FROM_BITRATE(frame_bit_rate, 1, avctx->sample_rate));
620 cutoff = bandwidth * 2 * wlen / avctx->sample_rate;
622 memcpy(sce->band_alt, sce->band_type, sizeof(sce->band_type));
623 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
625 for (g = 0; g < sce->ics.num_swb; g++) {
627 float dist1 = 0.0f, dist2 = 0.0f, noise_amp;
628 float pns_energy = 0.0f, pns_tgt_energy, energy_ratio, dist_thresh;
629 float sfb_energy = 0.0f, threshold = 0.0f, spread = 2.0f;
630 float min_energy = -1.0f, max_energy = 0.0f;
631 const int start = wstart+sce->ics.swb_offset[g];
632 const float freq = (start-wstart)*freq_mult;
633 const float freq_boost = FFMAX(0.88f*freq/NOISE_LOW_LIMIT, 1.0f);
634 if (freq < NOISE_LOW_LIMIT || (start-wstart) >= cutoff)
636 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
637 band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
638 sfb_energy += band->energy;
639 spread = FFMIN(spread, band->spread);
640 threshold += band->threshold;
642 min_energy = max_energy = band->energy;
644 min_energy = FFMIN(min_energy, band->energy);
645 max_energy = FFMAX(max_energy, band->energy);
649 /* Ramps down at ~8000Hz and loosens the dist threshold */
650 dist_thresh = av_clipf(2.5f*NOISE_LOW_LIMIT/freq, 0.5f, 2.5f) * dist_bias;
652 /* PNS is acceptable when all of these are true:
653 * 1. high spread energy (noise-like band)
654 * 2. near-threshold energy (high PE means the random nature of PNS content will be noticed)
655 * 3. on short window groups, all windows have similar energy (variations in energy would be destroyed by PNS)
657 * At this stage, point 2 is relaxed for zeroed bands near the noise threshold (hole avoidance is more important)
659 if (((sce->zeroes[w*16+g] || !sce->band_alt[w*16+g]) && sfb_energy < threshold*sqrtf(1.5f/freq_boost)) || spread < spread_threshold ||
660 (!sce->zeroes[w*16+g] && sce->band_alt[w*16+g] && sfb_energy > threshold*thr_mult*freq_boost) ||
661 min_energy < pns_transient_energy_r * max_energy ) {
662 sce->pns_ener[w*16+g] = sfb_energy;
666 pns_tgt_energy = sfb_energy*FFMIN(1.0f, spread*spread);
667 noise_sfi = av_clip(roundf(log2f(pns_tgt_energy)*2), -100, 155); /* Quantize */
668 noise_amp = -ff_aac_pow2sf_tab[noise_sfi + POW_SF2_ZERO]; /* Dequantize */
669 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
670 float band_energy, scale, pns_senergy;
671 const int start_c = (w+w2)*128+sce->ics.swb_offset[g];
672 band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
673 for (i = 0; i < sce->ics.swb_sizes[g]; i++)
674 PNS[i] = s->random_state = lcg_random(s->random_state);
675 band_energy = s->fdsp->scalarproduct_float(PNS, PNS, sce->ics.swb_sizes[g]);
676 scale = noise_amp/sqrtf(band_energy);
677 s->fdsp->vector_fmul_scalar(PNS, PNS, scale, sce->ics.swb_sizes[g]);
678 pns_senergy = s->fdsp->scalarproduct_float(PNS, PNS, sce->ics.swb_sizes[g]);
679 pns_energy += pns_senergy;
680 abs_pow34_v(NOR34, &sce->coeffs[start_c], sce->ics.swb_sizes[g]);
681 abs_pow34_v(PNS34, PNS, sce->ics.swb_sizes[g]);
682 dist1 += quantize_band_cost(s, &sce->coeffs[start_c],
684 sce->ics.swb_sizes[g],
685 sce->sf_idx[(w+w2)*16+g],
686 sce->band_alt[(w+w2)*16+g],
687 lambda/band->threshold, INFINITY, NULL, NULL, 0);
688 /* Estimate rd on average as 5 bits for SF, 4 for the CB, plus spread energy * lambda/thr */
689 dist2 += band->energy/(band->spread*band->spread)*lambda*dist_thresh/band->threshold;
691 if (g && sce->sf_idx[(w+w2)*16+g-1] == NOISE_BT) {
696 energy_ratio = pns_tgt_energy/pns_energy; /* Compensates for quantization error */
697 sce->pns_ener[w*16+g] = energy_ratio*pns_tgt_energy;
698 if (sce->zeroes[w*16+g] || !sce->band_alt[w*16+g] || (energy_ratio > 0.85f && energy_ratio < 1.25f && dist2 < dist1)) {
699 sce->band_type[w*16+g] = NOISE_BT;
700 sce->zeroes[w*16+g] = 0;
706 static void mark_pns(AACEncContext *s, AVCodecContext *avctx, SingleChannelElement *sce)
710 int wlen = 1024 / sce->ics.num_windows;
711 int bandwidth, cutoff;
712 const float lambda = s->lambda;
713 const float freq_mult = avctx->sample_rate*0.5f/wlen;
714 const float spread_threshold = FFMIN(0.75f, NOISE_SPREAD_THRESHOLD*FFMAX(0.5f, lambda/100.f));
715 const float pns_transient_energy_r = FFMIN(0.7f, lambda / 140.f);
717 int refbits = avctx->bit_rate * 1024.0 / avctx->sample_rate
718 / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels)
721 /** Keep this in sync with twoloop's cutoff selection */
722 float rate_bandwidth_multiplier = 1.5f;
723 int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE)
724 ? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024)
725 : (avctx->bit_rate / avctx->channels);
727 frame_bit_rate *= 1.15f;
729 if (avctx->cutoff > 0) {
730 bandwidth = avctx->cutoff;
732 bandwidth = FFMAX(3000, AAC_CUTOFF_FROM_BITRATE(frame_bit_rate, 1, avctx->sample_rate));
735 cutoff = bandwidth * 2 * wlen / avctx->sample_rate;
737 memcpy(sce->band_alt, sce->band_type, sizeof(sce->band_type));
738 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
739 for (g = 0; g < sce->ics.num_swb; g++) {
740 float sfb_energy = 0.0f, threshold = 0.0f, spread = 2.0f;
741 float min_energy = -1.0f, max_energy = 0.0f;
742 const int start = sce->ics.swb_offset[g];
743 const float freq = start*freq_mult;
744 const float freq_boost = FFMAX(0.88f*freq/NOISE_LOW_LIMIT, 1.0f);
745 if (freq < NOISE_LOW_LIMIT || start >= cutoff) {
746 sce->can_pns[w*16+g] = 0;
749 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
750 band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
751 sfb_energy += band->energy;
752 spread = FFMIN(spread, band->spread);
753 threshold += band->threshold;
755 min_energy = max_energy = band->energy;
757 min_energy = FFMIN(min_energy, band->energy);
758 max_energy = FFMAX(max_energy, band->energy);
762 /* PNS is acceptable when all of these are true:
763 * 1. high spread energy (noise-like band)
764 * 2. near-threshold energy (high PE means the random nature of PNS content will be noticed)
765 * 3. on short window groups, all windows have similar energy (variations in energy would be destroyed by PNS)
767 sce->pns_ener[w*16+g] = sfb_energy;
768 if (sfb_energy < threshold*sqrtf(1.5f/freq_boost) || spread < spread_threshold || min_energy < pns_transient_energy_r * max_energy) {
769 sce->can_pns[w*16+g] = 0;
771 sce->can_pns[w*16+g] = 1;
777 static void search_for_ms(AACEncContext *s, ChannelElement *cpe)
779 int start = 0, i, w, w2, g, sid_sf_boost;
780 float M[128], S[128];
781 float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
782 const float lambda = s->lambda;
783 const float mslambda = FFMIN(1.0f, lambda / 120.f);
784 SingleChannelElement *sce0 = &cpe->ch[0];
785 SingleChannelElement *sce1 = &cpe->ch[1];
786 if (!cpe->common_window)
788 for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
789 int min_sf_idx_mid = SCALE_MAX_POS;
790 int min_sf_idx_side = SCALE_MAX_POS;
791 for (g = 0; g < sce0->ics.num_swb; g++) {
792 if (!sce0->zeroes[w*16+g] && sce0->band_type[w*16+g] < RESERVED_BT)
793 min_sf_idx_mid = FFMIN(min_sf_idx_mid, sce0->sf_idx[w*16+g]);
794 if (!sce1->zeroes[w*16+g] && sce1->band_type[w*16+g] < RESERVED_BT)
795 min_sf_idx_side = FFMIN(min_sf_idx_side, sce1->sf_idx[w*16+g]);
799 for (g = 0; g < sce0->ics.num_swb; g++) {
800 float bmax = bval2bmax(g * 17.0f / sce0->ics.num_swb) / 0.0045f;
801 cpe->ms_mask[w*16+g] = 0;
802 if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {
803 float Mmax = 0.0f, Smax = 0.0f;
805 /* Must compute mid/side SF and book for the whole window group */
806 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
807 for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
808 M[i] = (sce0->coeffs[start+(w+w2)*128+i]
809 + sce1->coeffs[start+(w+w2)*128+i]) * 0.5;
811 - sce1->coeffs[start+(w+w2)*128+i];
813 abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);
814 abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);
815 for (i = 0; i < sce0->ics.swb_sizes[g]; i++ ) {
816 Mmax = FFMAX(Mmax, M34[i]);
817 Smax = FFMAX(Smax, S34[i]);
821 for (sid_sf_boost = 0; sid_sf_boost < 4; sid_sf_boost++) {
822 float dist1 = 0.0f, dist2 = 0.0f;
828 minidx = FFMIN(sce0->sf_idx[w*16+g], sce1->sf_idx[w*16+g]);
829 mididx = av_clip(minidx, min_sf_idx_mid, min_sf_idx_mid + SCALE_MAX_DIFF);
830 sididx = av_clip(minidx - sid_sf_boost * 3, min_sf_idx_side, min_sf_idx_side + SCALE_MAX_DIFF);
831 midcb = find_min_book(Mmax, mididx);
832 sidcb = find_min_book(Smax, sididx);
834 if ((mididx > minidx) || (sididx > minidx)) {
835 /* scalefactor range violation, bad stuff, will decrease quality unacceptably */
839 /* No CB can be zero */
840 midcb = FFMAX(1,midcb);
841 sidcb = FFMAX(1,sidcb);
843 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
844 FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
845 FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
846 float minthr = FFMIN(band0->threshold, band1->threshold);
848 for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
849 M[i] = (sce0->coeffs[start+(w+w2)*128+i]
850 + sce1->coeffs[start+(w+w2)*128+i]) * 0.5;
852 - sce1->coeffs[start+(w+w2)*128+i];
855 abs_pow34_v(L34, sce0->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
856 abs_pow34_v(R34, sce1->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
857 abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);
858 abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);
859 dist1 += quantize_band_cost(s, &sce0->coeffs[start + (w+w2)*128],
861 sce0->ics.swb_sizes[g],
862 sce0->sf_idx[(w+w2)*16+g],
863 sce0->band_type[(w+w2)*16+g],
864 lambda / band0->threshold, INFINITY, &b1, NULL, 0);
865 dist1 += quantize_band_cost(s, &sce1->coeffs[start + (w+w2)*128],
867 sce1->ics.swb_sizes[g],
868 sce1->sf_idx[(w+w2)*16+g],
869 sce1->band_type[(w+w2)*16+g],
870 lambda / band1->threshold, INFINITY, &b2, NULL, 0);
871 dist2 += quantize_band_cost(s, M,
873 sce0->ics.swb_sizes[g],
874 sce0->sf_idx[(w+w2)*16+g],
875 sce0->band_type[(w+w2)*16+g],
876 lambda / minthr, INFINITY, &b3, NULL, 0);
877 dist2 += quantize_band_cost(s, S,
879 sce1->ics.swb_sizes[g],
880 sce1->sf_idx[(w+w2)*16+g],
881 sce1->band_type[(w+w2)*16+g],
882 mslambda / (minthr * bmax), INFINITY, &b4, NULL, 0);
888 cpe->ms_mask[w*16+g] = dist2 <= dist1 && B1 < B0;
889 if (cpe->ms_mask[w*16+g]) {
890 /* Setting the M/S mask is useful with I/S, but only the flag */
891 if (!cpe->is_mask[w*16+g]) {
892 sce0->sf_idx[w*16+g] = mididx;
893 sce1->sf_idx[w*16+g] = sididx;
894 sce0->band_type[w*16+g] = midcb;
895 sce1->band_type[w*16+g] = sidcb;
898 } else if (B1 > B0) {
899 /* More boost won't fix this */
904 start += sce0->ics.swb_sizes[g];
909 AACCoefficientsEncoder ff_aac_coders[AAC_CODER_NB] = {
911 search_for_quantizers_faac,
912 encode_window_bands_info,
913 quantize_and_encode_band,
914 ff_aac_encode_tns_info,
915 ff_aac_encode_ltp_info,
916 ff_aac_encode_main_pred,
917 ff_aac_adjust_common_pred,
918 ff_aac_adjust_common_ltp,
919 ff_aac_apply_main_pred,
922 ff_aac_ltp_insert_new_frame,
923 set_special_band_scalefactors,
926 ff_aac_search_for_tns,
927 ff_aac_search_for_ltp,
929 ff_aac_search_for_is,
930 ff_aac_search_for_pred,
933 search_for_quantizers_anmr,
934 encode_window_bands_info,
935 quantize_and_encode_band,
936 ff_aac_encode_tns_info,
937 ff_aac_encode_ltp_info,
938 ff_aac_encode_main_pred,
939 ff_aac_adjust_common_pred,
940 ff_aac_adjust_common_ltp,
941 ff_aac_apply_main_pred,
944 ff_aac_ltp_insert_new_frame,
945 set_special_band_scalefactors,
948 ff_aac_search_for_tns,
949 ff_aac_search_for_ltp,
951 ff_aac_search_for_is,
952 ff_aac_search_for_pred,
954 [AAC_CODER_TWOLOOP] = {
955 search_for_quantizers_twoloop,
956 codebook_trellis_rate,
957 quantize_and_encode_band,
958 ff_aac_encode_tns_info,
959 ff_aac_encode_ltp_info,
960 ff_aac_encode_main_pred,
961 ff_aac_adjust_common_pred,
962 ff_aac_adjust_common_ltp,
963 ff_aac_apply_main_pred,
966 ff_aac_ltp_insert_new_frame,
967 set_special_band_scalefactors,
970 ff_aac_search_for_tns,
971 ff_aac_search_for_ltp,
973 ff_aac_search_for_is,
974 ff_aac_search_for_pred,
977 search_for_quantizers_fast,
978 encode_window_bands_info,
979 quantize_and_encode_band,
980 ff_aac_encode_tns_info,
981 ff_aac_encode_ltp_info,
982 ff_aac_encode_main_pred,
983 ff_aac_adjust_common_pred,
984 ff_aac_adjust_common_ltp,
985 ff_aac_apply_main_pred,
988 ff_aac_ltp_insert_new_frame,
989 set_special_band_scalefactors,
992 ff_aac_search_for_tns,
993 ff_aac_search_for_ltp,
995 ff_aac_search_for_is,
996 ff_aac_search_for_pred,