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