GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/aacsbr_template.c Lines: 775 928 83.5 %
Date: 2019-11-22 03:34:36 Branches: 531 710 74.8 %

Line Branch Exec Source
1
/*
2
 * AAC Spectral Band Replication decoding functions
3
 * Copyright (c) 2008-2009 Robert Swain ( rob opendot cl )
4
 * Copyright (c) 2009-2010 Alex Converse <alex.converse@gmail.com>
5
 *
6
 * Fixed point code
7
 * Copyright (c) 2013
8
 *      MIPS Technologies, Inc., California.
9
 *
10
 * This file is part of FFmpeg.
11
 *
12
 * FFmpeg is free software; you can redistribute it and/or
13
 * modify it under the terms of the GNU Lesser General Public
14
 * License as published by the Free Software Foundation; either
15
 * version 2.1 of the License, or (at your option) any later version.
16
 *
17
 * FFmpeg is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20
 * Lesser General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Lesser General Public
23
 * License along with FFmpeg; if not, write to the Free Software
24
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25
 */
26
27
/**
28
 * @file
29
 * AAC Spectral Band Replication decoding functions
30
 * @author Robert Swain ( rob opendot cl )
31
 * @author Stanislav Ocovaj ( stanislav.ocovaj@imgtec.com )
32
 * @author Zoran Basaric ( zoran.basaric@imgtec.com )
33
 */
34
35
#include "libavutil/qsort.h"
36
37
164
static av_cold void aacsbr_tableinit(void)
38
{
39
    int n;
40
52480
    for (n = 1; n < 320; n++)
41
52316
        sbr_qmf_window_us[320 + n] = sbr_qmf_window_us[320 - n];
42
164
    sbr_qmf_window_us[384] = -sbr_qmf_window_us[384];
43
164
    sbr_qmf_window_us[512] = -sbr_qmf_window_us[512];
44
45
52644
    for (n = 0; n < 320; n++)
46
52480
        sbr_qmf_window_ds[n] = sbr_qmf_window_us[2*n];
47
164
}
48
49
164
av_cold void AAC_RENAME(ff_aac_sbr_init)(void)
50
{
51
    static const struct {
52
        const void *sbr_codes, *sbr_bits;
53
        const unsigned int table_size, elem_size;
54
    } sbr_tmp[] = {
55
        SBR_VLC_ROW(t_huffman_env_1_5dB),
56
        SBR_VLC_ROW(f_huffman_env_1_5dB),
57
        SBR_VLC_ROW(t_huffman_env_bal_1_5dB),
58
        SBR_VLC_ROW(f_huffman_env_bal_1_5dB),
59
        SBR_VLC_ROW(t_huffman_env_3_0dB),
60
        SBR_VLC_ROW(f_huffman_env_3_0dB),
61
        SBR_VLC_ROW(t_huffman_env_bal_3_0dB),
62
        SBR_VLC_ROW(f_huffman_env_bal_3_0dB),
63
        SBR_VLC_ROW(t_huffman_noise_3_0dB),
64
        SBR_VLC_ROW(t_huffman_noise_bal_3_0dB),
65
    };
66
67
    // SBR VLC table initialization
68
164
    SBR_INIT_VLC_STATIC(0, 1098);
69
164
    SBR_INIT_VLC_STATIC(1, 1092);
70
164
    SBR_INIT_VLC_STATIC(2, 768);
71
164
    SBR_INIT_VLC_STATIC(3, 1026);
72
164
    SBR_INIT_VLC_STATIC(4, 1058);
73
164
    SBR_INIT_VLC_STATIC(5, 1052);
74
164
    SBR_INIT_VLC_STATIC(6, 544);
75
164
    SBR_INIT_VLC_STATIC(7, 544);
76
164
    SBR_INIT_VLC_STATIC(8, 592);
77
164
    SBR_INIT_VLC_STATIC(9, 512);
78
79
164
    aacsbr_tableinit();
80
81
164
    AAC_RENAME(ff_ps_init)();
82
164
}
83
84
/** Places SBR in pure upsampling mode. */
85
347
static void sbr_turnoff(SpectralBandReplication *sbr) {
86
347
    sbr->start = 0;
87
347
    sbr->ready_for_dequant = 0;
88
    // Init defults used in pure upsampling mode
89
347
    sbr->kx[1] = 32; //Typo in spec, kx' inits to 32
90
347
    sbr->m[1] = 0;
91
    // Reset values for first SBR header
92
347
    sbr->data[0].e_a[1] = sbr->data[1].e_a[1] = -1;
93
347
    memset(&sbr->spectrum_params, -1, sizeof(SpectrumParameters));
94
347
}
95
96
347
av_cold void AAC_RENAME(ff_aac_sbr_ctx_init)(AACContext *ac, SpectralBandReplication *sbr, int id_aac)
97
{
98
347
    if(sbr->mdct.mdct_bits)
99
        return;
100
347
    sbr->kx[0] = sbr->kx[1];
101
347
    sbr->id_aac = id_aac;
102
347
    sbr_turnoff(sbr);
103
347
    sbr->data[0].synthesis_filterbank_samples_offset = SBR_SYNTHESIS_BUF_SIZE - (1280 - 128);
104
347
    sbr->data[1].synthesis_filterbank_samples_offset = SBR_SYNTHESIS_BUF_SIZE - (1280 - 128);
105
    /* SBR requires samples to be scaled to +/-32768.0 to work correctly.
106
     * mdct scale factors are adjusted to scale up from +/-1.0 at analysis
107
     * and scale back down at synthesis. */
108
347
    AAC_RENAME_32(ff_mdct_init)(&sbr->mdct,     7, 1, 1.0 / (64 * 32768.0));
109
347
    AAC_RENAME_32(ff_mdct_init)(&sbr->mdct_ana, 7, 1, -2.0 * 32768.0);
110
347
    AAC_RENAME(ff_ps_ctx_init)(&sbr->ps);
111
347
    AAC_RENAME(ff_sbrdsp_init)(&sbr->dsp);
112
347
    aacsbr_func_ptr_init(&sbr->c);
113
}
114
115
347
av_cold void AAC_RENAME(ff_aac_sbr_ctx_close)(SpectralBandReplication *sbr)
116
{
117
347
    AAC_RENAME_32(ff_mdct_end)(&sbr->mdct);
118
347
    AAC_RENAME_32(ff_mdct_end)(&sbr->mdct_ana);
119
347
}
120
121
6109
static int qsort_comparison_function_int16(const void *a, const void *b)
122
{
123
6109
    return *(const int16_t *)a - *(const int16_t *)b;
124
}
125
126
381
static inline int in_table_int16(const int16_t *table, int last_el, int16_t needle)
127
{
128
    int i;
129
1771
    for (i = 0; i <= last_el; i++)
130
1532
        if (table[i] == needle)
131
142
            return 1;
132
239
    return 0;
133
}
134
135
/// Limiter Frequency Band Table (14496-3 sp04 p198)
136
65
static void sbr_make_f_tablelim(SpectralBandReplication *sbr)
137
{
138
    int k;
139
65
    if (sbr->bs_limiter_bands > 0) {
140
        static const INTFLOAT bands_warped[3] = { Q23(1.32715174233856803909f),   //2^(0.49/1.2)
141
                                               Q23(1.18509277094158210129f),   //2^(0.49/2)
142
                                               Q23(1.11987160404675912501f) }; //2^(0.49/3)
143
65
        const INTFLOAT lim_bands_per_octave_warped = bands_warped[sbr->bs_limiter_bands - 1];
144
        int16_t patch_borders[7];
145
65
        uint16_t *in = sbr->f_tablelim + 1, *out = sbr->f_tablelim;
146
147
65
        patch_borders[0] = sbr->kx[1];
148
251
        for (k = 1; k <= sbr->num_patches; k++)
149
186
            patch_borders[k] = patch_borders[k-1] + sbr->patch_num_subbands[k-1];
150
151
65
        memcpy(sbr->f_tablelim, sbr->f_tablelow,
152
65
               (sbr->n[0] + 1) * sizeof(sbr->f_tablelow[0]));
153
65
        if (sbr->num_patches > 1)
154
63
            memcpy(sbr->f_tablelim + sbr->n[0] + 1, patch_borders + 1,
155
63
                   (sbr->num_patches - 1) * sizeof(patch_borders[0]));
156
157











1540
        AV_QSORT(sbr->f_tablelim, sbr->num_patches + sbr->n[0],
158
              uint16_t,
159
              qsort_comparison_function_int16);
160
161
65
        sbr->n_lim = sbr->n[0] + sbr->num_patches - 1;
162
606
        while (out < sbr->f_tablelim + sbr->n_lim) {
163
#if USE_FIXED
164
35
            if ((*in << 23) >= *out * lim_bands_per_octave_warped) {
165
#else
166
506
            if (*in >= *out * lim_bands_per_octave_warped) {
167
#endif /* USE_FIXED */
168
212
                *++out = *in++;
169

612
            } else if (*in == *out ||
170
283
                !in_table_int16(patch_borders, sbr->num_patches, *in)) {
171
231
                in++;
172
231
                sbr->n_lim--;
173
98
            } else if (!in_table_int16(patch_borders, sbr->num_patches, *out)) {
174
54
                *out = *in++;
175
54
                sbr->n_lim--;
176
            } else {
177
44
                *++out = *in++;
178
            }
179
        }
180
    } else {
181
        sbr->f_tablelim[0] = sbr->f_tablelow[0];
182
        sbr->f_tablelim[1] = sbr->f_tablelow[sbr->n[0]];
183
        sbr->n_lim = 1;
184
    }
185
65
}
186
187
489
static unsigned int read_sbr_header(SpectralBandReplication *sbr, GetBitContext *gb)
188
{
189
489
    unsigned int cnt = get_bits_count(gb);
190
    uint8_t bs_header_extra_1;
191
    uint8_t bs_header_extra_2;
192
489
    int old_bs_limiter_bands = sbr->bs_limiter_bands;
193
    SpectrumParameters old_spectrum_params;
194
195
489
    sbr->start = 1;
196
489
    sbr->ready_for_dequant = 0;
197
198
    // Save last spectrum parameters variables to compare to new ones
199
489
    memcpy(&old_spectrum_params, &sbr->spectrum_params, sizeof(SpectrumParameters));
200
201
489
    sbr->bs_amp_res_header              = get_bits1(gb);
202
489
    sbr->spectrum_params.bs_start_freq  = get_bits(gb, 4);
203
489
    sbr->spectrum_params.bs_stop_freq   = get_bits(gb, 4);
204
489
    sbr->spectrum_params.bs_xover_band  = get_bits(gb, 3);
205
489
                                          skip_bits(gb, 2); // bs_reserved
206
207
489
    bs_header_extra_1 = get_bits1(gb);
208
489
    bs_header_extra_2 = get_bits1(gb);
209
210
489
    if (bs_header_extra_1) {
211
430
        sbr->spectrum_params.bs_freq_scale  = get_bits(gb, 2);
212
430
        sbr->spectrum_params.bs_alter_scale = get_bits1(gb);
213
430
        sbr->spectrum_params.bs_noise_bands = get_bits(gb, 2);
214
    } else {
215
59
        sbr->spectrum_params.bs_freq_scale  = 2;
216
59
        sbr->spectrum_params.bs_alter_scale = 1;
217
59
        sbr->spectrum_params.bs_noise_bands = 2;
218
    }
219
220
    // Check if spectrum parameters changed
221
489
    if (memcmp(&old_spectrum_params, &sbr->spectrum_params, sizeof(SpectrumParameters)))
222
65
        sbr->reset = 1;
223
224
489
    if (bs_header_extra_2) {
225
26
        sbr->bs_limiter_bands  = get_bits(gb, 2);
226
26
        sbr->bs_limiter_gains  = get_bits(gb, 2);
227
26
        sbr->bs_interpol_freq  = get_bits1(gb);
228
26
        sbr->bs_smoothing_mode = get_bits1(gb);
229
    } else {
230
463
        sbr->bs_limiter_bands  = 2;
231
463
        sbr->bs_limiter_gains  = 2;
232
463
        sbr->bs_interpol_freq  = 1;
233
463
        sbr->bs_smoothing_mode = 1;
234
    }
235
236

489
    if (sbr->bs_limiter_bands != old_bs_limiter_bands && !sbr->reset)
237
        sbr_make_f_tablelim(sbr);
238
239
489
    return get_bits_count(gb) - cnt;
240
}
241
242
12
static int array_min_int16(const int16_t *array, int nel)
243
{
244
12
    int i, min = array[0];
245
28
    for (i = 1; i < nel; i++)
246
16
        min = FFMIN(array[i], min);
247
12
    return min;
248
}
249
250
65
static int check_n_master(AVCodecContext *avctx, int n_master, int bs_xover_band)
251
{
252
    // Requirements (14496-3 sp04 p205)
253
65
    if (n_master <= 0) {
254
        av_log(avctx, AV_LOG_ERROR, "Invalid n_master: %d\n", n_master);
255
        return -1;
256
    }
257
65
    if (bs_xover_band >= n_master) {
258
        av_log(avctx, AV_LOG_ERROR,
259
               "Invalid bitstream, crossover band index beyond array bounds: %d\n",
260
               bs_xover_band);
261
        return -1;
262
    }
263
65
    return 0;
264
}
265
266
/// Master Frequency Band Table (14496-3 sp04 p194)
267
65
static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
268
                             SpectrumParameters *spectrum)
269
{
270
65
    unsigned int temp, max_qmf_subbands = 0;
271
    unsigned int start_min, stop_min;
272
    int k;
273
    const int8_t *sbr_offset_ptr;
274
    int16_t stop_dk[13];
275
276

65
    switch (sbr->sample_rate) {
277
6
    case 16000:
278
6
        sbr_offset_ptr = sbr_offset[0];
279
6
        break;
280
    case 22050:
281
        sbr_offset_ptr = sbr_offset[1];
282
        break;
283
    case 24000:
284
        sbr_offset_ptr = sbr_offset[2];
285
        break;
286
12
    case 32000:
287
12
        sbr_offset_ptr = sbr_offset[3];
288
12
        break;
289
45
    case 44100: case 48000: case 64000:
290
45
        sbr_offset_ptr = sbr_offset[4];
291
45
        break;
292
2
    case 88200: case 96000: case 128000: case 176400: case 192000:
293
2
        sbr_offset_ptr = sbr_offset[5];
294
2
        break;
295
    default:
296
        av_log(ac->avctx, AV_LOG_ERROR,
297
               "Unsupported sample rate for SBR: %d\n", sbr->sample_rate);
298
        return -1;
299
    }
300
301
65
    if (sbr->sample_rate < 32000) {
302
6
        temp = 3000;
303
59
    } else if (sbr->sample_rate < 64000) {
304
57
        temp = 4000;
305
    } else
306
2
        temp = 5000;
307
308
65
    start_min = ((temp << 7) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
309
65
    stop_min  = ((temp << 8) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
310
311
65
    sbr->k[0] = start_min + sbr_offset_ptr[spectrum->bs_start_freq];
312
313
65
    if (spectrum->bs_stop_freq < 14) {
314
65
        sbr->k[2] = stop_min;
315
65
        make_bands(stop_dk, stop_min, 64, 13);
316











1827
        AV_QSORT(stop_dk, 13, int16_t, qsort_comparison_function_int16);
317
725
        for (k = 0; k < spectrum->bs_stop_freq; k++)
318
660
            sbr->k[2] += stop_dk[k];
319
    } else if (spectrum->bs_stop_freq == 14) {
320
        sbr->k[2] = 2*sbr->k[0];
321
    } else if (spectrum->bs_stop_freq == 15) {
322
        sbr->k[2] = 3*sbr->k[0];
323
    } else {
324
        av_log(ac->avctx, AV_LOG_ERROR,
325
               "Invalid bs_stop_freq: %d\n", spectrum->bs_stop_freq);
326
        return -1;
327
    }
328
65
    sbr->k[2] = FFMIN(64, sbr->k[2]);
329
330
    // Requirements (14496-3 sp04 p205)
331
65
    if (sbr->sample_rate <= 32000) {
332
18
        max_qmf_subbands = 48;
333
47
    } else if (sbr->sample_rate == 44100) {
334
36
        max_qmf_subbands = 35;
335
11
    } else if (sbr->sample_rate >= 48000)
336
11
        max_qmf_subbands = 32;
337
    else
338
        av_assert0(0);
339
340
65
    if (sbr->k[2] - sbr->k[0] > max_qmf_subbands) {
341
        av_log(ac->avctx, AV_LOG_ERROR,
342
               "Invalid bitstream, too many QMF subbands: %d\n", sbr->k[2] - sbr->k[0]);
343
        return -1;
344
    }
345
346
65
    if (!spectrum->bs_freq_scale) {
347
        int dk, k2diff;
348
349
14
        dk = spectrum->bs_alter_scale + 1;
350
14
        sbr->n_master = ((sbr->k[2] - sbr->k[0] + (dk&2)) >> dk) << 1;
351
14
        if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
352
            return -1;
353
354
266
        for (k = 1; k <= sbr->n_master; k++)
355
252
            sbr->f_master[k] = dk;
356
357
14
        k2diff = sbr->k[2] - sbr->k[0] - sbr->n_master * dk;
358
14
        if (k2diff < 0) {
359
14
            sbr->f_master[1]--;
360
14
            sbr->f_master[2]-= (k2diff < -1);
361
        } else if (k2diff) {
362
            sbr->f_master[sbr->n_master]++;
363
        }
364
365
14
        sbr->f_master[0] = sbr->k[0];
366
266
        for (k = 1; k <= sbr->n_master; k++)
367
252
            sbr->f_master[k] += sbr->f_master[k - 1];
368
369
    } else {
370
51
        int half_bands = 7 - spectrum->bs_freq_scale;      // bs_freq_scale  = {1,2,3}
371
        int two_regions, num_bands_0;
372
        int vdk0_max, vdk1_min;
373
        int16_t vk0[49];
374
#if USE_FIXED
375
5
        int tmp, nz = 0;
376
#endif /* USE_FIXED */
377
378
51
        if (49 * sbr->k[2] > 110 * sbr->k[0]) {
379
12
            two_regions = 1;
380
12
            sbr->k[1] = 2 * sbr->k[0];
381
        } else {
382
39
            two_regions = 0;
383
39
            sbr->k[1] = sbr->k[2];
384
        }
385
386
#if USE_FIXED
387
5
        tmp = (sbr->k[1] << 23) / sbr->k[0];
388
35
        while (tmp < 0x40000000) {
389
30
          tmp <<= 1;
390
30
          nz++;
391
        }
392
5
        tmp = fixed_log(tmp - 0x80000000);
393
5
        tmp = (int)(((int64_t)tmp * CONST_RECIP_LN2 + 0x20000000) >> 30);
394
5
        tmp = (((tmp + 0x80) >> 8) + ((8 - nz) << 23)) * half_bands;
395
5
        num_bands_0 = ((tmp + 0x400000) >> 23) * 2;
396
#else
397
46
        num_bands_0 = lrintf(half_bands * log2f(sbr->k[1] / (float)sbr->k[0])) * 2;
398
#endif /* USE_FIXED */
399
400
51
        if (num_bands_0 <= 0) { // Requirements (14496-3 sp04 p205)
401
            av_log(ac->avctx, AV_LOG_ERROR, "Invalid num_bands_0: %d\n", num_bands_0);
402
            return -1;
403
        }
404
405
51
        vk0[0] = 0;
406
407
51
        make_bands(vk0+1, sbr->k[0], sbr->k[1], num_bands_0);
408
409











1037
        AV_QSORT(vk0 + 1, num_bands_0, int16_t, qsort_comparison_function_int16);
410
51
        vdk0_max = vk0[num_bands_0];
411
412
51
        vk0[0] = sbr->k[0];
413
611
        for (k = 1; k <= num_bands_0; k++) {
414
560
            if (vk0[k] <= 0) { // Requirements (14496-3 sp04 p205)
415
                av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk0[%d]: %d\n", k, vk0[k]);
416
                return -1;
417
            }
418
560
            vk0[k] += vk0[k-1];
419
        }
420
421
51
        if (two_regions) {
422
            int16_t vk1[49];
423
#if USE_FIXED
424
            int num_bands_1;
425
426
2
            tmp = (sbr->k[2] << 23) / sbr->k[1];
427
2
            nz = 0;
428
16
            while (tmp < 0x40000000) {
429
14
              tmp <<= 1;
430
14
              nz++;
431
            }
432
2
            tmp = fixed_log(tmp - 0x80000000);
433
2
            tmp = (int)(((int64_t)tmp * CONST_RECIP_LN2 + 0x20000000) >> 30);
434
2
            tmp = (((tmp + 0x80) >> 8) + ((8 - nz) << 23)) * half_bands;
435
2
            if (spectrum->bs_alter_scale)
436
2
                tmp = (int)(((int64_t)tmp * CONST_076923 + 0x40000000) >> 31);
437
2
            num_bands_1 = ((tmp + 0x400000) >> 23) * 2;
438
#else
439
20
            float invwarp = spectrum->bs_alter_scale ? 0.76923076923076923077f
440
10
                                                     : 1.0f; // bs_alter_scale = {0,1}
441
10
            int num_bands_1 = lrintf(half_bands * invwarp *
442
10
                                     log2f(sbr->k[2] / (float)sbr->k[1])) * 2;
443
#endif /* USE_FIXED */
444
12
            make_bands(vk1+1, sbr->k[1], sbr->k[2], num_bands_1);
445
446
12
            vdk1_min = array_min_int16(vk1 + 1, num_bands_1);
447
448
12
            if (vdk1_min < vdk0_max) {
449
                int change;
450
                AV_QSORT(vk1 + 1, num_bands_1, int16_t, qsort_comparison_function_int16);
451
                change = FFMIN(vdk0_max - vk1[1], (vk1[num_bands_1] - vk1[1]) >> 1);
452
                vk1[1]           += change;
453
                vk1[num_bands_1] -= change;
454
            }
455
456











32
            AV_QSORT(vk1 + 1, num_bands_1, int16_t, qsort_comparison_function_int16);
457
458
12
            vk1[0] = sbr->k[1];
459
40
            for (k = 1; k <= num_bands_1; k++) {
460
28
                if (vk1[k] <= 0) { // Requirements (14496-3 sp04 p205)
461
                    av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk1[%d]: %d\n", k, vk1[k]);
462
                    return -1;
463
                }
464
28
                vk1[k] += vk1[k-1];
465
            }
466
467
12
            sbr->n_master = num_bands_0 + num_bands_1;
468
12
            if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
469
                return -1;
470
12
            memcpy(&sbr->f_master[0],               vk0,
471
12
                   (num_bands_0 + 1) * sizeof(sbr->f_master[0]));
472
12
            memcpy(&sbr->f_master[num_bands_0 + 1], vk1 + 1,
473
                    num_bands_1      * sizeof(sbr->f_master[0]));
474
475
        } else {
476
39
            sbr->n_master = num_bands_0;
477
39
            if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
478
                return -1;
479
39
            memcpy(sbr->f_master, vk0, (num_bands_0 + 1) * sizeof(sbr->f_master[0]));
480
        }
481
    }
482
483
65
    return 0;
484
}
485
486
/// High Frequency Generation - Patch Construction (14496-3 sp04 p216 fig. 4.46)
487
65
static int sbr_hf_calc_npatches(AACContext *ac, SpectralBandReplication *sbr)
488
{
489
65
    int i, k, last_k = -1, last_msb = -1, sb = 0;
490
65
    int msb = sbr->k[0];
491
65
    int usb = sbr->kx[1];
492
65
    int goal_sb = ((1000 << 11) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
493
494
65
    sbr->num_patches = 0;
495
496
65
    if (goal_sb < sbr->kx[1] + sbr->m[1]) {
497
334
        for (k = 0; sbr->f_master[k] < goal_sb; k++) ;
498
    } else
499
34
        k = sbr->n_master;
500
501
    do {
502
186
        int odd = 0;
503

186
        if (k == last_k && msb == last_msb) {
504
            av_log(ac->avctx, AV_LOG_ERROR, "patch construction failed\n");
505
            return AVERROR_INVALIDDATA;
506
        }
507
186
        last_k = k;
508
186
        last_msb = msb;
509

1060
        for (i = k; i == k || sb > (sbr->k[0] - 1 + msb - odd); i--) {
510
874
            sb = sbr->f_master[i];
511
874
            odd = (sb + sbr->k[0]) & 1;
512
        }
513
514
        // Requirements (14496-3 sp04 p205) sets the maximum number of patches to 5.
515
        // After this check the final number of patches can still be six which is
516
        // illegal however the Coding Technologies decoder check stream has a final
517
        // count of 6 patches
518
186
        if (sbr->num_patches > 5) {
519
            av_log(ac->avctx, AV_LOG_ERROR, "Too many patches: %d\n", sbr->num_patches);
520
            return -1;
521
        }
522
523
186
        sbr->patch_num_subbands[sbr->num_patches]  = FFMAX(sb - usb, 0);
524
186
        sbr->patch_start_subband[sbr->num_patches] = sbr->k[0] - odd - sbr->patch_num_subbands[sbr->num_patches];
525
526
186
        if (sbr->patch_num_subbands[sbr->num_patches] > 0) {
527
186
            usb = sb;
528
186
            msb = sb;
529
186
            sbr->num_patches++;
530
        } else
531
            msb = sbr->kx[1];
532
533
186
        if (sbr->f_master[k] - sb < 3)
534
86
            k = sbr->n_master;
535
186
    } while (sb != sbr->kx[1] + sbr->m[1]);
536
537
65
    if (sbr->num_patches > 1 &&
538
63
        sbr->patch_num_subbands[sbr->num_patches - 1] < 3)
539
        sbr->num_patches--;
540
541
65
    return 0;
542
}
543
544
/// Derived Frequency Band Tables (14496-3 sp04 p197)
545
65
static int sbr_make_f_derived(AACContext *ac, SpectralBandReplication *sbr)
546
{
547
    int k, temp;
548
#if USE_FIXED
549
5
    int nz = 0;
550
#endif /* USE_FIXED */
551
552
65
    sbr->n[1] = sbr->n_master - sbr->spectrum_params.bs_xover_band;
553
65
    sbr->n[0] = (sbr->n[1] + 1) >> 1;
554
555
65
    memcpy(sbr->f_tablehigh, &sbr->f_master[sbr->spectrum_params.bs_xover_band],
556
65
           (sbr->n[1] + 1) * sizeof(sbr->f_master[0]));
557
65
    sbr->m[1] = sbr->f_tablehigh[sbr->n[1]] - sbr->f_tablehigh[0];
558
65
    sbr->kx[1] = sbr->f_tablehigh[0];
559
560
    // Requirements (14496-3 sp04 p205)
561
65
    if (sbr->kx[1] + sbr->m[1] > 64) {
562
        av_log(ac->avctx, AV_LOG_ERROR,
563
               "Stop frequency border too high: %d\n", sbr->kx[1] + sbr->m[1]);
564
        return -1;
565
    }
566
65
    if (sbr->kx[1] > 32) {
567
        av_log(ac->avctx, AV_LOG_ERROR, "Start frequency border too high: %d\n", sbr->kx[1]);
568
        return -1;
569
    }
570
571
65
    sbr->f_tablelow[0] = sbr->f_tablehigh[0];
572
65
    temp = sbr->n[1] & 1;
573
485
    for (k = 1; k <= sbr->n[0]; k++)
574
420
        sbr->f_tablelow[k] = sbr->f_tablehigh[2 * k - temp];
575
#if USE_FIXED
576
5
    temp = (sbr->k[2] << 23) / sbr->kx[1];
577
35
    while (temp < 0x40000000) {
578
30
        temp <<= 1;
579
30
        nz++;
580
    }
581
5
    temp = fixed_log(temp - 0x80000000);
582
5
    temp = (int)(((int64_t)temp * CONST_RECIP_LN2 + 0x20000000) >> 30);
583
5
    temp = (((temp + 0x80) >> 8) + ((8 - nz) << 23)) * sbr->spectrum_params.bs_noise_bands;
584
585
5
    sbr->n_q = (temp + 0x400000) >> 23;
586
5
    if (sbr->n_q < 1)
587
        sbr->n_q = 1;
588
#else
589
60
    sbr->n_q = FFMAX(1, lrintf(sbr->spectrum_params.bs_noise_bands *
590
                               log2f(sbr->k[2] / (float)sbr->kx[1]))); // 0 <= bs_noise_bands <= 3
591
#endif /* USE_FIXED */
592
593
65
    if (sbr->n_q > 5) {
594
        av_log(ac->avctx, AV_LOG_ERROR, "Too many noise floor scale factors: %d\n", sbr->n_q);
595
        return -1;
596
    }
597
598
65
    sbr->f_tablenoise[0] = sbr->f_tablelow[0];
599
65
    temp = 0;
600
266
    for (k = 1; k <= sbr->n_q; k++) {
601
201
        temp += (sbr->n[0] - temp) / (sbr->n_q + 1 - k);
602
201
        sbr->f_tablenoise[k] = sbr->f_tablelow[temp];
603
    }
604
605
65
    if (sbr_hf_calc_npatches(ac, sbr) < 0)
606
        return -1;
607
608
65
    sbr_make_f_tablelim(sbr);
609
610
65
    sbr->data[0].f_indexnoise = 0;
611
65
    sbr->data[1].f_indexnoise = 0;
612
613
65
    return 0;
614
}
615
616
22940
static av_always_inline void get_bits1_vector(GetBitContext *gb, uint8_t *vec,
617
                                              int elements)
618
{
619
    int i;
620
71495
    for (i = 0; i < elements; i++) {
621
48555
        vec[i] = get_bits1(gb);
622
    }
623
22940
}
624
625
/** ceil(log2(index+1)) */
626
static const int8_t ceil_log2[] = {
627
    0, 1, 2, 2, 3, 3,
628
};
629
630
7793
static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,
631
                         GetBitContext *gb, SBRData *ch_data)
632
{
633
    int i;
634
7793
    int bs_pointer = 0;
635
    // frameLengthFlag ? 15 : 16; 960 sample length frames unsupported; this value is numTimeSlots
636
7793
    int abs_bord_trail = 16;
637
    int num_rel_lead, num_rel_trail;
638
7793
    unsigned bs_num_env_old = ch_data->bs_num_env;
639
    int bs_frame_class, bs_num_env;
640
641
7793
    ch_data->bs_freq_res[0] = ch_data->bs_freq_res[ch_data->bs_num_env];
642
7793
    ch_data->bs_amp_res = sbr->bs_amp_res_header;
643
7793
    ch_data->t_env_num_env_old = ch_data->t_env[bs_num_env_old];
644
645

7793
    switch (bs_frame_class = get_bits(gb, 2)) {
646
6395
    case FIXFIX:
647
6395
        bs_num_env = 1 << get_bits(gb, 2);
648
6395
        if (bs_num_env > 4) {
649
            av_log(ac->avctx, AV_LOG_ERROR,
650
                   "Invalid bitstream, too many SBR envelopes in FIXFIX type SBR frame: %d\n",
651
                   bs_num_env);
652
            return -1;
653
        }
654
6395
        ch_data->bs_num_env = bs_num_env;
655
6395
        num_rel_lead                        = ch_data->bs_num_env - 1;
656
6395
        if (ch_data->bs_num_env == 1)
657
4929
            ch_data->bs_amp_res = 0;
658
659
660
6395
        ch_data->t_env[0]                   = 0;
661
6395
        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
662
663
6395
        abs_bord_trail = (abs_bord_trail + (ch_data->bs_num_env >> 1)) /
664
6395
                   ch_data->bs_num_env;
665
7861
        for (i = 0; i < num_rel_lead; i++)
666
1466
            ch_data->t_env[i + 1] = ch_data->t_env[i] + abs_bord_trail;
667
668
6395
        ch_data->bs_freq_res[1] = get_bits1(gb);
669
7861
        for (i = 1; i < ch_data->bs_num_env; i++)
670
1466
            ch_data->bs_freq_res[i + 1] = ch_data->bs_freq_res[1];
671
6395
        break;
672
630
    case FIXVAR:
673
630
        abs_bord_trail                     += get_bits(gb, 2);
674
630
        num_rel_trail                       = get_bits(gb, 2);
675
630
        ch_data->bs_num_env                 = num_rel_trail + 1;
676
630
        ch_data->t_env[0]                   = 0;
677
630
        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
678
679
1992
        for (i = 0; i < num_rel_trail; i++)
680
1362
            ch_data->t_env[ch_data->bs_num_env - 1 - i] =
681
1362
                ch_data->t_env[ch_data->bs_num_env - i] - 2 * get_bits(gb, 2) - 2;
682
683
630
        bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
684
685
2622
        for (i = 0; i < ch_data->bs_num_env; i++)
686
1992
            ch_data->bs_freq_res[ch_data->bs_num_env - i] = get_bits1(gb);
687
630
        break;
688
620
    case VARFIX:
689
620
        ch_data->t_env[0]                   = get_bits(gb, 2);
690
620
        num_rel_lead                        = get_bits(gb, 2);
691
620
        ch_data->bs_num_env                 = num_rel_lead + 1;
692
620
        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
693
694
1396
        for (i = 0; i < num_rel_lead; i++)
695
776
            ch_data->t_env[i + 1] = ch_data->t_env[i] + 2 * get_bits(gb, 2) + 2;
696
697
620
        bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
698
699
620
        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env);
700
620
        break;
701
148
    case VARVAR:
702
148
        ch_data->t_env[0]                   = get_bits(gb, 2);
703
148
        abs_bord_trail                     += get_bits(gb, 2);
704
148
        num_rel_lead                        = get_bits(gb, 2);
705
148
        num_rel_trail                       = get_bits(gb, 2);
706
148
        bs_num_env                          = num_rel_lead + num_rel_trail + 1;
707
708
148
        if (bs_num_env > 5) {
709
            av_log(ac->avctx, AV_LOG_ERROR,
710
                   "Invalid bitstream, too many SBR envelopes in VARVAR type SBR frame: %d\n",
711
                   bs_num_env);
712
            return -1;
713
        }
714
148
        ch_data->bs_num_env = bs_num_env;
715
716
148
        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
717
718
220
        for (i = 0; i < num_rel_lead; i++)
719
72
            ch_data->t_env[i + 1] = ch_data->t_env[i] + 2 * get_bits(gb, 2) + 2;
720
439
        for (i = 0; i < num_rel_trail; i++)
721
291
            ch_data->t_env[ch_data->bs_num_env - 1 - i] =
722
291
                ch_data->t_env[ch_data->bs_num_env - i] - 2 * get_bits(gb, 2) - 2;
723
724
148
        bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
725
726
148
        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env);
727
148
        break;
728
    }
729
7793
    ch_data->bs_frame_class = bs_frame_class;
730
731
7793
    av_assert0(bs_pointer >= 0);
732
7793
    if (bs_pointer > ch_data->bs_num_env + 1) {
733
        av_log(ac->avctx, AV_LOG_ERROR,
734
               "Invalid bitstream, bs_pointer points to a middle noise border outside the time borders table: %d\n",
735
               bs_pointer);
736
        return -1;
737
    }
738
739
19553
    for (i = 1; i <= ch_data->bs_num_env; i++) {
740
11760
        if (ch_data->t_env[i-1] >= ch_data->t_env[i]) {
741
            av_log(ac->avctx, AV_LOG_ERROR, "Not strictly monotone time borders\n");
742
            return -1;
743
        }
744
    }
745
746
7793
    ch_data->bs_num_noise = (ch_data->bs_num_env > 1) + 1;
747
748
7793
    ch_data->t_q[0]                     = ch_data->t_env[0];
749
7793
    ch_data->t_q[ch_data->bs_num_noise] = ch_data->t_env[ch_data->bs_num_env];
750
7793
    if (ch_data->bs_num_noise > 1) {
751
        int idx;
752
2864
        if (ch_data->bs_frame_class == FIXFIX) {
753
1466
            idx = ch_data->bs_num_env >> 1;
754
1398
        } else if (ch_data->bs_frame_class & 1) { // FIXVAR or VARVAR
755
778
            idx = ch_data->bs_num_env - FFMAX(bs_pointer - 1, 1);
756
        } else { // VARFIX
757
620
            if (!bs_pointer)
758
464
                idx = 1;
759
156
            else if (bs_pointer == 1)
760
156
                idx = ch_data->bs_num_env - 1;
761
            else // bs_pointer > 1
762
                idx = bs_pointer - 1;
763
        }
764
2864
        ch_data->t_q[1] = ch_data->t_env[idx];
765
    }
766
767
7793
    ch_data->e_a[0] = -(ch_data->e_a[1] != bs_num_env_old); // l_APrev
768
7793
    ch_data->e_a[1] = -1;
769

7793
    if ((ch_data->bs_frame_class & 1) && bs_pointer) { // FIXVAR or VARVAR and bs_pointer != 0
770
778
        ch_data->e_a[1] = ch_data->bs_num_env + 1 - bs_pointer;
771

7015
    } else if ((ch_data->bs_frame_class == 2) && (bs_pointer > 1)) // VARFIX and bs_pointer > 1
772
        ch_data->e_a[1] = bs_pointer - 1;
773
774
7793
    return 0;
775
}
776
777
2625
static void copy_sbr_grid(SBRData *dst, const SBRData *src) {
778
    //These variables are saved from the previous frame rather than copied
779
2625
    dst->bs_freq_res[0]    = dst->bs_freq_res[dst->bs_num_env];
780
2625
    dst->t_env_num_env_old = dst->t_env[dst->bs_num_env];
781
2625
    dst->e_a[0]            = -(dst->e_a[1] != dst->bs_num_env);
782
783
    //These variables are read from the bitstream and therefore copied
784
2625
    memcpy(dst->bs_freq_res+1, src->bs_freq_res+1, sizeof(dst->bs_freq_res)-sizeof(*dst->bs_freq_res));
785
2625
    memcpy(dst->t_env,         src->t_env,         sizeof(dst->t_env));
786
2625
    memcpy(dst->t_q,           src->t_q,           sizeof(dst->t_q));
787
2625
    dst->bs_num_env        = src->bs_num_env;
788
2625
    dst->bs_amp_res        = src->bs_amp_res;
789
2625
    dst->bs_num_noise      = src->bs_num_noise;
790
2625
    dst->bs_frame_class    = src->bs_frame_class;
791
2625
    dst->e_a[1]            = src->e_a[1];
792
2625
}
793
794
/// Read how the envelope and noise floor data is delta coded
795
10418
static void read_sbr_dtdf(SpectralBandReplication *sbr, GetBitContext *gb,
796
                          SBRData *ch_data)
797
{
798
10418
    get_bits1_vector(gb, ch_data->bs_df_env,   ch_data->bs_num_env);
799
10418
    get_bits1_vector(gb, ch_data->bs_df_noise, ch_data->bs_num_noise);
800
10418
}
801
802
/// Read inverse filtering data
803
7793
static void read_sbr_invf(SpectralBandReplication *sbr, GetBitContext *gb,
804
                          SBRData *ch_data)
805
{
806
    int i;
807
808
7793
    memcpy(ch_data->bs_invf_mode[1], ch_data->bs_invf_mode[0], 5 * sizeof(uint8_t));
809
31778
    for (i = 0; i < sbr->n_q; i++)
810
23985
        ch_data->bs_invf_mode[0][i] = get_bits(gb, 2);
811
7793
}
812
813
10418
static int read_sbr_envelope(AACContext *ac, SpectralBandReplication *sbr, GetBitContext *gb,
814
                              SBRData *ch_data, int ch)
815
{
816
    int bits;
817
    int i, j, k;
818
    VLC_TYPE (*t_huff)[2], (*f_huff)[2];
819
    int t_lav, f_lav;
820

10418
    const int delta = (ch == 1 && sbr->bs_coupling == 1) + 1;
821
10418
    const int odd = sbr->n[1] & 1;
822
823

10418
    if (sbr->bs_coupling && ch) {
824
2625
        if (ch_data->bs_amp_res) {
825
582
            bits   = 5;
826
582
            t_huff = vlc_sbr[T_HUFFMAN_ENV_BAL_3_0DB].table;
827
582
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_BAL_3_0DB];
828
582
            f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_3_0DB].table;
829
582
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_3_0DB];
830
        } else {
831
2043
            bits   = 6;
832
2043
            t_huff = vlc_sbr[T_HUFFMAN_ENV_BAL_1_5DB].table;
833
2043
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_BAL_1_5DB];
834
2043
            f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_1_5DB].table;
835
2043
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_1_5DB];
836
        }
837
    } else {
838
7793
        if (ch_data->bs_amp_res) {
839
2864
            bits   = 6;
840
2864
            t_huff = vlc_sbr[T_HUFFMAN_ENV_3_0DB].table;
841
2864
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_3_0DB];
842
2864
            f_huff = vlc_sbr[F_HUFFMAN_ENV_3_0DB].table;
843
2864
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_3_0DB];
844
        } else {
845
4929
            bits   = 7;
846
4929
            t_huff = vlc_sbr[T_HUFFMAN_ENV_1_5DB].table;
847
4929
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_1_5DB];
848
4929
            f_huff = vlc_sbr[F_HUFFMAN_ENV_1_5DB].table;
849
4929
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_1_5DB];
850
        }
851
    }
852
853
25578
    for (i = 0; i < ch_data->bs_num_env; i++) {
854
15160
        if (ch_data->bs_df_env[i]) {
855
            // bs_freq_res[0] == bs_freq_res[bs_num_env] from prev frame
856
4947
            if (ch_data->bs_freq_res[i + 1] == ch_data->bs_freq_res[i]) {
857
55736
                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {
858
51282
                    ch_data->env_facs_q[i + 1][j] = ch_data->env_facs_q[i][j] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
859
51282
                    if (ch_data->env_facs_q[i + 1][j] > 127U) {
860
                        av_log(ac->avctx, AV_LOG_ERROR, "env_facs_q %d is invalid\n", ch_data->env_facs_q[i + 1][j]);
861
                        return AVERROR_INVALIDDATA;
862
                    }
863
                }
864
493
            } else if (ch_data->bs_freq_res[i + 1]) {
865
4655
                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {
866
4282
                    k = (j + odd) >> 1; // find k such that f_tablelow[k] <= f_tablehigh[j] < f_tablelow[k + 1]
867
4282
                    ch_data->env_facs_q[i + 1][j] = ch_data->env_facs_q[i][k] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
868
4282
                    if (ch_data->env_facs_q[i + 1][j] > 127U) {
869
                        av_log(ac->avctx, AV_LOG_ERROR, "env_facs_q %d is invalid\n", ch_data->env_facs_q[i + 1][j]);
870
                        return AVERROR_INVALIDDATA;
871
                    }
872
                }
873
            } else {
874
799
                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {
875
679
                    k = j ? 2*j - odd : 0; // find k such that f_tablehigh[k] == f_tablelow[j]
876
679
                    ch_data->env_facs_q[i + 1][j] = ch_data->env_facs_q[i][k] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
877
679
                    if (ch_data->env_facs_q[i + 1][j] > 127U) {
878
                        av_log(ac->avctx, AV_LOG_ERROR, "env_facs_q %d is invalid\n", ch_data->env_facs_q[i + 1][j]);
879
                        return AVERROR_INVALIDDATA;
880
                    }
881
                }
882
            }
883
        } else {
884
10213
            ch_data->env_facs_q[i + 1][0] = delta * get_bits(gb, bits); // bs_env_start_value_balance
885
115673
            for (j = 1; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {
886
105460
                ch_data->env_facs_q[i + 1][j] = ch_data->env_facs_q[i + 1][j - 1] + delta * (get_vlc2(gb, f_huff, 9, 3) - f_lav);
887
105460
                if (ch_data->env_facs_q[i + 1][j] > 127U) {
888
                    av_log(ac->avctx, AV_LOG_ERROR, "env_facs_q %d is invalid\n", ch_data->env_facs_q[i + 1][j]);
889
                    return AVERROR_INVALIDDATA;
890
                }
891
            }
892
        }
893
    }
894
895
    //assign 0th elements of env_facs_q from last elements
896
10418
    memcpy(ch_data->env_facs_q[0], ch_data->env_facs_q[ch_data->bs_num_env],
897
           sizeof(ch_data->env_facs_q[0]));
898
899
10418
    return 0;
900
}
901
902
10418
static int read_sbr_noise(AACContext *ac, SpectralBandReplication *sbr, GetBitContext *gb,
903
                           SBRData *ch_data, int ch)
904
{
905
    int i, j;
906
    VLC_TYPE (*t_huff)[2], (*f_huff)[2];
907
    int t_lav, f_lav;
908

10418
    int delta = (ch == 1 && sbr->bs_coupling == 1) + 1;
909
910

10418
    if (sbr->bs_coupling && ch) {
911
2625
        t_huff = vlc_sbr[T_HUFFMAN_NOISE_BAL_3_0DB].table;
912
2625
        t_lav  = vlc_sbr_lav[T_HUFFMAN_NOISE_BAL_3_0DB];
913
2625
        f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_3_0DB].table;
914
2625
        f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_3_0DB];
915
    } else {
916
7793
        t_huff = vlc_sbr[T_HUFFMAN_NOISE_3_0DB].table;
917
7793
        t_lav  = vlc_sbr_lav[T_HUFFMAN_NOISE_3_0DB];
918
7793
        f_huff = vlc_sbr[F_HUFFMAN_ENV_3_0DB].table;
919
7793
        f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_3_0DB];
920
    }
921
922
24282
    for (i = 0; i < ch_data->bs_num_noise; i++) {
923
13864
        if (ch_data->bs_df_noise[i]) {
924
43693
            for (j = 0; j < sbr->n_q; j++) {
925
32863
                ch_data->noise_facs_q[i + 1][j] = ch_data->noise_facs_q[i][j] + delta * (get_vlc2(gb, t_huff, 9, 2) - t_lav);
926
32863
                if (ch_data->noise_facs_q[i + 1][j] > 30U) {
927
                    av_log(ac->avctx, AV_LOG_ERROR, "noise_facs_q %d is invalid\n", ch_data->noise_facs_q[i + 1][j]);
928
                    return AVERROR_INVALIDDATA;
929
                }
930
            }
931
        } else {
932
3034
            ch_data->noise_facs_q[i + 1][0] = delta * get_bits(gb, 5); // bs_noise_start_value_balance or bs_noise_start_value_level
933
8944
            for (j = 1; j < sbr->n_q; j++) {
934
5910
                ch_data->noise_facs_q[i + 1][j] = ch_data->noise_facs_q[i + 1][j - 1] + delta * (get_vlc2(gb, f_huff, 9, 3) - f_lav);
935
5910
                if (ch_data->noise_facs_q[i + 1][j] > 30U) {
936
                    av_log(ac->avctx, AV_LOG_ERROR, "noise_facs_q %d is invalid\n", ch_data->noise_facs_q[i + 1][j]);
937
                    return AVERROR_INVALIDDATA;
938
                }
939
            }
940
        }
941
    }
942
943
    //assign 0th elements of noise_facs_q from last elements
944
10418
    memcpy(ch_data->noise_facs_q[0], ch_data->noise_facs_q[ch_data->bs_num_noise],
945
           sizeof(ch_data->noise_facs_q[0]));
946
10418
    return 0;
947
}
948
949
1616
static void read_sbr_extension(AACContext *ac, SpectralBandReplication *sbr,
950
                               GetBitContext *gb,
951
                               int bs_extension_id, int *num_bits_left)
952
{
953
1616
    switch (bs_extension_id) {
954
1616
    case EXTENSION_ID_PS:
955
1616
        if (!ac->oc[1].m4ac.ps) {
956
            av_log(ac->avctx, AV_LOG_ERROR, "Parametric Stereo signaled to be not-present but was found in the bitstream.\n");
957
            skip_bits_long(gb, *num_bits_left); // bs_fill_bits
958
            *num_bits_left = 0;
959
        } else {
960
1616
            *num_bits_left -= AAC_RENAME(ff_ps_read_data)(ac->avctx, gb, &sbr->ps, *num_bits_left);
961
1616
            ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
962
        }
963
1616
        break;
964
    default:
965
        // some files contain 0-padding
966
        if (bs_extension_id || *num_bits_left > 16 || show_bits(gb, *num_bits_left))
967
            avpriv_request_sample(ac->avctx, "Reserved SBR extensions");
968
        skip_bits_long(gb, *num_bits_left); // bs_fill_bits
969
        *num_bits_left = 0;
970
        break;
971
    }
972
1616
}
973
974
2646
static int read_sbr_single_channel_element(AACContext *ac,
975
                                            SpectralBandReplication *sbr,
976
                                            GetBitContext *gb)
977
{
978
    int ret;
979
980
2646
    if (get_bits1(gb)) // bs_data_extra
981
        skip_bits(gb, 4); // bs_reserved
982
983
2646
    if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))
984
        return -1;
985
2646
    read_sbr_dtdf(sbr, gb, &sbr->data[0]);
986
2646
    read_sbr_invf(sbr, gb, &sbr->data[0]);
987
2646
    if((ret = read_sbr_envelope(ac, sbr, gb, &sbr->data[0], 0)) < 0)
988
        return ret;
989
2646
    if((ret = read_sbr_noise(ac, sbr, gb, &sbr->data[0], 0)) < 0)
990
        return ret;
991
992
2646
    if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb)))
993
174
        get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]);
994
995
2646
    return 0;
996
}
997
998
3886
static int read_sbr_channel_pair_element(AACContext *ac,
999
                                          SpectralBandReplication *sbr,
1000
                                          GetBitContext *gb)
1001
{
1002
    int ret;
1003
1004
3886
    if (get_bits1(gb))    // bs_data_extra
1005
        skip_bits(gb, 8); // bs_reserved
1006
1007
3886
    if ((sbr->bs_coupling = get_bits1(gb))) {
1008
2625
        if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))
1009
            return -1;
1010
2625
        copy_sbr_grid(&sbr->data[1], &sbr->data[0]);
1011
2625
        read_sbr_dtdf(sbr, gb, &sbr->data[0]);
1012
2625
        read_sbr_dtdf(sbr, gb, &sbr->data[1]);
1013
2625
        read_sbr_invf(sbr, gb, &sbr->data[0]);
1014
2625
        memcpy(sbr->data[1].bs_invf_mode[1], sbr->data[1].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0]));
1015
2625
        memcpy(sbr->data[1].bs_invf_mode[0], sbr->data[0].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0]));
1016
2625
        if((ret = read_sbr_envelope(ac, sbr, gb, &sbr->data[0], 0)) < 0)
1017
            return ret;
1018
2625
        if((ret = read_sbr_noise(ac, sbr, gb, &sbr->data[0], 0)) < 0)
1019
            return ret;
1020
2625
        if((ret = read_sbr_envelope(ac, sbr, gb, &sbr->data[1], 1)) < 0)
1021
            return ret;
1022
2625
        if((ret = read_sbr_noise(ac, sbr, gb, &sbr->data[1], 1)) < 0)
1023
            return ret;
1024
    } else {
1025

2522
        if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]) ||
1026
1261
            read_sbr_grid(ac, sbr, gb, &sbr->data[1]))
1027
            return -1;
1028
1261
        read_sbr_dtdf(sbr, gb, &sbr->data[0]);
1029
1261
        read_sbr_dtdf(sbr, gb, &sbr->data[1]);
1030
1261
        read_sbr_invf(sbr, gb, &sbr->data[0]);
1031
1261
        read_sbr_invf(sbr, gb, &sbr->data[1]);
1032
1261
        if((ret = read_sbr_envelope(ac, sbr, gb, &sbr->data[0], 0)) < 0)
1033
            return ret;
1034
1261
        if((ret = read_sbr_envelope(ac, sbr, gb, &sbr->data[1], 1)) < 0)
1035
            return ret;
1036
1261
        if((ret = read_sbr_noise(ac, sbr, gb, &sbr->data[0], 0)) < 0)
1037
            return ret;
1038
1261
        if((ret = read_sbr_noise(ac, sbr, gb, &sbr->data[1], 1)) < 0)
1039
            return ret;
1040
    }
1041
1042
3886
    if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb)))
1043
698
        get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]);
1044
3886
    if ((sbr->data[1].bs_add_harmonic_flag = get_bits1(gb)))
1045
464
        get_bits1_vector(gb, sbr->data[1].bs_add_harmonic, sbr->n[1]);
1046
1047
3886
    return 0;
1048
}
1049
1050
6532
static unsigned int read_sbr_data(AACContext *ac, SpectralBandReplication *sbr,
1051
                                  GetBitContext *gb, int id_aac)
1052
{
1053
6532
    unsigned int cnt = get_bits_count(gb);
1054
1055
6532
    sbr->id_aac = id_aac;
1056
6532
    sbr->ready_for_dequant = 1;
1057
1058

6532
    if (id_aac == TYPE_SCE || id_aac == TYPE_CCE) {
1059
2646
        if (read_sbr_single_channel_element(ac, sbr, gb)) {
1060
            sbr_turnoff(sbr);
1061
            return get_bits_count(gb) - cnt;
1062
        }
1063
3886
    } else if (id_aac == TYPE_CPE) {
1064
3886
        if (read_sbr_channel_pair_element(ac, sbr, gb)) {
1065
            sbr_turnoff(sbr);
1066
            return get_bits_count(gb) - cnt;
1067
        }
1068
    } else {
1069
        av_log(ac->avctx, AV_LOG_ERROR,
1070
            "Invalid bitstream - cannot apply SBR to element type %d\n", id_aac);
1071
        sbr_turnoff(sbr);
1072
        return get_bits_count(gb) - cnt;
1073
    }
1074
6532
    if (get_bits1(gb)) { // bs_extended_data
1075
1616
        int num_bits_left = get_bits(gb, 4); // bs_extension_size
1076
1616
        if (num_bits_left == 15)
1077
258
            num_bits_left += get_bits(gb, 8); // bs_esc_count
1078
1079
1616
        num_bits_left <<= 3;
1080
3232
        while (num_bits_left > 7) {
1081
1616
            num_bits_left -= 2;
1082
1616
            read_sbr_extension(ac, sbr, gb, get_bits(gb, 2), &num_bits_left); // bs_extension_id
1083
        }
1084
1616
        if (num_bits_left < 0) {
1085
            av_log(ac->avctx, AV_LOG_ERROR, "SBR Extension over read.\n");
1086
        }
1087
1616
        if (num_bits_left > 0)
1088
1451
            skip_bits(gb, num_bits_left);
1089
    }
1090
1091
6532
    return get_bits_count(gb) - cnt;
1092
}
1093
1094
65
static void sbr_reset(AACContext *ac, SpectralBandReplication *sbr)
1095
{
1096
    int err;
1097
65
    err = sbr_make_f_master(ac, sbr, &sbr->spectrum_params);
1098
65
    if (err >= 0)
1099
65
        err = sbr_make_f_derived(ac, sbr);
1100
65
    if (err < 0) {
1101
        av_log(ac->avctx, AV_LOG_ERROR,
1102
               "SBR reset failed. Switching SBR to pure upsampling mode.\n");
1103
        sbr_turnoff(sbr);
1104
    }
1105
65
}
1106
1107
/**
1108
 * Decode Spectral Band Replication extension data; reference: table 4.55.
1109
 *
1110
 * @param   crc flag indicating the presence of CRC checksum
1111
 * @param   cnt length of TYPE_FIL syntactic element in bytes
1112
 *
1113
 * @return  Returns number of bytes consumed from the TYPE_FIL element.
1114
 */
1115
10901
int AAC_RENAME(ff_decode_sbr_extension)(AACContext *ac, SpectralBandReplication *sbr,
1116
                            GetBitContext *gb_host, int crc, int cnt, int id_aac)
1117
{
1118
10901
    unsigned int num_sbr_bits = 0, num_align_bits;
1119
    unsigned bytes_read;
1120
10901
    GetBitContext gbc = *gb_host, *gb = &gbc;
1121
10901
    skip_bits_long(gb_host, cnt*8 - 4);
1122
1123
10901
    sbr->reset = 0;
1124
1125
10901
    if (!sbr->sample_rate)
1126
82
        sbr->sample_rate = 2 * ac->oc[1].m4ac.sample_rate; //TODO use the nominal sample rate for arbitrary sample rate support
1127
10901
    if (!ac->oc[1].m4ac.ext_sample_rate)
1128
18
        ac->oc[1].m4ac.ext_sample_rate = 2 * ac->oc[1].m4ac.sample_rate;
1129
1130
10901
    if (crc) {
1131
        skip_bits(gb, 10); // bs_sbr_crc_bits; TODO - implement CRC check
1132
        num_sbr_bits += 10;
1133
    }
1134
1135
    //Save some state from the previous frame.
1136
10901
    sbr->kx[0] = sbr->kx[1];
1137
10901
    sbr->m[0] = sbr->m[1];
1138
10901
    sbr->kx_and_m_pushed = 1;
1139
1140
10901
    num_sbr_bits++;
1141
10901
    if (get_bits1(gb)) // bs_header_flag
1142
489
        num_sbr_bits += read_sbr_header(sbr, gb);
1143
1144
10901
    if (sbr->reset)
1145
65
        sbr_reset(ac, sbr);
1146
1147
10901
    if (sbr->start)
1148
6532
        num_sbr_bits  += read_sbr_data(ac, sbr, gb, id_aac);
1149
1150
10901
    num_align_bits = ((cnt << 3) - 4 - num_sbr_bits) & 7;
1151
10901
    bytes_read = ((num_sbr_bits + num_align_bits + 4) >> 3);
1152
1153
10901
    if (bytes_read > cnt) {
1154
        av_log(ac->avctx, AV_LOG_ERROR,
1155
               "Expected to read %d SBR bytes actually read %d.\n", cnt, bytes_read);
1156
        sbr_turnoff(sbr);
1157
    }
1158
10901
    return cnt;
1159
}
1160
1161
/**
1162
 * Analysis QMF Bank (14496-3 sp04 p206)
1163
 *
1164
 * @param   x       pointer to the beginning of the first sample window
1165
 * @param   W       array of complex-valued samples split into subbands
1166
 */
1167
#ifndef sbr_qmf_analysis
1168
#if USE_FIXED
1169
8328
static void sbr_qmf_analysis(AVFixedDSPContext *dsp, FFTContext *mdct,
1170
#else
1171
11409
static void sbr_qmf_analysis(AVFloatDSPContext *dsp, FFTContext *mdct,
1172
#endif /* USE_FIXED */
1173
                             SBRDSPContext *sbrdsp, const INTFLOAT *in, INTFLOAT *x,
1174
                             INTFLOAT z[320], INTFLOAT W[2][32][32][2], int buf_idx)
1175
{
1176
    int i;
1177
#if USE_FIXED
1178
    int j;
1179
#endif
1180
19737
    memcpy(x    , x+1024, (320-32)*sizeof(x[0]));
1181
19737
    memcpy(x+288, in,         1024*sizeof(x[0]));
1182
651321
    for (i = 0; i < 32; i++) { // numTimeSlots*RATE = 16*2 as 960 sample frames
1183
                               // are not supported
1184
631584
        dsp->vector_fmul_reverse(z, sbr_qmf_window_ds, x, 320);
1185
631584
        sbrdsp->sum64x5(z);
1186
631584
        sbrdsp->qmf_pre_shuffle(z);
1187
#if USE_FIXED
1188
17322240
        for (j = 64; j < 128; j++) {
1189
17055744
            if (z[j] > 1<<24) {
1190
                av_log(NULL, AV_LOG_WARNING,
1191
                       "sbr_qmf_analysis: value %09d too large, setting to %09d\n",
1192
                       z[j], 1<<24);
1193
                z[j] = 1<<24;
1194
17055744
            } else if (z[j] < -(1<<24)) {
1195
                av_log(NULL, AV_LOG_WARNING,
1196
                       "sbr_qmf_analysis: value %09d too small, setting to %09d\n",
1197
                       z[j], -(1<<24));
1198
                z[j] = -(1<<24);
1199
            }
1200
        }
1201
#endif
1202
631584
        mdct->imdct_half(mdct, z, z+64);
1203
631584
        sbrdsp->qmf_post_shuffle(W[buf_idx][i], z);
1204
631584
        x += 32;
1205
    }
1206
19737
}
1207
#endif
1208
1209
/**
1210
 * Synthesis QMF Bank (14496-3 sp04 p206) and Downsampled Synthesis QMF Bank
1211
 * (14496-3 sp04 p206)
1212
 */
1213
#ifndef sbr_qmf_synthesis
1214
21736
static void sbr_qmf_synthesis(FFTContext *mdct,
1215
#if USE_FIXED
1216
                              SBRDSPContext *sbrdsp, AVFixedDSPContext *dsp,
1217
#else
1218
                              SBRDSPContext *sbrdsp, AVFloatDSPContext *dsp,
1219
#endif /* USE_FIXED */
1220
                              INTFLOAT *out, INTFLOAT X[2][38][64],
1221
                              INTFLOAT mdct_buf[2][64],
1222
                              INTFLOAT *v0, int *v_off, const unsigned int div)
1223
{
1224
    int i, n;
1225
21736
    const INTFLOAT *sbr_qmf_window = div ? sbr_qmf_window_ds : sbr_qmf_window_us;
1226
21736
    const int step = 128 >> div;
1227
    INTFLOAT *v;
1228
717288
    for (i = 0; i < 32; i++) {
1229
695552
        if (*v_off < step) {
1230
66284
            int saved_samples = (1280 - 128) >> div;
1231
66284
            memcpy(&v0[SBR_SYNTHESIS_BUF_SIZE - saved_samples], v0, saved_samples * sizeof(INTFLOAT));
1232
66284
            *v_off = SBR_SYNTHESIS_BUF_SIZE - saved_samples - step;
1233
        } else {
1234
629268
            *v_off -= step;
1235
        }
1236
695552
        v = v0 + *v_off;
1237
695552
        if (div) {
1238
4853376
            for (n = 0; n < 32; n++) {
1239
4706304
                X[0][i][   n] = -X[0][i][n];
1240
4706304
                X[0][i][32+n] =  X[1][i][31-n];
1241
            }
1242
147072
            mdct->imdct_half(mdct, mdct_buf[0], X[0][i]);
1243
147072
            sbrdsp->qmf_deint_neg(v, mdct_buf[0]);
1244
        } else {
1245
548480
            sbrdsp->neg_odd_64(X[1][i]);
1246
548480
            mdct->imdct_half(mdct, mdct_buf[0], X[0][i]);
1247
548480
            mdct->imdct_half(mdct, mdct_buf[1], X[1][i]);
1248
548480
            sbrdsp->qmf_deint_bfly(v, mdct_buf[1], mdct_buf[0]);
1249
        }
1250
695552
        dsp->vector_fmul    (out, v                , sbr_qmf_window                       , 64 >> div);
1251
695552
        dsp->vector_fmul_add(out, v + ( 192 >> div), sbr_qmf_window + ( 64 >> div), out   , 64 >> div);
1252
695552
        dsp->vector_fmul_add(out, v + ( 256 >> div), sbr_qmf_window + (128 >> div), out   , 64 >> div);
1253
695552
        dsp->vector_fmul_add(out, v + ( 448 >> div), sbr_qmf_window + (192 >> div), out   , 64 >> div);
1254
695552
        dsp->vector_fmul_add(out, v + ( 512 >> div), sbr_qmf_window + (256 >> div), out   , 64 >> div);
1255
695552
        dsp->vector_fmul_add(out, v + ( 704 >> div), sbr_qmf_window + (320 >> div), out   , 64 >> div);
1256
695552
        dsp->vector_fmul_add(out, v + ( 768 >> div), sbr_qmf_window + (384 >> div), out   , 64 >> div);
1257
695552
        dsp->vector_fmul_add(out, v + ( 960 >> div), sbr_qmf_window + (448 >> div), out   , 64 >> div);
1258
695552
        dsp->vector_fmul_add(out, v + (1024 >> div), sbr_qmf_window + (512 >> div), out   , 64 >> div);
1259
695552
        dsp->vector_fmul_add(out, v + (1216 >> div), sbr_qmf_window + (576 >> div), out   , 64 >> div);
1260
695552
        out += 64 >> div;
1261
    }
1262
21736
}
1263
#endif
1264
1265
/// Generate the subband filtered lowband
1266
19737
static int sbr_lf_gen(AACContext *ac, SpectralBandReplication *sbr,
1267
                      INTFLOAT X_low[32][40][2], const INTFLOAT W[2][32][32][2],
1268
                      int buf_idx)
1269
{
1270
    int i, k;
1271
19737
    const int t_HFGen = 8;
1272
19737
    const int i_f = 32;
1273
19737
    memset(X_low, 0, 32*sizeof(*X_low));
1274
510367
    for (k = 0; k < sbr->kx[1]; k++) {
1275
16190790
        for (i = t_HFGen; i < i_f + t_HFGen; i++) {
1276
15700160
            X_low[k][i][0] = W[buf_idx][i - t_HFGen][k][0];
1277
15700160
            X_low[k][i][1] = W[buf_idx][i - t_HFGen][k][1];
1278
        }
1279
    }
1280
19737
    buf_idx = 1-buf_idx;
1281
511207
    for (k = 0; k < sbr->kx[0]; k++) {
1282
4423230
        for (i = 0; i < t_HFGen; i++) {
1283
3931760
            X_low[k][i][0] = W[buf_idx][i + i_f - t_HFGen][k][0];
1284
3931760
            X_low[k][i][1] = W[buf_idx][i + i_f - t_HFGen][k][1];
1285
        }
1286
    }
1287
19737
    return 0;
1288
}
1289
1290
/// High Frequency Generator (14496-3 sp04 p215)
1291
10418
static int sbr_hf_gen(AACContext *ac, SpectralBandReplication *sbr,
1292
                      INTFLOAT X_high[64][40][2], const INTFLOAT X_low[32][40][2],
1293
                      const INTFLOAT (*alpha0)[2], const INTFLOAT (*alpha1)[2],
1294
                      const INTFLOAT bw_array[5], const uint8_t *t_env,
1295
                      int bs_num_env)
1296
{
1297
    int j, x;
1298
10418
    int g = 0;
1299
10418
    int k = sbr->kx[1];
1300
36609
    for (j = 0; j < sbr->num_patches; j++) {
1301
282933
        for (x = 0; x < sbr->patch_num_subbands[j]; x++, k++) {
1302
256742
            const int p = sbr->patch_start_subband[j] + x;
1303

533838
            while (g <= sbr->n_q && k >= sbr->f_tablenoise[g])
1304
277096
                g++;
1305
256742
            g--;
1306
1307
256742
            if (g < 0) {
1308
                av_log(ac->avctx, AV_LOG_ERROR,
1309
                       "ERROR : no subband found for frequency %d\n", k);
1310
                return -1;
1311
            }
1312
1313
256742
            sbr->dsp.hf_gen(X_high[k] + ENVELOPE_ADJUSTMENT_OFFSET,
1314
256742
                            X_low[p]  + ENVELOPE_ADJUSTMENT_OFFSET,
1315
256742
                            alpha0[p], alpha1[p], bw_array[g],
1316
256742
                            2 * t_env[0], 2 * t_env[bs_num_env]);
1317
        }
1318
    }
1319
10418
    if (k < sbr->m[1] + sbr->kx[1])
1320
        memset(X_high + k, 0, (sbr->m[1] + sbr->kx[1] - k) * sizeof(*X_high));
1321
1322
10418
    return 0;
1323
}
1324
1325
/// Generate the subband filtered lowband
1326
19737
static int sbr_x_gen(SpectralBandReplication *sbr, INTFLOAT X[2][38][64],
1327
                     const INTFLOAT Y0[38][64][2], const INTFLOAT Y1[38][64][2],
1328
                     const INTFLOAT X_low[32][40][2], int ch)
1329
{
1330
    int k, i;
1331
19737
    const int i_f = 32;
1332
19737
    const int i_Temp = FFMAX(2*sbr->data[ch].t_env_num_env_old - i_f, 0);
1333
19737
    memset(X, 0, 2*sizeof(*X));
1334
511207
    for (k = 0; k < sbr->kx[0]; k++) {
1335
547200
        for (i = 0; i < i_Temp; i++) {
1336
55730
            X[0][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][0];
1337
55730
            X[1][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][1];
1338
        }
1339
    }
1340
273883
    for (; k < sbr->kx[0] + sbr->m[0]; k++) {
1341
322412
        for (i = 0; i < i_Temp; i++) {
1342
68266
            X[0][i][k] = Y0[i + i_f][k][0];
1343
68266
            X[1][i][k] = Y0[i + i_f][k][1];
1344
        }
1345
    }
1346
1347
510367
    for (k = 0; k < sbr->kx[1]; k++) {
1348
19078840
        for (i = i_Temp; i < 38; i++) {
1349
18588210
            X[0][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][0];
1350
18588210
            X[1][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][1];
1351
        }
1352
    }
1353
276479
    for (; k < sbr->kx[1] + sbr->m[1]; k++) {
1354
8404220
        for (i = i_Temp; i < i_f; i++) {
1355
8147478
            X[0][i][k] = Y1[i][k][0];
1356
8147478
            X[1][i][k] = Y1[i][k][1];
1357
        }
1358
    }
1359
19737
    return 0;
1360
}
1361
1362
/** High Frequency Adjustment (14496-3 sp04 p217) and Mapping
1363
 * (14496-3 sp04 p217)
1364
 */
1365
10418
static int sbr_mapping(AACContext *ac, SpectralBandReplication *sbr,
1366
                        SBRData *ch_data, int e_a[2])
1367
{
1368
    int e, i, m;
1369
1370
10418
    memset(ch_data->s_indexmapped[1], 0, 7*sizeof(ch_data->s_indexmapped[1]));
1371
25578
    for (e = 0; e < ch_data->bs_num_env; e++) {
1372
15160
        const unsigned int ilim = sbr->n[ch_data->bs_freq_res[e + 1]];
1373
15160
        uint16_t *table = ch_data->bs_freq_res[e + 1] ? sbr->f_tablehigh : sbr->f_tablelow;
1374
        int k;
1375
1376
15160
        if (sbr->kx[1] != table[0]) {
1377
            av_log(ac->avctx, AV_LOG_ERROR, "kx != f_table{high,low}[0]. "
1378
                   "Derived frequency tables were not regenerated.\n");
1379
            sbr_turnoff(sbr);
1380
            return AVERROR_BUG;
1381
        }
1382
187076
        for (i = 0; i < ilim; i++)
1383
550938
            for (m = table[i]; m < table[i + 1]; m++)
1384
379022
                sbr->e_origmapped[e][m - sbr->kx[1]] = ch_data->env_facs[e+1][i];
1385
1386
        // ch_data->bs_num_noise > 1 => 2 noise floors
1387

15160
        k = (ch_data->bs_num_noise > 1) && (ch_data->t_env[e] >= ch_data->t_q[1]);
1388
60744
        for (i = 0; i < sbr->n_q; i++)
1389
424606
            for (m = sbr->f_tablenoise[i]; m < sbr->f_tablenoise[i + 1]; m++)
1390
379022
                sbr->q_mapped[e][m - sbr->kx[1]] = ch_data->noise_facs[k+1][i];
1391
1392
197376
        for (i = 0; i < sbr->n[1]; i++) {
1393
182216
            if (ch_data->bs_add_harmonic_flag) {
1394
32694
                const unsigned int m_midpoint =
1395
32694
                    (sbr->f_tablehigh[i] + sbr->f_tablehigh[i + 1]) >> 1;
1396
1397
32694
                ch_data->s_indexmapped[e + 1][m_midpoint - sbr->kx[1]] = ch_data->bs_add_harmonic[i] *
1398

32694
                    (e >= e_a[1] || (ch_data->s_indexmapped[0][m_midpoint - sbr->kx[1]] == 1));
1399
            }
1400
        }
1401
1402
187076
        for (i = 0; i < ilim; i++) {
1403
171916
            int additional_sinusoid_present = 0;
1404
544482
            for (m = table[i]; m < table[i + 1]; m++) {
1405
376296
                if (ch_data->s_indexmapped[e + 1][m - sbr->kx[1]]) {
1406
3730
                    additional_sinusoid_present = 1;
1407
3730
                    break;
1408
                }
1409
            }
1410
171916
            memset(&sbr->s_mapped[e][table[i] - sbr->kx[1]], additional_sinusoid_present,
1411
171916
                   (table[i + 1] - table[i]) * sizeof(sbr->s_mapped[e][0]));
1412
        }
1413
    }
1414
1415
10418
    memcpy(ch_data->s_indexmapped[0], ch_data->s_indexmapped[ch_data->bs_num_env], sizeof(ch_data->s_indexmapped[0]));
1416
10418
    return 0;
1417
}
1418
1419
/// Estimation of current envelope (14496-3 sp04 p218)
1420
10418
static void sbr_env_estimate(AAC_FLOAT (*e_curr)[48], INTFLOAT X_high[64][40][2],
1421
                             SpectralBandReplication *sbr, SBRData *ch_data)
1422
{
1423
    int e, m;
1424
10418
    int kx1 = sbr->kx[1];
1425
1426
10418
    if (sbr->bs_interpol_freq) {
1427
25578
        for (e = 0; e < ch_data->bs_num_env; e++) {
1428
#if USE_FIXED
1429
5588
            const SoftFloat recip_env_size = av_int2sf(0x20000000 / (ch_data->t_env[e + 1] - ch_data->t_env[e]), 30);
1430
#else
1431
9572
            const float recip_env_size = 0.5f / (ch_data->t_env[e + 1] - ch_data->t_env[e]);
1432
#endif /* USE_FIXED */
1433
15160
            int ilb = ch_data->t_env[e]     * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1434
15160
            int iub = ch_data->t_env[e + 1] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1435
1436
394182
            for (m = 0; m < sbr->m[1]; m++) {
1437
379022
                AAC_FLOAT sum = sbr->dsp.sum_square(X_high[m+kx1] + ilb, iub - ilb);
1438
#if USE_FIXED
1439
127837
                e_curr[e][m] = av_mul_sf(sum, recip_env_size);
1440
#else
1441
251185
                e_curr[e][m] = sum * recip_env_size;
1442
#endif /* USE_FIXED */
1443
            }
1444
        }
1445
    } else {
1446
        int k, p;
1447
1448
        for (e = 0; e < ch_data->bs_num_env; e++) {
1449
            const int env_size = 2 * (ch_data->t_env[e + 1] - ch_data->t_env[e]);
1450
            int ilb = ch_data->t_env[e]     * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1451
            int iub = ch_data->t_env[e + 1] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1452
            const uint16_t *table = ch_data->bs_freq_res[e + 1] ? sbr->f_tablehigh : sbr->f_tablelow;
1453
1454
            for (p = 0; p < sbr->n[ch_data->bs_freq_res[e + 1]]; p++) {
1455
#if USE_FIXED
1456
                SoftFloat sum = FLOAT_0;
1457
                const SoftFloat den = av_int2sf(0x20000000 / (env_size * (table[p + 1] - table[p])), 29);
1458
                for (k = table[p]; k < table[p + 1]; k++) {
1459
                    sum = av_add_sf(sum, sbr->dsp.sum_square(X_high[k] + ilb, iub - ilb));
1460
                }
1461
                sum = av_mul_sf(sum, den);
1462
#else
1463
                float sum = 0.0f;
1464
                const int den = env_size * (table[p + 1] - table[p]);
1465
1466
                for (k = table[p]; k < table[p + 1]; k++) {
1467
                    sum += sbr->dsp.sum_square(X_high[k] + ilb, iub - ilb);
1468
                }
1469
                sum /= den;
1470
#endif /* USE_FIXED */
1471
                for (k = table[p]; k < table[p + 1]; k++) {
1472
                    e_curr[e][k - kx1] = sum;
1473
                }
1474
            }
1475
        }
1476
    }
1477
10418
}
1478
1479
12411
void AAC_RENAME(ff_sbr_apply)(AACContext *ac, SpectralBandReplication *sbr, int id_aac,
1480
                  INTFLOAT* L, INTFLOAT* R)
1481
{
1482
12411
    int downsampled = ac->oc[1].m4ac.ext_sample_rate < sbr->sample_rate;
1483
    int ch;
1484
12411
    int nch = (id_aac == TYPE_CPE) ? 2 : 1;
1485
    int err;
1486
1487
12411
    if (id_aac != sbr->id_aac) {
1488
        av_log(ac->avctx, id_aac == TYPE_LFE ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1489
            "element type mismatch %d != %d\n", id_aac, sbr->id_aac);
1490
        sbr_turnoff(sbr);
1491
    }
1492
1493

12411
    if (sbr->start && !sbr->ready_for_dequant) {
1494
        av_log(ac->avctx, AV_LOG_ERROR,
1495
               "No quantized data read for sbr_dequant.\n");
1496
        sbr_turnoff(sbr);
1497
    }
1498
1499
12411
    if (!sbr->kx_and_m_pushed) {
1500
1510
        sbr->kx[0] = sbr->kx[1];
1501
1510
        sbr->m[0] = sbr->m[1];
1502
    } else {
1503
10901
        sbr->kx_and_m_pushed = 0;
1504
    }
1505
1506
12411
    if (sbr->start) {
1507
6532
        sbr_dequant(sbr, id_aac);
1508
6532
        sbr->ready_for_dequant = 0;
1509
    }
1510
32148
    for (ch = 0; ch < nch; ch++) {
1511
        /* decode channel */
1512
19737
        sbr_qmf_analysis(ac->fdsp, &sbr->mdct_ana, &sbr->dsp, ch ? R : L, sbr->data[ch].analysis_filterbank_samples,
1513
19737
                         (INTFLOAT*)sbr->qmf_filter_scratch,
1514
19737
                         sbr->data[ch].W, sbr->data[ch].Ypos);
1515
19737
        sbr->c.sbr_lf_gen(ac, sbr, sbr->X_low,
1516
19737
                          (const INTFLOAT (*)[32][32][2]) sbr->data[ch].W,
1517
                          sbr->data[ch].Ypos);
1518
19737
        sbr->data[ch].Ypos ^= 1;
1519
19737
        if (sbr->start) {
1520
10418
            sbr->c.sbr_hf_inverse_filter(&sbr->dsp, sbr->alpha0, sbr->alpha1,
1521
10418
                                         (const INTFLOAT (*)[40][2]) sbr->X_low, sbr->k[0]);
1522
10418
            sbr_chirp(sbr, &sbr->data[ch]);
1523
10418
            av_assert0(sbr->data[ch].bs_num_env > 0);
1524
10418
            sbr_hf_gen(ac, sbr, sbr->X_high,
1525
10418
                       (const INTFLOAT (*)[40][2]) sbr->X_low,
1526
10418
                       (const INTFLOAT (*)[2]) sbr->alpha0,
1527
10418
                       (const INTFLOAT (*)[2]) sbr->alpha1,
1528
10418
                       sbr->data[ch].bw_array, sbr->data[ch].t_env,
1529
6631
                       sbr->data[ch].bs_num_env);
1530
1531
            // hf_adj
1532
10418
            err = sbr_mapping(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);
1533
10418
            if (!err) {
1534
10418
                sbr_env_estimate(sbr->e_curr, sbr->X_high, sbr, &sbr->data[ch]);
1535
10418
                sbr_gain_calc(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);
1536
10418
                sbr->c.sbr_hf_assemble(sbr->data[ch].Y[sbr->data[ch].Ypos],
1537
10418
                                (const INTFLOAT (*)[40][2]) sbr->X_high,
1538
                                sbr, &sbr->data[ch],
1539
10418
                                sbr->data[ch].e_a);
1540
            }
1541
        }
1542
1543
        /* synthesis */
1544
19737
        sbr->c.sbr_x_gen(sbr, sbr->X[ch],
1545
19737
                  (const INTFLOAT (*)[64][2]) sbr->data[ch].Y[1-sbr->data[ch].Ypos],
1546
19737
                  (const INTFLOAT (*)[64][2]) sbr->data[ch].Y[  sbr->data[ch].Ypos],
1547
19737
                  (const INTFLOAT (*)[40][2]) sbr->X_low, ch);
1548
    }
1549
1550
12411
    if (ac->oc[1].m4ac.ps == 1) {
1551
1999
        if (sbr->ps.start) {
1552
1616
            AAC_RENAME(ff_ps_apply)(ac->avctx, &sbr->ps, sbr->X[0], sbr->X[1], sbr->kx[1] + sbr->m[1]);
1553
        } else {
1554
383
            memcpy(sbr->X[1], sbr->X[0], sizeof(sbr->X[0]));
1555
        }
1556
1999
        nch = 2;
1557
    }
1558
1559
12411
    sbr_qmf_synthesis(&sbr->mdct, &sbr->dsp, ac->fdsp,
1560
12411
                      L, sbr->X[0], sbr->qmf_filter_scratch,
1561
12411
                      sbr->data[0].synthesis_filterbank_samples,
1562
                      &sbr->data[0].synthesis_filterbank_samples_offset,
1563
                      downsampled);
1564
12411
    if (nch == 2)
1565
9325
        sbr_qmf_synthesis(&sbr->mdct, &sbr->dsp, ac->fdsp,
1566
9325
                          R, sbr->X[1], sbr->qmf_filter_scratch,
1567
9325
                          sbr->data[1].synthesis_filterbank_samples,
1568
                          &sbr->data[1].synthesis_filterbank_samples_offset,
1569
                          downsampled);
1570
12411
}
1571
1572
347
static void aacsbr_func_ptr_init(AACSBRContext *c)
1573
{
1574
347
    c->sbr_lf_gen            = sbr_lf_gen;
1575
347
    c->sbr_hf_assemble       = sbr_hf_assemble;
1576
347
    c->sbr_x_gen             = sbr_x_gen;
1577
347
    c->sbr_hf_inverse_filter = sbr_hf_inverse_filter;
1578
1579
#if !USE_FIXED
1580
    if(ARCH_MIPS)
1581
        ff_aacsbr_func_ptr_init_mips(c);
1582
#endif
1583
347
}