Statistics
| Branch: | Revision:

ffmpeg / libavcodec / aacsbr.c @ 2912e87a

History | View | Annotate | Download (65.2 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 Libav.
7
 *
8
 * Libav 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
 * Libav 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 Libav; 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
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
#include "aacps.h"
35

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

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

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

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

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

    
72
static VLC vlc_sbr[10];
73
static const int8_t vlc_sbr_lav[10] =
74
    { 60, 60, 24, 24, 31, 31, 12, 12, 31, 12 };
75
static const DECLARE_ALIGNED(16, float, zero64)[64];
76

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

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

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

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

    
117
    for (n = 1; n < 320; n++)
118
        sbr_qmf_window_us[320 + n] = sbr_qmf_window_us[320 - n];
119
    sbr_qmf_window_us[384] = -sbr_qmf_window_us[384];
120
    sbr_qmf_window_us[512] = -sbr_qmf_window_us[512];
121

    
122
    for (n = 0; n < 320; n++)
123
        sbr_qmf_window_ds[n] = sbr_qmf_window_us[2*n];
124

    
125
    ff_ps_init();
126
}
127

    
128
av_cold void ff_aac_sbr_ctx_init(SpectralBandReplication *sbr)
129
{
130
    sbr->kx[0] = sbr->kx[1] = 32; //Typo in spec, kx' inits to 32
131
    sbr->data[0].e_a[1] = sbr->data[1].e_a[1] = -1;
132
    sbr->data[0].synthesis_filterbank_samples_offset = SBR_SYNTHESIS_BUF_SIZE - (1280 - 128);
133
    sbr->data[1].synthesis_filterbank_samples_offset = SBR_SYNTHESIS_BUF_SIZE - (1280 - 128);
134
    ff_mdct_init(&sbr->mdct, 7, 1, 1.0/64);
135
    ff_mdct_init(&sbr->mdct_ana, 7, 1, -2.0);
136
    ff_ps_ctx_init(&sbr->ps);
137
}
138

    
139
av_cold void ff_aac_sbr_ctx_close(SpectralBandReplication *sbr)
140
{
141
    ff_mdct_end(&sbr->mdct);
142
    ff_mdct_end(&sbr->mdct_ana);
143
}
144

    
145
static int qsort_comparison_function_int16(const void *a, const void *b)
146
{
147
    return *(const int16_t *)a - *(const int16_t *)b;
148
}
149

    
150
static inline int in_table_int16(const int16_t *table, int last_el, int16_t needle)
151
{
152
    int i;
153
    for (i = 0; i <= last_el; i++)
154
        if (table[i] == needle)
155
            return 1;
156
    return 0;
157
}
158

    
159
/// Limiter Frequency Band Table (14496-3 sp04 p198)
160
static void sbr_make_f_tablelim(SpectralBandReplication *sbr)
161
{
162
    int k;
163
    if (sbr->bs_limiter_bands > 0) {
164
        static const float bands_warped[3] = { 1.32715174233856803909f,   //2^(0.49/1.2)
165
                                               1.18509277094158210129f,   //2^(0.49/2)
166
                                               1.11987160404675912501f }; //2^(0.49/3)
167
        const float lim_bands_per_octave_warped = bands_warped[sbr->bs_limiter_bands - 1];
168
        int16_t patch_borders[7];
169
        uint16_t *in = sbr->f_tablelim + 1, *out = sbr->f_tablelim;
170

    
171
        patch_borders[0] = sbr->kx[1];
172
        for (k = 1; k <= sbr->num_patches; k++)
173
            patch_borders[k] = patch_borders[k-1] + sbr->patch_num_subbands[k-1];
174

    
175
        memcpy(sbr->f_tablelim, sbr->f_tablelow,
176
               (sbr->n[0] + 1) * sizeof(sbr->f_tablelow[0]));
177
        if (sbr->num_patches > 1)
178
            memcpy(sbr->f_tablelim + sbr->n[0] + 1, patch_borders + 1,
179
                   (sbr->num_patches - 1) * sizeof(patch_borders[0]));
180

    
181
        qsort(sbr->f_tablelim, sbr->num_patches + sbr->n[0],
182
              sizeof(sbr->f_tablelim[0]),
183
              qsort_comparison_function_int16);
184

    
185
        sbr->n_lim = sbr->n[0] + sbr->num_patches - 1;
186
        while (out < sbr->f_tablelim + sbr->n_lim) {
187
            if (*in >= *out * lim_bands_per_octave_warped) {
188
                *++out = *in++;
189
            } else if (*in == *out ||
190
                !in_table_int16(patch_borders, sbr->num_patches, *in)) {
191
                in++;
192
                sbr->n_lim--;
193
            } else if (!in_table_int16(patch_borders, sbr->num_patches, *out)) {
194
                *out = *in++;
195
                sbr->n_lim--;
196
            } else {
197
                *++out = *in++;
198
            }
199
        }
200
    } else {
201
        sbr->f_tablelim[0] = sbr->f_tablelow[0];
202
        sbr->f_tablelim[1] = sbr->f_tablelow[sbr->n[0]];
203
        sbr->n_lim = 1;
204
    }
205
}
206

    
207
static unsigned int read_sbr_header(SpectralBandReplication *sbr, GetBitContext *gb)
208
{
209
    unsigned int cnt = get_bits_count(gb);
210
    uint8_t bs_header_extra_1;
211
    uint8_t bs_header_extra_2;
212
    int old_bs_limiter_bands = sbr->bs_limiter_bands;
213
    SpectrumParameters old_spectrum_params;
214

    
215
    sbr->start = 1;
216

    
217
    // Save last spectrum parameters variables to compare to new ones
218
    memcpy(&old_spectrum_params, &sbr->spectrum_params, sizeof(SpectrumParameters));
219

    
220
    sbr->bs_amp_res_header              = get_bits1(gb);
221
    sbr->spectrum_params.bs_start_freq  = get_bits(gb, 4);
222
    sbr->spectrum_params.bs_stop_freq   = get_bits(gb, 4);
223
    sbr->spectrum_params.bs_xover_band  = get_bits(gb, 3);
224
                                          skip_bits(gb, 2); // bs_reserved
225

    
226
    bs_header_extra_1 = get_bits1(gb);
227
    bs_header_extra_2 = get_bits1(gb);
228

    
229
    if (bs_header_extra_1) {
230
        sbr->spectrum_params.bs_freq_scale  = get_bits(gb, 2);
231
        sbr->spectrum_params.bs_alter_scale = get_bits1(gb);
232
        sbr->spectrum_params.bs_noise_bands = get_bits(gb, 2);
233
    } else {
234
        sbr->spectrum_params.bs_freq_scale  = 2;
235
        sbr->spectrum_params.bs_alter_scale = 1;
236
        sbr->spectrum_params.bs_noise_bands = 2;
237
    }
238

    
239
    // Check if spectrum parameters changed
240
    if (memcmp(&old_spectrum_params, &sbr->spectrum_params, sizeof(SpectrumParameters)))
241
        sbr->reset = 1;
242

    
243
    if (bs_header_extra_2) {
244
        sbr->bs_limiter_bands  = get_bits(gb, 2);
245
        sbr->bs_limiter_gains  = get_bits(gb, 2);
246
        sbr->bs_interpol_freq  = get_bits1(gb);
247
        sbr->bs_smoothing_mode = get_bits1(gb);
248
    } else {
249
        sbr->bs_limiter_bands  = 2;
250
        sbr->bs_limiter_gains  = 2;
251
        sbr->bs_interpol_freq  = 1;
252
        sbr->bs_smoothing_mode = 1;
253
    }
254

    
255
    if (sbr->bs_limiter_bands != old_bs_limiter_bands && !sbr->reset)
256
        sbr_make_f_tablelim(sbr);
257

    
258
    return get_bits_count(gb) - cnt;
259
}
260

    
261
static int array_min_int16(const int16_t *array, int nel)
262
{
263
    int i, min = array[0];
264
    for (i = 1; i < nel; i++)
265
        min = FFMIN(array[i], min);
266
    return min;
267
}
268

    
269
static void make_bands(int16_t* bands, int start, int stop, int num_bands)
270
{
271
    int k, previous, present;
272
    float base, prod;
273

    
274
    base = powf((float)stop / start, 1.0f / num_bands);
275
    prod = start;
276
    previous = start;
277

    
278
    for (k = 0; k < num_bands-1; k++) {
279
        prod *= base;
280
        present  = lrintf(prod);
281
        bands[k] = present - previous;
282
        previous = present;
283
    }
284
    bands[num_bands-1] = stop - previous;
285
}
286

    
287
static int check_n_master(AVCodecContext *avctx, int n_master, int bs_xover_band)
288
{
289
    // Requirements (14496-3 sp04 p205)
290
    if (n_master <= 0) {
291
        av_log(avctx, AV_LOG_ERROR, "Invalid n_master: %d\n", n_master);
292
        return -1;
293
    }
294
    if (bs_xover_band >= n_master) {
295
        av_log(avctx, AV_LOG_ERROR,
296
               "Invalid bitstream, crossover band index beyond array bounds: %d\n",
297
               bs_xover_band);
298
        return -1;
299
    }
300
    return 0;
301
}
302

    
303
/// Master Frequency Band Table (14496-3 sp04 p194)
304
static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
305
                             SpectrumParameters *spectrum)
306
{
307
    unsigned int temp, max_qmf_subbands;
308
    unsigned int start_min, stop_min;
309
    int k;
310
    const int8_t *sbr_offset_ptr;
311
    int16_t stop_dk[13];
312

    
313
    if (sbr->sample_rate < 32000) {
314
        temp = 3000;
315
    } else if (sbr->sample_rate < 64000) {
316
        temp = 4000;
317
    } else
318
        temp = 5000;
319

    
320
    start_min = ((temp << 7) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
321
    stop_min  = ((temp << 8) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
322

    
323
    switch (sbr->sample_rate) {
324
    case 16000:
325
        sbr_offset_ptr = sbr_offset[0];
326
        break;
327
    case 22050:
328
        sbr_offset_ptr = sbr_offset[1];
329
        break;
330
    case 24000:
331
        sbr_offset_ptr = sbr_offset[2];
332
        break;
333
    case 32000:
334
        sbr_offset_ptr = sbr_offset[3];
335
        break;
336
    case 44100: case 48000: case 64000:
337
        sbr_offset_ptr = sbr_offset[4];
338
        break;
339
    case 88200: case 96000: case 128000: case 176400: case 192000:
340
        sbr_offset_ptr = sbr_offset[5];
341
        break;
342
    default:
343
        av_log(ac->avctx, AV_LOG_ERROR,
344
               "Unsupported sample rate for SBR: %d\n", sbr->sample_rate);
345
        return -1;
346
    }
347

    
348
    sbr->k[0] = start_min + sbr_offset_ptr[spectrum->bs_start_freq];
349

    
350
    if (spectrum->bs_stop_freq < 14) {
351
        sbr->k[2] = stop_min;
352
        make_bands(stop_dk, stop_min, 64, 13);
353
        qsort(stop_dk, 13, sizeof(stop_dk[0]), qsort_comparison_function_int16);
354
        for (k = 0; k < spectrum->bs_stop_freq; k++)
355
            sbr->k[2] += stop_dk[k];
356
    } else if (spectrum->bs_stop_freq == 14) {
357
        sbr->k[2] = 2*sbr->k[0];
358
    } else if (spectrum->bs_stop_freq == 15) {
359
        sbr->k[2] = 3*sbr->k[0];
360
    } else {
361
        av_log(ac->avctx, AV_LOG_ERROR,
362
               "Invalid bs_stop_freq: %d\n", spectrum->bs_stop_freq);
363
        return -1;
364
    }
365
    sbr->k[2] = FFMIN(64, sbr->k[2]);
366

    
367
    // Requirements (14496-3 sp04 p205)
368
    if (sbr->sample_rate <= 32000) {
369
        max_qmf_subbands = 48;
370
    } else if (sbr->sample_rate == 44100) {
371
        max_qmf_subbands = 35;
372
    } else if (sbr->sample_rate >= 48000)
373
        max_qmf_subbands = 32;
374

    
375
    if (sbr->k[2] - sbr->k[0] > max_qmf_subbands) {
376
        av_log(ac->avctx, AV_LOG_ERROR,
377
               "Invalid bitstream, too many QMF subbands: %d\n", sbr->k[2] - sbr->k[0]);
378
        return -1;
379
    }
380

    
381
    if (!spectrum->bs_freq_scale) {
382
        int dk, k2diff;
383

    
384
        dk = spectrum->bs_alter_scale + 1;
385
        sbr->n_master = ((sbr->k[2] - sbr->k[0] + (dk&2)) >> dk) << 1;
386
        if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
387
            return -1;
388

    
389
        for (k = 1; k <= sbr->n_master; k++)
390
            sbr->f_master[k] = dk;
391

    
392
        k2diff = sbr->k[2] - sbr->k[0] - sbr->n_master * dk;
393
        if (k2diff < 0) {
394
            sbr->f_master[1]--;
395
            sbr->f_master[2]-= (k2diff < -1);
396
        } else if (k2diff) {
397
            sbr->f_master[sbr->n_master]++;
398
        }
399

    
400
        sbr->f_master[0] = sbr->k[0];
401
        for (k = 1; k <= sbr->n_master; k++)
402
            sbr->f_master[k] += sbr->f_master[k - 1];
403

    
404
    } else {
405
        int half_bands = 7 - spectrum->bs_freq_scale;      // bs_freq_scale  = {1,2,3}
406
        int two_regions, num_bands_0;
407
        int vdk0_max, vdk1_min;
408
        int16_t vk0[49];
409

    
410
        if (49 * sbr->k[2] > 110 * sbr->k[0]) {
411
            two_regions = 1;
412
            sbr->k[1] = 2 * sbr->k[0];
413
        } else {
414
            two_regions = 0;
415
            sbr->k[1] = sbr->k[2];
416
        }
417

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

    
420
        if (num_bands_0 <= 0) { // Requirements (14496-3 sp04 p205)
421
            av_log(ac->avctx, AV_LOG_ERROR, "Invalid num_bands_0: %d\n", num_bands_0);
422
            return -1;
423
        }
424

    
425
        vk0[0] = 0;
426

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

    
429
        qsort(vk0 + 1, num_bands_0, sizeof(vk0[1]), qsort_comparison_function_int16);
430
        vdk0_max = vk0[num_bands_0];
431

    
432
        vk0[0] = sbr->k[0];
433
        for (k = 1; k <= num_bands_0; k++) {
434
            if (vk0[k] <= 0) { // Requirements (14496-3 sp04 p205)
435
                av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk0[%d]: %d\n", k, vk0[k]);
436
                return -1;
437
            }
438
            vk0[k] += vk0[k-1];
439
        }
440

    
441
        if (two_regions) {
442
            int16_t vk1[49];
443
            float invwarp = spectrum->bs_alter_scale ? 0.76923076923076923077f
444
                                                     : 1.0f; // bs_alter_scale = {0,1}
445
            int num_bands_1 = lrintf(half_bands * invwarp *
446
                                     log2f(sbr->k[2] / (float)sbr->k[1])) * 2;
447

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

    
450
            vdk1_min = array_min_int16(vk1 + 1, num_bands_1);
451

    
452
            if (vdk1_min < vdk0_max) {
453
                int change;
454
                qsort(vk1 + 1, num_bands_1, sizeof(vk1[1]), qsort_comparison_function_int16);
455
                change = FFMIN(vdk0_max - vk1[1], (vk1[num_bands_1] - vk1[1]) >> 1);
456
                vk1[1]           += change;
457
                vk1[num_bands_1] -= change;
458
            }
459

    
460
            qsort(vk1 + 1, num_bands_1, sizeof(vk1[1]), qsort_comparison_function_int16);
461

    
462
            vk1[0] = sbr->k[1];
463
            for (k = 1; k <= num_bands_1; k++) {
464
                if (vk1[k] <= 0) { // Requirements (14496-3 sp04 p205)
465
                    av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk1[%d]: %d\n", k, vk1[k]);
466
                    return -1;
467
                }
468
                vk1[k] += vk1[k-1];
469
            }
470

    
471
            sbr->n_master = num_bands_0 + num_bands_1;
472
            if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
473
                return -1;
474
            memcpy(&sbr->f_master[0],               vk0,
475
                   (num_bands_0 + 1) * sizeof(sbr->f_master[0]));
476
            memcpy(&sbr->f_master[num_bands_0 + 1], vk1 + 1,
477
                    num_bands_1      * sizeof(sbr->f_master[0]));
478

    
479
        } else {
480
            sbr->n_master = num_bands_0;
481
            if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
482
                return -1;
483
            memcpy(sbr->f_master, vk0, (num_bands_0 + 1) * sizeof(sbr->f_master[0]));
484
        }
485
    }
486

    
487
    return 0;
488
}
489

    
490
/// High Frequency Generation - Patch Construction (14496-3 sp04 p216 fig. 4.46)
491
static int sbr_hf_calc_npatches(AACContext *ac, SpectralBandReplication *sbr)
492
{
493
    int i, k, sb = 0;
494
    int msb = sbr->k[0];
495
    int usb = sbr->kx[1];
496
    int goal_sb = ((1000 << 11) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
497

    
498
    sbr->num_patches = 0;
499

    
500
    if (goal_sb < sbr->kx[1] + sbr->m[1]) {
501
        for (k = 0; sbr->f_master[k] < goal_sb; k++) ;
502
    } else
503
        k = sbr->n_master;
504

    
505
    do {
506
        int odd = 0;
507
        for (i = k; i == k || sb > (sbr->k[0] - 1 + msb - odd); i--) {
508
            sb = sbr->f_master[i];
509
            odd = (sb + sbr->k[0]) & 1;
510
        }
511

    
512
        // Requirements (14496-3 sp04 p205) sets the maximum number of patches to 5.
513
        // After this check the final number of patches can still be six which is
514
        // illegal however the Coding Technologies decoder check stream has a final
515
        // count of 6 patches
516
        if (sbr->num_patches > 5) {
517
            av_log(ac->avctx, AV_LOG_ERROR, "Too many patches: %d\n", sbr->num_patches);
518
            return -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
    return 0;
539
}
540

    
541
/// Derived Frequency Band Tables (14496-3 sp04 p197)
542
static int sbr_make_f_derived(AACContext *ac, SpectralBandReplication *sbr)
543
{
544
    int k, temp;
545

    
546
    sbr->n[1] = sbr->n_master - sbr->spectrum_params.bs_xover_band;
547
    sbr->n[0] = (sbr->n[1] + 1) >> 1;
548

    
549
    memcpy(sbr->f_tablehigh, &sbr->f_master[sbr->spectrum_params.bs_xover_band],
550
           (sbr->n[1] + 1) * sizeof(sbr->f_master[0]));
551
    sbr->m[1] = sbr->f_tablehigh[sbr->n[1]] - sbr->f_tablehigh[0];
552
    sbr->kx[1] = sbr->f_tablehigh[0];
553

    
554
    // Requirements (14496-3 sp04 p205)
555
    if (sbr->kx[1] + sbr->m[1] > 64) {
556
        av_log(ac->avctx, AV_LOG_ERROR,
557
               "Stop frequency border too high: %d\n", sbr->kx[1] + sbr->m[1]);
558
        return -1;
559
    }
560
    if (sbr->kx[1] > 32) {
561
        av_log(ac->avctx, AV_LOG_ERROR, "Start frequency border too high: %d\n", sbr->kx[1]);
562
        return -1;
563
    }
564

    
565
    sbr->f_tablelow[0] = sbr->f_tablehigh[0];
566
    temp = sbr->n[1] & 1;
567
    for (k = 1; k <= sbr->n[0]; k++)
568
        sbr->f_tablelow[k] = sbr->f_tablehigh[2 * k - temp];
569

    
570
    sbr->n_q = FFMAX(1, lrintf(sbr->spectrum_params.bs_noise_bands *
571
                               log2f(sbr->k[2] / (float)sbr->kx[1]))); // 0 <= bs_noise_bands <= 3
572
    if (sbr->n_q > 5) {
573
        av_log(ac->avctx, AV_LOG_ERROR, "Too many noise floor scale factors: %d\n", sbr->n_q);
574
        return -1;
575
    }
576

    
577
    sbr->f_tablenoise[0] = sbr->f_tablelow[0];
578
    temp = 0;
579
    for (k = 1; k <= sbr->n_q; k++) {
580
        temp += (sbr->n[0] - temp) / (sbr->n_q + 1 - k);
581
        sbr->f_tablenoise[k] = sbr->f_tablelow[temp];
582
    }
583

    
584
    if (sbr_hf_calc_npatches(ac, sbr) < 0)
585
        return -1;
586

    
587
    sbr_make_f_tablelim(sbr);
588

    
589
    sbr->data[0].f_indexnoise = 0;
590
    sbr->data[1].f_indexnoise = 0;
591

    
592
    return 0;
593
}
594

    
595
static av_always_inline void get_bits1_vector(GetBitContext *gb, uint8_t *vec,
596
                                              int elements)
597
{
598
    int i;
599
    for (i = 0; i < elements; i++) {
600
        vec[i] = get_bits1(gb);
601
    }
602
}
603

    
604
/** ceil(log2(index+1)) */
605
static const int8_t ceil_log2[] = {
606
    0, 1, 2, 2, 3, 3,
607
};
608

    
609
static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,
610
                         GetBitContext *gb, SBRData *ch_data)
611
{
612
    int i;
613
    unsigned bs_pointer = 0;
614
    // frameLengthFlag ? 15 : 16; 960 sample length frames unsupported; this value is numTimeSlots
615
    int abs_bord_trail = 16;
616
    int num_rel_lead, num_rel_trail;
617
    unsigned bs_num_env_old = ch_data->bs_num_env;
618

    
619
    ch_data->bs_freq_res[0] = ch_data->bs_freq_res[ch_data->bs_num_env];
620
    ch_data->bs_amp_res = sbr->bs_amp_res_header;
621
    ch_data->t_env_num_env_old = ch_data->t_env[bs_num_env_old];
622

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

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

    
637
        ch_data->t_env[0]                   = 0;
638
        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
639

    
640
        abs_bord_trail = (abs_bord_trail + (ch_data->bs_num_env >> 1)) /
641
                   ch_data->bs_num_env;
642
        for (i = 0; i < num_rel_lead; i++)
643
            ch_data->t_env[i + 1] = ch_data->t_env[i] + abs_bord_trail;
644

    
645
        ch_data->bs_freq_res[1] = get_bits1(gb);
646
        for (i = 1; i < ch_data->bs_num_env; i++)
647
            ch_data->bs_freq_res[i + 1] = ch_data->bs_freq_res[1];
648
        break;
649
    case FIXVAR:
650
        abs_bord_trail                     += get_bits(gb, 2);
651
        num_rel_trail                       = get_bits(gb, 2);
652
        ch_data->bs_num_env                 = num_rel_trail + 1;
653
        ch_data->t_env[0]                   = 0;
654
        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
655

    
656
        for (i = 0; i < num_rel_trail; i++)
657
            ch_data->t_env[ch_data->bs_num_env - 1 - i] =
658
                ch_data->t_env[ch_data->bs_num_env - i] - 2 * get_bits(gb, 2) - 2;
659

    
660
        bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
661

    
662
        for (i = 0; i < ch_data->bs_num_env; i++)
663
            ch_data->bs_freq_res[ch_data->bs_num_env - i] = get_bits1(gb);
664
        break;
665
    case VARFIX:
666
        ch_data->t_env[0]                   = get_bits(gb, 2);
667
        num_rel_lead                        = get_bits(gb, 2);
668
        ch_data->bs_num_env                 = num_rel_lead + 1;
669
        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
670

    
671
        for (i = 0; i < num_rel_lead; i++)
672
            ch_data->t_env[i + 1] = ch_data->t_env[i] + 2 * get_bits(gb, 2) + 2;
673

    
674
        bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
675

    
676
        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env);
677
        break;
678
    case VARVAR:
679
        ch_data->t_env[0]                   = get_bits(gb, 2);
680
        abs_bord_trail                     += get_bits(gb, 2);
681
        num_rel_lead                        = get_bits(gb, 2);
682
        num_rel_trail                       = get_bits(gb, 2);
683
        ch_data->bs_num_env                 = num_rel_lead + num_rel_trail + 1;
684

    
685
        if (ch_data->bs_num_env > 5) {
686
            av_log(ac->avctx, AV_LOG_ERROR,
687
                   "Invalid bitstream, too many SBR envelopes in VARVAR type SBR frame: %d\n",
688
                   ch_data->bs_num_env);
689
            return -1;
690
        }
691

    
692
        ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
693

    
694
        for (i = 0; i < num_rel_lead; i++)
695
            ch_data->t_env[i + 1] = ch_data->t_env[i] + 2 * get_bits(gb, 2) + 2;
696
        for (i = 0; i < num_rel_trail; i++)
697
            ch_data->t_env[ch_data->bs_num_env - 1 - i] =
698
                ch_data->t_env[ch_data->bs_num_env - i] - 2 * get_bits(gb, 2) - 2;
699

    
700
        bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
701

    
702
        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env);
703
        break;
704
    }
705

    
706
    if (bs_pointer > ch_data->bs_num_env + 1) {
707
        av_log(ac->avctx, AV_LOG_ERROR,
708
               "Invalid bitstream, bs_pointer points to a middle noise border outside the time borders table: %d\n",
709
               bs_pointer);
710
        return -1;
711
    }
712

    
713
    for (i = 1; i <= ch_data->bs_num_env; i++) {
714
        if (ch_data->t_env[i-1] > ch_data->t_env[i]) {
715
            av_log(ac->avctx, AV_LOG_ERROR, "Non monotone time borders\n");
716
            return -1;
717
        }
718
    }
719

    
720
    ch_data->bs_num_noise = (ch_data->bs_num_env > 1) + 1;
721

    
722
    ch_data->t_q[0]                     = ch_data->t_env[0];
723
    ch_data->t_q[ch_data->bs_num_noise] = ch_data->t_env[ch_data->bs_num_env];
724
    if (ch_data->bs_num_noise > 1) {
725
        unsigned int idx;
726
        if (ch_data->bs_frame_class == FIXFIX) {
727
            idx = ch_data->bs_num_env >> 1;
728
        } else if (ch_data->bs_frame_class & 1) { // FIXVAR or VARVAR
729
            idx = ch_data->bs_num_env - FFMAX(bs_pointer - 1, 1);
730
        } else { // VARFIX
731
            if (!bs_pointer)
732
                idx = 1;
733
            else if (bs_pointer == 1)
734
                idx = ch_data->bs_num_env - 1;
735
            else // bs_pointer > 1
736
                idx = bs_pointer - 1;
737
        }
738
        ch_data->t_q[1] = ch_data->t_env[idx];
739
    }
740

    
741
    ch_data->e_a[0] = -(ch_data->e_a[1] != bs_num_env_old); // l_APrev
742
    ch_data->e_a[1] = -1;
743
    if ((ch_data->bs_frame_class & 1) && bs_pointer) { // FIXVAR or VARVAR and bs_pointer != 0
744
        ch_data->e_a[1] = ch_data->bs_num_env + 1 - bs_pointer;
745
    } else if ((ch_data->bs_frame_class == 2) && (bs_pointer > 1)) // VARFIX and bs_pointer > 1
746
        ch_data->e_a[1] = bs_pointer - 1;
747

    
748
    return 0;
749
}
750

    
751
static void copy_sbr_grid(SBRData *dst, const SBRData *src) {
752
    //These variables are saved from the previous frame rather than copied
753
    dst->bs_freq_res[0]    = dst->bs_freq_res[dst->bs_num_env];
754
    dst->t_env_num_env_old = dst->t_env[dst->bs_num_env];
755
    dst->e_a[0]            = -(dst->e_a[1] != dst->bs_num_env);
756

    
757
    //These variables are read from the bitstream and therefore copied
758
    memcpy(dst->bs_freq_res+1, src->bs_freq_res+1, sizeof(dst->bs_freq_res)-sizeof(*dst->bs_freq_res));
759
    memcpy(dst->t_env,         src->t_env,         sizeof(dst->t_env));
760
    memcpy(dst->t_q,           src->t_q,           sizeof(dst->t_q));
761
    dst->bs_num_env        = src->bs_num_env;
762
    dst->bs_amp_res        = src->bs_amp_res;
763
    dst->bs_num_noise      = src->bs_num_noise;
764
    dst->bs_frame_class    = src->bs_frame_class;
765
    dst->e_a[1]            = src->e_a[1];
766
}
767

    
768
/// Read how the envelope and noise floor data is delta coded
769
static void read_sbr_dtdf(SpectralBandReplication *sbr, GetBitContext *gb,
770
                          SBRData *ch_data)
771
{
772
    get_bits1_vector(gb, ch_data->bs_df_env,   ch_data->bs_num_env);
773
    get_bits1_vector(gb, ch_data->bs_df_noise, ch_data->bs_num_noise);
774
}
775

    
776
/// Read inverse filtering data
777
static void read_sbr_invf(SpectralBandReplication *sbr, GetBitContext *gb,
778
                          SBRData *ch_data)
779
{
780
    int i;
781

    
782
    memcpy(ch_data->bs_invf_mode[1], ch_data->bs_invf_mode[0], 5 * sizeof(uint8_t));
783
    for (i = 0; i < sbr->n_q; i++)
784
        ch_data->bs_invf_mode[0][i] = get_bits(gb, 2);
785
}
786

    
787
static void read_sbr_envelope(SpectralBandReplication *sbr, GetBitContext *gb,
788
                              SBRData *ch_data, int ch)
789
{
790
    int bits;
791
    int i, j, k;
792
    VLC_TYPE (*t_huff)[2], (*f_huff)[2];
793
    int t_lav, f_lav;
794
    const int delta = (ch == 1 && sbr->bs_coupling == 1) + 1;
795
    const int odd = sbr->n[1] & 1;
796

    
797
    if (sbr->bs_coupling && ch) {
798
        if (ch_data->bs_amp_res) {
799
            bits   = 5;
800
            t_huff = vlc_sbr[T_HUFFMAN_ENV_BAL_3_0DB].table;
801
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_BAL_3_0DB];
802
            f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_3_0DB].table;
803
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_3_0DB];
804
        } else {
805
            bits   = 6;
806
            t_huff = vlc_sbr[T_HUFFMAN_ENV_BAL_1_5DB].table;
807
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_BAL_1_5DB];
808
            f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_1_5DB].table;
809
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_1_5DB];
810
        }
811
    } else {
812
        if (ch_data->bs_amp_res) {
813
            bits   = 6;
814
            t_huff = vlc_sbr[T_HUFFMAN_ENV_3_0DB].table;
815
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_3_0DB];
816
            f_huff = vlc_sbr[F_HUFFMAN_ENV_3_0DB].table;
817
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_3_0DB];
818
        } else {
819
            bits   = 7;
820
            t_huff = vlc_sbr[T_HUFFMAN_ENV_1_5DB].table;
821
            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_1_5DB];
822
            f_huff = vlc_sbr[F_HUFFMAN_ENV_1_5DB].table;
823
            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_1_5DB];
824
        }
825
    }
826

    
827
    for (i = 0; i < ch_data->bs_num_env; i++) {
828
        if (ch_data->bs_df_env[i]) {
829
            // bs_freq_res[0] == bs_freq_res[bs_num_env] from prev frame
830
            if (ch_data->bs_freq_res[i + 1] == ch_data->bs_freq_res[i]) {
831
                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++)
832
                    ch_data->env_facs[i + 1][j] = ch_data->env_facs[i][j] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
833
            } else if (ch_data->bs_freq_res[i + 1]) {
834
                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {
835
                    k = (j + odd) >> 1; // find k such that f_tablelow[k] <= f_tablehigh[j] < f_tablelow[k + 1]
836
                    ch_data->env_facs[i + 1][j] = ch_data->env_facs[i][k] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
837
                }
838
            } else {
839
                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {
840
                    k = j ? 2*j - odd : 0; // find k such that f_tablehigh[k] == f_tablelow[j]
841
                    ch_data->env_facs[i + 1][j] = ch_data->env_facs[i][k] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
842
                }
843
            }
844
        } else {
845
            ch_data->env_facs[i + 1][0] = delta * get_bits(gb, bits); // bs_env_start_value_balance
846
            for (j = 1; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++)
847
                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);
848
        }
849
    }
850

    
851
    //assign 0th elements of env_facs from last elements
852
    memcpy(ch_data->env_facs[0], ch_data->env_facs[ch_data->bs_num_env],
853
           sizeof(ch_data->env_facs[0]));
854
}
855

    
856
static void read_sbr_noise(SpectralBandReplication *sbr, GetBitContext *gb,
857
                           SBRData *ch_data, int ch)
858
{
859
    int i, j;
860
    VLC_TYPE (*t_huff)[2], (*f_huff)[2];
861
    int t_lav, f_lav;
862
    int delta = (ch == 1 && sbr->bs_coupling == 1) + 1;
863

    
864
    if (sbr->bs_coupling && ch) {
865
        t_huff = vlc_sbr[T_HUFFMAN_NOISE_BAL_3_0DB].table;
866
        t_lav  = vlc_sbr_lav[T_HUFFMAN_NOISE_BAL_3_0DB];
867
        f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_3_0DB].table;
868
        f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_3_0DB];
869
    } else {
870
        t_huff = vlc_sbr[T_HUFFMAN_NOISE_3_0DB].table;
871
        t_lav  = vlc_sbr_lav[T_HUFFMAN_NOISE_3_0DB];
872
        f_huff = vlc_sbr[F_HUFFMAN_ENV_3_0DB].table;
873
        f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_3_0DB];
874
    }
875

    
876
    for (i = 0; i < ch_data->bs_num_noise; i++) {
877
        if (ch_data->bs_df_noise[i]) {
878
            for (j = 0; j < sbr->n_q; j++)
879
                ch_data->noise_facs[i + 1][j] = ch_data->noise_facs[i][j] + delta * (get_vlc2(gb, t_huff, 9, 2) - t_lav);
880
        } else {
881
            ch_data->noise_facs[i + 1][0] = delta * get_bits(gb, 5); // bs_noise_start_value_balance or bs_noise_start_value_level
882
            for (j = 1; j < sbr->n_q; j++)
883
                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);
884
        }
885
    }
886

    
887
    //assign 0th elements of noise_facs from last elements
888
    memcpy(ch_data->noise_facs[0], ch_data->noise_facs[ch_data->bs_num_noise],
889
           sizeof(ch_data->noise_facs[0]));
890
}
891

    
892
static void read_sbr_extension(AACContext *ac, SpectralBandReplication *sbr,
893
                               GetBitContext *gb,
894
                               int bs_extension_id, int *num_bits_left)
895
{
896
    switch (bs_extension_id) {
897
    case EXTENSION_ID_PS:
898
        if (!ac->m4ac.ps) {
899
            av_log(ac->avctx, AV_LOG_ERROR, "Parametric Stereo signaled to be not-present but was found in the bitstream.\n");
900
            skip_bits_long(gb, *num_bits_left); // bs_fill_bits
901
            *num_bits_left = 0;
902
        } else {
903
#if 1
904
            *num_bits_left -= ff_ps_read_data(ac->avctx, gb, &sbr->ps, *num_bits_left);
905
#else
906
            av_log_missing_feature(ac->avctx, "Parametric Stereo is", 0);
907
            skip_bits_long(gb, *num_bits_left); // bs_fill_bits
908
            *num_bits_left = 0;
909
#endif
910
        }
911
        break;
912
    default:
913
        av_log_missing_feature(ac->avctx, "Reserved SBR extensions are", 1);
914
        skip_bits_long(gb, *num_bits_left); // bs_fill_bits
915
        *num_bits_left = 0;
916
        break;
917
    }
918
}
919

    
920
static int read_sbr_single_channel_element(AACContext *ac,
921
                                            SpectralBandReplication *sbr,
922
                                            GetBitContext *gb)
923
{
924
    if (get_bits1(gb)) // bs_data_extra
925
        skip_bits(gb, 4); // bs_reserved
926

    
927
    if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))
928
        return -1;
929
    read_sbr_dtdf(sbr, gb, &sbr->data[0]);
930
    read_sbr_invf(sbr, gb, &sbr->data[0]);
931
    read_sbr_envelope(sbr, gb, &sbr->data[0], 0);
932
    read_sbr_noise(sbr, gb, &sbr->data[0], 0);
933

    
934
    if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb)))
935
        get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]);
936

    
937
    return 0;
938
}
939

    
940
static int read_sbr_channel_pair_element(AACContext *ac,
941
                                          SpectralBandReplication *sbr,
942
                                          GetBitContext *gb)
943
{
944
    if (get_bits1(gb))    // bs_data_extra
945
        skip_bits(gb, 8); // bs_reserved
946

    
947
    if ((sbr->bs_coupling = get_bits1(gb))) {
948
        if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))
949
            return -1;
950
        copy_sbr_grid(&sbr->data[1], &sbr->data[0]);
951
        read_sbr_dtdf(sbr, gb, &sbr->data[0]);
952
        read_sbr_dtdf(sbr, gb, &sbr->data[1]);
953
        read_sbr_invf(sbr, gb, &sbr->data[0]);
954
        memcpy(sbr->data[1].bs_invf_mode[1], sbr->data[1].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0]));
955
        memcpy(sbr->data[1].bs_invf_mode[0], sbr->data[0].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0]));
956
        read_sbr_envelope(sbr, gb, &sbr->data[0], 0);
957
        read_sbr_noise(sbr, gb, &sbr->data[0], 0);
958
        read_sbr_envelope(sbr, gb, &sbr->data[1], 1);
959
        read_sbr_noise(sbr, gb, &sbr->data[1], 1);
960
    } else {
961
        if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]) ||
962
            read_sbr_grid(ac, sbr, gb, &sbr->data[1]))
963
            return -1;
964
        read_sbr_dtdf(sbr, gb, &sbr->data[0]);
965
        read_sbr_dtdf(sbr, gb, &sbr->data[1]);
966
        read_sbr_invf(sbr, gb, &sbr->data[0]);
967
        read_sbr_invf(sbr, gb, &sbr->data[1]);
968
        read_sbr_envelope(sbr, gb, &sbr->data[0], 0);
969
        read_sbr_envelope(sbr, gb, &sbr->data[1], 1);
970
        read_sbr_noise(sbr, gb, &sbr->data[0], 0);
971
        read_sbr_noise(sbr, gb, &sbr->data[1], 1);
972
    }
973

    
974
    if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb)))
975
        get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]);
976
    if ((sbr->data[1].bs_add_harmonic_flag = get_bits1(gb)))
977
        get_bits1_vector(gb, sbr->data[1].bs_add_harmonic, sbr->n[1]);
978

    
979
    return 0;
980
}
981

    
982
static unsigned int read_sbr_data(AACContext *ac, SpectralBandReplication *sbr,
983
                                  GetBitContext *gb, int id_aac)
984
{
985
    unsigned int cnt = get_bits_count(gb);
986

    
987
    if (id_aac == TYPE_SCE || id_aac == TYPE_CCE) {
988
        if (read_sbr_single_channel_element(ac, sbr, gb)) {
989
            sbr->start = 0;
990
            return get_bits_count(gb) - cnt;
991
        }
992
    } else if (id_aac == TYPE_CPE) {
993
        if (read_sbr_channel_pair_element(ac, sbr, gb)) {
994
            sbr->start = 0;
995
            return get_bits_count(gb) - cnt;
996
        }
997
    } else {
998
        av_log(ac->avctx, AV_LOG_ERROR,
999
            "Invalid bitstream - cannot apply SBR to element type %d\n", id_aac);
1000
        sbr->start = 0;
1001
        return get_bits_count(gb) - cnt;
1002
    }
1003
    if (get_bits1(gb)) { // bs_extended_data
1004
        int num_bits_left = get_bits(gb, 4); // bs_extension_size
1005
        if (num_bits_left == 15)
1006
            num_bits_left += get_bits(gb, 8); // bs_esc_count
1007

    
1008
        num_bits_left <<= 3;
1009
        while (num_bits_left > 7) {
1010
            num_bits_left -= 2;
1011
            read_sbr_extension(ac, sbr, gb, get_bits(gb, 2), &num_bits_left); // bs_extension_id
1012
        }
1013
        if (num_bits_left < 0) {
1014
            av_log(ac->avctx, AV_LOG_ERROR, "SBR Extension over read.\n");
1015
        }
1016
        if (num_bits_left > 0)
1017
            skip_bits(gb, num_bits_left);
1018
    }
1019

    
1020
    return get_bits_count(gb) - cnt;
1021
}
1022

    
1023
static void sbr_reset(AACContext *ac, SpectralBandReplication *sbr)
1024
{
1025
    int err;
1026
    err = sbr_make_f_master(ac, sbr, &sbr->spectrum_params);
1027
    if (err >= 0)
1028
        err = sbr_make_f_derived(ac, sbr);
1029
    if (err < 0) {
1030
        av_log(ac->avctx, AV_LOG_ERROR,
1031
               "SBR reset failed. Switching SBR to pure upsampling mode.\n");
1032
        sbr->start = 0;
1033
    }
1034
}
1035

    
1036
/**
1037
 * Decode Spectral Band Replication extension data; reference: table 4.55.
1038
 *
1039
 * @param   crc flag indicating the presence of CRC checksum
1040
 * @param   cnt length of TYPE_FIL syntactic element in bytes
1041
 *
1042
 * @return  Returns number of bytes consumed from the TYPE_FIL element.
1043
 */
1044
int ff_decode_sbr_extension(AACContext *ac, SpectralBandReplication *sbr,
1045
                            GetBitContext *gb_host, int crc, int cnt, int id_aac)
1046
{
1047
    unsigned int num_sbr_bits = 0, num_align_bits;
1048
    unsigned bytes_read;
1049
    GetBitContext gbc = *gb_host, *gb = &gbc;
1050
    skip_bits_long(gb_host, cnt*8 - 4);
1051

    
1052
    sbr->reset = 0;
1053

    
1054
    if (!sbr->sample_rate)
1055
        sbr->sample_rate = 2 * ac->m4ac.sample_rate; //TODO use the nominal sample rate for arbitrary sample rate support
1056
    if (!ac->m4ac.ext_sample_rate)
1057
        ac->m4ac.ext_sample_rate = 2 * ac->m4ac.sample_rate;
1058

    
1059
    if (crc) {
1060
        skip_bits(gb, 10); // bs_sbr_crc_bits; TODO - implement CRC check
1061
        num_sbr_bits += 10;
1062
    }
1063

    
1064
    //Save some state from the previous frame.
1065
    sbr->kx[0] = sbr->kx[1];
1066
    sbr->m[0] = sbr->m[1];
1067

    
1068
    num_sbr_bits++;
1069
    if (get_bits1(gb)) // bs_header_flag
1070
        num_sbr_bits += read_sbr_header(sbr, gb);
1071

    
1072
    if (sbr->reset)
1073
        sbr_reset(ac, sbr);
1074

    
1075
    if (sbr->start)
1076
        num_sbr_bits  += read_sbr_data(ac, sbr, gb, id_aac);
1077

    
1078
    num_align_bits = ((cnt << 3) - 4 - num_sbr_bits) & 7;
1079
    bytes_read = ((num_sbr_bits + num_align_bits + 4) >> 3);
1080

    
1081
    if (bytes_read > cnt) {
1082
        av_log(ac->avctx, AV_LOG_ERROR,
1083
               "Expected to read %d SBR bytes actually read %d.\n", cnt, bytes_read);
1084
    }
1085
    return cnt;
1086
}
1087

    
1088
/// Dequantization and stereo decoding (14496-3 sp04 p203)
1089
static void sbr_dequant(SpectralBandReplication *sbr, int id_aac)
1090
{
1091
    int k, e;
1092
    int ch;
1093

    
1094
    if (id_aac == TYPE_CPE && sbr->bs_coupling) {
1095
        float alpha      = sbr->data[0].bs_amp_res ?  1.0f :  0.5f;
1096
        float pan_offset = sbr->data[0].bs_amp_res ? 12.0f : 24.0f;
1097
        for (e = 1; e <= sbr->data[0].bs_num_env; e++) {
1098
            for (k = 0; k < sbr->n[sbr->data[0].bs_freq_res[e]]; k++) {
1099
                float temp1 = exp2f(sbr->data[0].env_facs[e][k] * alpha + 7.0f);
1100
                float temp2 = exp2f((pan_offset - sbr->data[1].env_facs[e][k]) * alpha);
1101
                float fac   = temp1 / (1.0f + temp2);
1102
                sbr->data[0].env_facs[e][k] = fac;
1103
                sbr->data[1].env_facs[e][k] = fac * temp2;
1104
            }
1105
        }
1106
        for (e = 1; e <= sbr->data[0].bs_num_noise; e++) {
1107
            for (k = 0; k < sbr->n_q; k++) {
1108
                float temp1 = exp2f(NOISE_FLOOR_OFFSET - sbr->data[0].noise_facs[e][k] + 1);
1109
                float temp2 = exp2f(12 - sbr->data[1].noise_facs[e][k]);
1110
                float fac   = temp1 / (1.0f + temp2);
1111
                sbr->data[0].noise_facs[e][k] = fac;
1112
                sbr->data[1].noise_facs[e][k] = fac * temp2;
1113
            }
1114
        }
1115
    } else { // SCE or one non-coupled CPE
1116
        for (ch = 0; ch < (id_aac == TYPE_CPE) + 1; ch++) {
1117
            float alpha = sbr->data[ch].bs_amp_res ? 1.0f : 0.5f;
1118
            for (e = 1; e <= sbr->data[ch].bs_num_env; e++)
1119
                for (k = 0; k < sbr->n[sbr->data[ch].bs_freq_res[e]]; k++)
1120
                    sbr->data[ch].env_facs[e][k] =
1121
                        exp2f(alpha * sbr->data[ch].env_facs[e][k] + 6.0f);
1122
            for (e = 1; e <= sbr->data[ch].bs_num_noise; e++)
1123
                for (k = 0; k < sbr->n_q; k++)
1124
                    sbr->data[ch].noise_facs[e][k] =
1125
                        exp2f(NOISE_FLOOR_OFFSET - sbr->data[ch].noise_facs[e][k]);
1126
        }
1127
    }
1128
}
1129

    
1130
/**
1131
 * Analysis QMF Bank (14496-3 sp04 p206)
1132
 *
1133
 * @param   x       pointer to the beginning of the first sample window
1134
 * @param   W       array of complex-valued samples split into subbands
1135
 */
1136
static void sbr_qmf_analysis(DSPContext *dsp, FFTContext *mdct, const float *in, float *x,
1137
                             float z[320], float W[2][32][32][2])
1138
{
1139
    int i, k;
1140
    memcpy(W[0], W[1], sizeof(W[0]));
1141
    memcpy(x    , x+1024, (320-32)*sizeof(x[0]));
1142
    memcpy(x+288, in,         1024*sizeof(x[0]));
1143
    for (i = 0; i < 32; i++) { // numTimeSlots*RATE = 16*2 as 960 sample frames
1144
                               // are not supported
1145
        dsp->vector_fmul_reverse(z, sbr_qmf_window_ds, x, 320);
1146
        for (k = 0; k < 64; k++) {
1147
            float f = z[k] + z[k + 64] + z[k + 128] + z[k + 192] + z[k + 256];
1148
            z[k] = f;
1149
        }
1150
        //Shuffle to IMDCT
1151
        z[64] = z[0];
1152
        for (k = 1; k < 32; k++) {
1153
            z[64+2*k-1] =  z[   k];
1154
            z[64+2*k  ] = -z[64-k];
1155
        }
1156
        z[64+63] = z[32];
1157

    
1158
        ff_imdct_half(mdct, z, z+64);
1159
        for (k = 0; k < 32; k++) {
1160
            W[1][i][k][0] = -z[63-k];
1161
            W[1][i][k][1] = z[k];
1162
        }
1163
        x += 32;
1164
    }
1165
}
1166

    
1167
/**
1168
 * Synthesis QMF Bank (14496-3 sp04 p206) and Downsampled Synthesis QMF Bank
1169
 * (14496-3 sp04 p206)
1170
 */
1171
static void sbr_qmf_synthesis(DSPContext *dsp, FFTContext *mdct,
1172
                              float *out, float X[2][38][64],
1173
                              float mdct_buf[2][64],
1174
                              float *v0, int *v_off, const unsigned int div)
1175
{
1176
    int i, n;
1177
    const float *sbr_qmf_window = div ? sbr_qmf_window_ds : sbr_qmf_window_us;
1178
    float *v;
1179
    for (i = 0; i < 32; i++) {
1180
        if (*v_off == 0) {
1181
            int saved_samples = (1280 - 128) >> div;
1182
            memcpy(&v0[SBR_SYNTHESIS_BUF_SIZE - saved_samples], v0, saved_samples * sizeof(float));
1183
            *v_off = SBR_SYNTHESIS_BUF_SIZE - saved_samples - (128 >> div);
1184
        } else {
1185
            *v_off -= 128 >> div;
1186
        }
1187
        v = v0 + *v_off;
1188
        if (div) {
1189
            for (n = 0; n < 32; n++) {
1190
                X[0][i][   n] = -X[0][i][n];
1191
                X[0][i][32+n] =  X[1][i][31-n];
1192
            }
1193
            ff_imdct_half(mdct, mdct_buf[0], X[0][i]);
1194
            for (n = 0; n < 32; n++) {
1195
                v[     n] =  mdct_buf[0][63 - 2*n];
1196
                v[63 - n] = -mdct_buf[0][62 - 2*n];
1197
            }
1198
        } else {
1199
            for (n = 1; n < 64; n+=2) {
1200
                X[1][i][n] = -X[1][i][n];
1201
            }
1202
            ff_imdct_half(mdct, mdct_buf[0], X[0][i]);
1203
            ff_imdct_half(mdct, mdct_buf[1], X[1][i]);
1204
            for (n = 0; n < 64; n++) {
1205
                v[      n] = -mdct_buf[0][63 -   n] + mdct_buf[1][  n    ];
1206
                v[127 - n] =  mdct_buf[0][63 -   n] + mdct_buf[1][  n    ];
1207
            }
1208
        }
1209
        dsp->vector_fmul_add(out, v                , sbr_qmf_window               , zero64, 64 >> div);
1210
        dsp->vector_fmul_add(out, v + ( 192 >> div), sbr_qmf_window + ( 64 >> div), out   , 64 >> div);
1211
        dsp->vector_fmul_add(out, v + ( 256 >> div), sbr_qmf_window + (128 >> div), out   , 64 >> div);
1212
        dsp->vector_fmul_add(out, v + ( 448 >> div), sbr_qmf_window + (192 >> div), out   , 64 >> div);
1213
        dsp->vector_fmul_add(out, v + ( 512 >> div), sbr_qmf_window + (256 >> div), out   , 64 >> div);
1214
        dsp->vector_fmul_add(out, v + ( 704 >> div), sbr_qmf_window + (320 >> div), out   , 64 >> div);
1215
        dsp->vector_fmul_add(out, v + ( 768 >> div), sbr_qmf_window + (384 >> div), out   , 64 >> div);
1216
        dsp->vector_fmul_add(out, v + ( 960 >> div), sbr_qmf_window + (448 >> div), out   , 64 >> div);
1217
        dsp->vector_fmul_add(out, v + (1024 >> div), sbr_qmf_window + (512 >> div), out   , 64 >> div);
1218
        dsp->vector_fmul_add(out, v + (1216 >> div), sbr_qmf_window + (576 >> div), out   , 64 >> div);
1219
        out += 64 >> div;
1220
    }
1221
}
1222

    
1223
static void autocorrelate(const float x[40][2], float phi[3][2][2], int lag)
1224
{
1225
    int i;
1226
    float real_sum = 0.0f;
1227
    float imag_sum = 0.0f;
1228
    if (lag) {
1229
        for (i = 1; i < 38; i++) {
1230
            real_sum += x[i][0] * x[i+lag][0] + x[i][1] * x[i+lag][1];
1231
            imag_sum += x[i][0] * x[i+lag][1] - x[i][1] * x[i+lag][0];
1232
        }
1233
        phi[2-lag][1][0] = real_sum + x[ 0][0] * x[lag][0] + x[ 0][1] * x[lag][1];
1234
        phi[2-lag][1][1] = imag_sum + x[ 0][0] * x[lag][1] - x[ 0][1] * x[lag][0];
1235
        if (lag == 1) {
1236
            phi[0][0][0] = real_sum + x[38][0] * x[39][0] + x[38][1] * x[39][1];
1237
            phi[0][0][1] = imag_sum + x[38][0] * x[39][1] - x[38][1] * x[39][0];
1238
        }
1239
    } else {
1240
        for (i = 1; i < 38; i++) {
1241
            real_sum += x[i][0] * x[i][0] + x[i][1] * x[i][1];
1242
        }
1243
        phi[2][1][0] = real_sum + x[ 0][0] * x[ 0][0] + x[ 0][1] * x[ 0][1];
1244
        phi[1][0][0] = real_sum + x[38][0] * x[38][0] + x[38][1] * x[38][1];
1245
    }
1246
}
1247

    
1248
/** High Frequency Generation (14496-3 sp04 p214+) and Inverse Filtering
1249
 * (14496-3 sp04 p214)
1250
 * Warning: This routine does not seem numerically stable.
1251
 */
1252
static void sbr_hf_inverse_filter(float (*alpha0)[2], float (*alpha1)[2],
1253
                                  const float X_low[32][40][2], int k0)
1254
{
1255
    int k;
1256
    for (k = 0; k < k0; k++) {
1257
        float phi[3][2][2], dk;
1258

    
1259
        autocorrelate(X_low[k], phi, 0);
1260
        autocorrelate(X_low[k], phi, 1);
1261
        autocorrelate(X_low[k], phi, 2);
1262

    
1263
        dk =  phi[2][1][0] * phi[1][0][0] -
1264
             (phi[1][1][0] * phi[1][1][0] + phi[1][1][1] * phi[1][1][1]) / 1.000001f;
1265

    
1266
        if (!dk) {
1267
            alpha1[k][0] = 0;
1268
            alpha1[k][1] = 0;
1269
        } else {
1270
            float temp_real, temp_im;
1271
            temp_real = phi[0][0][0] * phi[1][1][0] -
1272
                        phi[0][0][1] * phi[1][1][1] -
1273
                        phi[0][1][0] * phi[1][0][0];
1274
            temp_im   = phi[0][0][0] * phi[1][1][1] +
1275
                        phi[0][0][1] * phi[1][1][0] -
1276
                        phi[0][1][1] * phi[1][0][0];
1277

    
1278
            alpha1[k][0] = temp_real / dk;
1279
            alpha1[k][1] = temp_im   / dk;
1280
        }
1281

    
1282
        if (!phi[1][0][0]) {
1283
            alpha0[k][0] = 0;
1284
            alpha0[k][1] = 0;
1285
        } else {
1286
            float temp_real, temp_im;
1287
            temp_real = phi[0][0][0] + alpha1[k][0] * phi[1][1][0] +
1288
                                       alpha1[k][1] * phi[1][1][1];
1289
            temp_im   = phi[0][0][1] + alpha1[k][1] * phi[1][1][0] -
1290
                                       alpha1[k][0] * phi[1][1][1];
1291

    
1292
            alpha0[k][0] = -temp_real / phi[1][0][0];
1293
            alpha0[k][1] = -temp_im   / phi[1][0][0];
1294
        }
1295

    
1296
        if (alpha1[k][0] * alpha1[k][0] + alpha1[k][1] * alpha1[k][1] >= 16.0f ||
1297
           alpha0[k][0] * alpha0[k][0] + alpha0[k][1] * alpha0[k][1] >= 16.0f) {
1298
            alpha1[k][0] = 0;
1299
            alpha1[k][1] = 0;
1300
            alpha0[k][0] = 0;
1301
            alpha0[k][1] = 0;
1302
        }
1303
    }
1304
}
1305

    
1306
/// Chirp Factors (14496-3 sp04 p214)
1307
static void sbr_chirp(SpectralBandReplication *sbr, SBRData *ch_data)
1308
{
1309
    int i;
1310
    float new_bw;
1311
    static const float bw_tab[] = { 0.0f, 0.75f, 0.9f, 0.98f };
1312

    
1313
    for (i = 0; i < sbr->n_q; i++) {
1314
        if (ch_data->bs_invf_mode[0][i] + ch_data->bs_invf_mode[1][i] == 1) {
1315
            new_bw = 0.6f;
1316
        } else
1317
            new_bw = bw_tab[ch_data->bs_invf_mode[0][i]];
1318

    
1319
        if (new_bw < ch_data->bw_array[i]) {
1320
            new_bw = 0.75f    * new_bw + 0.25f    * ch_data->bw_array[i];
1321
        } else
1322
            new_bw = 0.90625f * new_bw + 0.09375f * ch_data->bw_array[i];
1323
        ch_data->bw_array[i] = new_bw < 0.015625f ? 0.0f : new_bw;
1324
    }
1325
}
1326

    
1327
/// Generate the subband filtered lowband
1328
static int sbr_lf_gen(AACContext *ac, SpectralBandReplication *sbr,
1329
                      float X_low[32][40][2], const float W[2][32][32][2])
1330
{
1331
    int i, k;
1332
    const int t_HFGen = 8;
1333
    const int i_f = 32;
1334
    memset(X_low, 0, 32*sizeof(*X_low));
1335
    for (k = 0; k < sbr->kx[1]; k++) {
1336
        for (i = t_HFGen; i < i_f + t_HFGen; i++) {
1337
            X_low[k][i][0] = W[1][i - t_HFGen][k][0];
1338
            X_low[k][i][1] = W[1][i - t_HFGen][k][1];
1339
        }
1340
    }
1341
    for (k = 0; k < sbr->kx[0]; k++) {
1342
        for (i = 0; i < t_HFGen; i++) {
1343
            X_low[k][i][0] = W[0][i + i_f - t_HFGen][k][0];
1344
            X_low[k][i][1] = W[0][i + i_f - t_HFGen][k][1];
1345
        }
1346
    }
1347
    return 0;
1348
}
1349

    
1350
/// High Frequency Generator (14496-3 sp04 p215)
1351
static int sbr_hf_gen(AACContext *ac, SpectralBandReplication *sbr,
1352
                      float X_high[64][40][2], const float X_low[32][40][2],
1353
                      const float (*alpha0)[2], const float (*alpha1)[2],
1354
                      const float bw_array[5], const uint8_t *t_env,
1355
                      int bs_num_env)
1356
{
1357
    int i, j, x;
1358
    int g = 0;
1359
    int k = sbr->kx[1];
1360
    for (j = 0; j < sbr->num_patches; j++) {
1361
        for (x = 0; x < sbr->patch_num_subbands[j]; x++, k++) {
1362
            float alpha[4];
1363
            const int p = sbr->patch_start_subband[j] + x;
1364
            while (g <= sbr->n_q && k >= sbr->f_tablenoise[g])
1365
                g++;
1366
            g--;
1367

    
1368
            if (g < 0) {
1369
                av_log(ac->avctx, AV_LOG_ERROR,
1370
                       "ERROR : no subband found for frequency %d\n", k);
1371
                return -1;
1372
            }
1373

    
1374
            alpha[0] = alpha1[p][0] * bw_array[g] * bw_array[g];
1375
            alpha[1] = alpha1[p][1] * bw_array[g] * bw_array[g];
1376
            alpha[2] = alpha0[p][0] * bw_array[g];
1377
            alpha[3] = alpha0[p][1] * bw_array[g];
1378

    
1379
            for (i = 2 * t_env[0]; i < 2 * t_env[bs_num_env]; i++) {
1380
                const int idx = i + ENVELOPE_ADJUSTMENT_OFFSET;
1381
                X_high[k][idx][0] =
1382
                    X_low[p][idx - 2][0] * alpha[0] -
1383
                    X_low[p][idx - 2][1] * alpha[1] +
1384
                    X_low[p][idx - 1][0] * alpha[2] -
1385
                    X_low[p][idx - 1][1] * alpha[3] +
1386
                    X_low[p][idx][0];
1387
                X_high[k][idx][1] =
1388
                    X_low[p][idx - 2][1] * alpha[0] +
1389
                    X_low[p][idx - 2][0] * alpha[1] +
1390
                    X_low[p][idx - 1][1] * alpha[2] +
1391
                    X_low[p][idx - 1][0] * alpha[3] +
1392
                    X_low[p][idx][1];
1393
            }
1394
        }
1395
    }
1396
    if (k < sbr->m[1] + sbr->kx[1])
1397
        memset(X_high + k, 0, (sbr->m[1] + sbr->kx[1] - k) * sizeof(*X_high));
1398

    
1399
    return 0;
1400
}
1401

    
1402
/// Generate the subband filtered lowband
1403
static int sbr_x_gen(SpectralBandReplication *sbr, float X[2][38][64],
1404
                     const float X_low[32][40][2], const float Y[2][38][64][2],
1405
                     int ch)
1406
{
1407
    int k, i;
1408
    const int i_f = 32;
1409
    const int i_Temp = FFMAX(2*sbr->data[ch].t_env_num_env_old - i_f, 0);
1410
    memset(X, 0, 2*sizeof(*X));
1411
    for (k = 0; k < sbr->kx[0]; k++) {
1412
        for (i = 0; i < i_Temp; i++) {
1413
            X[0][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][0];
1414
            X[1][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][1];
1415
        }
1416
    }
1417
    for (; k < sbr->kx[0] + sbr->m[0]; k++) {
1418
        for (i = 0; i < i_Temp; i++) {
1419
            X[0][i][k] = Y[0][i + i_f][k][0];
1420
            X[1][i][k] = Y[0][i + i_f][k][1];
1421
        }
1422
    }
1423

    
1424
    for (k = 0; k < sbr->kx[1]; k++) {
1425
        for (i = i_Temp; i < 38; i++) {
1426
            X[0][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][0];
1427
            X[1][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][1];
1428
        }
1429
    }
1430
    for (; k < sbr->kx[1] + sbr->m[1]; k++) {
1431
        for (i = i_Temp; i < i_f; i++) {
1432
            X[0][i][k] = Y[1][i][k][0];
1433
            X[1][i][k] = Y[1][i][k][1];
1434
        }
1435
    }
1436
    return 0;
1437
}
1438

    
1439
/** High Frequency Adjustment (14496-3 sp04 p217) and Mapping
1440
 * (14496-3 sp04 p217)
1441
 */
1442
static void sbr_mapping(AACContext *ac, SpectralBandReplication *sbr,
1443
                        SBRData *ch_data, int e_a[2])
1444
{
1445
    int e, i, m;
1446

    
1447
    memset(ch_data->s_indexmapped[1], 0, 7*sizeof(ch_data->s_indexmapped[1]));
1448
    for (e = 0; e < ch_data->bs_num_env; e++) {
1449
        const unsigned int ilim = sbr->n[ch_data->bs_freq_res[e + 1]];
1450
        uint16_t *table = ch_data->bs_freq_res[e + 1] ? sbr->f_tablehigh : sbr->f_tablelow;
1451
        int k;
1452

    
1453
        for (i = 0; i < ilim; i++)
1454
            for (m = table[i]; m < table[i + 1]; m++)
1455
                sbr->e_origmapped[e][m - sbr->kx[1]] = ch_data->env_facs[e+1][i];
1456

    
1457
        // ch_data->bs_num_noise > 1 => 2 noise floors
1458
        k = (ch_data->bs_num_noise > 1) && (ch_data->t_env[e] >= ch_data->t_q[1]);
1459
        for (i = 0; i < sbr->n_q; i++)
1460
            for (m = sbr->f_tablenoise[i]; m < sbr->f_tablenoise[i + 1]; m++)
1461
                sbr->q_mapped[e][m - sbr->kx[1]] = ch_data->noise_facs[k+1][i];
1462

    
1463
        for (i = 0; i < sbr->n[1]; i++) {
1464
            if (ch_data->bs_add_harmonic_flag) {
1465
                const unsigned int m_midpoint =
1466
                    (sbr->f_tablehigh[i] + sbr->f_tablehigh[i + 1]) >> 1;
1467

    
1468
                ch_data->s_indexmapped[e + 1][m_midpoint - sbr->kx[1]] = ch_data->bs_add_harmonic[i] *
1469
                    (e >= e_a[1] || (ch_data->s_indexmapped[0][m_midpoint - sbr->kx[1]] == 1));
1470
            }
1471
        }
1472

    
1473
        for (i = 0; i < ilim; i++) {
1474
            int additional_sinusoid_present = 0;
1475
            for (m = table[i]; m < table[i + 1]; m++) {
1476
                if (ch_data->s_indexmapped[e + 1][m - sbr->kx[1]]) {
1477
                    additional_sinusoid_present = 1;
1478
                    break;
1479
                }
1480
            }
1481
            memset(&sbr->s_mapped[e][table[i] - sbr->kx[1]], additional_sinusoid_present,
1482
                   (table[i + 1] - table[i]) * sizeof(sbr->s_mapped[e][0]));
1483
        }
1484
    }
1485

    
1486
    memcpy(ch_data->s_indexmapped[0], ch_data->s_indexmapped[ch_data->bs_num_env], sizeof(ch_data->s_indexmapped[0]));
1487
}
1488

    
1489
/// Estimation of current envelope (14496-3 sp04 p218)
1490
static void sbr_env_estimate(float (*e_curr)[48], float X_high[64][40][2],
1491
                             SpectralBandReplication *sbr, SBRData *ch_data)
1492
{
1493
    int e, i, m;
1494

    
1495
    if (sbr->bs_interpol_freq) {
1496
        for (e = 0; e < ch_data->bs_num_env; e++) {
1497
            const float recip_env_size = 0.5f / (ch_data->t_env[e + 1] - ch_data->t_env[e]);
1498
            int ilb = ch_data->t_env[e]     * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1499
            int iub = ch_data->t_env[e + 1] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1500

    
1501
            for (m = 0; m < sbr->m[1]; m++) {
1502
                float sum = 0.0f;
1503

    
1504
                for (i = ilb; i < iub; i++) {
1505
                    sum += X_high[m + sbr->kx[1]][i][0] * X_high[m + sbr->kx[1]][i][0] +
1506
                           X_high[m + sbr->kx[1]][i][1] * X_high[m + sbr->kx[1]][i][1];
1507
                }
1508
                e_curr[e][m] = sum * recip_env_size;
1509
            }
1510
        }
1511
    } else {
1512
        int k, p;
1513

    
1514
        for (e = 0; e < ch_data->bs_num_env; e++) {
1515
            const int env_size = 2 * (ch_data->t_env[e + 1] - ch_data->t_env[e]);
1516
            int ilb = ch_data->t_env[e]     * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1517
            int iub = ch_data->t_env[e + 1] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1518
            const uint16_t *table = ch_data->bs_freq_res[e + 1] ? sbr->f_tablehigh : sbr->f_tablelow;
1519

    
1520
            for (p = 0; p < sbr->n[ch_data->bs_freq_res[e + 1]]; p++) {
1521
                float sum = 0.0f;
1522
                const int den = env_size * (table[p + 1] - table[p]);
1523

    
1524
                for (k = table[p]; k < table[p + 1]; k++) {
1525
                    for (i = ilb; i < iub; i++) {
1526
                        sum += X_high[k][i][0] * X_high[k][i][0] +
1527
                               X_high[k][i][1] * X_high[k][i][1];
1528
                    }
1529
                }
1530
                sum /= den;
1531
                for (k = table[p]; k < table[p + 1]; k++) {
1532
                    e_curr[e][k - sbr->kx[1]] = sum;
1533
                }
1534
            }
1535
        }
1536
    }
1537
}
1538

    
1539
/**
1540
 * Calculation of levels of additional HF signal components (14496-3 sp04 p219)
1541
 * and Calculation of gain (14496-3 sp04 p219)
1542
 */
1543
static void sbr_gain_calc(AACContext *ac, SpectralBandReplication *sbr,
1544
                          SBRData *ch_data, const int e_a[2])
1545
{
1546
    int e, k, m;
1547
    // max gain limits : -3dB, 0dB, 3dB, inf dB (limiter off)
1548
    static const float limgain[4] = { 0.70795, 1.0, 1.41254, 10000000000 };
1549

    
1550
    for (e = 0; e < ch_data->bs_num_env; e++) {
1551
        int delta = !((e == e_a[1]) || (e == e_a[0]));
1552
        for (k = 0; k < sbr->n_lim; k++) {
1553
            float gain_boost, gain_max;
1554
            float sum[2] = { 0.0f, 0.0f };
1555
            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1556
                const float temp = sbr->e_origmapped[e][m] / (1.0f + sbr->q_mapped[e][m]);
1557
                sbr->q_m[e][m] = sqrtf(temp * sbr->q_mapped[e][m]);
1558
                sbr->s_m[e][m] = sqrtf(temp * ch_data->s_indexmapped[e + 1][m]);
1559
                if (!sbr->s_mapped[e][m]) {
1560
                    sbr->gain[e][m] = sqrtf(sbr->e_origmapped[e][m] /
1561
                                            ((1.0f + sbr->e_curr[e][m]) *
1562
                                             (1.0f + sbr->q_mapped[e][m] * delta)));
1563
                } else {
1564
                    sbr->gain[e][m] = sqrtf(sbr->e_origmapped[e][m] * sbr->q_mapped[e][m] /
1565
                                            ((1.0f + sbr->e_curr[e][m]) *
1566
                                             (1.0f + sbr->q_mapped[e][m])));
1567
                }
1568
            }
1569
            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1570
                sum[0] += sbr->e_origmapped[e][m];
1571
                sum[1] += sbr->e_curr[e][m];
1572
            }
1573
            gain_max = limgain[sbr->bs_limiter_gains] * sqrtf((FLT_EPSILON + sum[0]) / (FLT_EPSILON + sum[1]));
1574
            gain_max = FFMIN(100000.f, gain_max);
1575
            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1576
                float q_m_max   = sbr->q_m[e][m] * gain_max / sbr->gain[e][m];
1577
                sbr->q_m[e][m]  = FFMIN(sbr->q_m[e][m], q_m_max);
1578
                sbr->gain[e][m] = FFMIN(sbr->gain[e][m], gain_max);
1579
            }
1580
            sum[0] = sum[1] = 0.0f;
1581
            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1582
                sum[0] += sbr->e_origmapped[e][m];
1583
                sum[1] += sbr->e_curr[e][m] * sbr->gain[e][m] * sbr->gain[e][m]
1584
                          + sbr->s_m[e][m] * sbr->s_m[e][m]
1585
                          + (delta && !sbr->s_m[e][m]) * sbr->q_m[e][m] * sbr->q_m[e][m];
1586
            }
1587
            gain_boost = sqrtf((FLT_EPSILON + sum[0]) / (FLT_EPSILON + sum[1]));
1588
            gain_boost = FFMIN(1.584893192f, gain_boost);
1589
            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1590
                sbr->gain[e][m] *= gain_boost;
1591
                sbr->q_m[e][m]  *= gain_boost;
1592
                sbr->s_m[e][m]  *= gain_boost;
1593
            }
1594
        }
1595
    }
1596
}
1597

    
1598
/// Assembling HF Signals (14496-3 sp04 p220)
1599
static void sbr_hf_assemble(float Y[2][38][64][2], const float X_high[64][40][2],
1600
                            SpectralBandReplication *sbr, SBRData *ch_data,
1601
                            const int e_a[2])
1602
{
1603
    int e, i, j, m;
1604
    const int h_SL = 4 * !sbr->bs_smoothing_mode;
1605
    const int kx = sbr->kx[1];
1606
    const int m_max = sbr->m[1];
1607
    static const float h_smooth[5] = {
1608
        0.33333333333333,
1609
        0.30150283239582,
1610
        0.21816949906249,
1611
        0.11516383427084,
1612
        0.03183050093751,
1613
    };
1614
    static const int8_t phi[2][4] = {
1615
        {  1,  0, -1,  0}, // real
1616
        {  0,  1,  0, -1}, // imaginary
1617
    };
1618
    float (*g_temp)[48] = ch_data->g_temp, (*q_temp)[48] = ch_data->q_temp;
1619
    int indexnoise = ch_data->f_indexnoise;
1620
    int indexsine  = ch_data->f_indexsine;
1621
    memcpy(Y[0], Y[1], sizeof(Y[0]));
1622

    
1623
    if (sbr->reset) {
1624
        for (i = 0; i < h_SL; i++) {
1625
            memcpy(g_temp[i + 2*ch_data->t_env[0]], sbr->gain[0], m_max * sizeof(sbr->gain[0][0]));
1626
            memcpy(q_temp[i + 2*ch_data->t_env[0]], sbr->q_m[0],  m_max * sizeof(sbr->q_m[0][0]));
1627
        }
1628
    } else if (h_SL) {
1629
        memcpy(g_temp[2*ch_data->t_env[0]], g_temp[2*ch_data->t_env_num_env_old], 4*sizeof(g_temp[0]));
1630
        memcpy(q_temp[2*ch_data->t_env[0]], q_temp[2*ch_data->t_env_num_env_old], 4*sizeof(q_temp[0]));
1631
    }
1632

    
1633
    for (e = 0; e < ch_data->bs_num_env; e++) {
1634
        for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {
1635
            memcpy(g_temp[h_SL + i], sbr->gain[e], m_max * sizeof(sbr->gain[0][0]));
1636
            memcpy(q_temp[h_SL + i], sbr->q_m[e],  m_max * sizeof(sbr->q_m[0][0]));
1637
        }
1638
    }
1639

    
1640
    for (e = 0; e < ch_data->bs_num_env; e++) {
1641
        for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {
1642
            int phi_sign = (1 - 2*(kx & 1));
1643

    
1644
            if (h_SL && e != e_a[0] && e != e_a[1]) {
1645
                for (m = 0; m < m_max; m++) {
1646
                    const int idx1 = i + h_SL;
1647
                    float g_filt = 0.0f;
1648
                    for (j = 0; j <= h_SL; j++)
1649
                        g_filt += g_temp[idx1 - j][m] * h_smooth[j];
1650
                    Y[1][i][m + kx][0] =
1651
                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][0] * g_filt;
1652
                    Y[1][i][m + kx][1] =
1653
                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][1] * g_filt;
1654
                }
1655
            } else {
1656
                for (m = 0; m < m_max; m++) {
1657
                    const float g_filt = g_temp[i + h_SL][m];
1658
                    Y[1][i][m + kx][0] =
1659
                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][0] * g_filt;
1660
                    Y[1][i][m + kx][1] =
1661
                        X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][1] * g_filt;
1662
                }
1663
            }
1664

    
1665
            if (e != e_a[0] && e != e_a[1]) {
1666
                for (m = 0; m < m_max; m++) {
1667
                    indexnoise = (indexnoise + 1) & 0x1ff;
1668
                    if (sbr->s_m[e][m]) {
1669
                        Y[1][i][m + kx][0] +=
1670
                            sbr->s_m[e][m] * phi[0][indexsine];
1671
                        Y[1][i][m + kx][1] +=
1672
                            sbr->s_m[e][m] * (phi[1][indexsine] * phi_sign);
1673
                    } else {
1674
                        float q_filt;
1675
                        if (h_SL) {
1676
                            const int idx1 = i + h_SL;
1677
                            q_filt = 0.0f;
1678
                            for (j = 0; j <= h_SL; j++)
1679
                                q_filt += q_temp[idx1 - j][m] * h_smooth[j];
1680
                        } else {
1681
                            q_filt = q_temp[i][m];
1682
                        }
1683
                        Y[1][i][m + kx][0] +=
1684
                            q_filt * sbr_noise_table[indexnoise][0];
1685
                        Y[1][i][m + kx][1] +=
1686
                            q_filt * sbr_noise_table[indexnoise][1];
1687
                    }
1688
                    phi_sign = -phi_sign;
1689
                }
1690
            } else {
1691
                indexnoise = (indexnoise + m_max) & 0x1ff;
1692
                for (m = 0; m < m_max; m++) {
1693
                    Y[1][i][m + kx][0] +=
1694
                        sbr->s_m[e][m] * phi[0][indexsine];
1695
                    Y[1][i][m + kx][1] +=
1696
                        sbr->s_m[e][m] * (phi[1][indexsine] * phi_sign);
1697
                    phi_sign = -phi_sign;
1698
                }
1699
            }
1700
            indexsine = (indexsine + 1) & 3;
1701
        }
1702
    }
1703
    ch_data->f_indexnoise = indexnoise;
1704
    ch_data->f_indexsine  = indexsine;
1705
}
1706

    
1707
void ff_sbr_apply(AACContext *ac, SpectralBandReplication *sbr, int id_aac,
1708
                  float* L, float* R)
1709
{
1710
    int downsampled = ac->m4ac.ext_sample_rate < sbr->sample_rate;
1711
    int ch;
1712
    int nch = (id_aac == TYPE_CPE) ? 2 : 1;
1713

    
1714
    if (sbr->start) {
1715
        sbr_dequant(sbr, id_aac);
1716
    }
1717
    for (ch = 0; ch < nch; ch++) {
1718
        /* decode channel */
1719
        sbr_qmf_analysis(&ac->dsp, &sbr->mdct_ana, ch ? R : L, sbr->data[ch].analysis_filterbank_samples,
1720
                         (float*)sbr->qmf_filter_scratch,
1721
                         sbr->data[ch].W);
1722
        sbr_lf_gen(ac, sbr, sbr->X_low, sbr->data[ch].W);
1723
        if (sbr->start) {
1724
            sbr_hf_inverse_filter(sbr->alpha0, sbr->alpha1, sbr->X_low, sbr->k[0]);
1725
            sbr_chirp(sbr, &sbr->data[ch]);
1726
            sbr_hf_gen(ac, sbr, sbr->X_high, sbr->X_low, sbr->alpha0, sbr->alpha1,
1727
                       sbr->data[ch].bw_array, sbr->data[ch].t_env,
1728
                       sbr->data[ch].bs_num_env);
1729

    
1730
            // hf_adj
1731
            sbr_mapping(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);
1732
            sbr_env_estimate(sbr->e_curr, sbr->X_high, sbr, &sbr->data[ch]);
1733
            sbr_gain_calc(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);
1734
            sbr_hf_assemble(sbr->data[ch].Y, sbr->X_high, sbr, &sbr->data[ch],
1735
                            sbr->data[ch].e_a);
1736
        }
1737

    
1738
        /* synthesis */
1739
        sbr_x_gen(sbr, sbr->X[ch], sbr->X_low, sbr->data[ch].Y, ch);
1740
    }
1741

    
1742
    if (ac->m4ac.ps == 1) {
1743
        if (sbr->ps.start) {
1744
            ff_ps_apply(ac->avctx, &sbr->ps, sbr->X[0], sbr->X[1], sbr->kx[1] + sbr->m[1]);
1745
        } else {
1746
            memcpy(sbr->X[1], sbr->X[0], sizeof(sbr->X[0]));
1747
        }
1748
        nch = 2;
1749
    }
1750

    
1751
    sbr_qmf_synthesis(&ac->dsp, &sbr->mdct, L, sbr->X[0], sbr->qmf_filter_scratch,
1752
                      sbr->data[0].synthesis_filterbank_samples,
1753
                      &sbr->data[0].synthesis_filterbank_samples_offset,
1754
                      downsampled);
1755
    if (nch == 2)
1756
        sbr_qmf_synthesis(&ac->dsp, &sbr->mdct, R, sbr->X[1], sbr->qmf_filter_scratch,
1757
                          sbr->data[1].synthesis_filterbank_samples,
1758
                          &sbr->data[1].synthesis_filterbank_samples_offset,
1759
                          downsampled);
1760
}