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