Statistics
| Branch: | Revision:

ffmpeg / libavcodec / aaccoder.c @ a5762c9b

History | View | Annotate | Download (39.8 KB)

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
#endif /* USE_REALLY_FULL_SEARCH */
90
}
91

    
92
static av_always_inline int quant2(float coef, const float Q)
93
{
94
    return pow(coef * Q, 0.75);
95
}
96

    
97
static const uint8_t aac_cb_range [12] = {0, 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17};
98
static const uint8_t aac_cb_maxval[12] = {0, 1, 1, 2, 2, 4, 4, 7, 7, 12, 12, 16};
99

    
100
/**
101
 * Calculate rate distortion cost for quantizing with given codebook
102
 *
103
 * @return quantization distortion
104
 */
105
static float quantize_band_cost(struct AACEncContext *s, const float *in,
106
                                const float *scaled, int size, int scale_idx,
107
                                int cb, const float lambda, const float uplim,
108
                                int *bits)
109
{
110
    const float IQ = ff_aac_pow2sf_tab[200 + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];
111
    const float  Q = ff_aac_pow2sf_tab[200 - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];
112
    const float CLIPPED_ESCAPE = 165140.0f*IQ;
113
    int i, j, k;
114
    float cost = 0;
115
    const int dim = cb < FIRST_PAIR_BT ? 4 : 2;
116
    int resbits = 0;
117
#ifndef USE_REALLY_FULL_SEARCH
118
    const float  Q34 = pow(Q, 0.75);
119
    const int range  = aac_cb_range[cb];
120
    const int maxval = aac_cb_maxval[cb];
121
    int offs[4];
122
#endif /* USE_REALLY_FULL_SEARCH */
123

    
124
    if (!cb) {
125
        for (i = 0; i < size; i++)
126
            cost += in[i]*in[i]*lambda;
127
        if (bits)
128
            *bits = 0;
129
        return cost;
130
    }
131
#ifndef USE_REALLY_FULL_SEARCH
132
    offs[0] = 1;
133
    for (i = 1; i < dim; i++)
134
        offs[i] = offs[i-1]*range;
135
    quantize_bands(s->qcoefs, in, scaled, size, Q34, !IS_CODEBOOK_UNSIGNED(cb), maxval);
136
#endif /* USE_REALLY_FULL_SEARCH */
137
    for (i = 0; i < size; i += dim) {
138
        float mincost;
139
        int minidx  = 0;
140
        int minbits = 0;
141
        const float *vec;
142
#ifndef USE_REALLY_FULL_SEARCH
143
        int (*quants)[2] = &s->qcoefs[i];
144
        mincost = 0.0f;
145
        for (j = 0; j < dim; j++)
146
            mincost += in[i+j]*in[i+j]*lambda;
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
        minidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;
262
        minbits = ff_aac_spectral_bits[cb-1][minidx];
263
        mincost += minbits;
264
        for (j = 0; j < (1<<dim); j++) {
265
            float rd = 0.0f;
266
            int curbits;
267
            int curidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;
268
            int same   = 0;
269
            for (k = 0; k < dim; k++) {
270
                if ((j & (1 << k)) && quants[k][0] == quants[k][1]) {
271
                    same = 1;
272
                    break;
273
                }
274
            }
275
            if (same)
276
                continue;
277
            for (k = 0; k < dim; k++)
278
                curidx += quants[k][!!(j & (1 << k))] * offs[dim - 1 - k];
279
            curbits =  ff_aac_spectral_bits[cb-1][curidx];
280
            vec     = &ff_aac_codebook_vectors[cb-1][curidx*dim];
281
#else
282
        vec = ff_aac_codebook_vectors[cb-1];
283
        mincost = INFINITY;
284
        for (j = 0; j < ff_aac_spectral_sizes[cb-1]; j++, vec += dim) {
285
            float rd = 0.0f;
286
            int curbits = ff_aac_spectral_bits[cb-1][j];
287
            int curidx  = j;
288
#endif /* USE_REALLY_FULL_SEARCH */
289
            if (IS_CODEBOOK_UNSIGNED(cb)) {
290
                for (k = 0; k < dim; k++) {
291
                    float t = fabsf(in[i+k]);
292
                    float di;
293
                    //do not code with escape sequence small values
294
                    if (vec[k] == 64.0f && t < 39.0f*IQ) {
295
                        rd = INFINITY;
296
                        break;
297
                    }
298
                    if (vec[k] == 64.0f) { //FIXME: slow
299
                        if (t >= CLIPPED_ESCAPE) {
300
                            di = t - CLIPPED_ESCAPE;
301
                            curbits += 21;
302
                        } else {
303
                            int c = av_clip(quant(t, Q), 0, 8191);
304
                            di = t - c*cbrt(c)*IQ;
305
                            curbits += av_log2(c)*2 - 4 + 1;
306
                        }
307
                    } else {
308
                        di = t - vec[k]*IQ;
309
                    }
310
                    if (vec[k] != 0.0f)
311
                        curbits++;
312
                    rd += di*di*lambda;
313
                }
314
            } else {
315
                for (k = 0; k < dim; k++) {
316
                    float di = in[i+k] - vec[k]*IQ;
317
                    rd += di*di*lambda;
318
                }
319
            }
320
            rd += curbits;
321
            if (rd < mincost) {
322
                mincost = rd;
323
                minidx  = curidx;
324
                minbits = curbits;
325
            }
326
        }
327
        put_bits(pb, ff_aac_spectral_bits[cb-1][minidx], ff_aac_spectral_codes[cb-1][minidx]);
328
        if (IS_CODEBOOK_UNSIGNED(cb))
329
            for (j = 0; j < dim; j++)
330
                if (ff_aac_codebook_vectors[cb-1][minidx*dim+j] != 0.0f)
331
                    put_bits(pb, 1, in[i+j] < 0.0f);
332
        if (cb == ESC_BT) {
333
            for (j = 0; j < 2; j++) {
334
                if (ff_aac_codebook_vectors[cb-1][minidx*2+j] == 64.0f) {
335
                    int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191);
336
                    int len = av_log2(coef);
337

    
338
                    put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);
339
                    put_bits(pb, len, coef & ((1 << len) - 1));
340
                }
341
            }
342
        }
343
    }
344
//STOP_TIMER("quantize_and_encode")
345
}
346

    
347
/**
348
 * structure used in optimal codebook search
349
 */
350
typedef struct BandCodingPath {
351
    int prev_idx; ///< pointer to the previous path point
352
    int codebook; ///< codebook for coding band run
353
    float cost;   ///< path cost
354
    int run;
355
} BandCodingPath;
356

    
357
/**
358
 * Encode band info for single window group bands.
359
 */
360
static void encode_window_bands_info(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     = 0.0f;
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
            next_minrd = INFINITY;
394
            next_mincb = 0;
395
            for (cb = 0; cb < 12; cb++) {
396
                float cost_stay_here, cost_get_here;
397
                float rd = 0.0f;
398
                for (w = 0; w < group_len; w++) {
399
                    FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(win+w)*16+swb];
400
                    rd += quantize_band_cost(s, sce->coeffs + start + w*128,
401
                                             s->scoefs + start + w*128, size,
402
                                             sce->sf_idx[(win+w)*16+swb], cb,
403
                                             lambda / band->threshold, INFINITY, NULL);
404
                }
405
                cost_stay_here = path[swb][cb].cost + rd;
406
                cost_get_here  = minrd              + rd + run_bits + 4;
407
                if (   run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run]
408
                    != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1])
409
                    cost_stay_here += run_bits;
410
                if (cost_get_here < cost_stay_here) {
411
                    path[swb+1][cb].prev_idx = mincb;
412
                    path[swb+1][cb].cost     = cost_get_here;
413
                    path[swb+1][cb].run      = 1;
414
                } else {
415
                    path[swb+1][cb].prev_idx = cb;
416
                    path[swb+1][cb].cost     = cost_stay_here;
417
                    path[swb+1][cb].run      = path[swb][cb].run + 1;
418
                }
419
                if (path[swb+1][cb].cost < next_minrd) {
420
                    next_minrd = path[swb+1][cb].cost;
421
                    next_mincb = cb;
422
                }
423
            }
424
        }
425
        start += sce->ics.swb_sizes[swb];
426
    }
427

    
428
    //convert resulting path from backward-linked list
429
    stack_len = 0;
430
    idx       = 0;
431
    for (cb = 1; cb < 12; cb++)
432
        if (path[max_sfb][cb].cost < path[max_sfb][idx].cost)
433
            idx = cb;
434
    ppos = max_sfb;
435
    while (ppos > 0) {
436
        cb = idx;
437
        stackrun[stack_len] = path[ppos][cb].run;
438
        stackcb [stack_len] = cb;
439
        idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx;
440
        ppos -= path[ppos][cb].run;
441
        stack_len++;
442
    }
443
    //perform actual band info encoding
444
    start = 0;
445
    for (i = stack_len - 1; i >= 0; i--) {
446
        put_bits(&s->pb, 4, stackcb[i]);
447
        count = stackrun[i];
448
        memset(sce->zeroes + win*16 + start, !stackcb[i], count);
449
        //XXX: memset when band_type is also uint8_t
450
        for (j = 0; j < count; j++) {
451
            sce->band_type[win*16 + start] =  stackcb[i];
452
            start++;
453
        }
454
        while (count >= run_esc) {
455
            put_bits(&s->pb, run_bits, run_esc);
456
            count -= run_esc;
457
        }
458
        put_bits(&s->pb, run_bits, count);
459
    }
460
}
461

    
462
typedef struct TrellisPath {
463
    float cost;
464
    int prev;
465
    int min_val;
466
    int max_val;
467
} TrellisPath;
468

    
469
static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,
470
                                       SingleChannelElement *sce,
471
                                       const float lambda)
472
{
473
    int q, w, w2, g, start = 0;
474
    int i;
475
    int idx;
476
    TrellisPath paths[256*121];
477
    int bandaddr[121];
478
    int minq;
479
    float mincost;
480

    
481
    for (i = 0; i < 256; i++) {
482
        paths[i].cost    = 0.0f;
483
        paths[i].prev    = -1;
484
        paths[i].min_val = i;
485
        paths[i].max_val = i;
486
    }
487
    for (i = 256; i < 256*121; i++) {
488
        paths[i].cost    = INFINITY;
489
        paths[i].prev    = -2;
490
        paths[i].min_val = INT_MAX;
491
        paths[i].max_val = 0;
492
    }
493
    idx = 256;
494
    abs_pow34_v(s->scoefs, sce->coeffs, 1024);
495
    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
496
        start = w*128;
497
        for (g = 0; g < sce->ics.num_swb; g++) {
498
            const float *coefs = sce->coeffs + start;
499
            float qmin, qmax;
500
            int nz = 0;
501

    
502
            bandaddr[idx >> 8] = w * 16 + g;
503
            qmin = INT_MAX;
504
            qmax = 0.0f;
505
            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
506
                FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
507
                if (band->energy <= band->threshold || band->threshold == 0.0f) {
508
                    sce->zeroes[(w+w2)*16+g] = 1;
509
                    continue;
510
                }
511
                sce->zeroes[(w+w2)*16+g] = 0;
512
                nz = 1;
513
                for (i = 0; i < sce->ics.swb_sizes[g]; i++) {
514
                    float t = fabsf(coefs[w2*128+i]);
515
                    if (t > 0.0f)
516
                        qmin = FFMIN(qmin, t);
517
                    qmax = FFMAX(qmax, t);
518
                }
519
            }
520
            if (nz) {
521
                int minscale, maxscale;
522
                float minrd = INFINITY;
523
                //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
524
                minscale = av_clip_uint8(log2(qmin)*4 - 69 + SCALE_ONE_POS - SCALE_DIV_512);
525
                //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
526
                maxscale = av_clip_uint8(log2(qmax)*4 +  6 + SCALE_ONE_POS - SCALE_DIV_512);
527
                for (q = minscale; q < maxscale; q++) {
528
                    float dists[12], dist;
529
                    memset(dists, 0, sizeof(dists));
530
                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
531
                        FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
532
                        int cb;
533
                        for (cb = 0; cb <= ESC_BT; cb++)
534
                            dists[cb] += quantize_band_cost(s, coefs + w2*128, s->scoefs + start + w2*128, sce->ics.swb_sizes[g],
535
                                                            q, cb, lambda / band->threshold, INFINITY, NULL);
536
                    }
537
                    dist = dists[0];
538
                    for (i = 1; i <= ESC_BT; i++)
539
                        dist = FFMIN(dist, dists[i]);
540
                    minrd = FFMIN(minrd, dist);
541

    
542
                    for (i = FFMAX(q - SCALE_MAX_DIFF, 0); i < FFMIN(q + SCALE_MAX_DIFF, 256); i++) {
543
                        float cost;
544
                        int minv, maxv;
545
                        if (isinf(paths[idx - 256 + i].cost))
546
                            continue;
547
                        cost = paths[idx - 256 + i].cost + dist
548
                               + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
549
                        minv = FFMIN(paths[idx - 256 + i].min_val, q);
550
                        maxv = FFMAX(paths[idx - 256 + i].max_val, q);
551
                        if (cost < paths[idx + q].cost && maxv-minv < SCALE_MAX_DIFF) {
552
                            paths[idx + q].cost    = cost;
553
                            paths[idx + q].prev    = idx - 256 + i;
554
                            paths[idx + q].min_val = minv;
555
                            paths[idx + q].max_val = maxv;
556
                        }
557
                    }
558
                }
559
            } else {
560
                for (q = 0; q < 256; q++) {
561
                    if (!isinf(paths[idx - 256 + q].cost)) {
562
                        paths[idx + q].cost = paths[idx - 256 + q].cost + 1;
563
                        paths[idx + q].prev = idx - 256 + q;
564
                        paths[idx + q].min_val = FFMIN(paths[idx - 256 + q].min_val, q);
565
                        paths[idx + q].max_val = FFMAX(paths[idx - 256 + q].max_val, q);
566
                        continue;
567
                    }
568
                    for (i = FFMAX(q - SCALE_MAX_DIFF, 0); i < FFMIN(q + SCALE_MAX_DIFF, 256); i++) {
569
                        float cost;
570
                        int minv, maxv;
571
                        if (isinf(paths[idx - 256 + i].cost))
572
                            continue;
573
                        cost = paths[idx - 256 + i].cost + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
574
                        minv = FFMIN(paths[idx - 256 + i].min_val, q);
575
                        maxv = FFMAX(paths[idx - 256 + i].max_val, q);
576
                        if (cost < paths[idx + q].cost && maxv-minv < SCALE_MAX_DIFF) {
577
                            paths[idx + q].cost    = cost;
578
                            paths[idx + q].prev    = idx - 256 + i;
579
                            paths[idx + q].min_val = minv;
580
                            paths[idx + q].max_val = maxv;
581
                        }
582
                    }
583
                }
584
            }
585
            sce->zeroes[w*16+g] = !nz;
586
            start += sce->ics.swb_sizes[g];
587
            idx   += 256;
588
        }
589
    }
590
    idx -= 256;
591
    mincost = paths[idx].cost;
592
    minq    = idx;
593
    for (i = 1; i < 256; i++) {
594
        if (paths[idx + i].cost < mincost) {
595
            mincost = paths[idx + i].cost;
596
            minq = idx + i;
597
        }
598
    }
599
    while (minq >= 256) {
600
        sce->sf_idx[bandaddr[minq>>8]] = minq & 0xFF;
601
        minq = paths[minq].prev;
602
    }
603
    //set the same quantizers inside window groups
604
    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
605
        for (g = 0;  g < sce->ics.num_swb; g++)
606
            for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
607
                sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
608
}
609

    
610
/**
611
 * two-loop quantizers search taken from ISO 13818-7 Appendix C
612
 */
613
static void search_for_quantizers_twoloop(AVCodecContext *avctx,
614
                                          AACEncContext *s,
615
                                          SingleChannelElement *sce,
616
                                          const float lambda)
617
{
618
    int start = 0, i, w, w2, g;
619
    int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate / avctx->channels;
620
    float dists[128], uplims[128];
621
    int fflag, minscaler;
622
    int its  = 0;
623
    int allz = 0;
624
    float minthr = INFINITY;
625

    
626
    //XXX: some heuristic to determine initial quantizers will reduce search time
627
    memset(dists, 0, sizeof(dists));
628
    //determine zero bands and upper limits
629
    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
630
        for (g = 0;  g < sce->ics.num_swb; g++) {
631
            int nz = 0;
632
            float uplim = 0.0f;
633
            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
634
                FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
635
                uplim += band->threshold;
636
                if (band->energy <= band->threshold || band->threshold == 0.0f) {
637
                    sce->zeroes[(w+w2)*16+g] = 1;
638
                    continue;
639
                }
640
                nz = 1;
641
            }
642
            uplims[w*16+g] = uplim *512;
643
            sce->zeroes[w*16+g] = !nz;
644
            if (nz)
645
                minthr = FFMIN(minthr, uplim);
646
            allz = FFMAX(allz, nz);
647
        }
648
    }
649
    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
650
        for (g = 0;  g < sce->ics.num_swb; g++) {
651
            if (sce->zeroes[w*16+g]) {
652
                sce->sf_idx[w*16+g] = SCALE_ONE_POS;
653
                continue;
654
            }
655
            sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2(uplims[w*16+g]/minthr)*4,59);
656
        }
657
    }
658

    
659
    if (!allz)
660
        return;
661
    abs_pow34_v(s->scoefs, sce->coeffs, 1024);
662
    //perform two-loop search
663
    //outer loop - improve quality
664
    do {
665
        int tbits, qstep;
666
        minscaler = sce->sf_idx[0];
667
        //inner loop - quantize spectrum to fit into given number of bits
668
        qstep = its ? 1 : 32;
669
        do {
670
            int prev = -1;
671
            tbits = 0;
672
            fflag = 0;
673
            for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
674
                start = w*128;
675
                for (g = 0;  g < sce->ics.num_swb; g++) {
676
                    const float *coefs = sce->coeffs + start;
677
                    const float *scaled = s->scoefs + start;
678
                    int bits = 0;
679
                    int cb;
680
                    float mindist = INFINITY;
681
                    int minbits = 0;
682

    
683
                    if (sce->zeroes[w*16+g] || sce->sf_idx[w*16+g] >= 218)
684
                        continue;
685
                    minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
686
                    for (cb = 0; cb <= ESC_BT; cb++) {
687
                        float dist = 0.0f;
688
                        int bb = 0;
689
                        for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
690
                            int b;
691
                            dist += quantize_band_cost(s, coefs + w2*128,
692
                                                       scaled + w2*128,
693
                                                       sce->ics.swb_sizes[g],
694
                                                       sce->sf_idx[w*16+g],
695
                                                       ESC_BT,
696
                                                       lambda,
697
                                                       INFINITY,
698
                                                       &b);
699
                            bb += b;
700
                        }
701
                        if (dist < mindist) {
702
                            mindist = dist;
703
                            minbits = bb;
704
                        }
705
                    }
706
                    dists[w*16+g] = (mindist - minbits) / lambda;
707
                    bits = minbits;
708
                    if (prev != -1) {
709
                        bits += ff_aac_scalefactor_bits[sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO];
710
                    }
711
                    tbits += bits;
712
                    start += sce->ics.swb_sizes[g];
713
                    prev = sce->sf_idx[w*16+g];
714
                }
715
            }
716
            if (tbits > destbits) {
717
                for (i = 0; i < 128; i++)
718
                    if (sce->sf_idx[i] < 218 - qstep)
719
                        sce->sf_idx[i] += qstep;
720
            } else {
721
                for (i = 0; i < 128; i++)
722
                    if (sce->sf_idx[i] > 60 - qstep)
723
                        sce->sf_idx[i] -= qstep;
724
            }
725
            qstep >>= 1;
726
            if (!qstep && tbits > destbits*1.02)
727
                qstep = 1;
728
            if (sce->sf_idx[0] >= 217)
729
                break;
730
        } while (qstep);
731

    
732
        fflag = 0;
733
        minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);
734
        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
735
            start = w*128;
736
            for (g = 0; g < sce->ics.num_swb; g++) {
737
                int prevsc = sce->sf_idx[w*16+g];
738
                if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60)
739
                    sce->sf_idx[w*16+g]--;
740
                sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
741
                sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);
742
                if (sce->sf_idx[w*16+g] != prevsc)
743
                    fflag = 1;
744
            }
745
        }
746
        its++;
747
    } while (fflag && its < 10);
748
}
749

    
750
static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
751
                                       SingleChannelElement *sce,
752
                                       const float lambda)
753
{
754
    int start = 0, i, w, w2, g;
755
    float uplim[128], maxq[128];
756
    int minq, maxsf;
757
    float distfact = ((sce->ics.num_windows > 1) ? 85.80 : 147.84) / lambda;
758
    int last = 0, lastband = 0, curband = 0;
759
    float avg_energy = 0.0;
760
    if (sce->ics.num_windows == 1) {
761
        start = 0;
762
        for (i = 0; i < 1024; i++) {
763
            if (i - start >= sce->ics.swb_sizes[curband]) {
764
                start += sce->ics.swb_sizes[curband];
765
                curband++;
766
            }
767
            if (sce->coeffs[i]) {
768
                avg_energy += sce->coeffs[i] * sce->coeffs[i];
769
                last = i;
770
                lastband = curband;
771
            }
772
        }
773
    } else {
774
        for (w = 0; w < 8; w++) {
775
            const float *coeffs = sce->coeffs + w*128;
776
            start = 0;
777
            for (i = 0; i < 128; i++) {
778
                if (i - start >= sce->ics.swb_sizes[curband]) {
779
                    start += sce->ics.swb_sizes[curband];
780
                    curband++;
781
                }
782
                if (coeffs[i]) {
783
                    avg_energy += coeffs[i] * coeffs[i];
784
                    last = FFMAX(last, i);
785
                    lastband = FFMAX(lastband, curband);
786
                }
787
            }
788
        }
789
    }
790
    last++;
791
    avg_energy /= last;
792
    if (avg_energy == 0.0f) {
793
        for (i = 0; i < FF_ARRAY_ELEMS(sce->sf_idx); i++)
794
            sce->sf_idx[i] = SCALE_ONE_POS;
795
        return;
796
    }
797
    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
798
        start = w*128;
799
        for (g = 0; g < sce->ics.num_swb; g++) {
800
            float *coefs   = sce->coeffs + start;
801
            const int size = sce->ics.swb_sizes[g];
802
            int start2 = start, end2 = start + size, peakpos = start;
803
            float maxval = -1, thr = 0.0f, t;
804
            maxq[w*16+g] = 0.0f;
805
            if (g > lastband) {
806
                maxq[w*16+g] = 0.0f;
807
                start += size;
808
                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
809
                    memset(coefs + w2*128, 0, sizeof(coefs[0])*size);
810
                continue;
811
            }
812
            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
813
                for (i = 0; i < size; i++) {
814
                    float t = coefs[w2*128+i]*coefs[w2*128+i];
815
                    maxq[w*16+g] = FFMAX(maxq[w*16+g], fabsf(coefs[w2*128 + i]));
816
                    thr += t;
817
                    if (sce->ics.num_windows == 1 && maxval < t) {
818
                        maxval  = t;
819
                        peakpos = start+i;
820
                    }
821
                }
822
            }
823
            if (sce->ics.num_windows == 1) {
824
                start2 = FFMAX(peakpos - 2, start2);
825
                end2   = FFMIN(peakpos + 3, end2);
826
            } else {
827
                start2 -= start;
828
                end2   -= start;
829
            }
830
            start += size;
831
            thr = pow(thr / (avg_energy * (end2 - start2)), 0.3 + 0.1*(lastband - g) / lastband);
832
            t   = 1.0 - (1.0 * start2 / last);
833
            uplim[w*16+g] = distfact / (1.4 * thr + t*t*t + 0.075);
834
        }
835
    }
836
    memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
837
    abs_pow34_v(s->scoefs, sce->coeffs, 1024);
838
    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
839
        start = w*128;
840
        for (g = 0;  g < sce->ics.num_swb; g++) {
841
            const float *coefs  = sce->coeffs + start;
842
            const float *scaled = s->scoefs   + start;
843
            const int size      = sce->ics.swb_sizes[g];
844
            int scf, prev_scf, step;
845
            int min_scf = 0, max_scf = 255;
846
            float curdiff;
847
            if (maxq[w*16+g] < 21.544) {
848
                sce->zeroes[w*16+g] = 1;
849
                start += size;
850
                continue;
851
            }
852
            sce->zeroes[w*16+g] = 0;
853
            scf  = prev_scf = av_clip(SCALE_ONE_POS - SCALE_DIV_512 - log2(1/maxq[w*16+g])*16/3, 60, 218);
854
            step = 16;
855
            for (;;) {
856
                float dist = 0.0f;
857
                int quant_max;
858

    
859
                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
860
                    int b;
861
                    dist += quantize_band_cost(s, coefs + w2*128,
862
                                               scaled + w2*128,
863
                                               sce->ics.swb_sizes[g],
864
                                               scf,
865
                                               ESC_BT,
866
                                               lambda,
867
                                               INFINITY,
868
                                               &b);
869
                    dist -= b;
870
                }
871
                dist *= 1.0f / 512.0f / lambda;
872
                quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[200 - scf + SCALE_ONE_POS - SCALE_DIV_512]);
873
                if (quant_max >= 8191) { // too much, return to the previous quantizer
874
                    sce->sf_idx[w*16+g] = prev_scf;
875
                    break;
876
                }
877
                prev_scf = scf;
878
                curdiff = fabsf(dist - uplim[w*16+g]);
879
                if (curdiff == 0.0f)
880
                    step = 0;
881
                else
882
                    step = fabsf(log2(curdiff));
883
                if (dist > uplim[w*16+g])
884
                    step = -step;
885
                if (FFABS(step) <= 1 || (step > 0 && scf >= max_scf) || (step < 0 && scf <= min_scf)) {
886
                    sce->sf_idx[w*16+g] = scf;
887
                    break;
888
                }
889
                scf += step;
890
                if (step > 0)
891
                    min_scf = scf;
892
                else
893
                    max_scf = scf;
894
            }
895
            start += size;
896
        }
897
    }
898
    minq = sce->sf_idx[0] ? sce->sf_idx[0] : INT_MAX;
899
    for (i = 1; i < 128; i++) {
900
        if (!sce->sf_idx[i])
901
            sce->sf_idx[i] = sce->sf_idx[i-1];
902
        else
903
            minq = FFMIN(minq, sce->sf_idx[i]);
904
    }
905
    if (minq == INT_MAX)
906
        minq = 0;
907
    minq = FFMIN(minq, SCALE_MAX_POS);
908
    maxsf = FFMIN(minq + SCALE_MAX_DIFF, SCALE_MAX_POS);
909
    for (i = 126; i >= 0; i--) {
910
        if (!sce->sf_idx[i])
911
            sce->sf_idx[i] = sce->sf_idx[i+1];
912
        sce->sf_idx[i] = av_clip(sce->sf_idx[i], minq, maxsf);
913
    }
914
}
915

    
916
static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,
917
                                       SingleChannelElement *sce,
918
                                       const float lambda)
919
{
920
    int start = 0, i, w, w2, g;
921
    int minq = 255;
922

    
923
    memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
924
    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
925
        start = w*128;
926
        for (g = 0; g < sce->ics.num_swb; g++) {
927
            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
928
                FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
929
                if (band->energy <= band->threshold) {
930
                    sce->sf_idx[(w+w2)*16+g] = 218;
931
                    sce->zeroes[(w+w2)*16+g] = 1;
932
                } else {
933
                    sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2(band->threshold), 80, 218);
934
                    sce->zeroes[(w+w2)*16+g] = 0;
935
                }
936
                minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
937
            }
938
        }
939
    }
940
    for (i = 0; i < 128; i++) {
941
        sce->sf_idx[i] = 140;
942
        //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);
943
    }
944
    //set the same quantizers inside window groups
945
    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
946
        for (g = 0;  g < sce->ics.num_swb; g++)
947
            for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
948
                sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
949
}
950

    
951
static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
952
                          const float lambda)
953
{
954
    int start = 0, i, w, w2, g;
955
    float M[128], S[128];
956
    float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
957
    SingleChannelElement *sce0 = &cpe->ch[0];
958
    SingleChannelElement *sce1 = &cpe->ch[1];
959
    if (!cpe->common_window)
960
        return;
961
    for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
962
        for (g = 0;  g < sce0->ics.num_swb; g++) {
963
            if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {
964
                float dist1 = 0.0f, dist2 = 0.0f;
965
                for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
966
                    FFPsyBand *band0 = &s->psy.psy_bands[(s->cur_channel+0)*PSY_MAX_BANDS+(w+w2)*16+g];
967
                    FFPsyBand *band1 = &s->psy.psy_bands[(s->cur_channel+1)*PSY_MAX_BANDS+(w+w2)*16+g];
968
                    float minthr = FFMIN(band0->threshold, band1->threshold);
969
                    float maxthr = FFMAX(band0->threshold, band1->threshold);
970
                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
971
                        M[i] = (sce0->coeffs[start+w2*128+i]
972
                              + sce1->coeffs[start+w2*128+i]) * 0.5;
973
                        S[i] =  sce0->coeffs[start+w2*128+i]
974
                              - sce1->coeffs[start+w2*128+i];
975
                    }
976
                    abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
977
                    abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
978
                    abs_pow34_v(M34, M,                         sce0->ics.swb_sizes[g]);
979
                    abs_pow34_v(S34, S,                         sce0->ics.swb_sizes[g]);
980
                    dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,
981
                                                L34,
982
                                                sce0->ics.swb_sizes[g],
983
                                                sce0->sf_idx[(w+w2)*16+g],
984
                                                sce0->band_type[(w+w2)*16+g],
985
                                                lambda / band0->threshold, INFINITY, NULL);
986
                    dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,
987
                                                R34,
988
                                                sce1->ics.swb_sizes[g],
989
                                                sce1->sf_idx[(w+w2)*16+g],
990
                                                sce1->band_type[(w+w2)*16+g],
991
                                                lambda / band1->threshold, INFINITY, NULL);
992
                    dist2 += quantize_band_cost(s, M,
993
                                                M34,
994
                                                sce0->ics.swb_sizes[g],
995
                                                sce0->sf_idx[(w+w2)*16+g],
996
                                                sce0->band_type[(w+w2)*16+g],
997
                                                lambda / maxthr, INFINITY, NULL);
998
                    dist2 += quantize_band_cost(s, S,
999
                                                S34,
1000
                                                sce1->ics.swb_sizes[g],
1001
                                                sce1->sf_idx[(w+w2)*16+g],
1002
                                                sce1->band_type[(w+w2)*16+g],
1003
                                                lambda / minthr, INFINITY, NULL);
1004
                }
1005
                cpe->ms_mask[w*16+g] = dist2 < dist1;
1006
            }
1007
            start += sce0->ics.swb_sizes[g];
1008
        }
1009
    }
1010
}
1011

    
1012
AACCoefficientsEncoder ff_aac_coders[] = {
1013
    {
1014
        search_for_quantizers_faac,
1015
        encode_window_bands_info,
1016
        quantize_and_encode_band,
1017
//        search_for_ms,
1018
    },
1019
    {
1020
        search_for_quantizers_anmr,
1021
        encode_window_bands_info,
1022
        quantize_and_encode_band,
1023
//        search_for_ms,
1024
    },
1025
    {
1026
        search_for_quantizers_twoloop,
1027
        encode_window_bands_info,
1028
        quantize_and_encode_band,
1029
//        search_for_ms,
1030
    },
1031
    {
1032
        search_for_quantizers_fast,
1033
        encode_window_bands_info,
1034
        quantize_and_encode_band,
1035
//        search_for_ms,
1036
    },
1037
};