Statistics
| Branch: | Revision:

ffmpeg / libavcodec / aaccoder.c @ 9072c29e

History | View | Annotate | Download (39.8 KB)

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