]> git.sesse.net Git - ffmpeg/blob - libavcodec/aaccoder.c
Remove misplaced Doxygen comment.
[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 <float.h>
34 #include "avcodec.h"
35 #include "put_bits.h"
36 #include "aac.h"
37 #include "aacenc.h"
38 #include "aactab.h"
39
40 /** bits needed to code codebook run value for long windows */
41 static const uint8_t run_value_bits_long[64] = {
42      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
43      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5, 10,
44     10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
45     10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 15
46 };
47
48 /** bits needed to code codebook run value for short windows */
49 static const uint8_t run_value_bits_short[16] = {
50     3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 6, 6, 9
51 };
52
53 static const uint8_t *run_value_bits[2] = {
54     run_value_bits_long, run_value_bits_short
55 };
56
57
58 /**
59  * Quantize one coefficient.
60  * @return absolute value of the quantized coefficient
61  * @see 3GPP TS26.403 5.6.2 "Scalefactor determination"
62  */
63 static av_always_inline int quant(float coef, const float Q)
64 {
65     float a = coef * Q;
66     return sqrtf(a * sqrtf(a)) + 0.4054;
67 }
68
69 static void quantize_bands(int *out, const float *in, const float *scaled,
70                            int size, float Q34, int is_signed, int maxval)
71 {
72     int i;
73     double qc;
74     for (i = 0; i < size; i++) {
75         qc = scaled[i] * Q34;
76         out[i] = (int)FFMIN(qc + 0.4054, (double)maxval);
77         if (is_signed && in[i] < 0.0f) {
78             out[i] = -out[i];
79         }
80     }
81 }
82
83 static void abs_pow34_v(float *out, const float *in, const int size)
84 {
85 #ifndef USE_REALLY_FULL_SEARCH
86     int i;
87     for (i = 0; i < size; i++) {
88         float a = fabsf(in[i]);
89         out[i] = sqrtf(a * sqrtf(a));
90     }
91 #endif /* USE_REALLY_FULL_SEARCH */
92 }
93
94 static const uint8_t aac_cb_range [12] = {0, 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17};
95 static const uint8_t aac_cb_maxval[12] = {0, 1, 1, 2, 2, 4, 4, 7, 7, 12, 12, 16};
96
97 /**
98  * Calculate rate distortion cost for quantizing with given codebook
99  *
100  * @return quantization distortion
101  */
102 static float quantize_and_encode_band_cost(struct AACEncContext *s,
103                                 PutBitContext *pb, const float *in,
104                                 const float *scaled, int size, int scale_idx,
105                                 int cb, const float lambda, const float uplim,
106                                 int *bits)
107 {
108     const float IQ = ff_aac_pow2sf_tab[200 + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];
109     const float  Q = ff_aac_pow2sf_tab[200 - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];
110     const float CLIPPED_ESCAPE = 165140.0f*IQ;
111     int i, j, k;
112     float cost = 0;
113     const int dim = cb < FIRST_PAIR_BT ? 4 : 2;
114     int resbits = 0;
115     const float  Q34 = sqrtf(Q * sqrtf(Q));
116     const int range  = aac_cb_range[cb];
117     const int maxval = aac_cb_maxval[cb];
118     int off;
119
120     if (!cb) {
121         for (i = 0; i < size; i++)
122             cost += in[i]*in[i];
123         if (bits)
124             *bits = 0;
125         return cost * lambda;
126     }
127     if (!scaled) {
128         abs_pow34_v(s->scoefs, in, size);
129         scaled = s->scoefs;
130     }
131     quantize_bands(s->qcoefs, in, scaled, size, Q34, !IS_CODEBOOK_UNSIGNED(cb), maxval);
132     if (IS_CODEBOOK_UNSIGNED(cb)) {
133         off = 0;
134     } else {
135         off = maxval;
136     }
137     for (i = 0; i < size; i += dim) {
138         const float *vec;
139         int *quants = s->qcoefs + i;
140         int curidx = 0;
141         int curbits;
142         float rd = 0.0f;
143         for (j = 0; j < dim; j++) {
144             curidx *= range;
145             curidx += quants[j] + off;
146         }
147             curbits =  ff_aac_spectral_bits[cb-1][curidx];
148             vec     = &ff_aac_codebook_vectors[cb-1][curidx*dim];
149             if (IS_CODEBOOK_UNSIGNED(cb)) {
150                 for (k = 0; k < dim; k++) {
151                     float t = fabsf(in[i+k]);
152                     float di;
153                     if (vec[k] == 64.0f) { //FIXME: slow
154                         if (t >= CLIPPED_ESCAPE) {
155                             di = t - CLIPPED_ESCAPE;
156                             curbits += 21;
157                         } else {
158                             int c = av_clip(quant(t, Q), 0, 8191);
159                             di = t - c*cbrtf(c)*IQ;
160                             curbits += av_log2(c)*2 - 4 + 1;
161                         }
162                     } else {
163                         di = t - vec[k]*IQ;
164                     }
165                     if (vec[k] != 0.0f)
166                         curbits++;
167                     rd += di*di;
168                 }
169             } else {
170                 for (k = 0; k < dim; k++) {
171                     float di = in[i+k] - vec[k]*IQ;
172                     rd += di*di;
173                 }
174             }
175         cost    += rd * lambda + curbits;
176         resbits += curbits;
177         if (cost >= uplim)
178             return uplim;
179         if (pb) {
180         put_bits(pb, ff_aac_spectral_bits[cb-1][curidx], ff_aac_spectral_codes[cb-1][curidx]);
181         if (IS_CODEBOOK_UNSIGNED(cb))
182             for (j = 0; j < dim; j++)
183                 if (ff_aac_codebook_vectors[cb-1][curidx*dim+j] != 0.0f)
184                     put_bits(pb, 1, in[i+j] < 0.0f);
185         if (cb == ESC_BT) {
186             for (j = 0; j < 2; j++) {
187                 if (ff_aac_codebook_vectors[cb-1][curidx*2+j] == 64.0f) {
188                     int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191);
189                     int len = av_log2(coef);
190
191                     put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);
192                     put_bits(pb, len, coef & ((1 << len) - 1));
193                 }
194             }
195         }
196         }
197     }
198
199     if (bits)
200         *bits = resbits;
201     return cost;
202 }
203 static float quantize_band_cost(struct AACEncContext *s, const float *in,
204                                 const float *scaled, int size, int scale_idx,
205                                 int cb, const float lambda, const float uplim,
206                                 int *bits)
207 {
208     return quantize_and_encode_band_cost(s, NULL, in, scaled, size, scale_idx,
209                                          cb, lambda, uplim, bits);
210 }
211
212 static void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb,
213                                      const float *in, int size, int scale_idx,
214                                      int cb, const float lambda)
215 {
216     quantize_and_encode_band_cost(s, pb, in, NULL, size, scale_idx, cb, lambda,
217                                   INFINITY, NULL);
218 }
219
220 static float find_max_val(int group_len, int swb_size, const float *scaled) {
221     float maxval = 0.0f;
222     int w2, i;
223     for (w2 = 0; w2 < group_len; w2++) {
224         for (i = 0; i < swb_size; i++) {
225             maxval = FFMAX(maxval, scaled[w2*128+i]);
226         }
227     }
228     return maxval;
229 }
230
231 static int find_min_book(float maxval, int sf) {
232     float Q = ff_aac_pow2sf_tab[200 - sf + SCALE_ONE_POS - SCALE_DIV_512];
233     float Q34 = sqrtf(Q * sqrtf(Q));
234     int qmaxval, cb;
235     qmaxval = maxval * Q34 + 0.4054f;
236     if      (qmaxval ==  0) cb = 0;
237     else if (qmaxval ==  1) cb = 1;
238     else if (qmaxval ==  2) cb = 3;
239     else if (qmaxval <=  4) cb = 5;
240     else if (qmaxval <=  7) cb = 7;
241     else if (qmaxval <= 12) cb = 9;
242     else                    cb = 11;
243     return cb;
244 }
245
246 /**
247  * structure used in optimal codebook search
248  */
249 typedef struct BandCodingPath {
250     int prev_idx; ///< pointer to the previous path point
251     float cost;   ///< path cost
252     int run;
253 } BandCodingPath;
254
255 /**
256  * Encode band info for single window group bands.
257  */
258 static void encode_window_bands_info(AACEncContext *s, SingleChannelElement *sce,
259                                      int win, int group_len, const float lambda)
260 {
261     BandCodingPath path[120][12];
262     int w, swb, cb, start, start2, size;
263     int i, j;
264     const int max_sfb  = sce->ics.max_sfb;
265     const int run_bits = sce->ics.num_windows == 1 ? 5 : 3;
266     const int run_esc  = (1 << run_bits) - 1;
267     int idx, ppos, count;
268     int stackrun[120], stackcb[120], stack_len;
269     float next_minrd = INFINITY;
270     int next_mincb = 0;
271
272     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
273     start = win*128;
274     for (cb = 0; cb < 12; cb++) {
275         path[0][cb].cost     = 0.0f;
276         path[0][cb].prev_idx = -1;
277         path[0][cb].run      = 0;
278     }
279     for (swb = 0; swb < max_sfb; swb++) {
280         start2 = start;
281         size = sce->ics.swb_sizes[swb];
282         if (sce->zeroes[win*16 + swb]) {
283             for (cb = 0; cb < 12; cb++) {
284                 path[swb+1][cb].prev_idx = cb;
285                 path[swb+1][cb].cost     = path[swb][cb].cost;
286                 path[swb+1][cb].run      = path[swb][cb].run + 1;
287             }
288         } else {
289             float minrd = next_minrd;
290             int mincb = next_mincb;
291             next_minrd = INFINITY;
292             next_mincb = 0;
293             for (cb = 0; cb < 12; cb++) {
294                 float cost_stay_here, cost_get_here;
295                 float rd = 0.0f;
296                 for (w = 0; w < group_len; w++) {
297                     FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(win+w)*16+swb];
298                     rd += quantize_band_cost(s, sce->coeffs + start + w*128,
299                                              s->scoefs + start + w*128, size,
300                                              sce->sf_idx[(win+w)*16+swb], cb,
301                                              lambda / band->threshold, INFINITY, NULL);
302                 }
303                 cost_stay_here = path[swb][cb].cost + rd;
304                 cost_get_here  = minrd              + rd + run_bits + 4;
305                 if (   run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run]
306                     != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1])
307                     cost_stay_here += run_bits;
308                 if (cost_get_here < cost_stay_here) {
309                     path[swb+1][cb].prev_idx = mincb;
310                     path[swb+1][cb].cost     = cost_get_here;
311                     path[swb+1][cb].run      = 1;
312                 } else {
313                     path[swb+1][cb].prev_idx = cb;
314                     path[swb+1][cb].cost     = cost_stay_here;
315                     path[swb+1][cb].run      = path[swb][cb].run + 1;
316                 }
317                 if (path[swb+1][cb].cost < next_minrd) {
318                     next_minrd = path[swb+1][cb].cost;
319                     next_mincb = cb;
320                 }
321             }
322         }
323         start += sce->ics.swb_sizes[swb];
324     }
325
326     //convert resulting path from backward-linked list
327     stack_len = 0;
328     idx       = 0;
329     for (cb = 1; cb < 12; cb++)
330         if (path[max_sfb][cb].cost < path[max_sfb][idx].cost)
331             idx = cb;
332     ppos = max_sfb;
333     while (ppos > 0) {
334         cb = idx;
335         stackrun[stack_len] = path[ppos][cb].run;
336         stackcb [stack_len] = cb;
337         idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx;
338         ppos -= path[ppos][cb].run;
339         stack_len++;
340     }
341     //perform actual band info encoding
342     start = 0;
343     for (i = stack_len - 1; i >= 0; i--) {
344         put_bits(&s->pb, 4, stackcb[i]);
345         count = stackrun[i];
346         memset(sce->zeroes + win*16 + start, !stackcb[i], count);
347         //XXX: memset when band_type is also uint8_t
348         for (j = 0; j < count; j++) {
349             sce->band_type[win*16 + start] =  stackcb[i];
350             start++;
351         }
352         while (count >= run_esc) {
353             put_bits(&s->pb, run_bits, run_esc);
354             count -= run_esc;
355         }
356         put_bits(&s->pb, run_bits, count);
357     }
358 }
359
360 static void codebook_trellis_rate(AACEncContext *s, SingleChannelElement *sce,
361                                   int win, int group_len, const float lambda)
362 {
363     BandCodingPath path[120][12];
364     int w, swb, cb, start, start2, size;
365     int i, j;
366     const int max_sfb  = sce->ics.max_sfb;
367     const int run_bits = sce->ics.num_windows == 1 ? 5 : 3;
368     const int run_esc  = (1 << run_bits) - 1;
369     int idx, ppos, count;
370     int stackrun[120], stackcb[120], stack_len;
371     float next_minrd = INFINITY;
372     int next_mincb = 0;
373
374     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
375     start = win*128;
376     for (cb = 0; cb < 12; cb++) {
377         path[0][cb].cost     = run_bits+4;
378         path[0][cb].prev_idx = -1;
379         path[0][cb].run      = 0;
380     }
381     for (swb = 0; swb < max_sfb; swb++) {
382         start2 = start;
383         size = sce->ics.swb_sizes[swb];
384         if (sce->zeroes[win*16 + swb]) {
385             for (cb = 0; cb < 12; cb++) {
386                 path[swb+1][cb].prev_idx = cb;
387                 path[swb+1][cb].cost     = path[swb][cb].cost;
388                 path[swb+1][cb].run      = path[swb][cb].run + 1;
389             }
390         } else {
391             float minrd = next_minrd;
392             int mincb = next_mincb;
393             int startcb = sce->band_type[win*16+swb];
394             next_minrd = INFINITY;
395             next_mincb = 0;
396             for (cb = 0; cb < startcb; cb++) {
397                 path[swb+1][cb].cost = 61450;
398                 path[swb+1][cb].prev_idx = -1;
399                 path[swb+1][cb].run = 0;
400             }
401             for (cb = startcb; cb < 12; cb++) {
402                 float cost_stay_here, cost_get_here;
403                 float rd = 0.0f;
404                 for (w = 0; w < group_len; w++) {
405                     rd += quantize_band_cost(s, sce->coeffs + start + w*128,
406                                              s->scoefs + start + w*128, size,
407                                              sce->sf_idx[(win+w)*16+swb], cb,
408                                              0, INFINITY, NULL);
409                 }
410                 cost_stay_here = path[swb][cb].cost + rd;
411                 cost_get_here  = minrd              + rd + run_bits + 4;
412                 if (   run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run]
413                     != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1])
414                     cost_stay_here += run_bits;
415                 if (cost_get_here < cost_stay_here) {
416                     path[swb+1][cb].prev_idx = mincb;
417                     path[swb+1][cb].cost     = cost_get_here;
418                     path[swb+1][cb].run      = 1;
419                 } else {
420                     path[swb+1][cb].prev_idx = cb;
421                     path[swb+1][cb].cost     = cost_stay_here;
422                     path[swb+1][cb].run      = path[swb][cb].run + 1;
423                 }
424                 if (path[swb+1][cb].cost < next_minrd) {
425                     next_minrd = path[swb+1][cb].cost;
426                     next_mincb = cb;
427                 }
428             }
429         }
430         start += sce->ics.swb_sizes[swb];
431     }
432
433     //convert resulting path from backward-linked list
434     stack_len = 0;
435     idx       = 0;
436     for (cb = 1; cb < 12; cb++)
437         if (path[max_sfb][cb].cost < path[max_sfb][idx].cost)
438             idx = cb;
439     ppos = max_sfb;
440     while (ppos > 0) {
441         if (idx < 0) abort();
442         cb = idx;
443         stackrun[stack_len] = path[ppos][cb].run;
444         stackcb [stack_len] = cb;
445         idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx;
446         ppos -= path[ppos][cb].run;
447         stack_len++;
448     }
449     //perform actual band info encoding
450     start = 0;
451     for (i = stack_len - 1; i >= 0; i--) {
452         put_bits(&s->pb, 4, stackcb[i]);
453         count = stackrun[i];
454         memset(sce->zeroes + win*16 + start, !stackcb[i], count);
455         //XXX: memset when band_type is also uint8_t
456         for (j = 0; j < count; j++) {
457             sce->band_type[win*16 + start] =  stackcb[i];
458             start++;
459         }
460         while (count >= run_esc) {
461             put_bits(&s->pb, run_bits, run_esc);
462             count -= run_esc;
463         }
464         put_bits(&s->pb, run_bits, count);
465     }
466 }
467
468 typedef struct TrellisPath {
469     float cost;
470     int prev;
471 } TrellisPath;
472
473 #define TRELLIS_STAGES 121
474 #define TRELLIS_STATES (SCALE_MAX_DIFF+1)
475
476 static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,
477                                        SingleChannelElement *sce,
478                                        const float lambda)
479 {
480     int q, w, w2, g, start = 0;
481     int i, j;
482     int idx;
483     TrellisPath paths[TRELLIS_STAGES][TRELLIS_STATES];
484     int bandaddr[TRELLIS_STAGES];
485     int minq;
486     float mincost;
487     float q0f = FLT_MAX, q1f = 0.0f, qnrgf = 0.0f;
488     int q0, q1, qcnt = 0;
489
490     for (i = 0; i < 1024; i++) {
491         float t = fabsf(sce->coeffs[i]);
492         if (t > 0.0f) {
493             q0f = FFMIN(q0f, t);
494             q1f = FFMAX(q1f, t);
495             qnrgf += t*t;
496             qcnt++;
497         }
498     }
499
500     if (!qcnt) {
501         memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
502         memset(sce->zeroes, 1, sizeof(sce->zeroes));
503         return;
504     }
505
506     //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
507     q0 = av_clip_uint8(log2(q0f)*4 - 69 + SCALE_ONE_POS - SCALE_DIV_512);
508     //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
509     q1 = av_clip_uint8(log2(q1f)*4 +  6 + SCALE_ONE_POS - SCALE_DIV_512);
510     //av_log(NULL, AV_LOG_ERROR, "q0 %d, q1 %d\n", q0, q1);
511     if (q1 - q0 > 60) {
512         int q0low  = q0;
513         int q1high = q1;
514         //minimum scalefactor index is when maximum nonzero coefficient after quantizing is not clipped
515         int qnrg = av_clip_uint8(log2(sqrt(qnrgf/qcnt))*4 - 31 + SCALE_ONE_POS - SCALE_DIV_512);
516         q1 = qnrg + 30;
517         q0 = qnrg - 30;
518     //av_log(NULL, AV_LOG_ERROR, "q0 %d, q1 %d\n", q0, q1);
519         if (q0 < q0low) {
520             q1 += q0low - q0;
521             q0  = q0low;
522         } else if (q1 > q1high) {
523             q0 -= q1 - q1high;
524             q1  = q1high;
525         }
526     }
527     //av_log(NULL, AV_LOG_ERROR, "q0 %d, q1 %d\n", q0, q1);
528
529     for (i = 0; i < TRELLIS_STATES; i++) {
530         paths[0][i].cost    = 0.0f;
531         paths[0][i].prev    = -1;
532     }
533     for (j = 1; j < TRELLIS_STAGES; j++) {
534         for (i = 0; i < TRELLIS_STATES; i++) {
535             paths[j][i].cost    = INFINITY;
536             paths[j][i].prev    = -2;
537         }
538     }
539     idx = 1;
540     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
541     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
542         start = w*128;
543         for (g = 0; g < sce->ics.num_swb; g++) {
544             const float *coefs = sce->coeffs + start;
545             float qmin, qmax;
546             int nz = 0;
547
548             bandaddr[idx] = w * 16 + g;
549             qmin = INT_MAX;
550             qmax = 0.0f;
551             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
552                 FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
553                 if (band->energy <= band->threshold || band->threshold == 0.0f) {
554                     sce->zeroes[(w+w2)*16+g] = 1;
555                     continue;
556                 }
557                 sce->zeroes[(w+w2)*16+g] = 0;
558                 nz = 1;
559                 for (i = 0; i < sce->ics.swb_sizes[g]; i++) {
560                     float t = fabsf(coefs[w2*128+i]);
561                     if (t > 0.0f)
562                         qmin = FFMIN(qmin, t);
563                     qmax = FFMAX(qmax, t);
564                 }
565             }
566             if (nz) {
567                 int minscale, maxscale;
568                 float minrd = INFINITY;
569                 float maxval;
570                 //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
571                 minscale = av_clip_uint8(log2(qmin)*4 - 69 + SCALE_ONE_POS - SCALE_DIV_512);
572                 //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
573                 maxscale = av_clip_uint8(log2(qmax)*4 +  6 + SCALE_ONE_POS - SCALE_DIV_512);
574                 minscale = av_clip(minscale - q0, 0, TRELLIS_STATES - 1);
575                 maxscale = av_clip(maxscale - q0, 0, TRELLIS_STATES);
576                 maxval = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], s->scoefs+start);
577                 for (q = minscale; q < maxscale; q++) {
578                     float dist = 0;
579                     int cb = find_min_book(maxval, sce->sf_idx[w*16+g]);
580                     for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
581                         FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
582                         dist += quantize_band_cost(s, coefs + w2*128, s->scoefs + start + w2*128, sce->ics.swb_sizes[g],
583                                                    q + q0, cb, lambda / band->threshold, INFINITY, NULL);
584                     }
585                     minrd = FFMIN(minrd, dist);
586
587                     for (i = 0; i < q1 - q0; i++) {
588                         float cost;
589                         cost = paths[idx - 1][i].cost + dist
590                                + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
591                         if (cost < paths[idx][q].cost) {
592                             paths[idx][q].cost    = cost;
593                             paths[idx][q].prev    = i;
594                         }
595                     }
596                 }
597             } else {
598                 for (q = 0; q < q1 - q0; q++) {
599                     paths[idx][q].cost = paths[idx - 1][q].cost + 1;
600                     paths[idx][q].prev = q;
601                 }
602             }
603             sce->zeroes[w*16+g] = !nz;
604             start += sce->ics.swb_sizes[g];
605             idx++;
606         }
607     }
608     idx--;
609     mincost = paths[idx][0].cost;
610     minq    = 0;
611     for (i = 1; i < TRELLIS_STATES; i++) {
612         if (paths[idx][i].cost < mincost) {
613             mincost = paths[idx][i].cost;
614             minq = i;
615         }
616     }
617     while (idx) {
618         sce->sf_idx[bandaddr[idx]] = minq + q0;
619         minq = paths[idx][minq].prev;
620         idx--;
621     }
622     //set the same quantizers inside window groups
623     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
624         for (g = 0;  g < sce->ics.num_swb; g++)
625             for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
626                 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
627 }
628
629 /**
630  * two-loop quantizers search taken from ISO 13818-7 Appendix C
631  */
632 static void search_for_quantizers_twoloop(AVCodecContext *avctx,
633                                           AACEncContext *s,
634                                           SingleChannelElement *sce,
635                                           const float lambda)
636 {
637     int start = 0, i, w, w2, g;
638     int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate / avctx->channels;
639     float dists[128], uplims[128];
640     int fflag, minscaler;
641     int its  = 0;
642     int allz = 0;
643     float minthr = INFINITY;
644
645     //XXX: some heuristic to determine initial quantizers will reduce search time
646     memset(dists, 0, sizeof(dists));
647     //determine zero bands and upper limits
648     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
649         for (g = 0;  g < sce->ics.num_swb; g++) {
650             int nz = 0;
651             float uplim = 0.0f;
652             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
653                 FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
654                 uplim += band->threshold;
655                 if (band->energy <= band->threshold || band->threshold == 0.0f) {
656                     sce->zeroes[(w+w2)*16+g] = 1;
657                     continue;
658                 }
659                 nz = 1;
660             }
661             uplims[w*16+g] = uplim *512;
662             sce->zeroes[w*16+g] = !nz;
663             if (nz)
664                 minthr = FFMIN(minthr, uplim);
665             allz = FFMAX(allz, nz);
666         }
667     }
668     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
669         for (g = 0;  g < sce->ics.num_swb; g++) {
670             if (sce->zeroes[w*16+g]) {
671                 sce->sf_idx[w*16+g] = SCALE_ONE_POS;
672                 continue;
673             }
674             sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2(uplims[w*16+g]/minthr)*4,59);
675         }
676     }
677
678     if (!allz)
679         return;
680     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
681     //perform two-loop search
682     //outer loop - improve quality
683     do {
684         int tbits, qstep;
685         minscaler = sce->sf_idx[0];
686         //inner loop - quantize spectrum to fit into given number of bits
687         qstep = its ? 1 : 32;
688         do {
689             int prev = -1;
690             tbits = 0;
691             fflag = 0;
692             for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
693                 start = w*128;
694                 for (g = 0;  g < sce->ics.num_swb; g++) {
695                     const float *coefs = sce->coeffs + start;
696                     const float *scaled = s->scoefs + start;
697                     int bits = 0;
698                     int cb;
699                     float dist = 0.0f;
700
701                     if (sce->zeroes[w*16+g] || sce->sf_idx[w*16+g] >= 218) {
702                         start += sce->ics.swb_sizes[g];
703                         continue;
704                     }
705                     minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
706                     cb = find_min_book(find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], scaled), sce->sf_idx[w*16+g]);
707                     for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
708                         int b;
709                         dist += quantize_band_cost(s, coefs + w2*128,
710                                                    scaled + w2*128,
711                                                    sce->ics.swb_sizes[g],
712                                                    sce->sf_idx[w*16+g],
713                                                    cb,
714                                                    1.0f,
715                                                    INFINITY,
716                                                    &b);
717                         bits += b;
718                     }
719                     dists[w*16+g] = dist - bits;
720                     if (prev != -1) {
721                         bits += ff_aac_scalefactor_bits[sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO];
722                     }
723                     tbits += bits;
724                     start += sce->ics.swb_sizes[g];
725                     prev = sce->sf_idx[w*16+g];
726                 }
727             }
728             if (tbits > destbits) {
729                 for (i = 0; i < 128; i++)
730                     if (sce->sf_idx[i] < 218 - qstep)
731                         sce->sf_idx[i] += qstep;
732             } else {
733                 for (i = 0; i < 128; i++)
734                     if (sce->sf_idx[i] > 60 - qstep)
735                         sce->sf_idx[i] -= qstep;
736             }
737             qstep >>= 1;
738             if (!qstep && tbits > destbits*1.02)
739                 qstep = 1;
740             if (sce->sf_idx[0] >= 217)
741                 break;
742         } while (qstep);
743
744         fflag = 0;
745         minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);
746         for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
747             start = w*128;
748             for (g = 0; g < sce->ics.num_swb; g++) {
749                 int prevsc = sce->sf_idx[w*16+g];
750                 const float *scaled = s->scoefs + start;
751                 if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60)
752                     sce->sf_idx[w*16+g]--;
753                 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
754                 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);
755                 if (sce->sf_idx[w*16+g] != prevsc)
756                     fflag = 1;
757                 sce->band_type[w*16+g] = find_min_book(find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], scaled), sce->sf_idx[w*16+g]);
758                 start += sce->ics.swb_sizes[g];
759             }
760         }
761         its++;
762     } while (fflag && its < 10);
763 }
764
765 static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
766                                        SingleChannelElement *sce,
767                                        const float lambda)
768 {
769     int start = 0, i, w, w2, g;
770     float uplim[128], maxq[128];
771     int minq, maxsf;
772     float distfact = ((sce->ics.num_windows > 1) ? 85.80 : 147.84) / lambda;
773     int last = 0, lastband = 0, curband = 0;
774     float avg_energy = 0.0;
775     if (sce->ics.num_windows == 1) {
776         start = 0;
777         for (i = 0; i < 1024; i++) {
778             if (i - start >= sce->ics.swb_sizes[curband]) {
779                 start += sce->ics.swb_sizes[curband];
780                 curband++;
781             }
782             if (sce->coeffs[i]) {
783                 avg_energy += sce->coeffs[i] * sce->coeffs[i];
784                 last = i;
785                 lastband = curband;
786             }
787         }
788     } else {
789         for (w = 0; w < 8; w++) {
790             const float *coeffs = sce->coeffs + w*128;
791             start = 0;
792             for (i = 0; i < 128; i++) {
793                 if (i - start >= sce->ics.swb_sizes[curband]) {
794                     start += sce->ics.swb_sizes[curband];
795                     curband++;
796                 }
797                 if (coeffs[i]) {
798                     avg_energy += coeffs[i] * coeffs[i];
799                     last = FFMAX(last, i);
800                     lastband = FFMAX(lastband, curband);
801                 }
802             }
803         }
804     }
805     last++;
806     avg_energy /= last;
807     if (avg_energy == 0.0f) {
808         for (i = 0; i < FF_ARRAY_ELEMS(sce->sf_idx); i++)
809             sce->sf_idx[i] = SCALE_ONE_POS;
810         return;
811     }
812     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
813         start = w*128;
814         for (g = 0; g < sce->ics.num_swb; g++) {
815             float *coefs   = sce->coeffs + start;
816             const int size = sce->ics.swb_sizes[g];
817             int start2 = start, end2 = start + size, peakpos = start;
818             float maxval = -1, thr = 0.0f, t;
819             maxq[w*16+g] = 0.0f;
820             if (g > lastband) {
821                 maxq[w*16+g] = 0.0f;
822                 start += size;
823                 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
824                     memset(coefs + w2*128, 0, sizeof(coefs[0])*size);
825                 continue;
826             }
827             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
828                 for (i = 0; i < size; i++) {
829                     float t = coefs[w2*128+i]*coefs[w2*128+i];
830                     maxq[w*16+g] = FFMAX(maxq[w*16+g], fabsf(coefs[w2*128 + i]));
831                     thr += t;
832                     if (sce->ics.num_windows == 1 && maxval < t) {
833                         maxval  = t;
834                         peakpos = start+i;
835                     }
836                 }
837             }
838             if (sce->ics.num_windows == 1) {
839                 start2 = FFMAX(peakpos - 2, start2);
840                 end2   = FFMIN(peakpos + 3, end2);
841             } else {
842                 start2 -= start;
843                 end2   -= start;
844             }
845             start += size;
846             thr = pow(thr / (avg_energy * (end2 - start2)), 0.3 + 0.1*(lastband - g) / lastband);
847             t   = 1.0 - (1.0 * start2 / last);
848             uplim[w*16+g] = distfact / (1.4 * thr + t*t*t + 0.075);
849         }
850     }
851     memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
852     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
853     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
854         start = w*128;
855         for (g = 0;  g < sce->ics.num_swb; g++) {
856             const float *coefs  = sce->coeffs + start;
857             const float *scaled = s->scoefs   + start;
858             const int size      = sce->ics.swb_sizes[g];
859             int scf, prev_scf, step;
860             int min_scf = -1, max_scf = 256;
861             float curdiff;
862             if (maxq[w*16+g] < 21.544) {
863                 sce->zeroes[w*16+g] = 1;
864                 start += size;
865                 continue;
866             }
867             sce->zeroes[w*16+g] = 0;
868             scf  = prev_scf = av_clip(SCALE_ONE_POS - SCALE_DIV_512 - log2(1/maxq[w*16+g])*16/3, 60, 218);
869             step = 16;
870             for (;;) {
871                 float dist = 0.0f;
872                 int quant_max;
873
874                 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
875                     int b;
876                     dist += quantize_band_cost(s, coefs + w2*128,
877                                                scaled + w2*128,
878                                                sce->ics.swb_sizes[g],
879                                                scf,
880                                                ESC_BT,
881                                                lambda,
882                                                INFINITY,
883                                                &b);
884                     dist -= b;
885                 }
886                 dist *= 1.0f / 512.0f / lambda;
887                 quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[200 - scf + SCALE_ONE_POS - SCALE_DIV_512]);
888                 if (quant_max >= 8191) { // too much, return to the previous quantizer
889                     sce->sf_idx[w*16+g] = prev_scf;
890                     break;
891                 }
892                 prev_scf = scf;
893                 curdiff = fabsf(dist - uplim[w*16+g]);
894                 if (curdiff <= 1.0f)
895                     step = 0;
896                 else
897                     step = log2(curdiff);
898                 if (dist > uplim[w*16+g])
899                     step = -step;
900                 scf += step;
901                 scf = av_clip_uint8(scf);
902                 step = scf - prev_scf;
903                 if (FFABS(step) <= 1 || (step > 0 && scf >= max_scf) || (step < 0 && scf <= min_scf)) {
904                     sce->sf_idx[w*16+g] = av_clip(scf, min_scf, max_scf);
905                     break;
906                 }
907                 if (step > 0)
908                     min_scf = prev_scf;
909                 else
910                     max_scf = prev_scf;
911             }
912             start += size;
913         }
914     }
915     minq = sce->sf_idx[0] ? sce->sf_idx[0] : INT_MAX;
916     for (i = 1; i < 128; i++) {
917         if (!sce->sf_idx[i])
918             sce->sf_idx[i] = sce->sf_idx[i-1];
919         else
920             minq = FFMIN(minq, sce->sf_idx[i]);
921     }
922     if (minq == INT_MAX)
923         minq = 0;
924     minq = FFMIN(minq, SCALE_MAX_POS);
925     maxsf = FFMIN(minq + SCALE_MAX_DIFF, SCALE_MAX_POS);
926     for (i = 126; i >= 0; i--) {
927         if (!sce->sf_idx[i])
928             sce->sf_idx[i] = sce->sf_idx[i+1];
929         sce->sf_idx[i] = av_clip(sce->sf_idx[i], minq, maxsf);
930     }
931 }
932
933 static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,
934                                        SingleChannelElement *sce,
935                                        const float lambda)
936 {
937     int start = 0, i, w, w2, g;
938     int minq = 255;
939
940     memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
941     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
942         start = w*128;
943         for (g = 0; g < sce->ics.num_swb; g++) {
944             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
945                 FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
946                 if (band->energy <= band->threshold) {
947                     sce->sf_idx[(w+w2)*16+g] = 218;
948                     sce->zeroes[(w+w2)*16+g] = 1;
949                 } else {
950                     sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2(band->threshold), 80, 218);
951                     sce->zeroes[(w+w2)*16+g] = 0;
952                 }
953                 minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
954             }
955         }
956     }
957     for (i = 0; i < 128; i++) {
958         sce->sf_idx[i] = 140;
959         //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);
960     }
961     //set the same quantizers inside window groups
962     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
963         for (g = 0;  g < sce->ics.num_swb; g++)
964             for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
965                 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
966 }
967
968 static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
969                           const float lambda)
970 {
971     int start = 0, i, w, w2, g;
972     float M[128], S[128];
973     float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
974     SingleChannelElement *sce0 = &cpe->ch[0];
975     SingleChannelElement *sce1 = &cpe->ch[1];
976     if (!cpe->common_window)
977         return;
978     for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
979         for (g = 0;  g < sce0->ics.num_swb; g++) {
980             if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {
981                 float dist1 = 0.0f, dist2 = 0.0f;
982                 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
983                     FFPsyBand *band0 = &s->psy.psy_bands[(s->cur_channel+0)*PSY_MAX_BANDS+(w+w2)*16+g];
984                     FFPsyBand *band1 = &s->psy.psy_bands[(s->cur_channel+1)*PSY_MAX_BANDS+(w+w2)*16+g];
985                     float minthr = FFMIN(band0->threshold, band1->threshold);
986                     float maxthr = FFMAX(band0->threshold, band1->threshold);
987                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
988                         M[i] = (sce0->coeffs[start+w2*128+i]
989                               + sce1->coeffs[start+w2*128+i]) * 0.5;
990                         S[i] =  sce0->coeffs[start+w2*128+i]
991                               - sce1->coeffs[start+w2*128+i];
992                     }
993                     abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
994                     abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
995                     abs_pow34_v(M34, M,                         sce0->ics.swb_sizes[g]);
996                     abs_pow34_v(S34, S,                         sce0->ics.swb_sizes[g]);
997                     dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,
998                                                 L34,
999                                                 sce0->ics.swb_sizes[g],
1000                                                 sce0->sf_idx[(w+w2)*16+g],
1001                                                 sce0->band_type[(w+w2)*16+g],
1002                                                 lambda / band0->threshold, INFINITY, NULL);
1003                     dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,
1004                                                 R34,
1005                                                 sce1->ics.swb_sizes[g],
1006                                                 sce1->sf_idx[(w+w2)*16+g],
1007                                                 sce1->band_type[(w+w2)*16+g],
1008                                                 lambda / band1->threshold, INFINITY, NULL);
1009                     dist2 += quantize_band_cost(s, M,
1010                                                 M34,
1011                                                 sce0->ics.swb_sizes[g],
1012                                                 sce0->sf_idx[(w+w2)*16+g],
1013                                                 sce0->band_type[(w+w2)*16+g],
1014                                                 lambda / maxthr, INFINITY, NULL);
1015                     dist2 += quantize_band_cost(s, S,
1016                                                 S34,
1017                                                 sce1->ics.swb_sizes[g],
1018                                                 sce1->sf_idx[(w+w2)*16+g],
1019                                                 sce1->band_type[(w+w2)*16+g],
1020                                                 lambda / minthr, INFINITY, NULL);
1021                 }
1022                 cpe->ms_mask[w*16+g] = dist2 < dist1;
1023             }
1024             start += sce0->ics.swb_sizes[g];
1025         }
1026     }
1027 }
1028
1029 AACCoefficientsEncoder ff_aac_coders[] = {
1030     {
1031         search_for_quantizers_faac,
1032         encode_window_bands_info,
1033         quantize_and_encode_band,
1034         search_for_ms,
1035     },
1036     {
1037         search_for_quantizers_anmr,
1038         encode_window_bands_info,
1039         quantize_and_encode_band,
1040         search_for_ms,
1041     },
1042     {
1043         search_for_quantizers_twoloop,
1044         codebook_trellis_rate,
1045         quantize_and_encode_band,
1046         search_for_ms,
1047     },
1048     {
1049         search_for_quantizers_fast,
1050         encode_window_bands_info,
1051         quantize_and_encode_band,
1052         search_for_ms,
1053     },
1054 };