AAC Encoder: clipping avoidance
[ffmpeg.git] / libavcodec / aaccoder.c
1 /*
2  * AAC coefficients encoder
3  * Copyright (C) 2008-2009 Konstantin Shishkov
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 /**
23  * @file
24  * AAC coefficients encoder
25  */
26
27 /***********************************
28  *              TODOs:
29  * speedup quantizer selection
30  * add sane pulse detection
31  ***********************************/
32
33 #include "libavutil/libm.h" // brought forward to work around cygwin header breakage
34
35 #include <float.h>
36 #include "libavutil/mathematics.h"
37 #include "avcodec.h"
38 #include "put_bits.h"
39 #include "aac.h"
40 #include "aacenc.h"
41 #include "aactab.h"
42 #include "aac_tablegen_decl.h"
43
44 /** Frequency in Hz for lower limit of noise substitution **/
45 #define NOISE_LOW_LIMIT 4500
46
47 /* Energy spread threshold value below which no PNS is used, this corresponds to
48  * typically around 17Khz, after which PNS usage decays ending at 19Khz */
49 #define NOISE_SPREAD_THRESHOLD 0.5f
50
51 /* This constant gets divided by lambda to return ~1.65 which when multiplied
52  * by the band->threshold and compared to band->energy is the boundary between
53  * excessive PNS and little PNS usage. */
54 #define NOISE_LAMBDA_NUMERATOR 252.1f
55
56 /** Frequency in Hz for lower limit of intensity stereo   **/
57 #define INT_STEREO_LOW_LIMIT 6100
58
59 /** Total number of usable codebooks **/
60 #define CB_TOT 12
61
62 /** Total number of codebooks, including special ones **/
63 #define CB_TOT_ALL 15
64
65 /** bits needed to code codebook run value for long windows */
66 static const uint8_t run_value_bits_long[64] = {
67      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
68      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5, 10,
69     10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
70     10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 15
71 };
72
73 /** bits needed to code codebook run value for short windows */
74 static const uint8_t run_value_bits_short[16] = {
75     3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 6, 6, 9
76 };
77
78 static const uint8_t * const run_value_bits[2] = {
79     run_value_bits_long, run_value_bits_short
80 };
81
82 #define ROUND_STANDARD 0.4054f
83 #define ROUND_TO_ZERO 0.1054f
84
85 /** Map to convert values from BandCodingPath index to a codebook index **/
86 static const uint8_t aac_cb_out_map[CB_TOT_ALL]  = {0,1,2,3,4,5,6,7,8,9,10,11,13,14,15};
87 /** Inverse map to convert from codebooks to BandCodingPath indices **/
88 static const uint8_t aac_cb_in_map[CB_TOT_ALL+1] = {0,1,2,3,4,5,6,7,8,9,10,11,0,12,13,14};
89
90 /**
91  * Quantize one coefficient.
92  * @return absolute value of the quantized coefficient
93  * @see 3GPP TS26.403 5.6.2 "Scalefactor determination"
94  */
95 static av_always_inline int quant(float coef, const float Q, const float rounding)
96 {
97     float a = coef * Q;
98     return sqrtf(a * sqrtf(a)) + rounding;
99 }
100
101 static void quantize_bands(int *out, const float *in, const float *scaled,
102                            int size, float Q34, int is_signed, int maxval, const float rounding)
103 {
104     int i;
105     double qc;
106     for (i = 0; i < size; i++) {
107         qc = scaled[i] * Q34;
108         out[i] = (int)FFMIN(qc + rounding, (double)maxval);
109         if (is_signed && in[i] < 0.0f) {
110             out[i] = -out[i];
111         }
112     }
113 }
114
115 static void abs_pow34_v(float *out, const float *in, const int size)
116 {
117 #ifndef USE_REALLY_FULL_SEARCH
118     int i;
119     for (i = 0; i < size; i++) {
120         float a = fabsf(in[i]);
121         out[i] = sqrtf(a * sqrtf(a));
122     }
123 #endif /* USE_REALLY_FULL_SEARCH */
124 }
125
126 static const uint8_t aac_cb_range [12] = {0, 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17};
127 static const uint8_t aac_cb_maxval[12] = {0, 1, 1, 2, 2, 4, 4, 7, 7, 12, 12, 16};
128
129 /**
130  * Calculate rate distortion cost for quantizing with given codebook
131  *
132  * @return quantization distortion
133  */
134 static av_always_inline float quantize_and_encode_band_cost_template(
135                                 struct AACEncContext *s,
136                                 PutBitContext *pb, const float *in,
137                                 const float *scaled, int size, int scale_idx,
138                                 int cb, const float lambda, const float uplim,
139                                 int *bits, int BT_ZERO, int BT_UNSIGNED,
140                                 int BT_PAIR, int BT_ESC, int BT_NOISE, int BT_STEREO,
141                                 const float ROUNDING)
142 {
143     const int q_idx = POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512;
144     const float Q   = ff_aac_pow2sf_tab [q_idx];
145     const float Q34 = ff_aac_pow34sf_tab[q_idx];
146     const float IQ  = ff_aac_pow2sf_tab [POW_SF2_ZERO + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];
147     const float CLIPPED_ESCAPE = 165140.0f*IQ;
148     int i, j;
149     float cost = 0;
150     const int dim = BT_PAIR ? 2 : 4;
151     int resbits = 0;
152     int off;
153
154     if (BT_ZERO || BT_NOISE || BT_STEREO) {
155         for (i = 0; i < size; i++)
156             cost += in[i]*in[i];
157         if (bits)
158             *bits = 0;
159         return cost * lambda;
160     }
161     if (!scaled) {
162         abs_pow34_v(s->scoefs, in, size);
163         scaled = s->scoefs;
164     }
165     quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, aac_cb_maxval[cb], ROUNDING);
166     if (BT_UNSIGNED) {
167         off = 0;
168     } else {
169         off = aac_cb_maxval[cb];
170     }
171     for (i = 0; i < size; i += dim) {
172         const float *vec;
173         int *quants = s->qcoefs + i;
174         int curidx = 0;
175         int curbits;
176         float rd = 0.0f;
177         for (j = 0; j < dim; j++) {
178             curidx *= aac_cb_range[cb];
179             curidx += quants[j] + off;
180         }
181         curbits =  ff_aac_spectral_bits[cb-1][curidx];
182         vec     = &ff_aac_codebook_vectors[cb-1][curidx*dim];
183         if (BT_UNSIGNED) {
184             for (j = 0; j < dim; j++) {
185                 float t = fabsf(in[i+j]);
186                 float di;
187                 if (BT_ESC && vec[j] == 64.0f) { //FIXME: slow
188                     if (t >= CLIPPED_ESCAPE) {
189                         di = t - CLIPPED_ESCAPE;
190                         curbits += 21;
191                     } else {
192                         int c = av_clip_uintp2(quant(t, Q, ROUNDING), 13);
193                         di = t - c*cbrtf(c)*IQ;
194                         curbits += av_log2(c)*2 - 4 + 1;
195                     }
196                 } else {
197                     di = t - vec[j]*IQ;
198                 }
199                 if (vec[j] != 0.0f)
200                     curbits++;
201                 rd += di*di;
202             }
203         } else {
204             for (j = 0; j < dim; j++) {
205                 float di = in[i+j] - vec[j]*IQ;
206                 rd += di*di;
207             }
208         }
209         cost    += rd * lambda + curbits;
210         resbits += curbits;
211         if (cost >= uplim)
212             return uplim;
213         if (pb) {
214             put_bits(pb, ff_aac_spectral_bits[cb-1][curidx], ff_aac_spectral_codes[cb-1][curidx]);
215             if (BT_UNSIGNED)
216                 for (j = 0; j < dim; j++)
217                     if (ff_aac_codebook_vectors[cb-1][curidx*dim+j] != 0.0f)
218                         put_bits(pb, 1, in[i+j] < 0.0f);
219             if (BT_ESC) {
220                 for (j = 0; j < 2; j++) {
221                     if (ff_aac_codebook_vectors[cb-1][curidx*2+j] == 64.0f) {
222                         int coef = av_clip_uintp2(quant(fabsf(in[i+j]), Q, ROUNDING), 13);
223                         int len = av_log2(coef);
224
225                         put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);
226                         put_sbits(pb, len, coef);
227                     }
228                 }
229             }
230         }
231     }
232
233     if (bits)
234         *bits = resbits;
235     return cost;
236 }
237
238 static float quantize_and_encode_band_cost_NONE(struct AACEncContext *s, PutBitContext *pb,
239                                                 const float *in, const float *scaled,
240                                                 int size, int scale_idx, int cb,
241                                                 const float lambda, const float uplim,
242                                                 int *bits) {
243     av_assert0(0);
244     return 0.0f;
245 }
246
247 #define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, BT_NOISE, BT_STEREO, ROUNDING) \
248 static float quantize_and_encode_band_cost_ ## NAME(                                         \
249                                 struct AACEncContext *s,                                     \
250                                 PutBitContext *pb, const float *in,                          \
251                                 const float *scaled, int size, int scale_idx,                \
252                                 int cb, const float lambda, const float uplim,               \
253                                 int *bits) {                                                 \
254     return quantize_and_encode_band_cost_template(                                           \
255                                 s, pb, in, scaled, size, scale_idx,                          \
256                                 BT_ESC ? ESC_BT : cb, lambda, uplim, bits,                   \
257                                 BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, BT_NOISE, BT_STEREO,  \
258                                 ROUNDING);                                                   \
259 }
260
261 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO,  1, 0, 0, 0, 0, 0, ROUND_STANDARD)
262 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD, 0, 0, 0, 0, 0, 0, ROUND_STANDARD)
263 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD, 0, 1, 0, 0, 0, 0, ROUND_STANDARD)
264 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR, 0, 0, 1, 0, 0, 0, ROUND_STANDARD)
265 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR, 0, 1, 1, 0, 0, 0, ROUND_STANDARD)
266 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC,   0, 1, 1, 1, 0, 0, ROUND_STANDARD)
267 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC_RTZ, 0, 1, 1, 1, 0, 0, ROUND_TO_ZERO)
268 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NOISE, 0, 0, 0, 0, 1, 0, ROUND_STANDARD)
269 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(STEREO,0, 0, 0, 0, 0, 1, ROUND_STANDARD)
270
271 static float (*const quantize_and_encode_band_cost_arr[])(
272                                 struct AACEncContext *s,
273                                 PutBitContext *pb, const float *in,
274                                 const float *scaled, int size, int scale_idx,
275                                 int cb, const float lambda, const float uplim,
276                                 int *bits) = {
277     quantize_and_encode_band_cost_ZERO,
278     quantize_and_encode_band_cost_SQUAD,
279     quantize_and_encode_band_cost_SQUAD,
280     quantize_and_encode_band_cost_UQUAD,
281     quantize_and_encode_band_cost_UQUAD,
282     quantize_and_encode_band_cost_SPAIR,
283     quantize_and_encode_band_cost_SPAIR,
284     quantize_and_encode_band_cost_UPAIR,
285     quantize_and_encode_band_cost_UPAIR,
286     quantize_and_encode_band_cost_UPAIR,
287     quantize_and_encode_band_cost_UPAIR,
288     quantize_and_encode_band_cost_ESC,
289     quantize_and_encode_band_cost_NONE,     /* CB 12 doesn't exist */
290     quantize_and_encode_band_cost_NOISE,
291     quantize_and_encode_band_cost_STEREO,
292     quantize_and_encode_band_cost_STEREO,
293 };
294
295 static float (*const quantize_and_encode_band_cost_rtz_arr[])(
296                                 struct AACEncContext *s,
297                                 PutBitContext *pb, const float *in,
298                                 const float *scaled, int size, int scale_idx,
299                                 int cb, const float lambda, const float uplim,
300                                 int *bits) = {
301     quantize_and_encode_band_cost_ZERO,
302     quantize_and_encode_band_cost_SQUAD,
303     quantize_and_encode_band_cost_SQUAD,
304     quantize_and_encode_band_cost_UQUAD,
305     quantize_and_encode_band_cost_UQUAD,
306     quantize_and_encode_band_cost_SPAIR,
307     quantize_and_encode_band_cost_SPAIR,
308     quantize_and_encode_band_cost_UPAIR,
309     quantize_and_encode_band_cost_UPAIR,
310     quantize_and_encode_band_cost_UPAIR,
311     quantize_and_encode_band_cost_UPAIR,
312     quantize_and_encode_band_cost_ESC_RTZ,
313     quantize_and_encode_band_cost_NONE,     /* CB 12 doesn't exist */
314     quantize_and_encode_band_cost_NOISE,
315     quantize_and_encode_band_cost_STEREO,
316     quantize_and_encode_band_cost_STEREO,
317 };
318
319 #define quantize_and_encode_band_cost(                                  \
320                                 s, pb, in, scaled, size, scale_idx, cb, \
321                                 lambda, uplim, bits, rtz)               \
322     ((rtz) ? quantize_and_encode_band_cost_rtz_arr : quantize_and_encode_band_cost_arr)[cb]( \
323                                 s, pb, in, scaled, size, scale_idx, cb, \
324                                 lambda, uplim, bits)
325
326 static float quantize_band_cost(struct AACEncContext *s, const float *in,
327                                 const float *scaled, int size, int scale_idx,
328                                 int cb, const float lambda, const float uplim,
329                                 int *bits, int rtz)
330 {
331     return quantize_and_encode_band_cost(s, NULL, in, scaled, size, scale_idx,
332                                          cb, lambda, uplim, bits, rtz);
333 }
334
335 static void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb,
336                                      const float *in, int size, int scale_idx,
337                                      int cb, const float lambda, int rtz)
338 {
339     quantize_and_encode_band_cost(s, pb, in, NULL, size, scale_idx, cb, lambda,
340                                   INFINITY, NULL, rtz);
341 }
342
343 static float find_max_val(int group_len, int swb_size, const float *scaled) {
344     float maxval = 0.0f;
345     int w2, i;
346     for (w2 = 0; w2 < group_len; w2++) {
347         for (i = 0; i < swb_size; i++) {
348             maxval = FFMAX(maxval, scaled[w2*128+i]);
349         }
350     }
351     return maxval;
352 }
353
354 static int find_min_book(float maxval, int sf) {
355     float Q = ff_aac_pow2sf_tab[POW_SF2_ZERO - sf + SCALE_ONE_POS - SCALE_DIV_512];
356     float Q34 = sqrtf(Q * sqrtf(Q));
357     int qmaxval, cb;
358     qmaxval = maxval * Q34 + 0.4054f;
359     if      (qmaxval ==  0) cb = 0;
360     else if (qmaxval ==  1) cb = 1;
361     else if (qmaxval ==  2) cb = 3;
362     else if (qmaxval <=  4) cb = 5;
363     else if (qmaxval <=  7) cb = 7;
364     else if (qmaxval <= 12) cb = 9;
365     else                    cb = 11;
366     return cb;
367 }
368
369 /**
370  * structure used in optimal codebook search
371  */
372 typedef struct BandCodingPath {
373     int prev_idx; ///< pointer to the previous path point
374     float cost;   ///< path cost
375     int run;
376 } BandCodingPath;
377
378 /**
379  * Encode band info for single window group bands.
380  */
381 static void encode_window_bands_info(AACEncContext *s, SingleChannelElement *sce,
382                                      int win, int group_len, const float lambda)
383 {
384     BandCodingPath path[120][CB_TOT_ALL];
385     int w, swb, cb, start, size;
386     int i, j;
387     const int max_sfb  = sce->ics.max_sfb;
388     const int run_bits = sce->ics.num_windows == 1 ? 5 : 3;
389     const int run_esc  = (1 << run_bits) - 1;
390     int idx, ppos, count;
391     int stackrun[120], stackcb[120], stack_len;
392     float next_minrd = INFINITY;
393     int next_mincb = 0;
394
395     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
396     start = win*128;
397     for (cb = 0; cb < CB_TOT_ALL; cb++) {
398         path[0][cb].cost     = 0.0f;
399         path[0][cb].prev_idx = -1;
400         path[0][cb].run      = 0;
401     }
402     for (swb = 0; swb < max_sfb; swb++) {
403         size = sce->ics.swb_sizes[swb];
404         if (sce->zeroes[win*16 + swb]) {
405             for (cb = 0; cb < CB_TOT_ALL; cb++) {
406                 path[swb+1][cb].prev_idx = cb;
407                 path[swb+1][cb].cost     = path[swb][cb].cost;
408                 path[swb+1][cb].run      = path[swb][cb].run + 1;
409             }
410         } else {
411             float minrd = next_minrd;
412             int mincb = next_mincb;
413             next_minrd = INFINITY;
414             next_mincb = 0;
415             for (cb = 0; cb < CB_TOT_ALL; cb++) {
416                 float cost_stay_here, cost_get_here;
417                 float rd = 0.0f;
418                 if (cb >= 12 && sce->band_type[win*16+swb] < aac_cb_out_map[cb] ||
419                     cb  < aac_cb_in_map[sce->band_type[win*16+swb]] && sce->band_type[win*16+swb] > aac_cb_out_map[cb]) {
420                     path[swb+1][cb].prev_idx = -1;
421                     path[swb+1][cb].cost     = INFINITY;
422                     path[swb+1][cb].run      = path[swb][cb].run + 1;
423                     continue;
424                 }
425                 for (w = 0; w < group_len; w++) {
426                     FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(win+w)*16+swb];
427                     rd += quantize_band_cost(s, sce->coeffs + start + w*128,
428                                              s->scoefs + start + w*128, size,
429                                              sce->sf_idx[(win+w)*16+swb], aac_cb_out_map[cb],
430                                              lambda / band->threshold, INFINITY, NULL, 0);
431                 }
432                 cost_stay_here = path[swb][cb].cost + rd;
433                 cost_get_here  = minrd              + rd + run_bits + 4;
434                 if (   run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run]
435                     != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1])
436                     cost_stay_here += run_bits;
437                 if (cost_get_here < cost_stay_here) {
438                     path[swb+1][cb].prev_idx = mincb;
439                     path[swb+1][cb].cost     = cost_get_here;
440                     path[swb+1][cb].run      = 1;
441                 } else {
442                     path[swb+1][cb].prev_idx = cb;
443                     path[swb+1][cb].cost     = cost_stay_here;
444                     path[swb+1][cb].run      = path[swb][cb].run + 1;
445                 }
446                 if (path[swb+1][cb].cost < next_minrd) {
447                     next_minrd = path[swb+1][cb].cost;
448                     next_mincb = cb;
449                 }
450             }
451         }
452         start += sce->ics.swb_sizes[swb];
453     }
454
455     //convert resulting path from backward-linked list
456     stack_len = 0;
457     idx       = 0;
458     for (cb = 1; cb < CB_TOT_ALL; cb++)
459         if (path[max_sfb][cb].cost < path[max_sfb][idx].cost)
460             idx = cb;
461     ppos = max_sfb;
462     while (ppos > 0) {
463         av_assert1(idx >= 0);
464         cb = idx;
465         stackrun[stack_len] = path[ppos][cb].run;
466         stackcb [stack_len] = cb;
467         idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx;
468         ppos -= path[ppos][cb].run;
469         stack_len++;
470     }
471     //perform actual band info encoding
472     start = 0;
473     for (i = stack_len - 1; i >= 0; i--) {
474         cb = aac_cb_out_map[stackcb[i]];
475         put_bits(&s->pb, 4, cb);
476         count = stackrun[i];
477         memset(sce->zeroes + win*16 + start, !cb, count);
478         //XXX: memset when band_type is also uint8_t
479         for (j = 0; j < count; j++) {
480             sce->band_type[win*16 + start] = cb;
481             start++;
482         }
483         while (count >= run_esc) {
484             put_bits(&s->pb, run_bits, run_esc);
485             count -= run_esc;
486         }
487         put_bits(&s->pb, run_bits, count);
488     }
489 }
490
491 static void codebook_trellis_rate(AACEncContext *s, SingleChannelElement *sce,
492                                   int win, int group_len, const float lambda)
493 {
494     BandCodingPath path[120][CB_TOT_ALL];
495     int w, swb, cb, start, size;
496     int i, j;
497     const int max_sfb  = sce->ics.max_sfb;
498     const int run_bits = sce->ics.num_windows == 1 ? 5 : 3;
499     const int run_esc  = (1 << run_bits) - 1;
500     int idx, ppos, count;
501     int stackrun[120], stackcb[120], stack_len;
502     float next_minbits = INFINITY;
503     int next_mincb = 0;
504
505     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
506     start = win*128;
507     for (cb = 0; cb < CB_TOT_ALL; cb++) {
508         path[0][cb].cost     = run_bits+4;
509         path[0][cb].prev_idx = -1;
510         path[0][cb].run      = 0;
511     }
512     for (swb = 0; swb < max_sfb; swb++) {
513         size = sce->ics.swb_sizes[swb];
514         if (sce->zeroes[win*16 + swb]) {
515             float cost_stay_here = path[swb][0].cost;
516             float cost_get_here  = next_minbits + run_bits + 4;
517             if (   run_value_bits[sce->ics.num_windows == 8][path[swb][0].run]
518                 != run_value_bits[sce->ics.num_windows == 8][path[swb][0].run+1])
519                 cost_stay_here += run_bits;
520             if (cost_get_here < cost_stay_here) {
521                 path[swb+1][0].prev_idx = next_mincb;
522                 path[swb+1][0].cost     = cost_get_here;
523                 path[swb+1][0].run      = 1;
524             } else {
525                 path[swb+1][0].prev_idx = 0;
526                 path[swb+1][0].cost     = cost_stay_here;
527                 path[swb+1][0].run      = path[swb][0].run + 1;
528             }
529             next_minbits = path[swb+1][0].cost;
530             next_mincb = 0;
531             for (cb = 1; cb < CB_TOT_ALL; cb++) {
532                 path[swb+1][cb].cost = 61450;
533                 path[swb+1][cb].prev_idx = -1;
534                 path[swb+1][cb].run = 0;
535             }
536         } else {
537             float minbits = next_minbits;
538             int mincb = next_mincb;
539             int startcb = sce->band_type[win*16+swb];
540             startcb = aac_cb_in_map[startcb];
541             next_minbits = INFINITY;
542             next_mincb = 0;
543             for (cb = 0; cb < startcb; cb++) {
544                 path[swb+1][cb].cost = 61450;
545                 path[swb+1][cb].prev_idx = -1;
546                 path[swb+1][cb].run = 0;
547             }
548             for (cb = startcb; cb < CB_TOT_ALL; cb++) {
549                 float cost_stay_here, cost_get_here;
550                 float bits = 0.0f;
551                 if (cb >= 12 && sce->band_type[win*16+swb] != aac_cb_out_map[cb]) {
552                     path[swb+1][cb].cost = 61450;
553                     path[swb+1][cb].prev_idx = -1;
554                     path[swb+1][cb].run = 0;
555                     continue;
556                 }
557                 for (w = 0; w < group_len; w++) {
558                     bits += quantize_band_cost(s, sce->coeffs + start + w*128,
559                                                s->scoefs + start + w*128, size,
560                                                sce->sf_idx[win*16+swb],
561                                                aac_cb_out_map[cb],
562                                                0, INFINITY, NULL, 0);
563                 }
564                 cost_stay_here = path[swb][cb].cost + bits;
565                 cost_get_here  = minbits            + bits + run_bits + 4;
566                 if (   run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run]
567                     != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1])
568                     cost_stay_here += run_bits;
569                 if (cost_get_here < cost_stay_here) {
570                     path[swb+1][cb].prev_idx = mincb;
571                     path[swb+1][cb].cost     = cost_get_here;
572                     path[swb+1][cb].run      = 1;
573                 } else {
574                     path[swb+1][cb].prev_idx = cb;
575                     path[swb+1][cb].cost     = cost_stay_here;
576                     path[swb+1][cb].run      = path[swb][cb].run + 1;
577                 }
578                 if (path[swb+1][cb].cost < next_minbits) {
579                     next_minbits = path[swb+1][cb].cost;
580                     next_mincb = cb;
581                 }
582             }
583         }
584         start += sce->ics.swb_sizes[swb];
585     }
586
587     //convert resulting path from backward-linked list
588     stack_len = 0;
589     idx       = 0;
590     for (cb = 1; cb < CB_TOT_ALL; cb++)
591         if (path[max_sfb][cb].cost < path[max_sfb][idx].cost)
592             idx = cb;
593     ppos = max_sfb;
594     while (ppos > 0) {
595         av_assert1(idx >= 0);
596         cb = idx;
597         stackrun[stack_len] = path[ppos][cb].run;
598         stackcb [stack_len] = cb;
599         idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx;
600         ppos -= path[ppos][cb].run;
601         stack_len++;
602     }
603     //perform actual band info encoding
604     start = 0;
605     for (i = stack_len - 1; i >= 0; i--) {
606         cb = aac_cb_out_map[stackcb[i]];
607         put_bits(&s->pb, 4, cb);
608         count = stackrun[i];
609         memset(sce->zeroes + win*16 + start, !cb, count);
610         //XXX: memset when band_type is also uint8_t
611         for (j = 0; j < count; j++) {
612             sce->band_type[win*16 + start] = cb;
613             start++;
614         }
615         while (count >= run_esc) {
616             put_bits(&s->pb, run_bits, run_esc);
617             count -= run_esc;
618         }
619         put_bits(&s->pb, run_bits, count);
620     }
621 }
622
623 /** Return the minimum scalefactor where the quantized coef does not clip. */
624 static av_always_inline uint8_t coef2minsf(float coef) {
625     return av_clip_uint8(log2f(coef)*4 - 69 + SCALE_ONE_POS - SCALE_DIV_512);
626 }
627
628 /** Return the maximum scalefactor where the quantized coef is not zero. */
629 static av_always_inline uint8_t coef2maxsf(float coef) {
630     return av_clip_uint8(log2f(coef)*4 +  6 + SCALE_ONE_POS - SCALE_DIV_512);
631 }
632
633 typedef struct TrellisPath {
634     float cost;
635     int prev;
636 } TrellisPath;
637
638 #define TRELLIS_STAGES 121
639 #define TRELLIS_STATES (SCALE_MAX_DIFF+1)
640
641 static void set_special_band_scalefactors(AACEncContext *s, SingleChannelElement *sce)
642 {
643     int w, g, start = 0;
644     int minscaler_n = sce->sf_idx[0], minscaler_i = sce->sf_idx[0];
645     int bands = 0;
646
647     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
648         start = 0;
649         for (g = 0;  g < sce->ics.num_swb; g++) {
650             if (sce->band_type[w*16+g] == INTENSITY_BT || sce->band_type[w*16+g] == INTENSITY_BT2) {
651                 sce->sf_idx[w*16+g] = av_clip(ceilf(log2f(sce->is_ener[w*16+g])*2), -155, 100);
652                 minscaler_i = FFMIN(minscaler_i, sce->sf_idx[w*16+g]);
653                 bands++;
654             } else if (sce->band_type[w*16+g] == NOISE_BT) {
655                 sce->sf_idx[w*16+g] = av_clip(4+log2f(sce->pns_ener[w*16+g])*2, -100, 155);
656                 minscaler_n = FFMIN(minscaler_n, sce->sf_idx[w*16+g]);
657                 bands++;
658             }
659             start += sce->ics.swb_sizes[g];
660         }
661     }
662
663     if (!bands)
664         return;
665
666     /* Clip the scalefactor indices */
667     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
668         for (g = 0;  g < sce->ics.num_swb; g++) {
669             if (sce->band_type[w*16+g] == INTENSITY_BT || sce->band_type[w*16+g] == INTENSITY_BT2) {
670                 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler_i, minscaler_i + SCALE_MAX_DIFF);
671             } else if (sce->band_type[w*16+g] == NOISE_BT) {
672                 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler_n, minscaler_n + SCALE_MAX_DIFF);
673             }
674         }
675     }
676 }
677
678 static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,
679                                        SingleChannelElement *sce,
680                                        const float lambda)
681 {
682     int q, w, w2, g, start = 0;
683     int i, j;
684     int idx;
685     TrellisPath paths[TRELLIS_STAGES][TRELLIS_STATES];
686     int bandaddr[TRELLIS_STAGES];
687     int minq;
688     float mincost;
689     float q0f = FLT_MAX, q1f = 0.0f, qnrgf = 0.0f;
690     int q0, q1, qcnt = 0;
691
692     for (i = 0; i < 1024; i++) {
693         float t = fabsf(sce->coeffs[i]);
694         if (t > 0.0f) {
695             q0f = FFMIN(q0f, t);
696             q1f = FFMAX(q1f, t);
697             qnrgf += t*t;
698             qcnt++;
699         }
700     }
701
702     if (!qcnt) {
703         memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
704         memset(sce->zeroes, 1, sizeof(sce->zeroes));
705         return;
706     }
707
708     //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
709     q0 = coef2minsf(q0f);
710     //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
711     q1 = coef2maxsf(q1f);
712     if (q1 - q0 > 60) {
713         int q0low  = q0;
714         int q1high = q1;
715         //minimum scalefactor index is when maximum nonzero coefficient after quantizing is not clipped
716         int qnrg = av_clip_uint8(log2f(sqrtf(qnrgf/qcnt))*4 - 31 + SCALE_ONE_POS - SCALE_DIV_512);
717         q1 = qnrg + 30;
718         q0 = qnrg - 30;
719         if (q0 < q0low) {
720             q1 += q0low - q0;
721             q0  = q0low;
722         } else if (q1 > q1high) {
723             q0 -= q1 - q1high;
724             q1  = q1high;
725         }
726     }
727
728     for (i = 0; i < TRELLIS_STATES; i++) {
729         paths[0][i].cost    = 0.0f;
730         paths[0][i].prev    = -1;
731     }
732     for (j = 1; j < TRELLIS_STAGES; j++) {
733         for (i = 0; i < TRELLIS_STATES; i++) {
734             paths[j][i].cost    = INFINITY;
735             paths[j][i].prev    = -2;
736         }
737     }
738     idx = 1;
739     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
740     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
741         start = w*128;
742         for (g = 0; g < sce->ics.num_swb; g++) {
743             const float *coefs = sce->coeffs + start;
744             float qmin, qmax;
745             int nz = 0;
746
747             bandaddr[idx] = w * 16 + g;
748             qmin = INT_MAX;
749             qmax = 0.0f;
750             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
751                 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
752                 if (band->energy <= band->threshold || band->threshold == 0.0f) {
753                     sce->zeroes[(w+w2)*16+g] = 1;
754                     continue;
755                 }
756                 sce->zeroes[(w+w2)*16+g] = 0;
757                 nz = 1;
758                 for (i = 0; i < sce->ics.swb_sizes[g]; i++) {
759                     float t = fabsf(coefs[w2*128+i]);
760                     if (t > 0.0f)
761                         qmin = FFMIN(qmin, t);
762                     qmax = FFMAX(qmax, t);
763                 }
764             }
765             if (nz) {
766                 int minscale, maxscale;
767                 float minrd = INFINITY;
768                 float maxval;
769                 //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
770                 minscale = coef2minsf(qmin);
771                 //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
772                 maxscale = coef2maxsf(qmax);
773                 minscale = av_clip(minscale - q0, 0, TRELLIS_STATES - 1);
774                 maxscale = av_clip(maxscale - q0, 0, TRELLIS_STATES);
775                 maxval = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], s->scoefs+start);
776                 for (q = minscale; q < maxscale; q++) {
777                     float dist = 0;
778                     int cb = find_min_book(maxval, sce->sf_idx[w*16+g]);
779                     for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
780                         FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
781                         dist += quantize_band_cost(s, coefs + w2*128, s->scoefs + start + w2*128, sce->ics.swb_sizes[g],
782                                                    q + q0, cb, lambda / band->threshold, INFINITY, NULL, 0);
783                     }
784                     minrd = FFMIN(minrd, dist);
785
786                     for (i = 0; i < q1 - q0; i++) {
787                         float cost;
788                         cost = paths[idx - 1][i].cost + dist
789                                + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
790                         if (cost < paths[idx][q].cost) {
791                             paths[idx][q].cost    = cost;
792                             paths[idx][q].prev    = i;
793                         }
794                     }
795                 }
796             } else {
797                 for (q = 0; q < q1 - q0; q++) {
798                     paths[idx][q].cost = paths[idx - 1][q].cost + 1;
799                     paths[idx][q].prev = q;
800                 }
801             }
802             sce->zeroes[w*16+g] = !nz;
803             start += sce->ics.swb_sizes[g];
804             idx++;
805         }
806     }
807     idx--;
808     mincost = paths[idx][0].cost;
809     minq    = 0;
810     for (i = 1; i < TRELLIS_STATES; i++) {
811         if (paths[idx][i].cost < mincost) {
812             mincost = paths[idx][i].cost;
813             minq = i;
814         }
815     }
816     while (idx) {
817         sce->sf_idx[bandaddr[idx]] = minq + q0;
818         minq = paths[idx][minq].prev;
819         idx--;
820     }
821     //set the same quantizers inside window groups
822     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
823         for (g = 0;  g < sce->ics.num_swb; g++)
824             for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
825                 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
826 }
827
828 /**
829  * two-loop quantizers search taken from ISO 13818-7 Appendix C
830  */
831 static void search_for_quantizers_twoloop(AVCodecContext *avctx,
832                                           AACEncContext *s,
833                                           SingleChannelElement *sce,
834                                           const float lambda)
835 {
836     int start = 0, i, w, w2, g;
837     int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate / avctx->channels * (lambda / 120.f);
838     float dists[128] = { 0 }, uplims[128] = { 0 };
839     float maxvals[128];
840     int fflag, minscaler;
841     int its  = 0;
842     int allz = 0;
843     float minthr = INFINITY;
844
845     // for values above this the decoder might end up in an endless loop
846     // due to always having more bits than what can be encoded.
847     destbits = FFMIN(destbits, 5800);
848     //XXX: some heuristic to determine initial quantizers will reduce search time
849     //determine zero bands and upper limits
850     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
851         for (g = 0;  g < sce->ics.num_swb; g++) {
852             int nz = 0;
853             float uplim = 0.0f, energy = 0.0f;
854             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
855                 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
856                 uplim  += band->threshold;
857                 energy += band->energy;
858                 if (band->energy <= band->threshold || band->threshold == 0.0f) {
859                     sce->zeroes[(w+w2)*16+g] = 1;
860                     continue;
861                 }
862                 nz = 1;
863             }
864             uplims[w*16+g] = uplim *512;
865             sce->zeroes[w*16+g] = !nz;
866             if (nz)
867                 minthr = FFMIN(minthr, uplim);
868             allz |= nz;
869         }
870     }
871     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
872         for (g = 0;  g < sce->ics.num_swb; g++) {
873             if (sce->zeroes[w*16+g]) {
874                 sce->sf_idx[w*16+g] = SCALE_ONE_POS;
875                 continue;
876             }
877             sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2f(uplims[w*16+g]/minthr)*4,59);
878         }
879     }
880
881     if (!allz)
882         return;
883     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
884
885     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
886         start = w*128;
887         for (g = 0;  g < sce->ics.num_swb; g++) {
888             const float *scaled = s->scoefs + start;
889             maxvals[w*16+g] = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], scaled);
890             start += sce->ics.swb_sizes[g];
891         }
892     }
893
894     //perform two-loop search
895     //outer loop - improve quality
896     do {
897         int tbits, qstep;
898         minscaler = sce->sf_idx[0];
899         //inner loop - quantize spectrum to fit into given number of bits
900         qstep = its ? 1 : 32;
901         do {
902             int prev = -1;
903             tbits = 0;
904             for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
905                 start = w*128;
906                 for (g = 0;  g < sce->ics.num_swb; g++) {
907                     const float *coefs = sce->coeffs + start;
908                     const float *scaled = s->scoefs + start;
909                     int bits = 0;
910                     int cb;
911                     float dist = 0.0f;
912
913                     if (sce->zeroes[w*16+g] || sce->sf_idx[w*16+g] >= 218) {
914                         start += sce->ics.swb_sizes[g];
915                         continue;
916                     }
917                     minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
918                     cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
919                     for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
920                         int b;
921                         dist += quantize_band_cost(s, coefs + w2*128,
922                                                    scaled + w2*128,
923                                                    sce->ics.swb_sizes[g],
924                                                    sce->sf_idx[w*16+g],
925                                                    cb,
926                                                    1.0f,
927                                                    INFINITY,
928                                                    &b,
929                                                    0);
930                         bits += b;
931                     }
932                     dists[w*16+g] = dist - bits;
933                     if (prev != -1) {
934                         bits += ff_aac_scalefactor_bits[sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO];
935                     }
936                     tbits += bits;
937                     start += sce->ics.swb_sizes[g];
938                     prev = sce->sf_idx[w*16+g];
939                 }
940             }
941             if (tbits > destbits) {
942                 for (i = 0; i < 128; i++)
943                     if (sce->sf_idx[i] < 218 - qstep)
944                         sce->sf_idx[i] += qstep;
945             } else {
946                 for (i = 0; i < 128; i++)
947                     if (sce->sf_idx[i] > 60 - qstep)
948                         sce->sf_idx[i] -= qstep;
949             }
950             qstep >>= 1;
951             if (!qstep && tbits > destbits*1.02 && sce->sf_idx[0] < 217)
952                 qstep = 1;
953         } while (qstep);
954
955         fflag = 0;
956         minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);
957
958         for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
959             for (g = 0; g < sce->ics.num_swb; g++) {
960                 int prevsc = sce->sf_idx[w*16+g];
961                 if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60) {
962                     if (find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1))
963                         sce->sf_idx[w*16+g]--;
964                     else //Try to make sure there is some energy in every band
965                         sce->sf_idx[w*16+g]-=2;
966                 }
967                 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
968                 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);
969                 if (sce->sf_idx[w*16+g] != prevsc)
970                     fflag = 1;
971                 sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
972             }
973         }
974         its++;
975     } while (fflag && its < 10);
976 }
977
978 static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
979                                        SingleChannelElement *sce,
980                                        const float lambda)
981 {
982     int start = 0, i, w, w2, g;
983     float uplim[128], maxq[128];
984     int minq, maxsf;
985     float distfact = ((sce->ics.num_windows > 1) ? 85.80 : 147.84) / lambda;
986     int last = 0, lastband = 0, curband = 0;
987     float avg_energy = 0.0;
988     if (sce->ics.num_windows == 1) {
989         start = 0;
990         for (i = 0; i < 1024; i++) {
991             if (i - start >= sce->ics.swb_sizes[curband]) {
992                 start += sce->ics.swb_sizes[curband];
993                 curband++;
994             }
995             if (sce->coeffs[i]) {
996                 avg_energy += sce->coeffs[i] * sce->coeffs[i];
997                 last = i;
998                 lastband = curband;
999             }
1000         }
1001     } else {
1002         for (w = 0; w < 8; w++) {
1003             const float *coeffs = sce->coeffs + w*128;
1004             curband = start = 0;
1005             for (i = 0; i < 128; i++) {
1006                 if (i - start >= sce->ics.swb_sizes[curband]) {
1007                     start += sce->ics.swb_sizes[curband];
1008                     curband++;
1009                 }
1010                 if (coeffs[i]) {
1011                     avg_energy += coeffs[i] * coeffs[i];
1012                     last = FFMAX(last, i);
1013                     lastband = FFMAX(lastband, curband);
1014                 }
1015             }
1016         }
1017     }
1018     last++;
1019     avg_energy /= last;
1020     if (avg_energy == 0.0f) {
1021         for (i = 0; i < FF_ARRAY_ELEMS(sce->sf_idx); i++)
1022             sce->sf_idx[i] = SCALE_ONE_POS;
1023         return;
1024     }
1025     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
1026         start = w*128;
1027         for (g = 0; g < sce->ics.num_swb; g++) {
1028             float *coefs   = sce->coeffs + start;
1029             const int size = sce->ics.swb_sizes[g];
1030             int start2 = start, end2 = start + size, peakpos = start;
1031             float maxval = -1, thr = 0.0f, t;
1032             maxq[w*16+g] = 0.0f;
1033             if (g > lastband) {
1034                 maxq[w*16+g] = 0.0f;
1035                 start += size;
1036                 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
1037                     memset(coefs + w2*128, 0, sizeof(coefs[0])*size);
1038                 continue;
1039             }
1040             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
1041                 for (i = 0; i < size; i++) {
1042                     float t = coefs[w2*128+i]*coefs[w2*128+i];
1043                     maxq[w*16+g] = FFMAX(maxq[w*16+g], fabsf(coefs[w2*128 + i]));
1044                     thr += t;
1045                     if (sce->ics.num_windows == 1 && maxval < t) {
1046                         maxval  = t;
1047                         peakpos = start+i;
1048                     }
1049                 }
1050             }
1051             if (sce->ics.num_windows == 1) {
1052                 start2 = FFMAX(peakpos - 2, start2);
1053                 end2   = FFMIN(peakpos + 3, end2);
1054             } else {
1055                 start2 -= start;
1056                 end2   -= start;
1057             }
1058             start += size;
1059             thr = pow(thr / (avg_energy * (end2 - start2)), 0.3 + 0.1*(lastband - g) / lastband);
1060             t   = 1.0 - (1.0 * start2 / last);
1061             uplim[w*16+g] = distfact / (1.4 * thr + t*t*t + 0.075);
1062         }
1063     }
1064     memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
1065     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
1066     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
1067         start = w*128;
1068         for (g = 0;  g < sce->ics.num_swb; g++) {
1069             const float *coefs  = sce->coeffs + start;
1070             const float *scaled = s->scoefs   + start;
1071             const int size      = sce->ics.swb_sizes[g];
1072             int scf, prev_scf, step;
1073             int min_scf = -1, max_scf = 256;
1074             float curdiff;
1075             if (maxq[w*16+g] < 21.544) {
1076                 sce->zeroes[w*16+g] = 1;
1077                 start += size;
1078                 continue;
1079             }
1080             sce->zeroes[w*16+g] = 0;
1081             scf  = prev_scf = av_clip(SCALE_ONE_POS - SCALE_DIV_512 - log2f(1/maxq[w*16+g])*16/3, 60, 218);
1082             for (;;) {
1083                 float dist = 0.0f;
1084                 int quant_max;
1085
1086                 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
1087                     int b;
1088                     dist += quantize_band_cost(s, coefs + w2*128,
1089                                                scaled + w2*128,
1090                                                sce->ics.swb_sizes[g],
1091                                                scf,
1092                                                ESC_BT,
1093                                                lambda,
1094                                                INFINITY,
1095                                                &b,
1096                                                0);
1097                     dist -= b;
1098                 }
1099                 dist *= 1.0f / 512.0f / lambda;
1100                 quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512], ROUND_STANDARD);
1101                 if (quant_max >= 8191) { // too much, return to the previous quantizer
1102                     sce->sf_idx[w*16+g] = prev_scf;
1103                     break;
1104                 }
1105                 prev_scf = scf;
1106                 curdiff = fabsf(dist - uplim[w*16+g]);
1107                 if (curdiff <= 1.0f)
1108                     step = 0;
1109                 else
1110                     step = log2f(curdiff);
1111                 if (dist > uplim[w*16+g])
1112                     step = -step;
1113                 scf += step;
1114                 scf = av_clip_uint8(scf);
1115                 step = scf - prev_scf;
1116                 if (FFABS(step) <= 1 || (step > 0 && scf >= max_scf) || (step < 0 && scf <= min_scf)) {
1117                     sce->sf_idx[w*16+g] = av_clip(scf, min_scf, max_scf);
1118                     break;
1119                 }
1120                 if (step > 0)
1121                     min_scf = prev_scf;
1122                 else
1123                     max_scf = prev_scf;
1124             }
1125             start += size;
1126         }
1127     }
1128     minq = sce->sf_idx[0] ? sce->sf_idx[0] : INT_MAX;
1129     for (i = 1; i < 128; i++) {
1130         if (!sce->sf_idx[i])
1131             sce->sf_idx[i] = sce->sf_idx[i-1];
1132         else
1133             minq = FFMIN(minq, sce->sf_idx[i]);
1134     }
1135     if (minq == INT_MAX)
1136         minq = 0;
1137     minq = FFMIN(minq, SCALE_MAX_POS);
1138     maxsf = FFMIN(minq + SCALE_MAX_DIFF, SCALE_MAX_POS);
1139     for (i = 126; i >= 0; i--) {
1140         if (!sce->sf_idx[i])
1141             sce->sf_idx[i] = sce->sf_idx[i+1];
1142         sce->sf_idx[i] = av_clip(sce->sf_idx[i], minq, maxsf);
1143     }
1144 }
1145
1146 static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,
1147                                        SingleChannelElement *sce,
1148                                        const float lambda)
1149 {
1150     int i, w, w2, g;
1151     int minq = 255;
1152
1153     memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
1154     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
1155         for (g = 0; g < sce->ics.num_swb; g++) {
1156             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
1157                 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
1158                 if (band->energy <= band->threshold) {
1159                     sce->sf_idx[(w+w2)*16+g] = 218;
1160                     sce->zeroes[(w+w2)*16+g] = 1;
1161                 } else {
1162                     sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2f(band->threshold), 80, 218);
1163                     sce->zeroes[(w+w2)*16+g] = 0;
1164                 }
1165                 minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
1166             }
1167         }
1168     }
1169     for (i = 0; i < 128; i++) {
1170         sce->sf_idx[i] = 140;
1171         //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);
1172     }
1173     //set the same quantizers inside window groups
1174     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
1175         for (g = 0;  g < sce->ics.num_swb; g++)
1176             for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
1177                 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
1178 }
1179
1180 static void search_for_pns(AACEncContext *s, AVCodecContext *avctx, SingleChannelElement *sce,
1181                            const float lambda)
1182 {
1183     int start = 0, w, w2, g;
1184     const float freq_mult = avctx->sample_rate/(1024.0f/sce->ics.num_windows)/2.0f;
1185     const float spread_threshold = NOISE_SPREAD_THRESHOLD*(lambda/120.f);
1186     const float thr_mult = NOISE_LAMBDA_NUMERATOR/lambda;
1187
1188     /* Coders !twoloop don't reset the band_types */
1189     for (w = 0; w < 128; w++)
1190         if (sce->band_type[w] == NOISE_BT)
1191             sce->band_type[w] = 0;
1192
1193     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
1194         start = 0;
1195         for (g = 0;  g < sce->ics.num_swb; g++) {
1196             if (start*freq_mult > NOISE_LOW_LIMIT*(lambda/170.0f)) {
1197                 float energy = 0.0f, threshold = 0.0f, spread = 0.0f;
1198                 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
1199                     FFPsyBand *band = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
1200                     energy += band->energy;
1201                     threshold += band->threshold;
1202                     spread += band->spread;
1203                 }
1204                 if (spread > spread_threshold*sce->ics.group_len[w] &&
1205                     ((sce->zeroes[w*16+g] && energy >= threshold) ||
1206                     energy < threshold*thr_mult*sce->ics.group_len[w])) {
1207                     sce->band_type[w*16+g] = NOISE_BT;
1208                     sce->pns_ener[w*16+g] = energy / sce->ics.group_len[w];
1209                     sce->zeroes[w*16+g] = 0;
1210                 }
1211             }
1212             start += sce->ics.swb_sizes[g];
1213         }
1214     }
1215 }
1216
1217 static void search_for_is(AACEncContext *s, AVCodecContext *avctx, ChannelElement *cpe,
1218                           const float lambda)
1219 {
1220     float IS[128];
1221     float *L34  = s->scoefs + 128*0, *R34  = s->scoefs + 128*1;
1222     float *I34  = s->scoefs + 128*2;
1223     SingleChannelElement *sce0 = &cpe->ch[0];
1224     SingleChannelElement *sce1 = &cpe->ch[1];
1225     int start = 0, count = 0, i, w, w2, g;
1226     const float freq_mult = avctx->sample_rate/(1024.0f/sce0->ics.num_windows)/2.0f;
1227
1228     for (w = 0; w < 128; w++)
1229         if (sce1->band_type[w] >= INTENSITY_BT2)
1230             sce1->band_type[w] = 0;
1231
1232     if (!cpe->common_window)
1233         return;
1234     for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
1235         start = 0;
1236         for (g = 0;  g < sce0->ics.num_swb; g++) {
1237             if (start*freq_mult > INT_STEREO_LOW_LIMIT*(lambda/170.0f) &&
1238                 cpe->ch[0].band_type[w*16+g] != NOISE_BT && !cpe->ch[0].zeroes[w*16+g] &&
1239                 cpe->ch[1].band_type[w*16+g] != NOISE_BT && !cpe->ch[1].zeroes[w*16+g]) {
1240                 int phase = 0;
1241                 float ener0 = 0.0f, ener1 = 0.0f, ener01 = 0.0f;
1242                 float dist1 = 0.0f, dist2 = 0.0f;
1243                 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
1244                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
1245                         float coef0 = sce0->pcoeffs[start+(w+w2)*128+i];
1246                         float coef1 = sce1->pcoeffs[start+(w+w2)*128+i];
1247                         phase += coef0*coef1 >= 0.0f ? 1 : -1;
1248                         ener0 += coef0*coef0;
1249                         ener1 += coef1*coef1;
1250                         ener01 += (coef0 + coef1)*(coef0 + coef1);
1251                     }
1252                 }
1253                 if (!phase) { /* Too much phase difference between channels */
1254                     start += sce0->ics.swb_sizes[g];
1255                     continue;
1256                 }
1257                 phase = av_clip(phase, -1, 1);
1258                 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
1259                     FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
1260                     FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
1261                     int is_band_type, is_sf_idx = FFMAX(1, sce0->sf_idx[(w+w2)*16+g]-4);
1262                     float e01_34 = phase*pow(sqrt(ener1/ener0), 3.0/4.0);
1263                     float maxval, dist_spec_err = 0.0f;
1264                     float minthr = FFMIN(band0->threshold, band1->threshold);
1265                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++)
1266                         IS[i] = (sce0->pcoeffs[start+(w+w2)*128+i] + phase*sce1->pcoeffs[start+(w+w2)*128+i]) * sqrt(ener0/ener01);
1267                     abs_pow34_v(L34, sce0->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
1268                     abs_pow34_v(R34, sce1->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
1269                     abs_pow34_v(I34, IS,                            sce0->ics.swb_sizes[g]);
1270                     maxval = find_max_val(1, sce0->ics.swb_sizes[g], I34);
1271                     is_band_type = find_min_book(maxval, is_sf_idx);
1272                     dist1 += quantize_band_cost(s, sce0->coeffs + start + (w+w2)*128,
1273                                                 L34,
1274                                                 sce0->ics.swb_sizes[g],
1275                                                 sce0->sf_idx[(w+w2)*16+g],
1276                                                 sce0->band_type[(w+w2)*16+g],
1277                                                 lambda / band0->threshold, INFINITY, NULL, 0);
1278                     dist1 += quantize_band_cost(s, sce1->coeffs + start + (w+w2)*128,
1279                                                 R34,
1280                                                 sce1->ics.swb_sizes[g],
1281                                                 sce1->sf_idx[(w+w2)*16+g],
1282                                                 sce1->band_type[(w+w2)*16+g],
1283                                                 lambda / band1->threshold, INFINITY, NULL, 0);
1284                     dist2 += quantize_band_cost(s, IS,
1285                                                 I34,
1286                                                 sce0->ics.swb_sizes[g],
1287                                                 is_sf_idx,
1288                                                 is_band_type,
1289                                                 lambda / minthr, INFINITY, NULL, 0);
1290                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
1291                         dist_spec_err += (L34[i] - I34[i])*(L34[i] - I34[i]);
1292                         dist_spec_err += (R34[i] - I34[i]*e01_34)*(R34[i] - I34[i]*e01_34);
1293                     }
1294                     dist_spec_err *= lambda / minthr;
1295                     dist2 += dist_spec_err;
1296                 }
1297                 if (dist2 <= dist1) {
1298                     cpe->is_mask[w*16+g] = 1;
1299                     cpe->ms_mask[w*16+g] = 0;
1300                     cpe->ch[0].is_ener[w*16+g] = sqrt(ener0/ener01);
1301                     cpe->ch[1].is_ener[w*16+g] = ener0/ener1;
1302                     if (phase)
1303                         cpe->ch[1].band_type[w*16+g] = INTENSITY_BT;
1304                     else
1305                         cpe->ch[1].band_type[w*16+g] = INTENSITY_BT2;
1306                     count++;
1307                 }
1308             }
1309             start += sce0->ics.swb_sizes[g];
1310         }
1311     }
1312     cpe->is_mode = !!count;
1313 }
1314
1315 static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
1316                           const float lambda)
1317 {
1318     int start = 0, i, w, w2, g;
1319     float M[128], S[128];
1320     float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
1321     SingleChannelElement *sce0 = &cpe->ch[0];
1322     SingleChannelElement *sce1 = &cpe->ch[1];
1323     if (!cpe->common_window)
1324         return;
1325     for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
1326         start = 0;
1327         for (g = 0;  g < sce0->ics.num_swb; g++) {
1328             if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g] && !cpe->is_mask[w*16+g]) {
1329                 float dist1 = 0.0f, dist2 = 0.0f;
1330                 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
1331                     FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
1332                     FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
1333                     float minthr = FFMIN(band0->threshold, band1->threshold);
1334                     float maxthr = FFMAX(band0->threshold, band1->threshold);
1335                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
1336                         M[i] = (sce0->pcoeffs[start+(w+w2)*128+i]
1337                               + sce1->pcoeffs[start+(w+w2)*128+i]) * 0.5;
1338                         S[i] =  M[i]
1339                               - sce1->pcoeffs[start+(w+w2)*128+i];
1340                     }
1341                     abs_pow34_v(L34, sce0->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
1342                     abs_pow34_v(R34, sce1->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
1343                     abs_pow34_v(M34, M,                         sce0->ics.swb_sizes[g]);
1344                     abs_pow34_v(S34, S,                         sce0->ics.swb_sizes[g]);
1345                     dist1 += quantize_band_cost(s, sce0->coeffs + start + (w+w2)*128,
1346                                                 L34,
1347                                                 sce0->ics.swb_sizes[g],
1348                                                 sce0->sf_idx[(w+w2)*16+g],
1349                                                 sce0->band_type[(w+w2)*16+g],
1350                                                 lambda / band0->threshold, INFINITY, NULL, 0);
1351                     dist1 += quantize_band_cost(s, sce1->coeffs + start + (w+w2)*128,
1352                                                 R34,
1353                                                 sce1->ics.swb_sizes[g],
1354                                                 sce1->sf_idx[(w+w2)*16+g],
1355                                                 sce1->band_type[(w+w2)*16+g],
1356                                                 lambda / band1->threshold, INFINITY, NULL, 0);
1357                     dist2 += quantize_band_cost(s, M,
1358                                                 M34,
1359                                                 sce0->ics.swb_sizes[g],
1360                                                 sce0->sf_idx[(w+w2)*16+g],
1361                                                 sce0->band_type[(w+w2)*16+g],
1362                                                 lambda / maxthr, INFINITY, NULL, 0);
1363                     dist2 += quantize_band_cost(s, S,
1364                                                 S34,
1365                                                 sce1->ics.swb_sizes[g],
1366                                                 sce1->sf_idx[(w+w2)*16+g],
1367                                                 sce1->band_type[(w+w2)*16+g],
1368                                                 lambda / minthr, INFINITY, NULL, 0);
1369                 }
1370                 cpe->ms_mask[w*16+g] = dist2 < dist1;
1371             }
1372             start += sce0->ics.swb_sizes[g];
1373         }
1374     }
1375 }
1376
1377 AACCoefficientsEncoder ff_aac_coders[AAC_CODER_NB] = {
1378     [AAC_CODER_FAAC] = {
1379         search_for_quantizers_faac,
1380         encode_window_bands_info,
1381         quantize_and_encode_band,
1382         set_special_band_scalefactors,
1383         search_for_pns,
1384         search_for_ms,
1385         search_for_is,
1386     },
1387     [AAC_CODER_ANMR] = {
1388         search_for_quantizers_anmr,
1389         encode_window_bands_info,
1390         quantize_and_encode_band,
1391         set_special_band_scalefactors,
1392         search_for_pns,
1393         search_for_ms,
1394         search_for_is,
1395     },
1396     [AAC_CODER_TWOLOOP] = {
1397         search_for_quantizers_twoloop,
1398         codebook_trellis_rate,
1399         quantize_and_encode_band,
1400         set_special_band_scalefactors,
1401         search_for_pns,
1402         search_for_ms,
1403         search_for_is,
1404     },
1405     [AAC_CODER_FAST] = {
1406         search_for_quantizers_fast,
1407         encode_window_bands_info,
1408         quantize_and_encode_band,
1409         set_special_band_scalefactors,
1410         search_for_pns,
1411         search_for_ms,
1412         search_for_is,
1413     },
1414 };