17b14d638115d1b238027af10a81d4ee172e7e5f
[ffmpeg.git] / libavcodec / aaccoder.c
1 /*
2  * AAC coefficients encoder
3  * Copyright (C) 2008-2009 Konstantin Shishkov
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * AAC coefficients encoder
25  */
26
27 /***********************************
28  *              TODOs:
29  * speedup quantizer selection
30  * add sane pulse detection
31  ***********************************/
32
33 #include "libavutil/libm.h" // brought forward to work around cygwin header breakage
34
35 #include <float.h>
36 #include "libavutil/mathematics.h"
37 #include "avcodec.h"
38 #include "put_bits.h"
39 #include "aac.h"
40 #include "aacenc.h"
41 #include "aactab.h"
42 #include "aac_tablegen_decl.h"
43
44 /** Frequency in Hz for lower limit of noise substitution **/
45 #define NOISE_LOW_LIMIT 4500
46
47 /* Energy spread threshold value below which no PNS is used, this corresponds to
48  * typically around 17Khz, after which PNS usage decays ending at 19Khz */
49 #define NOISE_SPREAD_THRESHOLD 0.5f
50
51 /* This constant gets divided by lambda to return ~1.65 which when multiplied
52  * by the band->threshold and compared to band->energy is the boundary between
53  * excessive PNS and little PNS usage. */
54 #define NOISE_LAMBDA_NUMERATOR 252.1f
55
56 /** Frequency in Hz for lower limit of intensity stereo   **/
57 #define INT_STEREO_LOW_LIMIT 6100
58
59 /** Total number of usable codebooks **/
60 #define CB_TOT 12
61
62 /** Total number of codebooks, including special ones **/
63 #define CB_TOT_ALL 15
64
65 /** bits needed to code codebook run value for long windows */
66 static const uint8_t run_value_bits_long[64] = {
67      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
68      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5, 10,
69     10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
70     10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 15
71 };
72
73 /** bits needed to code codebook run value for short windows */
74 static const uint8_t run_value_bits_short[16] = {
75     3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 6, 6, 9
76 };
77
78 static const uint8_t * const run_value_bits[2] = {
79     run_value_bits_long, run_value_bits_short
80 };
81
82 /** Map to convert values from BandCodingPath index to a codebook index **/
83 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};
84 /** Inverse map to convert from codebooks to BandCodingPath indices **/
85 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};
86
87 /**
88  * Quantize one coefficient.
89  * @return absolute value of the quantized coefficient
90  * @see 3GPP TS26.403 5.6.2 "Scalefactor determination"
91  */
92 static av_always_inline int quant(float coef, const float Q)
93 {
94     float a = coef * Q;
95     return sqrtf(a * sqrtf(a)) + 0.4054;
96 }
97
98 static void quantize_bands(int *out, const float *in, const float *scaled,
99                            int size, float Q34, int is_signed, int maxval)
100 {
101     int i;
102     double qc;
103     for (i = 0; i < size; i++) {
104         qc = scaled[i] * Q34;
105         out[i] = (int)FFMIN(qc + 0.4054, (double)maxval);
106         if (is_signed && in[i] < 0.0f) {
107             out[i] = -out[i];
108         }
109     }
110 }
111
112 static void abs_pow34_v(float *out, const float *in, const int size)
113 {
114 #ifndef USE_REALLY_FULL_SEARCH
115     int i;
116     for (i = 0; i < size; i++) {
117         float a = fabsf(in[i]);
118         out[i] = sqrtf(a * sqrtf(a));
119     }
120 #endif /* USE_REALLY_FULL_SEARCH */
121 }
122
123 static const uint8_t aac_cb_range [12] = {0, 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17};
124 static const uint8_t aac_cb_maxval[12] = {0, 1, 1, 2, 2, 4, 4, 7, 7, 12, 12, 16};
125
126 /**
127  * Calculate rate distortion cost for quantizing with given codebook
128  *
129  * @return quantization distortion
130  */
131 static av_always_inline float quantize_and_encode_band_cost_template(
132                                 struct AACEncContext *s,
133                                 PutBitContext *pb, const float *in,
134                                 const float *scaled, int size, int scale_idx,
135                                 int cb, const float lambda, const float uplim,
136                                 int *bits, int BT_ZERO, int BT_UNSIGNED,
137                                 int BT_PAIR, int BT_ESC, int BT_NOISE, int BT_STEREO)
138 {
139     const int q_idx = POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512;
140     const float Q   = ff_aac_pow2sf_tab [q_idx];
141     const float Q34 = ff_aac_pow34sf_tab[q_idx];
142     const float IQ  = ff_aac_pow2sf_tab [POW_SF2_ZERO + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];
143     const float CLIPPED_ESCAPE = 165140.0f*IQ;
144     int i, j;
145     float cost = 0;
146     const int dim = BT_PAIR ? 2 : 4;
147     int resbits = 0;
148     int off;
149
150     if (BT_ZERO || BT_NOISE || BT_STEREO) {
151         for (i = 0; i < size; i++)
152             cost += in[i]*in[i];
153         if (bits)
154             *bits = 0;
155         return cost * lambda;
156     }
157     if (!scaled) {
158         abs_pow34_v(s->scoefs, in, size);
159         scaled = s->scoefs;
160     }
161     quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, aac_cb_maxval[cb]);
162     if (BT_UNSIGNED) {
163         off = 0;
164     } else {
165         off = aac_cb_maxval[cb];
166     }
167     for (i = 0; i < size; i += dim) {
168         const float *vec;
169         int *quants = s->qcoefs + i;
170         int curidx = 0;
171         int curbits;
172         float rd = 0.0f;
173         for (j = 0; j < dim; j++) {
174             curidx *= aac_cb_range[cb];
175             curidx += quants[j] + off;
176         }
177         curbits =  ff_aac_spectral_bits[cb-1][curidx];
178         vec     = &ff_aac_codebook_vectors[cb-1][curidx*dim];
179         if (BT_UNSIGNED) {
180             for (j = 0; j < dim; j++) {
181                 float t = fabsf(in[i+j]);
182                 float di;
183                 if (BT_ESC && vec[j] == 64.0f) { //FIXME: slow
184                     if (t >= CLIPPED_ESCAPE) {
185                         di = t - CLIPPED_ESCAPE;
186                         curbits += 21;
187                     } else {
188                         int c = av_clip_uintp2(quant(t, Q), 13);
189                         di = t - c*cbrtf(c)*IQ;
190                         curbits += av_log2(c)*2 - 4 + 1;
191                     }
192                 } else {
193                     di = t - vec[j]*IQ;
194                 }
195                 if (vec[j] != 0.0f)
196                     curbits++;
197                 rd += di*di;
198             }
199         } else {
200             for (j = 0; j < dim; j++) {
201                 float di = in[i+j] - vec[j]*IQ;
202                 rd += di*di;
203             }
204         }
205         cost    += rd * lambda + curbits;
206         resbits += curbits;
207         if (cost >= uplim)
208             return uplim;
209         if (pb) {
210             put_bits(pb, ff_aac_spectral_bits[cb-1][curidx], ff_aac_spectral_codes[cb-1][curidx]);
211             if (BT_UNSIGNED)
212                 for (j = 0; j < dim; j++)
213                     if (ff_aac_codebook_vectors[cb-1][curidx*dim+j] != 0.0f)
214                         put_bits(pb, 1, in[i+j] < 0.0f);
215             if (BT_ESC) {
216                 for (j = 0; j < 2; j++) {
217                     if (ff_aac_codebook_vectors[cb-1][curidx*2+j] == 64.0f) {
218                         int coef = av_clip_uintp2(quant(fabsf(in[i+j]), Q), 13);
219                         int len = av_log2(coef);
220
221                         put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);
222                         put_sbits(pb, len, coef);
223                     }
224                 }
225             }
226         }
227     }
228
229     if (bits)
230         *bits = resbits;
231     return cost;
232 }
233
234 static float quantize_and_encode_band_cost_NONE(struct AACEncContext *s, PutBitContext *pb,
235                                                 const float *in, const float *scaled,
236                                                 int size, int scale_idx, int cb,
237                                                 const float lambda, const float uplim,
238                                                 int *bits) {
239     av_assert0(0);
240     return 0.0f;
241 }
242
243 #define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, BT_NOISE, BT_STEREO) \
244 static float quantize_and_encode_band_cost_ ## NAME(                                         \
245                                 struct AACEncContext *s,                                     \
246                                 PutBitContext *pb, const float *in,                          \
247                                 const float *scaled, int size, int scale_idx,                \
248                                 int cb, const float lambda, const float uplim,               \
249                                 int *bits) {                                                 \
250     return quantize_and_encode_band_cost_template(                                           \
251                                 s, pb, in, scaled, size, scale_idx,                          \
252                                 BT_ESC ? ESC_BT : cb, lambda, uplim, bits,                   \
253                                 BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, BT_NOISE, BT_STEREO); \
254 }
255
256 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO,  1, 0, 0, 0, 0, 0)
257 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD, 0, 0, 0, 0, 0, 0)
258 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD, 0, 1, 0, 0, 0, 0)
259 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR, 0, 0, 1, 0, 0, 0)
260 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR, 0, 1, 1, 0, 0, 0)
261 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC,   0, 1, 1, 1, 0, 0)
262 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NOISE, 0, 0, 0, 0, 1, 0)
263 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(STEREO,0, 0, 0, 0, 0, 1)
264
265 static float (*const quantize_and_encode_band_cost_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,
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)                    \
292     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)
300 {
301     return quantize_and_encode_band_cost(s, NULL, in, scaled, size, scale_idx,
302                                          cb, lambda, uplim, bits);
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)
308 {
309     quantize_and_encode_band_cost(s, pb, in, NULL, size, scale_idx, cb, lambda,
310                                   INFINITY, NULL);
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);
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+w)*16+swb],
531                                                aac_cb_out_map[cb],
532                                                0, INFINITY, NULL);
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);
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                         bits += b;
900                     }
901                     dists[w*16+g] = dist - bits;
902                     if (prev != -1) {
903                         bits += ff_aac_scalefactor_bits[sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO];
904                     }
905                     tbits += bits;
906                     start += sce->ics.swb_sizes[g];
907                     prev = sce->sf_idx[w*16+g];
908                 }
909             }
910             if (tbits > destbits) {
911                 for (i = 0; i < 128; i++)
912                     if (sce->sf_idx[i] < 218 - qstep)
913                         sce->sf_idx[i] += qstep;
914             } else {
915                 for (i = 0; i < 128; i++)
916                     if (sce->sf_idx[i] > 60 - qstep)
917                         sce->sf_idx[i] -= qstep;
918             }
919             qstep >>= 1;
920             if (!qstep && tbits > destbits*1.02 && sce->sf_idx[0] < 217)
921                 qstep = 1;
922         } while (qstep);
923
924         fflag = 0;
925         minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);
926
927         for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
928             for (g = 0; g < sce->ics.num_swb; g++) {
929                 int prevsc = sce->sf_idx[w*16+g];
930                 if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60) {
931                     if (find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1))
932                         sce->sf_idx[w*16+g]--;
933                     else //Try to make sure there is some energy in every band
934                         sce->sf_idx[w*16+g]-=2;
935                 }
936                 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
937                 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);
938                 if (sce->sf_idx[w*16+g] != prevsc)
939                     fflag = 1;
940                 sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
941             }
942         }
943         its++;
944     } while (fflag && its < 10);
945 }
946
947 static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
948                                        SingleChannelElement *sce,
949                                        const float lambda)
950 {
951     int start = 0, i, w, w2, g;
952     float uplim[128], maxq[128];
953     int minq, maxsf;
954     float distfact = ((sce->ics.num_windows > 1) ? 85.80 : 147.84) / lambda;
955     int last = 0, lastband = 0, curband = 0;
956     float avg_energy = 0.0;
957     if (sce->ics.num_windows == 1) {
958         start = 0;
959         for (i = 0; i < 1024; i++) {
960             if (i - start >= sce->ics.swb_sizes[curband]) {
961                 start += sce->ics.swb_sizes[curband];
962                 curband++;
963             }
964             if (sce->coeffs[i]) {
965                 avg_energy += sce->coeffs[i] * sce->coeffs[i];
966                 last = i;
967                 lastband = curband;
968             }
969         }
970     } else {
971         for (w = 0; w < 8; w++) {
972             const float *coeffs = sce->coeffs + w*128;
973             curband = start = 0;
974             for (i = 0; i < 128; i++) {
975                 if (i - start >= sce->ics.swb_sizes[curband]) {
976                     start += sce->ics.swb_sizes[curband];
977                     curband++;
978                 }
979                 if (coeffs[i]) {
980                     avg_energy += coeffs[i] * coeffs[i];
981                     last = FFMAX(last, i);
982                     lastband = FFMAX(lastband, curband);
983                 }
984             }
985         }
986     }
987     last++;
988     avg_energy /= last;
989     if (avg_energy == 0.0f) {
990         for (i = 0; i < FF_ARRAY_ELEMS(sce->sf_idx); i++)
991             sce->sf_idx[i] = SCALE_ONE_POS;
992         return;
993     }
994     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
995         start = w*128;
996         for (g = 0; g < sce->ics.num_swb; g++) {
997             float *coefs   = sce->coeffs + start;
998             const int size = sce->ics.swb_sizes[g];
999             int start2 = start, end2 = start + size, peakpos = start;
1000             float maxval = -1, thr = 0.0f, t;
1001             maxq[w*16+g] = 0.0f;
1002             if (g > lastband) {
1003                 maxq[w*16+g] = 0.0f;
1004                 start += size;
1005                 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
1006                     memset(coefs + w2*128, 0, sizeof(coefs[0])*size);
1007                 continue;
1008             }
1009             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
1010                 for (i = 0; i < size; i++) {
1011                     float t = coefs[w2*128+i]*coefs[w2*128+i];
1012                     maxq[w*16+g] = FFMAX(maxq[w*16+g], fabsf(coefs[w2*128 + i]));
1013                     thr += t;
1014                     if (sce->ics.num_windows == 1 && maxval < t) {
1015                         maxval  = t;
1016                         peakpos = start+i;
1017                     }
1018                 }
1019             }
1020             if (sce->ics.num_windows == 1) {
1021                 start2 = FFMAX(peakpos - 2, start2);
1022                 end2   = FFMIN(peakpos + 3, end2);
1023             } else {
1024                 start2 -= start;
1025                 end2   -= start;
1026             }
1027             start += size;
1028             thr = pow(thr / (avg_energy * (end2 - start2)), 0.3 + 0.1*(lastband - g) / lastband);
1029             t   = 1.0 - (1.0 * start2 / last);
1030             uplim[w*16+g] = distfact / (1.4 * thr + t*t*t + 0.075);
1031         }
1032     }
1033     memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
1034     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
1035     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
1036         start = w*128;
1037         for (g = 0;  g < sce->ics.num_swb; g++) {
1038             const float *coefs  = sce->coeffs + start;
1039             const float *scaled = s->scoefs   + start;
1040             const int size      = sce->ics.swb_sizes[g];
1041             int scf, prev_scf, step;
1042             int min_scf = -1, max_scf = 256;
1043             float curdiff;
1044             if (maxq[w*16+g] < 21.544) {
1045                 sce->zeroes[w*16+g] = 1;
1046                 start += size;
1047                 continue;
1048             }
1049             sce->zeroes[w*16+g] = 0;
1050             scf  = prev_scf = av_clip(SCALE_ONE_POS - SCALE_DIV_512 - log2f(1/maxq[w*16+g])*16/3, 60, 218);
1051             for (;;) {
1052                 float dist = 0.0f;
1053                 int quant_max;
1054
1055                 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
1056                     int b;
1057                     dist += quantize_band_cost(s, coefs + w2*128,
1058                                                scaled + w2*128,
1059                                                sce->ics.swb_sizes[g],
1060                                                scf,
1061                                                ESC_BT,
1062                                                lambda,
1063                                                INFINITY,
1064                                                &b);
1065                     dist -= b;
1066                 }
1067                 dist *= 1.0f / 512.0f / lambda;
1068                 quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512]);
1069                 if (quant_max >= 8191) { // too much, return to the previous quantizer
1070                     sce->sf_idx[w*16+g] = prev_scf;
1071                     break;
1072                 }
1073                 prev_scf = scf;
1074                 curdiff = fabsf(dist - uplim[w*16+g]);
1075                 if (curdiff <= 1.0f)
1076                     step = 0;
1077                 else
1078                     step = log2f(curdiff);
1079                 if (dist > uplim[w*16+g])
1080                     step = -step;
1081                 scf += step;
1082                 scf = av_clip_uint8(scf);
1083                 step = scf - prev_scf;
1084                 if (FFABS(step) <= 1 || (step > 0 && scf >= max_scf) || (step < 0 && scf <= min_scf)) {
1085                     sce->sf_idx[w*16+g] = av_clip(scf, min_scf, max_scf);
1086                     break;
1087                 }
1088                 if (step > 0)
1089                     min_scf = prev_scf;
1090                 else
1091                     max_scf = prev_scf;
1092             }
1093             start += size;
1094         }
1095     }
1096     minq = sce->sf_idx[0] ? sce->sf_idx[0] : INT_MAX;
1097     for (i = 1; i < 128; i++) {
1098         if (!sce->sf_idx[i])
1099             sce->sf_idx[i] = sce->sf_idx[i-1];
1100         else
1101             minq = FFMIN(minq, sce->sf_idx[i]);
1102     }
1103     if (minq == INT_MAX)
1104         minq = 0;
1105     minq = FFMIN(minq, SCALE_MAX_POS);
1106     maxsf = FFMIN(minq + SCALE_MAX_DIFF, SCALE_MAX_POS);
1107     for (i = 126; i >= 0; i--) {
1108         if (!sce->sf_idx[i])
1109             sce->sf_idx[i] = sce->sf_idx[i+1];
1110         sce->sf_idx[i] = av_clip(sce->sf_idx[i], minq, maxsf);
1111     }
1112 }
1113
1114 static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,
1115                                        SingleChannelElement *sce,
1116                                        const float lambda)
1117 {
1118     int i, w, w2, g;
1119     int minq = 255;
1120
1121     memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
1122     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
1123         for (g = 0; g < sce->ics.num_swb; g++) {
1124             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
1125                 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
1126                 if (band->energy <= band->threshold) {
1127                     sce->sf_idx[(w+w2)*16+g] = 218;
1128                     sce->zeroes[(w+w2)*16+g] = 1;
1129                 } else {
1130                     sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2f(band->threshold), 80, 218);
1131                     sce->zeroes[(w+w2)*16+g] = 0;
1132                 }
1133                 minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
1134             }
1135         }
1136     }
1137     for (i = 0; i < 128; i++) {
1138         sce->sf_idx[i] = 140;
1139         //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);
1140     }
1141     //set the same quantizers inside window groups
1142     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
1143         for (g = 0;  g < sce->ics.num_swb; g++)
1144             for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
1145                 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
1146 }
1147
1148 static void search_for_pns(AACEncContext *s, AVCodecContext *avctx, SingleChannelElement *sce,
1149                            const float lambda)
1150 {
1151     int start = 0, w, w2, g;
1152     const float freq_mult = avctx->sample_rate/(1024.0f/sce->ics.num_windows)/2.0f;
1153     const float spread_threshold = NOISE_SPREAD_THRESHOLD*(lambda/120.f);
1154     const float thr_mult = NOISE_LAMBDA_NUMERATOR/lambda;
1155
1156     /* Coders !twoloop don't reset the band_types */
1157     for (w = 0; w < 128; w++)
1158         if (sce->band_type[w] == NOISE_BT)
1159             sce->band_type[w] = 0;
1160
1161     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
1162         start = 0;
1163         for (g = 0;  g < sce->ics.num_swb; g++) {
1164             if (start*freq_mult > NOISE_LOW_LIMIT*(lambda/170.0f)) {
1165                 float energy = 0.0f, threshold = 0.0f, spread = 0.0f;
1166                 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
1167                     FFPsyBand *band = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
1168                     energy += band->energy;
1169                     threshold += band->threshold;
1170                     spread += band->spread;
1171                 }
1172                 if (spread > spread_threshold*sce->ics.group_len[w] &&
1173                     ((sce->zeroes[w*16+g] && energy >= threshold) ||
1174                     energy < threshold*thr_mult*sce->ics.group_len[w])) {
1175                     sce->band_type[w*16+g] = NOISE_BT;
1176                     sce->pns_ener[w*16+g] = energy / sce->ics.group_len[w];
1177                     sce->zeroes[w*16+g] = 0;
1178                 }
1179             }
1180             start += sce->ics.swb_sizes[g];
1181         }
1182     }
1183 }
1184
1185 static void search_for_is(AACEncContext *s, AVCodecContext *avctx, ChannelElement *cpe,
1186                           const float lambda)
1187 {
1188     float IS[128];
1189     float *L34  = s->scoefs + 128*0, *R34  = s->scoefs + 128*1;
1190     float *I34  = s->scoefs + 128*2;
1191     SingleChannelElement *sce0 = &cpe->ch[0];
1192     SingleChannelElement *sce1 = &cpe->ch[1];
1193     int start = 0, count = 0, i, w, w2, g;
1194     const float freq_mult = avctx->sample_rate/(1024.0f/sce0->ics.num_windows)/2.0f;
1195
1196     for (w = 0; w < 128; w++)
1197         if (sce1->band_type[w] >= INTENSITY_BT2)
1198             sce1->band_type[w] = 0;
1199
1200     if (!cpe->common_window)
1201         return;
1202     for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
1203         start = 0;
1204         for (g = 0;  g < sce0->ics.num_swb; g++) {
1205             if (start*freq_mult > INT_STEREO_LOW_LIMIT*(lambda/170.0f) &&
1206                 cpe->ch[0].band_type[w*16+g] != NOISE_BT && !cpe->ch[0].zeroes[w*16+g] &&
1207                 cpe->ch[1].band_type[w*16+g] != NOISE_BT && !cpe->ch[1].zeroes[w*16+g]) {
1208                 int phase = 0;
1209                 float ener0 = 0.0f, ener1 = 0.0f, ener01 = 0.0f;
1210                 float dist1 = 0.0f, dist2 = 0.0f;
1211                 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
1212                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
1213                         float coef0 = sce0->pcoeffs[start+(w+w2)*128+i];
1214                         float coef1 = sce1->pcoeffs[start+(w+w2)*128+i];
1215                         phase += coef0*coef1 >= 0.0f ? 1 : -1;
1216                         ener0 += coef0*coef0;
1217                         ener1 += coef1*coef1;
1218                         ener01 += (coef0 + coef1)*(coef0 + coef1);
1219                     }
1220                 }
1221                 if (!phase) { /* Too much phase difference between channels */
1222                     start += sce0->ics.swb_sizes[g];
1223                     continue;
1224                 }
1225                 phase = av_clip(phase, -1, 1);
1226                 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
1227                     FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
1228                     FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
1229                     int is_band_type, is_sf_idx = FFMAX(1, sce0->sf_idx[(w+w2)*16+g]-4);
1230                     float e01_34 = phase*pow(sqrt(ener1/ener0), 3.0/4.0);
1231                     float maxval, dist_spec_err = 0.0f;
1232                     float minthr = FFMIN(band0->threshold, band1->threshold);
1233                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++)
1234                         IS[i] = (sce0->pcoeffs[start+(w+w2)*128+i] + phase*sce1->pcoeffs[start+(w+w2)*128+i]) * sqrt(ener0/ener01);
1235                     abs_pow34_v(L34, sce0->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
1236                     abs_pow34_v(R34, sce1->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
1237                     abs_pow34_v(I34, IS,                            sce0->ics.swb_sizes[g]);
1238                     maxval = find_max_val(1, sce0->ics.swb_sizes[g], I34);
1239                     is_band_type = find_min_book(maxval, is_sf_idx);
1240                     dist1 += quantize_band_cost(s, sce0->coeffs + start + (w+w2)*128,
1241                                                 L34,
1242                                                 sce0->ics.swb_sizes[g],
1243                                                 sce0->sf_idx[(w+w2)*16+g],
1244                                                 sce0->band_type[(w+w2)*16+g],
1245                                                 lambda / band0->threshold, INFINITY, NULL);
1246                     dist1 += quantize_band_cost(s, sce1->coeffs + start + (w+w2)*128,
1247                                                 R34,
1248                                                 sce1->ics.swb_sizes[g],
1249                                                 sce1->sf_idx[(w+w2)*16+g],
1250                                                 sce1->band_type[(w+w2)*16+g],
1251                                                 lambda / band1->threshold, INFINITY, NULL);
1252                     dist2 += quantize_band_cost(s, IS,
1253                                                 I34,
1254                                                 sce0->ics.swb_sizes[g],
1255                                                 is_sf_idx,
1256                                                 is_band_type,
1257                                                 lambda / minthr, INFINITY, NULL);
1258                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
1259                         dist_spec_err += (L34[i] - I34[i])*(L34[i] - I34[i]);
1260                         dist_spec_err += (R34[i] - I34[i]*e01_34)*(R34[i] - I34[i]*e01_34);
1261                     }
1262                     dist_spec_err *= lambda / minthr;
1263                     dist2 += dist_spec_err;
1264                 }
1265                 if (dist2 <= dist1) {
1266                     cpe->is_mask[w*16+g] = 1;
1267                     cpe->ms_mask[w*16+g] = 0;
1268                     cpe->ch[0].is_ener[w*16+g] = sqrt(ener0/ener01);
1269                     cpe->ch[1].is_ener[w*16+g] = ener0/ener1;
1270                     if (phase)
1271                         cpe->ch[1].band_type[w*16+g] = INTENSITY_BT;
1272                     else
1273                         cpe->ch[1].band_type[w*16+g] = INTENSITY_BT2;
1274                     count++;
1275                 }
1276             }
1277             start += sce0->ics.swb_sizes[g];
1278         }
1279     }
1280     cpe->is_mode = !!count;
1281 }
1282
1283 static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
1284                           const float lambda)
1285 {
1286     int start = 0, i, w, w2, g;
1287     float M[128], S[128];
1288     float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
1289     SingleChannelElement *sce0 = &cpe->ch[0];
1290     SingleChannelElement *sce1 = &cpe->ch[1];
1291     if (!cpe->common_window)
1292         return;
1293     for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
1294         start = 0;
1295         for (g = 0;  g < sce0->ics.num_swb; g++) {
1296             if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g] && !cpe->is_mask[w*16+g]) {
1297                 float dist1 = 0.0f, dist2 = 0.0f;
1298                 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
1299                     FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
1300                     FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
1301                     float minthr = FFMIN(band0->threshold, band1->threshold);
1302                     float maxthr = FFMAX(band0->threshold, band1->threshold);
1303                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
1304                         M[i] = (sce0->pcoeffs[start+(w+w2)*128+i]
1305                               + sce1->pcoeffs[start+(w+w2)*128+i]) * 0.5;
1306                         S[i] =  M[i]
1307                               - sce1->pcoeffs[start+(w+w2)*128+i];
1308                     }
1309                     abs_pow34_v(L34, sce0->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
1310                     abs_pow34_v(R34, sce1->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
1311                     abs_pow34_v(M34, M,                         sce0->ics.swb_sizes[g]);
1312                     abs_pow34_v(S34, S,                         sce0->ics.swb_sizes[g]);
1313                     dist1 += quantize_band_cost(s, sce0->coeffs + start + (w+w2)*128,
1314                                                 L34,
1315                                                 sce0->ics.swb_sizes[g],
1316                                                 sce0->sf_idx[(w+w2)*16+g],
1317                                                 sce0->band_type[(w+w2)*16+g],
1318                                                 lambda / band0->threshold, INFINITY, NULL);
1319                     dist1 += quantize_band_cost(s, sce1->coeffs + start + (w+w2)*128,
1320                                                 R34,
1321                                                 sce1->ics.swb_sizes[g],
1322                                                 sce1->sf_idx[(w+w2)*16+g],
1323                                                 sce1->band_type[(w+w2)*16+g],
1324                                                 lambda / band1->threshold, INFINITY, NULL);
1325                     dist2 += quantize_band_cost(s, M,
1326                                                 M34,
1327                                                 sce0->ics.swb_sizes[g],
1328                                                 sce0->sf_idx[(w+w2)*16+g],
1329                                                 sce0->band_type[(w+w2)*16+g],
1330                                                 lambda / maxthr, INFINITY, NULL);
1331                     dist2 += quantize_band_cost(s, S,
1332                                                 S34,
1333                                                 sce1->ics.swb_sizes[g],
1334                                                 sce1->sf_idx[(w+w2)*16+g],
1335                                                 sce1->band_type[(w+w2)*16+g],
1336                                                 lambda / minthr, INFINITY, NULL);
1337                 }
1338                 cpe->ms_mask[w*16+g] = dist2 < dist1;
1339             }
1340             start += sce0->ics.swb_sizes[g];
1341         }
1342     }
1343 }
1344
1345 AACCoefficientsEncoder ff_aac_coders[AAC_CODER_NB] = {
1346     [AAC_CODER_FAAC] = {
1347         search_for_quantizers_faac,
1348         encode_window_bands_info,
1349         quantize_and_encode_band,
1350         set_special_band_scalefactors,
1351         search_for_pns,
1352         search_for_ms,
1353         search_for_is,
1354     },
1355     [AAC_CODER_ANMR] = {
1356         search_for_quantizers_anmr,
1357         encode_window_bands_info,
1358         quantize_and_encode_band,
1359         set_special_band_scalefactors,
1360         search_for_pns,
1361         search_for_ms,
1362         search_for_is,
1363     },
1364     [AAC_CODER_TWOLOOP] = {
1365         search_for_quantizers_twoloop,
1366         codebook_trellis_rate,
1367         quantize_and_encode_band,
1368         set_special_band_scalefactors,
1369         search_for_pns,
1370         search_for_ms,
1371         search_for_is,
1372     },
1373     [AAC_CODER_FAST] = {
1374         search_for_quantizers_fast,
1375         encode_window_bands_info,
1376         quantize_and_encode_band,
1377         set_special_band_scalefactors,
1378         search_for_pns,
1379         search_for_ms,
1380         search_for_is,
1381     },
1382 };