aacenc: Split find_max_val() from find_min_book() to eliminate duplicate searches.
[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 <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                 //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
570                 minscale = av_clip_uint8(log2(qmin)*4 - 69 + SCALE_ONE_POS - SCALE_DIV_512);
571                 //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
572                 maxscale = av_clip_uint8(log2(qmax)*4 +  6 + SCALE_ONE_POS - SCALE_DIV_512);
573                 minscale = av_clip(minscale - q0, 0, TRELLIS_STATES - 1);
574                 maxscale = av_clip(maxscale - q0, 0, TRELLIS_STATES);
575                 float maxval = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], s->scoefs+start);
576                 for (q = minscale; q < maxscale; q++) {
577                     float dist = 0;
578                     int cb = find_min_book(maxval, sce->sf_idx[w*16+g]);
579                     for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
580                         FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
581                         dist += quantize_band_cost(s, coefs + w2*128, s->scoefs + start + w2*128, sce->ics.swb_sizes[g],
582                                                             q + q0, cb, lambda / band->threshold, INFINITY, NULL);
583                     }
584                     minrd = FFMIN(minrd, dist);
585
586                     for (i = 0; i < q1 - q0; i++) {
587                         float cost;
588                         cost = paths[idx - 1][i].cost + dist
589                                + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
590                         if (cost < paths[idx][q].cost) {
591                             paths[idx][q].cost    = cost;
592                             paths[idx][q].prev    = i;
593                         }
594                     }
595                 }
596             } else {
597                 for (q = 0; q < q1 - q0; q++) {
598                         paths[idx][q].cost = paths[idx - 1][q].cost + 1;
599                         paths[idx][q].prev = q;
600                 }
601             }
602             sce->zeroes[w*16+g] = !nz;
603             start += sce->ics.swb_sizes[g];
604             idx++;
605         }
606     }
607     idx--;
608     mincost = paths[idx][0].cost;
609     minq    = 0;
610     for (i = 1; i < TRELLIS_STATES; i++) {
611         if (paths[idx][i].cost < mincost) {
612             mincost = paths[idx][i].cost;
613             minq = i;
614         }
615     }
616     while (idx) {
617         sce->sf_idx[bandaddr[idx]] = minq + q0;
618         minq = paths[idx][minq].prev;
619         idx--;
620     }
621     //set the same quantizers inside window groups
622     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
623         for (g = 0;  g < sce->ics.num_swb; g++)
624             for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
625                 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
626 }
627
628 /**
629  * two-loop quantizers search taken from ISO 13818-7 Appendix C
630  */
631 static void search_for_quantizers_twoloop(AVCodecContext *avctx,
632                                           AACEncContext *s,
633                                           SingleChannelElement *sce,
634                                           const float lambda)
635 {
636     int start = 0, i, w, w2, g;
637     int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate / avctx->channels;
638     float dists[128], uplims[128];
639     int fflag, minscaler;
640     int its  = 0;
641     int allz = 0;
642     float minthr = INFINITY;
643
644     //XXX: some heuristic to determine initial quantizers will reduce search time
645     memset(dists, 0, sizeof(dists));
646     //determine zero bands and upper limits
647     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
648         for (g = 0;  g < sce->ics.num_swb; g++) {
649             int nz = 0;
650             float uplim = 0.0f;
651             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
652                 FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
653                 uplim += band->threshold;
654                 if (band->energy <= band->threshold || band->threshold == 0.0f) {
655                     sce->zeroes[(w+w2)*16+g] = 1;
656                     continue;
657                 }
658                 nz = 1;
659             }
660             uplims[w*16+g] = uplim *512;
661             sce->zeroes[w*16+g] = !nz;
662             if (nz)
663                 minthr = FFMIN(minthr, uplim);
664             allz = FFMAX(allz, nz);
665         }
666     }
667     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
668         for (g = 0;  g < sce->ics.num_swb; g++) {
669             if (sce->zeroes[w*16+g]) {
670                 sce->sf_idx[w*16+g] = SCALE_ONE_POS;
671                 continue;
672             }
673             sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2(uplims[w*16+g]/minthr)*4,59);
674         }
675     }
676
677     if (!allz)
678         return;
679     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
680     //perform two-loop search
681     //outer loop - improve quality
682     do {
683         int tbits, qstep;
684         minscaler = sce->sf_idx[0];
685         //inner loop - quantize spectrum to fit into given number of bits
686         qstep = its ? 1 : 32;
687         do {
688             int prev = -1;
689             tbits = 0;
690             fflag = 0;
691             for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
692                 start = w*128;
693                 for (g = 0;  g < sce->ics.num_swb; g++) {
694                     const float *coefs = sce->coeffs + start;
695                     const float *scaled = s->scoefs + start;
696                     int bits = 0;
697                     int cb;
698                     float mindist = INFINITY;
699                     int minbits = 0;
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                     {
707                         float dist = 0.0f;
708                         int bb = 0;
709                         cb = find_min_book(find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], scaled), sce->sf_idx[w*16+g]);
710                         sce->band_type[w*16+g] = cb;
711                         for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
712                             int b;
713                             dist += quantize_band_cost(s, coefs + w2*128,
714                                                        scaled + w2*128,
715                                                        sce->ics.swb_sizes[g],
716                                                        sce->sf_idx[w*16+g],
717                                                        cb,
718                                                        lambda,
719                                                        INFINITY,
720                                                        &b);
721                             bb += b;
722                         }
723                             mindist = dist;
724                             minbits = bb;
725                     }
726                     dists[w*16+g] = (mindist - minbits) / lambda;
727                     bits = minbits;
728                     if (prev != -1) {
729                         bits += ff_aac_scalefactor_bits[sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO];
730                     }
731                     tbits += bits;
732                     start += sce->ics.swb_sizes[g];
733                     prev = sce->sf_idx[w*16+g];
734                 }
735             }
736             if (tbits > destbits) {
737                 for (i = 0; i < 128; i++)
738                     if (sce->sf_idx[i] < 218 - qstep)
739                         sce->sf_idx[i] += qstep;
740             } else {
741                 for (i = 0; i < 128; i++)
742                     if (sce->sf_idx[i] > 60 - qstep)
743                         sce->sf_idx[i] -= qstep;
744             }
745             qstep >>= 1;
746             if (!qstep && tbits > destbits*1.02)
747                 qstep = 1;
748             if (sce->sf_idx[0] >= 217)
749                 break;
750         } while (qstep);
751
752         fflag = 0;
753         minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);
754         for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
755             start = w*128;
756             for (g = 0; g < sce->ics.num_swb; g++) {
757                 int prevsc = sce->sf_idx[w*16+g];
758                 if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60)
759                     sce->sf_idx[w*16+g]--;
760                 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
761                 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);
762                 if (sce->sf_idx[w*16+g] != prevsc)
763                     fflag = 1;
764             }
765         }
766         its++;
767     } while (fflag && its < 10);
768 }
769
770 static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
771                                        SingleChannelElement *sce,
772                                        const float lambda)
773 {
774     int start = 0, i, w, w2, g;
775     float uplim[128], maxq[128];
776     int minq, maxsf;
777     float distfact = ((sce->ics.num_windows > 1) ? 85.80 : 147.84) / lambda;
778     int last = 0, lastband = 0, curband = 0;
779     float avg_energy = 0.0;
780     if (sce->ics.num_windows == 1) {
781         start = 0;
782         for (i = 0; i < 1024; i++) {
783             if (i - start >= sce->ics.swb_sizes[curband]) {
784                 start += sce->ics.swb_sizes[curband];
785                 curband++;
786             }
787             if (sce->coeffs[i]) {
788                 avg_energy += sce->coeffs[i] * sce->coeffs[i];
789                 last = i;
790                 lastband = curband;
791             }
792         }
793     } else {
794         for (w = 0; w < 8; w++) {
795             const float *coeffs = sce->coeffs + w*128;
796             start = 0;
797             for (i = 0; i < 128; i++) {
798                 if (i - start >= sce->ics.swb_sizes[curband]) {
799                     start += sce->ics.swb_sizes[curband];
800                     curband++;
801                 }
802                 if (coeffs[i]) {
803                     avg_energy += coeffs[i] * coeffs[i];
804                     last = FFMAX(last, i);
805                     lastband = FFMAX(lastband, curband);
806                 }
807             }
808         }
809     }
810     last++;
811     avg_energy /= last;
812     if (avg_energy == 0.0f) {
813         for (i = 0; i < FF_ARRAY_ELEMS(sce->sf_idx); i++)
814             sce->sf_idx[i] = SCALE_ONE_POS;
815         return;
816     }
817     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
818         start = w*128;
819         for (g = 0; g < sce->ics.num_swb; g++) {
820             float *coefs   = sce->coeffs + start;
821             const int size = sce->ics.swb_sizes[g];
822             int start2 = start, end2 = start + size, peakpos = start;
823             float maxval = -1, thr = 0.0f, t;
824             maxq[w*16+g] = 0.0f;
825             if (g > lastband) {
826                 maxq[w*16+g] = 0.0f;
827                 start += size;
828                 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
829                     memset(coefs + w2*128, 0, sizeof(coefs[0])*size);
830                 continue;
831             }
832             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
833                 for (i = 0; i < size; i++) {
834                     float t = coefs[w2*128+i]*coefs[w2*128+i];
835                     maxq[w*16+g] = FFMAX(maxq[w*16+g], fabsf(coefs[w2*128 + i]));
836                     thr += t;
837                     if (sce->ics.num_windows == 1 && maxval < t) {
838                         maxval  = t;
839                         peakpos = start+i;
840                     }
841                 }
842             }
843             if (sce->ics.num_windows == 1) {
844                 start2 = FFMAX(peakpos - 2, start2);
845                 end2   = FFMIN(peakpos + 3, end2);
846             } else {
847                 start2 -= start;
848                 end2   -= start;
849             }
850             start += size;
851             thr = pow(thr / (avg_energy * (end2 - start2)), 0.3 + 0.1*(lastband - g) / lastband);
852             t   = 1.0 - (1.0 * start2 / last);
853             uplim[w*16+g] = distfact / (1.4 * thr + t*t*t + 0.075);
854         }
855     }
856     memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
857     abs_pow34_v(s->scoefs, sce->coeffs, 1024);
858     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
859         start = w*128;
860         for (g = 0;  g < sce->ics.num_swb; g++) {
861             const float *coefs  = sce->coeffs + start;
862             const float *scaled = s->scoefs   + start;
863             const int size      = sce->ics.swb_sizes[g];
864             int scf, prev_scf, step;
865             int min_scf = -1, max_scf = 256;
866             float curdiff;
867             if (maxq[w*16+g] < 21.544) {
868                 sce->zeroes[w*16+g] = 1;
869                 start += size;
870                 continue;
871             }
872             sce->zeroes[w*16+g] = 0;
873             scf  = prev_scf = av_clip(SCALE_ONE_POS - SCALE_DIV_512 - log2(1/maxq[w*16+g])*16/3, 60, 218);
874             step = 16;
875             for (;;) {
876                 float dist = 0.0f;
877                 int quant_max;
878
879                 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
880                     int b;
881                     dist += quantize_band_cost(s, coefs + w2*128,
882                                                scaled + w2*128,
883                                                sce->ics.swb_sizes[g],
884                                                scf,
885                                                ESC_BT,
886                                                lambda,
887                                                INFINITY,
888                                                &b);
889                     dist -= b;
890                 }
891                 dist *= 1.0f / 512.0f / lambda;
892                 quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[200 - scf + SCALE_ONE_POS - SCALE_DIV_512]);
893                 if (quant_max >= 8191) { // too much, return to the previous quantizer
894                     sce->sf_idx[w*16+g] = prev_scf;
895                     break;
896                 }
897                 prev_scf = scf;
898                 curdiff = fabsf(dist - uplim[w*16+g]);
899                 if (curdiff <= 1.0f)
900                     step = 0;
901                 else
902                     step = log2(curdiff);
903                 if (dist > uplim[w*16+g])
904                     step = -step;
905                 scf += step;
906                 scf = av_clip_uint8(scf);
907                 step = scf - prev_scf;
908                 if (FFABS(step) <= 1 || (step > 0 && scf >= max_scf) || (step < 0 && scf <= min_scf)) {
909                     sce->sf_idx[w*16+g] = av_clip(scf, min_scf, max_scf);
910                     break;
911                 }
912                 if (step > 0)
913                     min_scf = prev_scf;
914                 else
915                     max_scf = prev_scf;
916             }
917             start += size;
918         }
919     }
920     minq = sce->sf_idx[0] ? sce->sf_idx[0] : INT_MAX;
921     for (i = 1; i < 128; i++) {
922         if (!sce->sf_idx[i])
923             sce->sf_idx[i] = sce->sf_idx[i-1];
924         else
925             minq = FFMIN(minq, sce->sf_idx[i]);
926     }
927     if (minq == INT_MAX)
928         minq = 0;
929     minq = FFMIN(minq, SCALE_MAX_POS);
930     maxsf = FFMIN(minq + SCALE_MAX_DIFF, SCALE_MAX_POS);
931     for (i = 126; i >= 0; i--) {
932         if (!sce->sf_idx[i])
933             sce->sf_idx[i] = sce->sf_idx[i+1];
934         sce->sf_idx[i] = av_clip(sce->sf_idx[i], minq, maxsf);
935     }
936 }
937
938 static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,
939                                        SingleChannelElement *sce,
940                                        const float lambda)
941 {
942     int start = 0, i, w, w2, g;
943     int minq = 255;
944
945     memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
946     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
947         start = w*128;
948         for (g = 0; g < sce->ics.num_swb; g++) {
949             for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
950                 FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
951                 if (band->energy <= band->threshold) {
952                     sce->sf_idx[(w+w2)*16+g] = 218;
953                     sce->zeroes[(w+w2)*16+g] = 1;
954                 } else {
955                     sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2(band->threshold), 80, 218);
956                     sce->zeroes[(w+w2)*16+g] = 0;
957                 }
958                 minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
959             }
960         }
961     }
962     for (i = 0; i < 128; i++) {
963         sce->sf_idx[i] = 140;
964         //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);
965     }
966     //set the same quantizers inside window groups
967     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
968         for (g = 0;  g < sce->ics.num_swb; g++)
969             for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
970                 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
971 }
972
973 static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
974                           const float lambda)
975 {
976     int start = 0, i, w, w2, g;
977     float M[128], S[128];
978     float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
979     SingleChannelElement *sce0 = &cpe->ch[0];
980     SingleChannelElement *sce1 = &cpe->ch[1];
981     if (!cpe->common_window)
982         return;
983     for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
984         for (g = 0;  g < sce0->ics.num_swb; g++) {
985             if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {
986                 float dist1 = 0.0f, dist2 = 0.0f;
987                 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
988                     FFPsyBand *band0 = &s->psy.psy_bands[(s->cur_channel+0)*PSY_MAX_BANDS+(w+w2)*16+g];
989                     FFPsyBand *band1 = &s->psy.psy_bands[(s->cur_channel+1)*PSY_MAX_BANDS+(w+w2)*16+g];
990                     float minthr = FFMIN(band0->threshold, band1->threshold);
991                     float maxthr = FFMAX(band0->threshold, band1->threshold);
992                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
993                         M[i] = (sce0->coeffs[start+w2*128+i]
994                               + sce1->coeffs[start+w2*128+i]) * 0.5;
995                         S[i] =  sce0->coeffs[start+w2*128+i]
996                               - sce1->coeffs[start+w2*128+i];
997                     }
998                     abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
999                     abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
1000                     abs_pow34_v(M34, M,                         sce0->ics.swb_sizes[g]);
1001                     abs_pow34_v(S34, S,                         sce0->ics.swb_sizes[g]);
1002                     dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,
1003                                                 L34,
1004                                                 sce0->ics.swb_sizes[g],
1005                                                 sce0->sf_idx[(w+w2)*16+g],
1006                                                 sce0->band_type[(w+w2)*16+g],
1007                                                 lambda / band0->threshold, INFINITY, NULL);
1008                     dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,
1009                                                 R34,
1010                                                 sce1->ics.swb_sizes[g],
1011                                                 sce1->sf_idx[(w+w2)*16+g],
1012                                                 sce1->band_type[(w+w2)*16+g],
1013                                                 lambda / band1->threshold, INFINITY, NULL);
1014                     dist2 += quantize_band_cost(s, M,
1015                                                 M34,
1016                                                 sce0->ics.swb_sizes[g],
1017                                                 sce0->sf_idx[(w+w2)*16+g],
1018                                                 sce0->band_type[(w+w2)*16+g],
1019                                                 lambda / maxthr, INFINITY, NULL);
1020                     dist2 += quantize_band_cost(s, S,
1021                                                 S34,
1022                                                 sce1->ics.swb_sizes[g],
1023                                                 sce1->sf_idx[(w+w2)*16+g],
1024                                                 sce1->band_type[(w+w2)*16+g],
1025                                                 lambda / minthr, INFINITY, NULL);
1026                 }
1027                 cpe->ms_mask[w*16+g] = dist2 < dist1;
1028             }
1029             start += sce0->ics.swb_sizes[g];
1030         }
1031     }
1032 }
1033
1034 AACCoefficientsEncoder ff_aac_coders[] = {
1035     {
1036         search_for_quantizers_faac,
1037         encode_window_bands_info,
1038         quantize_and_encode_band,
1039         search_for_ms,
1040     },
1041     {
1042         search_for_quantizers_anmr,
1043         encode_window_bands_info,
1044         quantize_and_encode_band,
1045         search_for_ms,
1046     },
1047     {
1048         search_for_quantizers_twoloop,
1049         codebook_trellis_rate,
1050         quantize_and_encode_band,
1051         search_for_ms,
1052     },
1053     {
1054         search_for_quantizers_fast,
1055         encode_window_bands_info,
1056         quantize_and_encode_band,
1057         search_for_ms,
1058     },
1059 };