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