Statistics
| Branch: | Revision:

ffmpeg / libavcodec / aacsbr.c @ 7333f849

History | View | Annotate | Download (66.5 KB)

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
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22

    
23
/**
24
 * @file libavcodec/aacsbr.c
25
 * AAC Spectral Band Replication decoding functions
26
 * @author Robert Swain ( rob opendot cl )
27
 */
28

    
29
#include "aac.h"
30
#include "sbr.h"
31
#include "aacsbr.h"
32
#include "aacsbrdata.h"
33
#include "fft.h"
34

    
35
#include <stdint.h>
36
#include <float.h>
37

    
38
#define ENVELOPE_ADJUSTMENT_OFFSET 2
39
#define NOISE_FLOOR_OFFSET 6.0f
40

    
41
/**
42
 * SBR VLC tables
43
 */
44
enum {
45
    T_HUFFMAN_ENV_1_5DB,
46
    F_HUFFMAN_ENV_1_5DB,
47
    T_HUFFMAN_ENV_BAL_1_5DB,
48
    F_HUFFMAN_ENV_BAL_1_5DB,
49
    T_HUFFMAN_ENV_3_0DB,
50
    F_HUFFMAN_ENV_3_0DB,
51
    T_HUFFMAN_ENV_BAL_3_0DB,
52
    F_HUFFMAN_ENV_BAL_3_0DB,
53
    T_HUFFMAN_NOISE_3_0DB,
54
    T_HUFFMAN_NOISE_BAL_3_0DB,
55
};
56

    
57
/**
58
 * bs_frame_class - frame class of current SBR frame (14496-3 sp04 p98)
59
 */
60
enum {
61
    FIXFIX,
62
    FIXVAR,
63
    VARFIX,
64
    VARVAR,
65
};
66

    
67
enum {
68
    EXTENSION_ID_PS = 2,
69
};
70

    
71
static VLC vlc_sbr[10];
72
static const int8_t vlc_sbr_lav[10] =
73
    { 60, 60, 24, 24, 31, 31, 12, 12, 31, 12 };
74
static DECLARE_ALIGNED(16, float, analysis_cos_pre)[64];
75
static DECLARE_ALIGNED(16, float, analysis_sin_pre)[64];
76
static DECLARE_ALIGNED(16, float, analysis_cossin_post)[32][2];
77
static const DECLARE_ALIGNED(16, float, zero64)[64];
78

    
79
#define SBR_INIT_VLC_STATIC(num, size) \
80
    INIT_VLC_STATIC(&vlc_sbr[num], 9, sbr_tmp[num].table_size / sbr_tmp[num].elem_size,     \
81
                    sbr_tmp[num].sbr_bits ,                      1,                      1, \
82
                    sbr_tmp[num].sbr_codes, sbr_tmp[num].elem_size, sbr_tmp[num].elem_size, \
83
                    size)
84

    
85
#define SBR_VLC_ROW(name) \
86
    { name ## _codes, name ## _bits, sizeof(name ## _codes), sizeof(name ## _codes[0]) }
87

    
88
av_cold void ff_aac_sbr_init(void)
89
{
90
    int n, k;
91
    static const struct {
92
        const void *sbr_codes, *sbr_bits;
93
        const unsigned int table_size, elem_size;
94
    } sbr_tmp[] = {
95
        SBR_VLC_ROW(t_huffman_env_1_5dB),
96
        SBR_VLC_ROW(f_huffman_env_1_5dB),
97
        SBR_VLC_ROW(t_huffman_env_bal_1_5dB),
98
        SBR_VLC_ROW(f_huffman_env_bal_1_5dB),
99
        SBR_VLC_ROW(t_huffman_env_3_0dB),
100
        SBR_VLC_ROW(f_huffman_env_3_0dB),
101
        SBR_VLC_ROW(t_huffman_env_bal_3_0dB),
102
        SBR_VLC_ROW(f_huffman_env_bal_3_0dB),
103
        SBR_VLC_ROW(t_huffman_noise_3_0dB),
104
        SBR_VLC_ROW(t_huffman_noise_bal_3_0dB),
105
    };
106

    
107
    // SBR VLC table initialization
108
    SBR_INIT_VLC_STATIC(0, 1098);
109
    SBR_INIT_VLC_STATIC(1, 1092);
110
    SBR_INIT_VLC_STATIC(2, 768);
111
    SBR_INIT_VLC_STATIC(3, 1026);
112
    SBR_INIT_VLC_STATIC(4, 1058);
113
    SBR_INIT_VLC_STATIC(5, 1052);
114
    SBR_INIT_VLC_STATIC(6, 544);
115
    SBR_INIT_VLC_STATIC(7, 544);
116
    SBR_INIT_VLC_STATIC(8, 592);
117
    SBR_INIT_VLC_STATIC(9, 512);
118

    
119
    for (n = 0; n < 64; n++) {
120
        float pre = M_PI * n / 64;
121
        analysis_cos_pre[n] = cosf(pre);
122
        analysis_sin_pre[n] = sinf(pre);
123
    }
124
    for (k = 0; k < 32; k++) {
125
        float post = M_PI * (k + 0.5) / 128;
126
        analysis_cossin_post[k][0] =  4.0 * cosf(post);
127
        analysis_cossin_post[k][1] = -4.0 * sinf(post);
128
    }
129
    for (n = 1; n < 320; n++)
130
        sbr_qmf_window_us[320 + n] = sbr_qmf_window_us[320 - n];
131
    sbr_qmf_window_us[384] = -sbr_qmf_window_us[384];
132
    sbr_qmf_window_us[512] = -sbr_qmf_window_us[512];
133

    
134
    for (n = 0; n < 320; n++)
135
        sbr_qmf_window_ds[n] = sbr_qmf_window_us[2*n];
136
}
137

    
138
av_cold void ff_aac_sbr_ctx_init(SpectralBandReplication *sbr)
139
{
140
    sbr->kx[0] = sbr->kx[1] = 32; //Typo in spec, kx' inits to 32
141
    sbr->data[0].synthesis_filterbank_samples_offset = SBR_SYNTHESIS_BUF_SIZE - (1280 - 128);
142
    sbr->data[1].synthesis_filterbank_samples_offset = SBR_SYNTHESIS_BUF_SIZE - (1280 - 128);
143
    ff_mdct_init(&sbr->mdct, 7, 1, 1.0/64);
144
    ff_rdft_init(&sbr->rdft, 6, IDFT_R2C);
145
}
146

    
147
av_cold void ff_aac_sbr_ctx_close(SpectralBandReplication *sbr)
148
{
149
    ff_mdct_end(&sbr->mdct);
150
    ff_rdft_end(&sbr->rdft);
151
}
152

    
153
static int qsort_comparison_function_int16(const void *a, const void *b)
154
{
155
    return *(const int16_t *)a - *(const int16_t *)b;
156
}
157

    
158
static inline int in_table_int16(const int16_t *table, int last_el, int16_t needle)
159
{
160
    int i;
161
    for (i = 0; i <= last_el; i++)
162
        if (table[i] == needle)
163
            return 1;
164
    return 0;
165
}
166

    
167
/// Limiter Frequency Band Table (14496-3 sp04 p198)
168
static void sbr_make_f_tablelim(SpectralBandReplication *sbr)
169
{
170
    int k;
171
    if (sbr->bs_limiter_bands > 0) {
172
        static const float bands_warped[3] = { 1.32715174233856803909f,   //2^(0.49/1.2)
173
                                               1.18509277094158210129f,   //2^(0.49/2)
174
                                               1.11987160404675912501f }; //2^(0.49/3)
175
        const float lim_bands_per_octave_warped = bands_warped[sbr->bs_limiter_bands - 1];
176
        int16_t patch_borders[5];
177
        uint16_t *in = sbr->f_tablelim + 1, *out = sbr->f_tablelim;
178

    
179
        patch_borders[0] = sbr->kx[1];
180
        for (k = 1; k <= sbr->num_patches; k++)
181
            patch_borders[k] = patch_borders[k-1] + sbr->patch_num_subbands[k-1];
182

    
183
        memcpy(sbr->f_tablelim, sbr->f_tablelow,
184
               (sbr->n[0] + 1) * sizeof(sbr->f_tablelow[0]));
185
        if (sbr->num_patches > 1)
186
            memcpy(sbr->f_tablelim + sbr->n[0] + 1, patch_borders + 1,
187
                   (sbr->num_patches - 1) * sizeof(patch_borders[0]));
188

    
189
        qsort(sbr->f_tablelim, sbr->num_patches + sbr->n[0],
190
              sizeof(sbr->f_tablelim[0]),
191
              qsort_comparison_function_int16);
192

    
193
        sbr->n_lim = sbr->n[0] + sbr->num_patches - 1;
194
        while (out < sbr->f_tablelim + sbr->n_lim) {
195
            if (*in >= *out * lim_bands_per_octave_warped) {
196
                *++out = *in++;
197
            } else if (*in == *out ||
198
                !in_table_int16(patch_borders, sbr->num_patches, *in)) {
199
                in++;
200
                sbr->n_lim--;
201
            } else if (!in_table_int16(patch_borders, sbr->num_patches, *out)) {
202
                *out = *in++;
203
                sbr->n_lim--;
204
            } else {
205
                *++out = *in++;
206
            }
207
        }
208
    } else {
209
        sbr->f_tablelim[0] = sbr->f_tablelow[0];
210
        sbr->f_tablelim[1] = sbr->f_tablelow[sbr->n[0]];
211
        sbr->n_lim = 1;
212
    }
213
}
214

    
215
static unsigned int read_sbr_header(SpectralBandReplication *sbr, GetBitContext *gb)
216
{
217
    unsigned int cnt = get_bits_count(gb);
218
    uint8_t bs_header_extra_1;
219
    uint8_t bs_header_extra_2;
220
    int old_bs_limiter_bands = sbr->bs_limiter_bands;
221
    SpectrumParameters old_spectrum_params;
222

    
223
    sbr->start = 1;
224

    
225
    // Save last spectrum parameters variables to compare to new ones
226
    memcpy(&old_spectrum_params, &sbr->spectrum_params, sizeof(SpectrumParameters));
227

    
228
    sbr->bs_amp_res_header              = get_bits1(gb);
229
    sbr->spectrum_params.bs_start_freq  = get_bits(gb, 4);
230
    sbr->spectrum_params.bs_stop_freq   = get_bits(gb, 4);
231
    sbr->spectrum_params.bs_xover_band  = get_bits(gb, 3);
232
                                          skip_bits(gb, 2); // bs_reserved
233

    
234
    bs_header_extra_1 = get_bits1(gb);
235
    bs_header_extra_2 = get_bits1(gb);
236

    
237
    if (bs_header_extra_1) {
238
        sbr->spectrum_params.bs_freq_scale  = get_bits(gb, 2);
239
        sbr->spectrum_params.bs_alter_scale = get_bits1(gb);
240
        sbr->spectrum_params.bs_noise_bands = get_bits(gb, 2);
241
    } else {
242
        sbr->spectrum_params.bs_freq_scale  = 2;
243
        sbr->spectrum_params.bs_alter_scale = 1;
244
        sbr->spectrum_params.bs_noise_bands = 2;
245
    }
246

    
247
    // Check if spectrum parameters changed
248
    if (memcmp(&old_spectrum_params, &sbr->spectrum_params, sizeof(SpectrumParameters)))
249
        sbr->reset = 1;
250

    
251
    if (bs_header_extra_2) {
252
        sbr->bs_limiter_bands  = get_bits(gb, 2);
253
        sbr->bs_limiter_gains  = get_bits(gb, 2);
254
        sbr->bs_interpol_freq  = get_bits1(gb);
255
        sbr->bs_smoothing_mode = get_bits1(gb);
256
    } else {
257
        sbr->bs_limiter_bands  = 2;
258
        sbr->bs_limiter_gains  = 2;
259
        sbr->bs_interpol_freq  = 1;
260
        sbr->bs_smoothing_mode = 1;
261
    }
262

    
263
    if (sbr->bs_limiter_bands != old_bs_limiter_bands && !sbr->reset)
264
        sbr_make_f_tablelim(sbr);
265

    
266
    return get_bits_count(gb) - cnt;
267
}
268

    
269
static int array_min_int16(const int16_t *array, int nel)
270
{
271
    int i, min = array[0];
272
    for (i = 1; i < nel; i++)
273
        min = FFMIN(array[i], min);
274
    return min;
275
}
276

    
277
static void make_bands(int16_t* bands, int start, int stop, int num_bands)
278
{
279
    int k, previous, present;
280
    float base, prod;
281

    
282
    base = powf((float)stop / start, 1.0f / num_bands);
283
    prod = start;
284
    previous = start;
285

    
286
    for (k = 0; k < num_bands-1; k++) {
287
        prod *= base;
288
        present  = lrintf(prod);
289
        bands[k] = present - previous;
290
        previous = present;
291
    }
292
    bands[num_bands-1] = stop - previous;
293
}
294

    
295
static int check_n_master(AVCodecContext *avccontext, int n_master, int bs_xover_band)
296
{
297
    // Requirements (14496-3 sp04 p205)
298
    if (n_master <= 0) {
299
        av_log(avccontext, AV_LOG_ERROR, "Invalid n_master: %d\n", n_master);
300
        return -1;
301
    }
302
    if (bs_xover_band >= n_master) {
303
        av_log(avccontext, AV_LOG_ERROR,
304
               "Invalid bitstream, crossover band index beyond array bounds: %d\n",
305
               bs_xover_band);
306
        return -1;
307
    }
308
    return 0;
309
}
310

    
311
/// Master Frequency Band Table (14496-3 sp04 p194)
312
static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
313
                             SpectrumParameters *spectrum)
314
{
315
    unsigned int temp, max_qmf_subbands;
316
    unsigned int start_min, stop_min;
317
    int k;
318
    const int8_t *sbr_offset_ptr;
319
    int16_t stop_dk[13];
320

    
321
    if (sbr->sample_rate < 32000) {
322
        temp = 3000;
323
    } else if (sbr->sample_rate < 64000) {
324
        temp = 4000;
325
    } else
326
        temp = 5000;
327

    
328
    start_min = ((temp << 7) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
329
    stop_min  = ((temp << 8) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
330

    
331
    switch (sbr->sample_rate) {
332
    case 16000:
333
        sbr_offset_ptr = sbr_offset[0];
334
        break;
335
    case 22050:
336
        sbr_offset_ptr = sbr_offset[1];
337
        break;
338
    case 24000:
339
        sbr_offset_ptr = sbr_offset[2];
340
        break;
341
    case 32000:
342
        sbr_offset_ptr = sbr_offset[3];
343
        break;
344
    case 44100: case 48000: case 64000:
345
        sbr_offset_ptr = sbr_offset[4];
346
        break;
347
    case 88200: case 96000: case 128000: case 176400: case 192000:
348
        sbr_offset_ptr = sbr_offset[5];
349
        break;
350
    default:
351
        av_log(ac->avccontext, AV_LOG_ERROR,
352
               "Unsupported sample rate for SBR: %d\n", sbr->sample_rate);
353
        return -1;
354
    }
355

    
356
    sbr->k[0] = start_min + sbr_offset_ptr[spectrum->bs_start_freq];
357

    
358
    if (spectrum->bs_stop_freq < 14) {
359
        sbr->k[2] = stop_min;
360
        make_bands(stop_dk, stop_min, 64, 13);
361
        qsort(stop_dk, 13, sizeof(stop_dk[0]), qsort_comparison_function_int16);
362
        for (k = 0; k < spectrum->bs_stop_freq; k++)
363
            sbr->k[2] += stop_dk[k];
364
    } else if (spectrum->bs_stop_freq == 14) {
365
        sbr->k[2] = 2*sbr->k[0];
366
    } else if (spectrum->bs_stop_freq == 15) {
367
        sbr->k[2] = 3*sbr->k[0];
368
    } else {
369
        av_log(ac->avccontext, AV_LOG_ERROR,
370
               "Invalid bs_stop_freq: %d\n", spectrum->bs_stop_freq);
371
        return -1;
372
    }
373
    sbr->k[2] = FFMIN(64, sbr->k[2]);
374

    
375
    // Requirements (14496-3 sp04 p205)
376
    if (sbr->sample_rate <= 32000) {
377
        max_qmf_subbands = 48;
378
    } else if (sbr->sample_rate == 44100) {
379
        max_qmf_subbands = 35;
380
    } else if (sbr->sample_rate >= 48000)
381
        max_qmf_subbands = 32;
382

    
383
    if (sbr->k[2] - sbr->k[0] > max_qmf_subbands) {
384
        av_log(ac->avccontext, AV_LOG_ERROR,
385
               "Invalid bitstream, too many QMF subbands: %d\n", sbr->k[2] - sbr->k[0]);
386
        return -1;
387
    }
388

    
389
    if (!spectrum->bs_freq_scale) {
390
        unsigned int dk;
391
        int k2diff;
392

    
393
        dk = spectrum->bs_alter_scale + 1;
394
        sbr->n_master = ((sbr->k[2] - sbr->k[0] + (dk&2)) >> dk) << 1;
395
        if (check_n_master(ac->avccontext, sbr->n_master, sbr->spectrum_params.bs_xover_band))
396
            return -1;
397

    
398
        for (k = 1; k <= sbr->n_master; k++)
399
            sbr->f_master[k] = dk;
400

    
401
        k2diff = sbr->k[2] - sbr->k[0] - sbr->n_master * dk;
402
        if (k2diff < 0) {
403
            sbr->f_master[1]--;
404
            sbr->f_master[2]-= (k2diff < 1);
405
        } else if (k2diff) {
406
            sbr->f_master[sbr->n_master]++;
407
        }
408

    
409
        sbr->f_master[0] = sbr->k[0];
410
        for (k = 1; k <= sbr->n_master; k++)
411
            sbr->f_master[k] += sbr->f_master[k - 1];
412

    
413
    } else {
414
        int half_bands = 7 - spectrum->bs_freq_scale;      // bs_freq_scale  = {1,2,3}
415
        int two_regions, num_bands_0;
416
        int vdk0_max, vdk1_min;
417
        int16_t vk0[49];
418

    
419
        if (49 * sbr->k[2] > 110 * sbr->k[0]) {
420
            two_regions = 1;
421
            sbr->k[1] = 2 * sbr->k[0];
422
        } else {
423
            two_regions = 0;
424
            sbr->k[1] = sbr->k[2];
425
        }
426

    
427
        num_bands_0 = lrintf(half_bands * log2f(sbr->k[1] / (float)sbr->k[0])) * 2;
428

    
429
        if (num_bands_0 <= 0) { // Requirements (14496-3 sp04 p205)
430
            av_log(ac->avccontext, AV_LOG_ERROR, "Invalid num_bands_0: %d\n", num_bands_0);
431
            return -1;
432
        }
433

    
434
        vk0[0] = 0;
435

    
436
        make_bands(vk0+1, sbr->k[0], sbr->k[1], num_bands_0);
437

    
438
        qsort(vk0 + 1, num_bands_0, sizeof(vk0[1]), qsort_comparison_function_int16);
439
        vdk0_max = vk0[num_bands_0];
440

    
441
        vk0[0] = sbr->k[0];
442
        for (k = 1; k <= num_bands_0; k++) {
443
            if (vk0[k] <= 0) { // Requirements (14496-3 sp04 p205)
444
                av_log(ac->avccontext, AV_LOG_ERROR, "Invalid vDk0[%d]: %d\n", k, vk0[k]);
445
                return -1;
446
            }
447
            vk0[k] += vk0[k-1];
448
        }
449

    
450
        if (two_regions) {
451
            int16_t vk1[49];
452
            float invwarp = spectrum->bs_alter_scale ? 0.76923076923076923077f
453
                                                     : 1.0f; // bs_alter_scale = {0,1}
454
            int num_bands_1 = lrintf(half_bands * invwarp *
455
                                     log2f(sbr->k[2] / (float)sbr->k[1])) * 2;
456

    
457
            make_bands(vk1+1, sbr->k[1], sbr->k[2], num_bands_1);
458

    
459
            vdk1_min = array_min_int16(vk1 + 1, num_bands_1);
460

    
461
            if (vdk1_min < vdk0_max) {
462
                int change;
463
                qsort(vk1 + 1, num_bands_1, sizeof(vk1[1]), qsort_comparison_function_int16);
464
                change = FFMIN(vdk0_max - vk1[1], (vk1[num_bands_1] - vk1[1]) >> 1);
465
                vk1[1]           += change;
466
                vk1[num_bands_1] -= change;
467
            }
468

    
469
            qsort(vk1 + 1, num_bands_1, sizeof(vk1[1]), qsort_comparison_function_int16);
470

    
471
            vk1[0] = sbr->k[1];
472
            for (k = 1; k <= num_bands_1; k++) {
473
                if (vk1[k] <= 0) { // Requirements (14496-3 sp04 p205)
474
                    av_log(ac->avccontext, AV_LOG_ERROR, "Invalid vDk1[%d]: %d\n", k, vk1[k]);
475
                    return -1;
476
                }
477
                vk1[k] += vk1[k-1];
478
            }
479

    
480
            sbr->n_master = num_bands_0 + num_bands_1;
481
            if (check_n_master(ac->avccontext, sbr->n_master, sbr->spectrum_params.bs_xover_band))
482
                return -1;
483
            memcpy(&sbr->f_master[0],               vk0,
484
                   (num_bands_0 + 1) * sizeof(sbr->f_master[0]));
485
            memcpy(&sbr->f_master[num_bands_0 + 1], vk1 + 1,
486
                    num_bands_1      * sizeof(sbr->f_master[0]));
487

    
488
        } else {
489
            sbr->n_master = num_bands_0;
490
            if (check_n_master(ac->avccontext, sbr->n_master, sbr->spectrum_params.bs_xover_band))
491
                return -1;
492
            memcpy(sbr->f_master, vk0, (num_bands_0 + 1) * sizeof(sbr->f_master[0]));
493
        }
494
    }
495

    
496
    return 0;
497
}
498

    
499
/// High Frequency Generation - Patch Construction (14496-3 sp04 p216 fig. 4.46)
500
static int sbr_hf_calc_npatches(AACContext *ac, SpectralBandReplication *sbr)
501
{
502
    int i, k, sb = 0;
503
    int msb = sbr->k[0];
504
    int usb = sbr->kx[1];
505
    int goal_sb = ((1000 << 11) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
506

    
507
    sbr->num_patches = 0;
508

    
509
    if (goal_sb < sbr->kx[1] + sbr->m[1]) {
510
        for (k = 0; sbr->f_master[k] < goal_sb; k++) ;
511
    } else
512
        k = sbr->n_master;
513

    
514
    do {
515
        int odd = 0;
516
        for (i = k; i == k || sb > (sbr->k[0] - 1 + msb - odd); i--) {
517
            sb = sbr->f_master[i];
518
            odd = (sb + sbr->k[0]) & 1;
519
        }
520

    
521
        sbr->patch_num_subbands[sbr->num_patches]  = FFMAX(sb - usb, 0);
522
        sbr->patch_start_subband[sbr->num_patches] = sbr->k[0] - odd - sbr->patch_num_subbands[sbr->num_patches];
523

    
524
        if (sbr->patch_num_subbands[sbr->num_patches] > 0) {
525
            usb = sb;
526
            msb = sb;
527
            sbr->num_patches++;
528
        } else
529
            msb = sbr->kx[1];
530

    
531
        if (sbr->f_master[k] - sb < 3)
532
            k = sbr->n_master;
533
    } while (sb != sbr->kx[1] + sbr->m[1]);
534

    
535
    if (sbr->patch_num_subbands[sbr->num_patches-1] < 3 && sbr->num_patches > 1)
536
        sbr->num_patches--;
537

    
538
    // Requirements (14496-3 sp04 p205) sets the maximum number of patches to 5
539
    // However the Coding Technologies decoder check uses 6 patches
540
    if (sbr->num_patches > 6) {
541
        av_log(ac->avccontext, AV_LOG_ERROR, "Too many patches: %d\n", sbr->num_patches);
542
        return -1;
543
    }
544

    
545
    return 0;
546
}
547

    
548
/// Derived Frequency Band Tables (14496-3 sp04 p197)
549
static int sbr_make_f_derived(AACContext *ac, SpectralBandReplication *sbr)
550
{
551
    int k, temp;
552

    
553
    sbr->n[1] = sbr->n_master - sbr->spectrum_params.bs_xover_band;
554
    sbr->n[0] = (sbr->n[1] + 1) >> 1;
555

    
556
    memcpy(sbr->f_tablehigh, &sbr->f_master[sbr->spectrum_params.bs_xover_band],
557
           (sbr->n[1] + 1) * sizeof(sbr->f_master[0]));
558
    sbr->m[1] = sbr->f_tablehigh[sbr->n[1]] - sbr->f_tablehigh[0];
559
    sbr->kx[1] = sbr->f_tablehigh[0];
560

    
561
    // Requirements (14496-3 sp04 p205)
562
    if (sbr->kx[1] + sbr->m[1] > 64) {
563
        av_log(ac->avccontext, AV_LOG_ERROR,
564
               "Stop frequency border too high: %d\n", sbr->kx[1] + sbr->m[1]);
565
        return -1;
566
    }
567
    if (sbr->kx[1] > 32) {
568
        av_log(ac->avccontext, AV_LOG_ERROR, "Start frequency border too high: %d\n", sbr->kx[1]);
569
        return -1;
570
    }
571

    
572
    sbr->f_tablelow[0] = sbr->f_tablehigh[0];
573
    temp = sbr->n[1] & 1;
574
    for (k = 1; k <= sbr->n[0]; k++)
575
        sbr->f_tablelow[k] = sbr->f_tablehigh[2 * k - temp];
576

    
577
    sbr->n_q = FFMAX(1, lrintf(sbr->spectrum_params.bs_noise_bands *
578
                               log2f(sbr->k[2] / (float)sbr->kx[1]))); // 0 <= bs_noise_bands <= 3
579
    if (sbr->n_q > 5) {
580
        av_log(ac->avccontext, AV_LOG_ERROR, "Too many noise floor scale factors: %d\n", sbr->n_q);
581
        return -1;
582
    }
583

    
584
    sbr->f_tablenoise[0] = sbr->f_tablelow[0];
585
    temp = 0;
586
    for (k = 1; k <= sbr->n_q; k++) {
587
        temp += (sbr->n[0] - temp) / (sbr->n_q + 1 - k);
588
        sbr->f_tablenoise[k] = sbr->f_tablelow[temp];
589
    }
590

    
591
    if (sbr_hf_calc_npatches(ac, sbr) < 0)
592
        return -1;
593

    
594
    sbr_make_f_tablelim(sbr);
595

    
596
    sbr->data[0].f_indexnoise = 0;
597
    sbr->data[1].f_indexnoise = 0;
598

    
599
    return 0;
600
}
601

    
602
static av_always_inline void get_bits1_vector(GetBitContext *gb, uint8_t *vec,
603
                                              int elements)
604
{
605
    int i;
606
    for (i = 0; i < elements; i++) {
607
        vec[i] = get_bits1(gb);
608
    }
609
}
610

    
611
/** ceil(log2(index+1)) */
612
static const int8_t ceil_log2[] = {
613
    0, 1, 2, 2, 3, 3,
614
};
615

    
616
static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,
617
                         GetBitContext *gb, SBRData *ch_data)
618
{
619
    int i;
620

    
621
    ch_data->bs_freq_res[0] = ch_data->bs_freq_res[ch_data->bs_num_env[1]];
622
    ch_data->bs_num_env[0] = ch_data->bs_num_env[1];
623
    ch_data->bs_amp_res = sbr->bs_amp_res_header;
624

    
625
    switch (ch_data->bs_frame_class = get_bits(gb, 2)) {
626
    case FIXFIX:
627
        ch_data->bs_num_env[1] = 1 << get_bits(gb, 2);
628
        if (ch_data->bs_num_env[1] == 1)
629
            ch_data->bs_amp_res = 0;
630

    
631
        if (ch_data->bs_num_env[1] > 4) {
632
            av_log(ac->avccontext, AV_LOG_ERROR,
633
                   "Invalid bitstream, too many SBR envelopes in FIXFIX type SBR frame: %d\n",
634
                   ch_data->bs_num_env[1]);
635
            return -1;
636
        }
637

    
638
        ch_data->bs_pointer = 0;
639

    
640
        ch_data->bs_freq_res[1] = get_bits1(gb);
641
        for (i = 1; i < ch_data->bs_num_env[1]; i++)
642
            ch_data->bs_freq_res[i + 1] = ch_data->bs_freq_res[1];
643
        break;
644
    case FIXVAR:
645
        ch_data->bs_var_bord[1] = get_bits(gb, 2);
646
        ch_data->bs_num_rel[1]  = get_bits(gb, 2);
647
        ch_data->bs_num_env[1]  = ch_data->bs_num_rel[1] + 1;
648

    
649
        for (i = 0; i < ch_data->bs_num_rel[1]; i++)
650
            ch_data->bs_rel_bord[1][i] = 2 * get_bits(gb, 2) + 2;
651

    
652
        ch_data->bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env[1]]);
653

    
654
        for (i = 0; i < ch_data->bs_num_env[1]; i++)
655
            ch_data->bs_freq_res[ch_data->bs_num_env[1] - i] = get_bits1(gb);
656
        break;
657
    case VARFIX:
658
        ch_data->bs_var_bord[0] = get_bits(gb, 2);
659
        ch_data->bs_num_rel[0]  = get_bits(gb, 2);
660
        ch_data->bs_num_env[1]  = ch_data->bs_num_rel[0] + 1;
661

    
662
        for (i = 0; i < ch_data->bs_num_rel[0]; i++)
663
            ch_data->bs_rel_bord[0][i] = 2 * get_bits(gb, 2) + 2;
664

    
665
        ch_data->bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env[1]]);
666

    
667
        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env[1]);
668
        break;
669
    case VARVAR:
670
        ch_data->bs_var_bord[0] = get_bits(gb, 2);
671
        ch_data->bs_var_bord[1] = get_bits(gb, 2);
672
        ch_data->bs_num_rel[0]  = get_bits(gb, 2);
673
        ch_data->bs_num_rel[1]  = get_bits(gb, 2);
674
        ch_data->bs_num_env[1]  = ch_data->bs_num_rel[0] + ch_data->bs_num_rel[1] + 1;
675

    
676
        if (ch_data->bs_num_env[1] > 5) {
677
            av_log(ac->avccontext, AV_LOG_ERROR,
678
                   "Invalid bitstream, too many SBR envelopes in VARVAR type SBR frame: %d\n",
679
                   ch_data->bs_num_env[1]);
680
            return -1;
681
        }
682

    
683
        for (i = 0; i < ch_data->bs_num_rel[0]; i++)
684
            ch_data->bs_rel_bord[0][i] = 2 * get_bits(gb, 2) + 2;
685
        for (i = 0; i < ch_data->bs_num_rel[1]; i++)
686
            ch_data->bs_rel_bord[1][i] = 2 * get_bits(gb, 2) + 2;
687

    
688
        ch_data->bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env[1]]);
689

    
690
        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env[1]);
691
        break;
692
    }
693

    
694
    if (ch_data->bs_pointer > ch_data->bs_num_env[1] + 1) {
695
        av_log(ac->avccontext, AV_LOG_ERROR,
696
               "Invalid bitstream, bs_pointer points to a middle noise border outside the time borders table: %d\n",
697
               ch_data->bs_pointer);
698
        return -1;
699
    }
700

    
701
    int abs_bord_lead  =  ch_data->bs_frame_class >= 2 ? ch_data->bs_var_bord[0] : 0;
702
    // frameLengthFlag ? 15 : 16; 960 sample length frames unsupported; this value is numTimeSlots
703
    int abs_bord_trail = (ch_data->bs_frame_class & 1 ? ch_data->bs_var_bord[1] : 0) + 16;
704
    int n_rel_lead;
705

    
706
    if (ch_data->bs_frame_class == FIXFIX) {
707
        n_rel_lead = ch_data->bs_num_env[1] - 1;
708
    } else if (ch_data->bs_frame_class == FIXVAR) {
709
        n_rel_lead = 0;
710
    } else if (ch_data->bs_frame_class < 4) { // VARFIX or VARVAR
711
        n_rel_lead = ch_data->bs_num_rel[0];
712
    } else {
713
        av_log(ac->avccontext, AV_LOG_ERROR,
714
               "Invalid bs_frame_class for SBR: %d\n", ch_data->bs_frame_class);
715
        return -1;
716
    }
717

    
718
    ch_data->t_env_num_env_old = ch_data->t_env[ch_data->bs_num_env[0]];
719
    ch_data->t_env[0]                      = abs_bord_lead;
720
    ch_data->t_env[ch_data->bs_num_env[1]] = abs_bord_trail;
721

    
722
    if (ch_data->bs_frame_class == FIXFIX) {
723
        int temp = (abs_bord_trail + (ch_data->bs_num_env[1] >> 1)) /
724
                   ch_data->bs_num_env[1];
725
        for (i = 0; i < n_rel_lead; i++)
726
            ch_data->t_env[i + 1] = ch_data->t_env[i] + temp;
727
    } else if (ch_data->bs_frame_class > 1) { // VARFIX or VARVAR
728
        for (i = 0; i < n_rel_lead; i++)
729
            ch_data->t_env[i + 1] = ch_data->t_env[i] + ch_data->bs_rel_bord[0][i];
730
    } else { // FIXVAR
731
        for (i = 0; i < n_rel_lead; i++)
732
            ch_data->t_env[i + 1] = abs_bord_lead;
733
    }
734

    
735
    if (ch_data->bs_frame_class & 1) { // FIXVAR or VARVAR
736
        for (i = ch_data->bs_num_env[1] - 1; i > n_rel_lead; i--)
737
            ch_data->t_env[i] = ch_data->t_env[i + 1] -
738
                                ch_data->bs_rel_bord[1][ch_data->bs_num_env[1] - 1 - i];
739
    } else { // FIXFIX or VARFIX
740
        for (i = n_rel_lead; i < ch_data->bs_num_env[1]; i++)
741
            ch_data->t_env[i + 1] = abs_bord_trail;
742
    }
743

    
744
    ch_data->bs_num_noise = (ch_data->bs_num_env[1] > 1) + 1;
745

    
746
    ch_data->t_q[0] = ch_data->t_env[0];
747
    if (ch_data->bs_num_noise > 1) { // typo in spec bases this on bs_num_env...
748
        unsigned int idx;
749
        if (ch_data->bs_frame_class == FIXFIX) {
750
            idx = ch_data->bs_num_env[1] >> 1;
751
        } else if (ch_data->bs_frame_class & 1) { // FIXVAR or VARVAR
752
            idx = ch_data->bs_num_env[1] - FFMAX(ch_data->bs_pointer - 1, 1);
753
        } else { // VARFIX
754
            if (!ch_data->bs_pointer)
755
                idx = 1;
756
            else if (ch_data->bs_pointer == 1)
757
                idx = ch_data->bs_num_env[1] - 1;
758
            else // bs_pointer > 1
759
                idx = ch_data->bs_pointer - 1;
760
        }
761
        ch_data->t_q[1] = ch_data->t_env[idx];
762
        ch_data->t_q[2] = ch_data->t_env[ch_data->bs_num_env[1]];
763
    } else
764
        ch_data->t_q[1] = ch_data->t_env[ch_data->bs_num_env[1]];
765

    
766
    ch_data->e_a[0] = -(ch_data->e_a[1] != ch_data->bs_num_env[0]); // l_APrev
767
    ch_data->e_a[1] = -1;
768
    if ((ch_data->bs_frame_class & 1) && ch_data->bs_pointer) { // FIXVAR or VARVAR and bs_pointer != 0
769
        ch_data->e_a[1] = ch_data->bs_num_env[1] + 1 - ch_data->bs_pointer;
770
    } else if ((ch_data->bs_frame_class == 2) && (ch_data->bs_pointer > 1)) // VARFIX and bs_pointer > 1
771
        ch_data->e_a[1] = ch_data->bs_pointer - 1;
772

    
773
    return 0;
774
}
775

    
776
static void copy_sbr_grid(SBRData *dst, const SBRData *src) {
777
    //These variables are saved from the previous frame rather than copied
778
    dst->bs_freq_res[0] = dst->bs_freq_res[dst->bs_num_env[1]];
779
    dst->bs_num_env[0]  = dst->bs_num_env[1];
780
    dst->t_env_num_env_old = dst->t_env[dst->bs_num_env[0]];
781
    dst->e_a[0]         = -(dst->e_a[1] != dst->bs_num_env[0]);
782

    
783
    //These variables are read from the bitstream and therefore copied
784
    memcpy(dst->bs_freq_res+1, src->bs_freq_res+1, sizeof(dst->bs_freq_res)-sizeof(*dst->bs_freq_res));
785
    memcpy(dst->bs_num_env+1,  src->bs_num_env+1,  sizeof(dst->bs_num_env)- sizeof(*dst->bs_num_env));
786
    memcpy(dst->bs_var_bord,   src->bs_var_bord,   sizeof(dst->bs_var_bord));
787
    memcpy(dst->bs_rel_bord,   src->bs_rel_bord,   sizeof(dst->bs_rel_bord));
788
    memcpy(dst->bs_num_rel,    src->bs_num_rel,    sizeof(dst->bs_rel_bord));
789
    memcpy(dst->t_env,         src->t_env,         sizeof(dst->t_env));
790
    memcpy(dst->t_q,           src->t_q,           sizeof(dst->t_q));
791
    dst->bs_amp_res     = src->bs_amp_res;
792
    dst->bs_num_noise   = src->bs_num_noise;
793
    dst->bs_pointer     = src->bs_pointer;
794
    dst->bs_frame_class = src->bs_frame_class;
795
    dst->e_a[1]         = src->e_a[1];
796
}
797

    
798
/// Read how the envelope and noise floor data is delta coded
799
static void read_sbr_dtdf(SpectralBandReplication *sbr, GetBitContext *gb,
800
                          SBRData *ch_data)
801
{
802
    get_bits1_vector(gb, ch_data->bs_df_env,   ch_data->bs_num_env[1]);
803
    get_bits1_vector(gb, ch_data->bs_df_noise, ch_data->bs_num_noise);
804
}
805

    
806
/// Read inverse filtering data
807
static void read_sbr_invf(SpectralBandReplication *sbr, GetBitContext *gb,
808
                          SBRData *ch_data)
809
{
810
    int i;
811

    
812
    memcpy(ch_data->bs_invf_mode[1], ch_data->bs_invf_mode[0], 5 * sizeof(uint8_t));
813
    for (i = 0; i < sbr->n_q; i++)
814
        ch_data->bs_invf_mode[0][i] = get_bits(gb, 2);
815
}
816

    
817
static void read_sbr_envelope(SpectralBandReplication *sbr, GetBitContext *gb,
818
                              SBRData *ch_data, int ch)
819
{
820
    int bits;
821
    int i, j, k;
822
    VLC_TYPE (*t_huff)[2], (*f_huff)[2];
823
    int t_lav, f_lav;
824
    const int delta = (ch == 1 && sbr->bs_coupling == 1) + 1;
825
    const int odd = sbr->n[1] & 1;
826

    
827
    if (sbr->bs_coupling && ch) {
828
        if (ch_data->bs_amp_res) {
829
            bits   = 5;
830
            t_huff = vlc_sbr[T_HUFFMAN_ENV_BAL_3_0DB].table;
831
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_BAL_3_0DB];
832
            f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_3_0DB].table;
833
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_3_0DB];
834
        } else {
835
            bits   = 6;
836
            t_huff = vlc_sbr[T_HUFFMAN_ENV_BAL_1_5DB].table;
837
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_BAL_1_5DB];
838
            f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_1_5DB].table;
839
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_1_5DB];
840
        }
841
    } else {
842
        if (ch_data->bs_amp_res) {
843
            bits   = 6;
844
            t_huff = vlc_sbr[T_HUFFMAN_ENV_3_0DB].table;
845
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_3_0DB];
846
            f_huff = vlc_sbr[F_HUFFMAN_ENV_3_0DB].table;
847
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_3_0DB];
848
        } else {
849
            bits   = 7;
850
            t_huff = vlc_sbr[T_HUFFMAN_ENV_1_5DB].table;
851
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_1_5DB];
852
            f_huff = vlc_sbr[F_HUFFMAN_ENV_1_5DB].table;
853
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_1_5DB];
854
        }
855
    }
856

    
857
    for (i = 0; i < ch_data->bs_num_env[1]; i++) {
858
        if (ch_data->bs_df_env[i]) {
859
            // bs_freq_res[0] == bs_freq_res[bs_num_env[1]] from prev frame
860
            if (ch_data->bs_freq_res[i + 1] == ch_data->bs_freq_res[i]) {
861
                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++)
862
                    ch_data->env_facs[i + 1][j] = ch_data->env_facs[i][j] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
863
            } else if (ch_data->bs_freq_res[i + 1]) {
864
                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {
865
                    k = (j + odd) >> 1; // find k such that f_tablelow[k] <= f_tablehigh[j] < f_tablelow[k + 1]
866
                    ch_data->env_facs[i + 1][j] = ch_data->env_facs[i][k] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
867
                }
868
            } else {
869
                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {
870
                    k = j ? 2*j - odd : 0; // find k such that f_tablehigh[k] == f_tablelow[j]
871
                    ch_data->env_facs[i + 1][j] = ch_data->env_facs[i][k] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
872
                }
873
            }
874
        } else {
875
            ch_data->env_facs[i + 1][0] = delta * get_bits(gb, bits); // bs_env_start_value_balance
876
            for (j = 1; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++)
877
                ch_data->env_facs[i + 1][j] = ch_data->env_facs[i + 1][j - 1] + delta * (get_vlc2(gb, f_huff, 9, 3) - f_lav);
878
        }
879
    }
880

    
881
    //assign 0th elements of env_facs from last elements
882
    memcpy(ch_data->env_facs[0], ch_data->env_facs[ch_data->bs_num_env[1]],
883
           sizeof(ch_data->env_facs[0]));
884
}
885

    
886
static void read_sbr_noise(SpectralBandReplication *sbr, GetBitContext *gb,
887
                           SBRData *ch_data, int ch)
888
{
889
    int i, j;
890
    VLC_TYPE (*t_huff)[2], (*f_huff)[2];
891
    int t_lav, f_lav;
892
    int delta = (ch == 1 && sbr->bs_coupling == 1) + 1;
893

    
894
    if (sbr->bs_coupling && ch) {
895
        t_huff = vlc_sbr[T_HUFFMAN_NOISE_BAL_3_0DB].table;
896
        t_lav  = vlc_sbr_lav[T_HUFFMAN_NOISE_BAL_3_0DB];
897
        f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_3_0DB].table;
898
        f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_3_0DB];
899
    } else {
900
        t_huff = vlc_sbr[T_HUFFMAN_NOISE_3_0DB].table;
901
        t_lav  = vlc_sbr_lav[T_HUFFMAN_NOISE_3_0DB];
902
        f_huff = vlc_sbr[F_HUFFMAN_ENV_3_0DB].table;
903
        f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_3_0DB];
904
    }
905

    
906
    for (i = 0; i < ch_data->bs_num_noise; i++) {
907
        if (ch_data->bs_df_noise[i]) {
908
            for (j = 0; j < sbr->n_q; j++)
909
                ch_data->noise_facs[i + 1][j] = ch_data->noise_facs[i][j] + delta * (get_vlc2(gb, t_huff, 9, 2) - t_lav);
910
        } else {
911
            ch_data->noise_facs[i + 1][0] = delta * get_bits(gb, 5); // bs_noise_start_value_balance or bs_noise_start_value_level
912
            for (j = 1; j < sbr->n_q; j++)
913
                ch_data->noise_facs[i + 1][j] = ch_data->noise_facs[i + 1][j - 1] + delta * (get_vlc2(gb, f_huff, 9, 3) - f_lav);
914
        }
915
    }
916

    
917
    //assign 0th elements of noise_facs from last elements
918
    memcpy(ch_data->noise_facs[0], ch_data->noise_facs[ch_data->bs_num_noise],
919
           sizeof(ch_data->noise_facs[0]));
920
}
921

    
922
static void read_sbr_extension(AACContext *ac, SpectralBandReplication *sbr,
923
                               GetBitContext *gb,
924
                          int bs_extension_id, int *num_bits_left)
925
{
926
//TODO - implement ps_data for parametric stereo parsing
927
    switch (bs_extension_id) {
928
    case EXTENSION_ID_PS:
929
#if 0
930
        *num_bits_left -= ff_ps_data(gb, ps);
931
#else
932
        av_log_missing_feature(ac->avccontext, "Parametric Stereo is", 0);
933
        skip_bits_long(gb, *num_bits_left); // bs_fill_bits
934
        *num_bits_left = 0;
935
#endif
936
        break;
937
    default:
938
        av_log_missing_feature(ac->avccontext, "Reserved SBR extensions are", 1);
939
        skip_bits_long(gb, *num_bits_left); // bs_fill_bits
940
        *num_bits_left = 0;
941
        break;
942
    }
943
}
944

    
945
static int read_sbr_single_channel_element(AACContext *ac,
946
                                            SpectralBandReplication *sbr,
947
                                            GetBitContext *gb)
948
{
949
    if (get_bits1(gb)) // bs_data_extra
950
        skip_bits(gb, 4); // bs_reserved
951

    
952
    if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))
953
        return -1;
954
    read_sbr_dtdf(sbr, gb, &sbr->data[0]);
955
    read_sbr_invf(sbr, gb, &sbr->data[0]);
956
    read_sbr_envelope(sbr, gb, &sbr->data[0], 0);
957
    read_sbr_noise(sbr, gb, &sbr->data[0], 0);
958

    
959
    if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb)))
960
        get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]);
961

    
962
    return 0;
963
}
964

    
965
static int read_sbr_channel_pair_element(AACContext *ac,
966
                                          SpectralBandReplication *sbr,
967
                                          GetBitContext *gb)
968
{
969
    if (get_bits1(gb))    // bs_data_extra
970
        skip_bits(gb, 8); // bs_reserved
971

    
972
    if ((sbr->bs_coupling = get_bits1(gb))) {
973
        if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))
974
            return -1;
975
        copy_sbr_grid(&sbr->data[1], &sbr->data[0]);
976
        read_sbr_dtdf(sbr, gb, &sbr->data[0]);
977
        read_sbr_dtdf(sbr, gb, &sbr->data[1]);
978
        read_sbr_invf(sbr, gb, &sbr->data[0]);
979
        memcpy(sbr->data[1].bs_invf_mode[1], sbr->data[1].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0]));
980
        memcpy(sbr->data[1].bs_invf_mode[0], sbr->data[0].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0]));
981
        read_sbr_envelope(sbr, gb, &sbr->data[0], 0);
982
        read_sbr_noise(sbr, gb, &sbr->data[0], 0);
983
        read_sbr_envelope(sbr, gb, &sbr->data[1], 1);
984
        read_sbr_noise(sbr, gb, &sbr->data[1], 1);
985
    } else {
986
        if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]) ||
987
            read_sbr_grid(ac, sbr, gb, &sbr->data[1]))
988
            return -1;
989
        read_sbr_dtdf(sbr, gb, &sbr->data[0]);
990
        read_sbr_dtdf(sbr, gb, &sbr->data[1]);
991
        read_sbr_invf(sbr, gb, &sbr->data[0]);
992
        read_sbr_invf(sbr, gb, &sbr->data[1]);
993
        read_sbr_envelope(sbr, gb, &sbr->data[0], 0);
994
        read_sbr_envelope(sbr, gb, &sbr->data[1], 1);
995
        read_sbr_noise(sbr, gb, &sbr->data[0], 0);
996
        read_sbr_noise(sbr, gb, &sbr->data[1], 1);
997
    }
998

    
999
    if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb)))
1000
        get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]);
1001
    if ((sbr->data[1].bs_add_harmonic_flag = get_bits1(gb)))
1002
        get_bits1_vector(gb, sbr->data[1].bs_add_harmonic, sbr->n[1]);
1003

    
1004
    return 0;
1005
}
1006

    
1007
static unsigned int read_sbr_data(AACContext *ac, SpectralBandReplication *sbr,
1008
                                  GetBitContext *gb, int id_aac)
1009
{
1010
    unsigned int cnt = get_bits_count(gb);
1011

    
1012
    if (id_aac == TYPE_SCE || id_aac == TYPE_CCE) {
1013
        if (read_sbr_single_channel_element(ac, sbr, gb)) {
1014
            sbr->start = 0;
1015
            return get_bits_count(gb) - cnt;
1016
        }
1017
    } else if (id_aac == TYPE_CPE) {
1018
        if (read_sbr_channel_pair_element(ac, sbr, gb)) {
1019
            sbr->start = 0;
1020
            return get_bits_count(gb) - cnt;
1021
        }
1022
    } else {
1023
        av_log(ac->avccontext, AV_LOG_ERROR,
1024
            "Invalid bitstream - cannot apply SBR to element type %d\n", id_aac);
1025
        sbr->start = 0;
1026
        return get_bits_count(gb) - cnt;
1027
    }
1028
    if (get_bits1(gb)) { // bs_extended_data
1029
        int num_bits_left = get_bits(gb, 4); // bs_extension_size
1030
        if (num_bits_left == 15)
1031
            num_bits_left += get_bits(gb, 8); // bs_esc_count
1032

    
1033
        num_bits_left <<= 3;
1034
        while (num_bits_left > 7) {
1035
            num_bits_left -= 2;
1036
            read_sbr_extension(ac, sbr, gb, get_bits(gb, 2), &num_bits_left); // bs_extension_id
1037
        }
1038
    }
1039

    
1040
    return get_bits_count(gb) - cnt;
1041
}
1042

    
1043
static void sbr_reset(AACContext *ac, SpectralBandReplication *sbr)
1044
{
1045
    int err;
1046
    err = sbr_make_f_master(ac, sbr, &sbr->spectrum_params);
1047
    if (err >= 0)
1048
        err = sbr_make_f_derived(ac, sbr);
1049
    if (err < 0) {
1050
        av_log(ac->avccontext, AV_LOG_ERROR,
1051
               "SBR reset failed. Switching SBR to pure upsampling mode.\n");
1052
        sbr->start = 0;
1053
    }
1054
}
1055

    
1056
/**
1057
 * Decode Spectral Band Replication extension data; reference: table 4.55.
1058
 *
1059
 * @param   crc flag indicating the presence of CRC checksum
1060
 * @param   cnt length of TYPE_FIL syntactic element in bytes
1061
 *
1062
 * @return  Returns number of bytes consumed from the TYPE_FIL element.
1063
 */
1064
int ff_decode_sbr_extension(AACContext *ac, SpectralBandReplication *sbr,
1065
                            GetBitContext *gb_host, int crc, int cnt, int id_aac)
1066
{
1067
    unsigned int num_sbr_bits = 0, num_align_bits;
1068
    unsigned bytes_read;
1069
    GetBitContext gbc = *gb_host, *gb = &gbc;
1070
    skip_bits_long(gb_host, cnt*8 - 4);
1071

    
1072
    sbr->reset = 0;
1073

    
1074
    if (!sbr->sample_rate)
1075
        sbr->sample_rate = 2 * ac->m4ac.sample_rate; //TODO use the nominal sample rate for arbitrary sample rate support
1076
    if (!ac->m4ac.ext_sample_rate)
1077
        ac->m4ac.ext_sample_rate = 2 * ac->m4ac.sample_rate;
1078

    
1079
    if (crc) {
1080
        skip_bits(gb, 10); // bs_sbr_crc_bits; TODO - implement CRC check
1081
        num_sbr_bits += 10;
1082
    }
1083

    
1084
    //Save some state from the previous frame.
1085
    sbr->kx[0] = sbr->kx[1];
1086
    sbr->m[0] = sbr->m[1];
1087

    
1088
    num_sbr_bits++;
1089
    if (get_bits1(gb)) // bs_header_flag
1090
        num_sbr_bits += read_sbr_header(sbr, gb);
1091

    
1092
    if (sbr->reset)
1093
        sbr_reset(ac, sbr);
1094

    
1095
    if (sbr->start)
1096
        num_sbr_bits  += read_sbr_data(ac, sbr, gb, id_aac);
1097

    
1098
    num_align_bits = ((cnt << 3) - 4 - num_sbr_bits) & 7;
1099
    bytes_read = ((num_sbr_bits + num_align_bits + 4) >> 3);
1100

    
1101
    if (bytes_read > cnt) {
1102
        av_log(ac->avccontext, AV_LOG_ERROR,
1103
               "Expected to read %d SBR bytes actually read %d.\n", cnt, bytes_read);
1104
    }
1105
    return cnt;
1106
}
1107

    
1108
/// Dequantization and stereo decoding (14496-3 sp04 p203)
1109
static void sbr_dequant(SpectralBandReplication *sbr, int id_aac)
1110
{
1111
    int k, e;
1112
    int ch;
1113

    
1114
    if (id_aac == TYPE_CPE && sbr->bs_coupling) {
1115
        float alpha      = sbr->data[0].bs_amp_res ?  1.0f :  0.5f;
1116
        float pan_offset = sbr->data[0].bs_amp_res ? 12.0f : 24.0f;
1117
        for (e = 1; e <= sbr->data[0].bs_num_env[1]; e++) {
1118
            for (k = 0; k < sbr->n[sbr->data[0].bs_freq_res[e]]; k++) {
1119
                float temp1 = exp2f(sbr->data[0].env_facs[e][k] * alpha + 7.0f);
1120
                float temp2 = exp2f((pan_offset - sbr->data[1].env_facs[e][k]) * alpha);
1121
                float fac   = temp1 / (1.0f + temp2);
1122
                sbr->data[0].env_facs[e][k] = fac;
1123
                sbr->data[1].env_facs[e][k] = fac * temp2;
1124
            }
1125
        }
1126
        for (e = 1; e <= sbr->data[0].bs_num_noise; e++) {
1127
            for (k = 0; k < sbr->n_q; k++) {
1128
                float temp1 = exp2f(NOISE_FLOOR_OFFSET - sbr->data[0].noise_facs[e][k] + 1);
1129
                float temp2 = exp2f(12 - sbr->data[1].noise_facs[e][k]);
1130
                float fac   = temp1 / (1.0f + temp2);
1131
                sbr->data[0].noise_facs[e][k] = fac;
1132
                sbr->data[1].noise_facs[e][k] = fac * temp2;
1133
            }
1134
        }
1135
    } else { // SCE or one non-coupled CPE
1136
        for (ch = 0; ch < (id_aac == TYPE_CPE) + 1; ch++) {
1137
            float alpha = sbr->data[ch].bs_amp_res ? 1.0f : 0.5f;
1138
            for (e = 1; e <= sbr->data[ch].bs_num_env[1]; e++)
1139
                for (k = 0; k < sbr->n[sbr->data[ch].bs_freq_res[e]]; k++)
1140
                    sbr->data[ch].env_facs[e][k] =
1141
                        exp2f(alpha * sbr->data[ch].env_facs[e][k] + 6.0f);
1142
            for (e = 1; e <= sbr->data[ch].bs_num_noise; e++)
1143
                for (k = 0; k < sbr->n_q; k++)
1144
                    sbr->data[ch].noise_facs[e][k] =
1145
                        exp2f(NOISE_FLOOR_OFFSET - sbr->data[ch].noise_facs[e][k]);
1146
        }
1147
    }
1148
}
1149

    
1150
/**
1151
 * Analysis QMF Bank (14496-3 sp04 p206)
1152
 *
1153
 * @param   x       pointer to the beginning of the first sample window
1154
 * @param   W       array of complex-valued samples split into subbands
1155
 */
1156
static void sbr_qmf_analysis(DSPContext *dsp, RDFTContext *rdft, const float *in, float *x,
1157
                             float z[320], float W[2][32][32][2],
1158
                             float bias, float scale)
1159
{
1160
    int i, k;
1161
    memcpy(W[0], W[1], sizeof(W[0]));
1162
    memcpy(x    , x+1024, (320-32)*sizeof(x[0]));
1163
    if (scale != 1.0f || bias != 0.0f)
1164
        for (i = 0; i < 1024; i++)
1165
            x[288 + i] = (in[i] - bias) * scale;
1166
    else
1167
        memcpy(x+288, in, 1024*sizeof(*x));
1168
    for (i = 0; i < 32; i++) { // numTimeSlots*RATE = 16*2 as 960 sample frames
1169
                               // are not supported
1170
        float re, im;
1171
        dsp->vector_fmul_reverse(z, sbr_qmf_window_ds, x, 320);
1172
        for (k = 0; k < 64; k++) {
1173
            float f = z[k] + z[k + 64] + z[k + 128] + z[k + 192] + z[k + 256];
1174
            z[k] = f * analysis_cos_pre[k];
1175
            z[k+64] = f;
1176
        }
1177
        ff_rdft_calc(rdft, z);
1178
        re = z[0] * 0.5f;
1179
        im = 0.5f * dsp->scalarproduct_float(z+64, analysis_sin_pre, 64);
1180
        W[1][i][0][0] = re * analysis_cossin_post[0][0] - im * analysis_cossin_post[0][1];
1181
        W[1][i][0][1] = re * analysis_cossin_post[0][1] + im * analysis_cossin_post[0][0];
1182
        for (k = 1; k < 32; k++) {
1183
            re = z[2*k  ] - re;
1184
            im = z[2*k+1] - im;
1185
            W[1][i][k][0] = re * analysis_cossin_post[k][0] - im * analysis_cossin_post[k][1];
1186
            W[1][i][k][1] = re * analysis_cossin_post[k][1] + im * analysis_cossin_post[k][0];
1187
        }
1188
        x += 32;
1189
    }
1190
}
1191

    
1192
/**
1193
 * Synthesis QMF Bank (14496-3 sp04 p206) and Downsampled Synthesis QMF Bank
1194
 * (14496-3 sp04 p206)
1195
 */
1196
static void sbr_qmf_synthesis(DSPContext *dsp, FFTContext *mdct,
1197
                              float *out, float X[2][32][64],
1198
                              float mdct_buf[2][64],
1199
                              float *v0, int *v_off, const unsigned int div,
1200
                              float bias, float scale)
1201
{
1202
    int i, n;
1203
    const float *sbr_qmf_window = div ? sbr_qmf_window_ds : sbr_qmf_window_us;
1204
    int scale_and_bias = scale != 1.0f || bias != 0.0f;
1205
    float *v;
1206
    for (i = 0; i < 32; i++) {
1207
        if (*v_off == 0) {
1208
            int saved_samples = (1280 - 128) >> div;
1209
            memcpy(&v0[SBR_SYNTHESIS_BUF_SIZE - saved_samples], v0, saved_samples * sizeof(float));
1210
            *v_off = SBR_SYNTHESIS_BUF_SIZE - saved_samples - (128 >> div);
1211
        } else {
1212
            *v_off -= 128 >> div;
1213
        }
1214
        v = v0 + *v_off;
1215
        for (n = 1; n < 64 >> div; n+=2) {
1216
            X[1][i][n] = -X[1][i][n];
1217
        }
1218
        if (div) {
1219
            memset(X[0][i]+32, 0, 32*sizeof(float));
1220
            memset(X[1][i]+32, 0, 32*sizeof(float));
1221
        }
1222
        ff_imdct_half(mdct, mdct_buf[0], X[0][i]);
1223
        ff_imdct_half(mdct, mdct_buf[1], X[1][i]);
1224
        if (div) {
1225
            for (n = 0; n < 32; n++) {
1226
                v[      n] = -mdct_buf[0][63 - 2*n] + mdct_buf[1][2*n    ];
1227
                v[ 63 - n] =  mdct_buf[0][62 - 2*n] + mdct_buf[1][2*n + 1];
1228
            }
1229
        } else {
1230
            for (n = 0; n < 64; n++) {
1231
                v[      n] = -mdct_buf[0][63 -   n] + mdct_buf[1][  n    ];
1232
                v[127 - n] =  mdct_buf[0][63 -   n] + mdct_buf[1][  n    ];
1233
            }
1234
        }
1235
        dsp->vector_fmul_add(out, v                , sbr_qmf_window               , zero64, 64 >> div);
1236
        dsp->vector_fmul_add(out, v + ( 192 >> div), sbr_qmf_window + ( 64 >> div), out   , 64 >> div);
1237
        dsp->vector_fmul_add(out, v + ( 256 >> div), sbr_qmf_window + (128 >> div), out   , 64 >> div);
1238
        dsp->vector_fmul_add(out, v + ( 448 >> div), sbr_qmf_window + (192 >> div), out   , 64 >> div);
1239
        dsp->vector_fmul_add(out, v + ( 512 >> div), sbr_qmf_window + (256 >> div), out   , 64 >> div);
1240
        dsp->vector_fmul_add(out, v + ( 704 >> div), sbr_qmf_window + (320 >> div), out   , 64 >> div);
1241
        dsp->vector_fmul_add(out, v + ( 768 >> div), sbr_qmf_window + (384 >> div), out   , 64 >> div);
1242
        dsp->vector_fmul_add(out, v + ( 960 >> div), sbr_qmf_window + (448 >> div), out   , 64 >> div);
1243
        dsp->vector_fmul_add(out, v + (1024 >> div), sbr_qmf_window + (512 >> div), out   , 64 >> div);
1244
        dsp->vector_fmul_add(out, v + (1216 >> div), sbr_qmf_window + (576 >> div), out   , 64 >> div);
1245
        if (scale_and_bias)
1246
            for (n = 0; n < 64 >> div; n++)
1247
                out[n] = out[n] * scale + bias;
1248
        out += 64 >> div;
1249
    }
1250
}
1251

    
1252
static void autocorrelate(const float x[40][2], float phi[3][2][2], int lag)
1253
{
1254
    int i;
1255
    float real_sum = 0.0f;
1256
    float imag_sum = 0.0f;
1257
    if (lag) {
1258
        for (i = 1; i < 38; i++) {
1259
            real_sum += x[i][0] * x[i+lag][0] + x[i][1] * x[i+lag][1];
1260
            imag_sum += x[i][0] * x[i+lag][1] - x[i][1] * x[i+lag][0];
1261
        }
1262
        phi[2-lag][1][0] = real_sum + x[ 0][0] * x[lag][0] + x[ 0][1] * x[lag][1];
1263
        phi[2-lag][1][1] = imag_sum + x[ 0][0] * x[lag][1] - x[ 0][1] * x[lag][0];
1264
        if (lag == 1) {
1265
            phi[0][0][0] = real_sum + x[38][0] * x[39][0] + x[38][1] * x[39][1];
1266
            phi[0][0][1] = imag_sum + x[38][0] * x[39][1] - x[38][1] * x[39][0];
1267
        }
1268
    } else {
1269
        for (i = 1; i < 38; i++) {
1270
            real_sum += x[i][0] * x[i][0] + x[i][1] * x[i][1];
1271
        }
1272
        phi[2][1][0] = real_sum + x[ 0][0] * x[ 0][0] + x[ 0][1] * x[ 0][1];
1273
        phi[1][0][0] = real_sum + x[38][0] * x[38][0] + x[38][1] * x[38][1];
1274
    }
1275
}
1276

    
1277
/** High Frequency Generation (14496-3 sp04 p214+) and Inverse Filtering
1278
 * (14496-3 sp04 p214)
1279
 * Warning: This routine does not seem numerically stable.
1280
 */
1281
static void sbr_hf_inverse_filter(float (*alpha0)[2], float (*alpha1)[2],
1282
                                  const float X_low[32][40][2], int k0)
1283
{
1284
    int k;
1285
    for (k = 0; k < k0; k++) {
1286
        float phi[3][2][2], dk;
1287

    
1288
        autocorrelate(X_low[k], phi, 0);
1289
        autocorrelate(X_low[k], phi, 1);
1290
        autocorrelate(X_low[k], phi, 2);
1291

    
1292
        dk =  phi[2][1][0] * phi[1][0][0] -
1293
             (phi[1][1][0] * phi[1][1][0] + phi[1][1][1] * phi[1][1][1]) / 1.000001f;
1294

    
1295
        if (!dk) {
1296
            alpha1[k][0] = 0;
1297
            alpha1[k][1] = 0;
1298
        } else {
1299
            float temp_real, temp_im;
1300
            temp_real = phi[0][0][0] * phi[1][1][0] -
1301
                        phi[0][0][1] * phi[1][1][1] -
1302
                        phi[0][1][0] * phi[1][0][0];
1303
            temp_im   = phi[0][0][0] * phi[1][1][1] +
1304
                        phi[0][0][1] * phi[1][1][0] -
1305
                        phi[0][1][1] * phi[1][0][0];
1306

    
1307
            alpha1[k][0] = temp_real / dk;
1308
            alpha1[k][1] = temp_im   / dk;
1309
        }
1310

    
1311
        if (!phi[1][0][0]) {
1312
            alpha0[k][0] = 0;
1313
            alpha0[k][1] = 0;
1314
        } else {
1315
            float temp_real, temp_im;
1316
            temp_real = phi[0][0][0] + alpha1[k][0] * phi[1][1][0] +
1317
                                       alpha1[k][1] * phi[1][1][1];
1318
            temp_im   = phi[0][0][1] + alpha1[k][1] * phi[1][1][0] -
1319
                                       alpha1[k][0] * phi[1][1][1];
1320

    
1321
            alpha0[k][0] = -temp_real / phi[1][0][0];
1322
            alpha0[k][1] = -temp_im   / phi[1][0][0];
1323
        }
1324

    
1325
        if (alpha1[k][0] * alpha1[k][0] + alpha1[k][1] * alpha1[k][1] >= 16.0f ||
1326
           alpha0[k][0] * alpha0[k][0] + alpha0[k][1] * alpha0[k][1] >= 16.0f) {
1327
            alpha1[k][0] = 0;
1328
            alpha1[k][1] = 0;
1329
            alpha0[k][0] = 0;
1330
            alpha0[k][1] = 0;
1331
        }
1332
    }
1333
}
1334

    
1335
/// Chirp Factors (14496-3 sp04 p214)
1336
static void sbr_chirp(SpectralBandReplication *sbr, SBRData *ch_data)
1337
{
1338
    int i;
1339
    float new_bw;
1340
    static const float bw_tab[] = { 0.0f, 0.75f, 0.9f, 0.98f };
1341

    
1342
    for (i = 0; i < sbr->n_q; i++) {
1343
        if (ch_data->bs_invf_mode[0][i] + ch_data->bs_invf_mode[1][i] == 1) {
1344
            new_bw = 0.6f;
1345
        } else
1346
            new_bw = bw_tab[ch_data->bs_invf_mode[0][i]];
1347

    
1348
        if (new_bw < ch_data->bw_array[i]) {
1349
            new_bw = 0.75f    * new_bw + 0.25f    * ch_data->bw_array[i];
1350
        } else
1351
            new_bw = 0.90625f * new_bw + 0.09375f * ch_data->bw_array[i];
1352
        ch_data->bw_array[i] = new_bw < 0.015625f ? 0.0f : new_bw;
1353
    }
1354
}
1355

    
1356
/// Generate the subband filtered lowband
1357
static int sbr_lf_gen(AACContext *ac, SpectralBandReplication *sbr,
1358
                      float X_low[32][40][2], const float W[2][32][32][2])
1359
{
1360
    int i, k;
1361
    const int t_HFGen = 8;
1362
    const int i_f = 32;
1363
    memset(X_low, 0, 32*sizeof(*X_low));
1364
    for (k = 0; k < sbr->kx[1]; k++) {
1365
        for (i = t_HFGen; i < i_f + t_HFGen; i++) {
1366
            X_low[k][i][0] = W[1][i - t_HFGen][k][0];
1367
            X_low[k][i][1] = W[1][i - t_HFGen][k][1];
1368
        }
1369
    }
1370
    for (k = 0; k < sbr->kx[0]; k++) {
1371
        for (i = 0; i < t_HFGen; i++) {
1372
            X_low[k][i][0] = W[0][i + i_f - t_HFGen][k][0];
1373
            X_low[k][i][1] = W[0][i + i_f - t_HFGen][k][1];
1374
        }
1375
    }
1376
    return 0;
1377
}
1378

    
1379
/// High Frequency Generator (14496-3 sp04 p215)
1380
static int sbr_hf_gen(AACContext *ac, SpectralBandReplication *sbr,
1381
                      float X_high[64][40][2], const float X_low[32][40][2],
1382
                      const float (*alpha0)[2], const float (*alpha1)[2],
1383
                      const float bw_array[5], const uint8_t *t_env,
1384
                      int bs_num_env)
1385
{
1386
    int i, j, x;
1387
    int g = 0;
1388
    int k = sbr->kx[1];
1389
    for (j = 0; j < sbr->num_patches; j++) {
1390
        for (x = 0; x < sbr->patch_num_subbands[j]; x++, k++) {
1391
            float alpha[4];
1392
            const int p = sbr->patch_start_subband[j] + x;
1393
            while (g <= sbr->n_q && k >= sbr->f_tablenoise[g])
1394
                g++;
1395
            g--;
1396

    
1397
            if (g < 0) {
1398
                av_log(ac->avccontext, AV_LOG_ERROR,
1399
                       "ERROR : no subband found for frequency %d\n", k);
1400
                return -1;
1401
            }
1402

    
1403
            alpha[0] = alpha1[p][0] * bw_array[g] * bw_array[g];
1404
            alpha[1] = alpha1[p][1] * bw_array[g] * bw_array[g];
1405
            alpha[2] = alpha0[p][0] * bw_array[g];
1406
            alpha[3] = alpha0[p][1] * bw_array[g];
1407

    
1408
            for (i = 2 * t_env[0]; i < 2 * t_env[bs_num_env]; i++) {
1409
                const int idx = i + ENVELOPE_ADJUSTMENT_OFFSET;
1410
                X_high[k][idx][0] =
1411
                    X_low[p][idx - 2][0] * alpha[0] -
1412
                    X_low[p][idx - 2][1] * alpha[1] +
1413
                    X_low[p][idx - 1][0] * alpha[2] -
1414
                    X_low[p][idx - 1][1] * alpha[3] +
1415
                    X_low[p][idx][0];
1416
                X_high[k][idx][1] =
1417
                    X_low[p][idx - 2][1] * alpha[0] +
1418
                    X_low[p][idx - 2][0] * alpha[1] +
1419
                    X_low[p][idx - 1][1] * alpha[2] +
1420
                    X_low[p][idx - 1][0] * alpha[3] +
1421
                    X_low[p][idx][1];
1422
            }
1423
        }
1424
    }
1425
    if (k < sbr->m[1] + sbr->kx[1])
1426
        memset(X_high + k, 0, (sbr->m[1] + sbr->kx[1] - k) * sizeof(*X_high));
1427

    
1428
    return 0;
1429
}
1430

    
1431
/// Generate the subband filtered lowband
1432
static int sbr_x_gen(SpectralBandReplication *sbr, float X[2][32][64],
1433
                     const float X_low[32][40][2], const float Y[2][38][64][2],
1434
                     int ch)
1435
{
1436
    int k, i;
1437
    const int i_f = 32;
1438
    const int i_Temp = FFMAX(2*sbr->data[ch].t_env_num_env_old - i_f, 0);
1439
    memset(X, 0, 2*sizeof(*X));
1440
    for (k = 0; k < sbr->kx[0]; k++) {
1441
        for (i = 0; i < i_Temp; i++) {
1442
            X[0][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][0];
1443
            X[1][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][1];
1444
        }
1445
    }
1446
    for (; k < sbr->kx[0] + sbr->m[0]; k++) {
1447
        for (i = 0; i < i_Temp; i++) {
1448
            X[0][i][k] = Y[0][i + i_f][k][0];
1449
            X[1][i][k] = Y[0][i + i_f][k][1];
1450
        }
1451
    }
1452

    
1453
    for (k = 0; k < sbr->kx[1]; k++) {
1454
        for (i = i_Temp; i < i_f; i++) {
1455
            X[0][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][0];
1456
            X[1][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][1];
1457
        }
1458
    }
1459
    for (; k < sbr->kx[1] + sbr->m[1]; k++) {
1460
        for (i = i_Temp; i < i_f; i++) {
1461
            X[0][i][k] = Y[1][i][k][0];
1462
            X[1][i][k] = Y[1][i][k][1];
1463
        }
1464
    }
1465
    return 0;
1466
}
1467

    
1468
/** High Frequency Adjustment (14496-3 sp04 p217) and Mapping
1469
 * (14496-3 sp04 p217)
1470
 */
1471
static void sbr_mapping(AACContext *ac, SpectralBandReplication *sbr,
1472
                        SBRData *ch_data, int e_a[2])
1473
{
1474
    int e, i, m;
1475

    
1476
    memset(ch_data->s_indexmapped[1], 0, 7*sizeof(ch_data->s_indexmapped[1]));
1477
    for (e = 0; e < ch_data->bs_num_env[1]; e++) {
1478
        const unsigned int ilim = sbr->n[ch_data->bs_freq_res[e + 1]];
1479
        uint16_t *table = ch_data->bs_freq_res[e + 1] ? sbr->f_tablehigh : sbr->f_tablelow;
1480
        int k;
1481

    
1482
        for (i = 0; i < ilim; i++)
1483
            for (m = table[i]; m < table[i + 1]; m++)
1484
                sbr->e_origmapped[e][m - sbr->kx[1]] = ch_data->env_facs[e+1][i];
1485

    
1486
        // ch_data->bs_num_noise > 1 => 2 noise floors
1487
        k = (ch_data->bs_num_noise > 1) && (ch_data->t_env[e] >= ch_data->t_q[1]);
1488
        for (i = 0; i < sbr->n_q; i++)
1489
            for (m = sbr->f_tablenoise[i]; m < sbr->f_tablenoise[i + 1]; m++)
1490
                sbr->q_mapped[e][m - sbr->kx[1]] = ch_data->noise_facs[k+1][i];
1491

    
1492
        for (i = 0; i < sbr->n[1]; i++) {
1493
            if (ch_data->bs_add_harmonic_flag) {
1494
                const unsigned int m_midpoint =
1495
                    (sbr->f_tablehigh[i] + sbr->f_tablehigh[i + 1]) >> 1;
1496

    
1497
                ch_data->s_indexmapped[e + 1][m_midpoint - sbr->kx[1]] = ch_data->bs_add_harmonic[i] *
1498
                    (e >= e_a[1] || (ch_data->s_indexmapped[0][m_midpoint - sbr->kx[1]] == 1));
1499
            }
1500
        }
1501

    
1502
        for (i = 0; i < ilim; i++) {
1503
            int additional_sinusoid_present = 0;
1504
            for (m = table[i]; m < table[i + 1]; m++) {
1505
                if (ch_data->s_indexmapped[e + 1][m - sbr->kx[1]]) {
1506
                    additional_sinusoid_present = 1;
1507
                    break;
1508
                }
1509
            }
1510
            memset(&sbr->s_mapped[e][table[i] - sbr->kx[1]], additional_sinusoid_present,
1511
                   (table[i + 1] - table[i]) * sizeof(sbr->s_mapped[e][0]));
1512
        }
1513
    }
1514

    
1515
    memcpy(ch_data->s_indexmapped[0], ch_data->s_indexmapped[ch_data->bs_num_env[1]], sizeof(ch_data->s_indexmapped[0]));
1516
}
1517

    
1518
/// Estimation of current envelope (14496-3 sp04 p218)
1519
static void sbr_env_estimate(float (*e_curr)[48], float X_high[64][40][2],
1520
                             SpectralBandReplication *sbr, SBRData *ch_data)
1521
{
1522
    int e, i, m;
1523

    
1524
    if (sbr->bs_interpol_freq) {
1525
        for (e = 0; e < ch_data->bs_num_env[1]; e++) {
1526
            const float recip_env_size = 0.5f / (ch_data->t_env[e + 1] - ch_data->t_env[e]);
1527
            int ilb = ch_data->t_env[e]     * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1528
            int iub = ch_data->t_env[e + 1] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1529

    
1530
            for (m = 0; m < sbr->m[1]; m++) {
1531
                float sum = 0.0f;
1532

    
1533
                for (i = ilb; i < iub; i++) {
1534
                    sum += X_high[m + sbr->kx[1]][i][0] * X_high[m + sbr->kx[1]][i][0] +
1535
                           X_high[m + sbr->kx[1]][i][1] * X_high[m + sbr->kx[1]][i][1];
1536
                }
1537
                e_curr[e][m] = sum * recip_env_size;
1538
            }
1539
        }
1540
    } else {
1541
        int k, p;
1542

    
1543
        for (e = 0; e < ch_data->bs_num_env[1]; e++) {
1544
            const int env_size = 2 * (ch_data->t_env[e + 1] - ch_data->t_env[e]);
1545
            int ilb = ch_data->t_env[e]     * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1546
            int iub = ch_data->t_env[e + 1] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1547
            const uint16_t *table = ch_data->bs_freq_res[e + 1] ? sbr->f_tablehigh : sbr->f_tablelow;
1548

    
1549
            for (p = 0; p < sbr->n[ch_data->bs_freq_res[e + 1]]; p++) {
1550
                float sum = 0.0f;
1551
                const int den = env_size * (table[p + 1] - table[p]);
1552

    
1553
                for (k = table[p]; k < table[p + 1]; k++) {
1554
                    for (i = ilb; i < iub; i++) {
1555
                        sum += X_high[k][i][0] * X_high[k][i][0] +
1556
                               X_high[k][i][1] * X_high[k][i][1];
1557
                    }
1558
                }
1559
                sum /= den;
1560
                for (k = table[p]; k < table[p + 1]; k++) {
1561
                    e_curr[e][k - sbr->kx[1]] = sum;
1562
                }
1563
            }
1564
        }
1565
    }
1566
}
1567

    
1568
/**
1569
 * Calculation of levels of additional HF signal components (14496-3 sp04 p219)
1570
 * and Calculation of gain (14496-3 sp04 p219)
1571
 */
1572
static void sbr_gain_calc(AACContext *ac, SpectralBandReplication *sbr,
1573
                          SBRData *ch_data, const int e_a[2])
1574
{
1575
    int e, k, m;
1576
    // max gain limits : -3dB, 0dB, 3dB, inf dB (limiter off)
1577
    static const float limgain[4] = { 0.70795, 1.0, 1.41254, 10000000000 };
1578

    
1579
    for (e = 0; e < ch_data->bs_num_env[1]; e++) {
1580
        int delta = !((e == e_a[1]) || (e == e_a[0]));
1581
        for (k = 0; k < sbr->n_lim; k++) {
1582
            float gain_boost, gain_max;
1583
            float sum[2] = { 0.0f, 0.0f };
1584
            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1585
                const float temp = sbr->e_origmapped[e][m] / (1.0f + sbr->q_mapped[e][m]);
1586
                sbr->q_m[e][m] = sqrtf(temp * sbr->q_mapped[e][m]);
1587
                sbr->s_m[e][m] = sqrtf(temp * ch_data->s_indexmapped[e + 1][m]);
1588
                if (!sbr->s_mapped[e][m]) {
1589
                    sbr->gain[e][m] = sqrtf(sbr->e_origmapped[e][m] /
1590
                                            ((1.0f + sbr->e_curr[e][m]) *
1591
                                             (1.0f + sbr->q_mapped[e][m] * delta)));
1592
                } else {
1593
                    sbr->gain[e][m] = sqrtf(sbr->e_origmapped[e][m] * sbr->q_mapped[e][m] /
1594
                                            ((1.0f + sbr->e_curr[e][m]) *
1595
                                             (1.0f + sbr->q_mapped[e][m])));
1596
                }
1597
            }
1598
            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1599
                sum[0] += sbr->e_origmapped[e][m];
1600
                sum[1] += sbr->e_curr[e][m];
1601
            }
1602
            gain_max = limgain[sbr->bs_limiter_gains] * sqrtf((FLT_EPSILON + sum[0]) / (FLT_EPSILON + sum[1]));
1603
            gain_max = FFMIN(100000, gain_max);
1604
            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1605
                float q_m_max   = sbr->q_m[e][m] * gain_max / sbr->gain[e][m];
1606
                sbr->q_m[e][m]  = FFMIN(sbr->q_m[e][m], q_m_max);
1607
                sbr->gain[e][m] = FFMIN(sbr->gain[e][m], gain_max);
1608
            }
1609
            sum[0] = sum[1] = 0.0f;
1610
            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1611
                sum[0] += sbr->e_origmapped[e][m];
1612
                sum[1] += sbr->e_curr[e][m] * sbr->gain[e][m] * sbr->gain[e][m]
1613
                          + sbr->s_m[e][m] * sbr->s_m[e][m]
1614
                          + (delta && !sbr->s_m[e][m]) * sbr->q_m[e][m] * sbr->q_m[e][m];
1615
            }
1616
            gain_boost = sqrtf((FLT_EPSILON + sum[0]) / (FLT_EPSILON + sum[1]));
1617
            gain_boost = FFMIN(1.584893192, gain_boost);
1618
            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1619
                sbr->gain[e][m] *= gain_boost;
1620
                sbr->q_m[e][m]  *= gain_boost;
1621
                sbr->s_m[e][m]  *= gain_boost;
1622
            }
1623
        }
1624
    }
1625
}
1626

    
1627
/// Assembling HF Signals (14496-3 sp04 p220)
1628
static void sbr_hf_assemble(float Y[2][38][64][2], const float X_high[64][40][2],
1629
                            SpectralBandReplication *sbr, SBRData *ch_data,
1630
                            const int e_a[2])
1631
{
1632
    int e, i, j, m;
1633
    const int h_SL = 4 * !sbr->bs_smoothing_mode;
1634
    const int kx = sbr->kx[1];
1635
    const int m_max = sbr->m[1];
1636
    static const float h_smooth[5] = {
1637
        0.33333333333333,
1638
        0.30150283239582,
1639
        0.21816949906249,
1640
        0.11516383427084,
1641
        0.03183050093751,
1642
    };
1643
    static const int8_t phi[2][4] = {
1644
        {  1,  0, -1,  0}, // real
1645
        {  0,  1,  0, -1}, // imaginary
1646
    };
1647
    float (*g_temp)[48] = ch_data->g_temp, (*q_temp)[48] = ch_data->q_temp;
1648
    int indexnoise = ch_data->f_indexnoise;
1649
    int indexsine  = ch_data->f_indexsine;
1650
    memcpy(Y[0], Y[1], sizeof(Y[0]));
1651

    
1652
    if (sbr->reset) {
1653
        for (i = 0; i < h_SL; i++) {
1654
            memcpy(g_temp[i + 2*ch_data->t_env[0]], sbr->gain[0], m_max * sizeof(sbr->gain[0][0]));
1655
            memcpy(q_temp[i + 2*ch_data->t_env[0]], sbr->q_m[0],  m_max * sizeof(sbr->q_m[0][0]));
1656
        }
1657
    } else if (h_SL) {
1658
        memcpy(g_temp[2*ch_data->t_env[0]], g_temp[2*ch_data->t_env_num_env_old], 4*sizeof(g_temp[0]));
1659
        memcpy(q_temp[2*ch_data->t_env[0]], q_temp[2*ch_data->t_env_num_env_old], 4*sizeof(q_temp[0]));
1660
    }
1661

    
1662
    for (e = 0; e < ch_data->bs_num_env[1]; e++) {
1663
        for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {
1664
            memcpy(g_temp[h_SL + i], sbr->gain[e], m_max * sizeof(sbr->gain[0][0]));
1665
            memcpy(q_temp[h_SL + i], sbr->q_m[e],  m_max * sizeof(sbr->q_m[0][0]));
1666
        }
1667
    }
1668

    
1669
    for (e = 0; e < ch_data->bs_num_env[1]; e++) {
1670
        for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {
1671
            int phi_sign = (1 - 2*(kx & 1));
1672

    
1673
            if (h_SL && e != e_a[0] && e != e_a[1]) {
1674
                for (m = 0; m < m_max; m++) {
1675
                    const int idx1 = i + h_SL;
1676
                    float g_filt = 0.0f;
1677
                    for (j = 0; j <= h_SL; j++)
1678
                        g_filt += g_temp[idx1 - j][m] * h_smooth[j];
1679
                    Y[1][i][m + kx][0] =
1680
                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][0] * g_filt;
1681
                    Y[1][i][m + kx][1] =
1682
                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][1] * g_filt;
1683
                }
1684
            } else {
1685
                for (m = 0; m < m_max; m++) {
1686
                    const float g_filt = g_temp[i + h_SL][m];
1687
                    Y[1][i][m + kx][0] =
1688
                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][0] * g_filt;
1689
                    Y[1][i][m + kx][1] =
1690
                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][1] * g_filt;
1691
                }
1692
            }
1693

    
1694
            if (e != e_a[0] && e != e_a[1]) {
1695
                for (m = 0; m < m_max; m++) {
1696
                    indexnoise = (indexnoise + 1) & 0x1ff;
1697
                    if (sbr->s_m[e][m]) {
1698
                        Y[1][i][m + kx][0] +=
1699
                            sbr->s_m[e][m] * phi[0][indexsine];
1700
                        Y[1][i][m + kx][1] +=
1701
                            sbr->s_m[e][m] * (phi[1][indexsine] * phi_sign);
1702
                    } else {
1703
                        float q_filt;
1704
                        if (h_SL) {
1705
                            const int idx1 = i + h_SL;
1706
                            q_filt = 0.0f;
1707
                            for (j = 0; j <= h_SL; j++)
1708
                                q_filt += q_temp[idx1 - j][m] * h_smooth[j];
1709
                        } else {
1710
                            q_filt = q_temp[i][m];
1711
                        }
1712
                        Y[1][i][m + kx][0] +=
1713
                            q_filt * sbr_noise_table[indexnoise][0];
1714
                        Y[1][i][m + kx][1] +=
1715
                            q_filt * sbr_noise_table[indexnoise][1];
1716
                    }
1717
                    phi_sign = -phi_sign;
1718
                }
1719
            } else {
1720
                indexnoise = (indexnoise + m_max) & 0x1ff;
1721
                for (m = 0; m < m_max; m++) {
1722
                    Y[1][i][m + kx][0] +=
1723
                        sbr->s_m[e][m] * phi[0][indexsine];
1724
                    Y[1][i][m + kx][1] +=
1725
                        sbr->s_m[e][m] * (phi[1][indexsine] * phi_sign);
1726
                    phi_sign = -phi_sign;
1727
                }
1728
            }
1729
            indexsine = (indexsine + 1) & 3;
1730
        }
1731
    }
1732
    ch_data->f_indexnoise = indexnoise;
1733
    ch_data->f_indexsine  = indexsine;
1734
}
1735

    
1736
void ff_sbr_dequant(AACContext *ac, SpectralBandReplication *sbr, int id_aac)
1737
{
1738
    if (sbr->start) {
1739
        sbr_dequant(sbr, id_aac);
1740
    }
1741
}
1742

    
1743
void ff_sbr_apply(AACContext *ac, SpectralBandReplication *sbr, int ch,
1744
                  const float* in, float* out)
1745
{
1746
    int downsampled = ac->m4ac.ext_sample_rate < sbr->sample_rate;
1747

    
1748
    /* decode channel */
1749
    sbr_qmf_analysis(&ac->dsp, &sbr->rdft, in, sbr->data[ch].analysis_filterbank_samples,
1750
                     (float*)sbr->qmf_filter_scratch,
1751
                     sbr->data[ch].W, ac->add_bias, 1/(-1024 * ac->sf_scale));
1752
    sbr_lf_gen(ac, sbr, sbr->X_low, sbr->data[ch].W);
1753
    if (sbr->start) {
1754
        sbr_hf_inverse_filter(sbr->alpha0, sbr->alpha1, sbr->X_low, sbr->k[0]);
1755
        sbr_chirp(sbr, &sbr->data[ch]);
1756
        sbr_hf_gen(ac, sbr, sbr->X_high, sbr->X_low, sbr->alpha0, sbr->alpha1,
1757
                   sbr->data[ch].bw_array, sbr->data[ch].t_env,
1758
                   sbr->data[ch].bs_num_env[1]);
1759

    
1760
        // hf_adj
1761
        sbr_mapping(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);
1762
        sbr_env_estimate(sbr->e_curr, sbr->X_high, sbr, &sbr->data[ch]);
1763
        sbr_gain_calc(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);
1764
        sbr_hf_assemble(sbr->data[ch].Y, sbr->X_high, sbr, &sbr->data[ch],
1765
                        sbr->data[ch].e_a);
1766
    }
1767

    
1768
    /* synthesis */
1769
    sbr_x_gen(sbr, sbr->X, sbr->X_low, sbr->data[ch].Y, ch);
1770
    sbr_qmf_synthesis(&ac->dsp, &sbr->mdct, out, sbr->X, sbr->qmf_filter_scratch,
1771
                      sbr->data[ch].synthesis_filterbank_samples,
1772
                      &sbr->data[ch].synthesis_filterbank_samples_offset,
1773
                      downsampled,
1774
                      ac->add_bias, -1024 * ac->sf_scale);
1775
}