Move Parametric Stereo related ps* files to aacps*.
[libav.git] / libavcodec / aacsbr.c
CommitLineData
ed492b61
AC
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/**
ba87f080 24 * @file
ed492b61
AC
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"
e0be7630 33#include "fft.h"
fd6eb4a0 34#include "aacps.h"
ed492b61
AC
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 */
45enum {
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 */
61enum {
62 FIXFIX,
63 FIXVAR,
64 VARFIX,
65 VARVAR,
66};
67
68enum {
69 EXTENSION_ID_PS = 2,
70};
71
72static VLC vlc_sbr[10];
73static const int8_t vlc_sbr_lav[10] =
74 { 60, 60, 24, 24, 31, 31, 12, 12, 31, 12 };
ed492b61
AC
75static 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
86av_cold void ff_aac_sbr_init(void)
87{
388c7955 88 int n;
ed492b61
AC
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
ed492b61
AC
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];
a2063901
AC
124
125 ff_ps_init();
ed492b61
AC
126}
127
128av_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
46751a65 131 sbr->data[0].e_a[1] = sbr->data[1].e_a[1] = -1;
ed492b61
AC
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);
932963b8 135 ff_mdct_init(&sbr->mdct_ana, 7, 1, -2.0);
a2063901 136 ff_ps_ctx_init(&sbr->ps);
ed492b61
AC
137}
138
139av_cold void ff_aac_sbr_ctx_close(SpectralBandReplication *sbr)
140{
141 ff_mdct_end(&sbr->mdct);
932963b8 142 ff_mdct_end(&sbr->mdct_ana);
ed492b61
AC
143}
144
145static int qsort_comparison_function_int16(const void *a, const void *b)
146{
147 return *(const int16_t *)a - *(const int16_t *)b;
148}
149
150static 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)
160static 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];
10678e5c 168 int16_t patch_borders[7];
ed492b61
AC
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
207static 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
261static 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
269static 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
dd8871a6 287static int check_n_master(AVCodecContext *avctx, int n_master, int bs_xover_band)
ed492b61
AC
288{
289 // Requirements (14496-3 sp04 p205)
290 if (n_master <= 0) {
dd8871a6 291 av_log(avctx, AV_LOG_ERROR, "Invalid n_master: %d\n", n_master);
ed492b61
AC
292 return -1;
293 }
294 if (bs_xover_band >= n_master) {
dd8871a6 295 av_log(avctx, AV_LOG_ERROR,
ed492b61
AC
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)
304static 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:
dd8871a6 343 av_log(ac->avctx, AV_LOG_ERROR,
ed492b61
AC
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 {
dd8871a6 361 av_log(ac->avctx, AV_LOG_ERROR,
ed492b61
AC
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) {
dd8871a6 376 av_log(ac->avctx, AV_LOG_ERROR,
ed492b61
AC
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) {
cf3b4d9a 382 int dk, k2diff;
ed492b61
AC
383
384 dk = spectrum->bs_alter_scale + 1;
385 sbr->n_master = ((sbr->k[2] - sbr->k[0] + (dk&2)) >> dk) << 1;
dd8871a6 386 if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
ed492b61
AC
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]--;
bd9e0e29 395 sbr->f_master[2]-= (k2diff < -1);
ed492b61
AC
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)
dd8871a6 421 av_log(ac->avctx, AV_LOG_ERROR, "Invalid num_bands_0: %d\n", num_bands_0);
ed492b61
AC
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)
dd8871a6 435 av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk0[%d]: %d\n", k, vk0[k]);
ed492b61
AC
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)
dd8871a6 465 av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk1[%d]: %d\n", k, vk1[k]);
ed492b61
AC
466 return -1;
467 }
468 vk1[k] += vk1[k-1];
469 }
470
471 sbr->n_master = num_bands_0 + num_bands_1;
dd8871a6 472 if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
ed492b61
AC
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;
dd8871a6 481 if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
ed492b61
AC
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)
491static 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
a91d82b5
AC
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) {
dd8871a6 517 av_log(ac->avctx, AV_LOG_ERROR, "Too many patches: %d\n", sbr->num_patches);
a91d82b5
AC
518 return -1;
519 }
520
ed492b61
AC
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
ed492b61
AC
538 return 0;
539}
540
541/// Derived Frequency Band Tables (14496-3 sp04 p197)
542static 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) {
dd8871a6 556 av_log(ac->avctx, AV_LOG_ERROR,
ed492b61
AC
557 "Stop frequency border too high: %d\n", sbr->kx[1] + sbr->m[1]);
558 return -1;
559 }
560 if (sbr->kx[1] > 32) {
dd8871a6 561 av_log(ac->avctx, AV_LOG_ERROR, "Start frequency border too high: %d\n", sbr->kx[1]);
ed492b61
AC
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) {
dd8871a6 573 av_log(ac->avctx, AV_LOG_ERROR, "Too many noise floor scale factors: %d\n", sbr->n_q);
ed492b61
AC
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
595static 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)) */
605static const int8_t ceil_log2[] = {
606 0, 1, 2, 2, 3, 3,
607};
608
609static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,
610 GetBitContext *gb, SBRData *ch_data)
611{
612 int i;
134b8cbb 613 unsigned bs_pointer = 0;
79350786
AC
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;
ecc1f8c3 617 unsigned bs_num_env_old = ch_data->bs_num_env;
ed492b61 618
ecc1f8c3 619 ch_data->bs_freq_res[0] = ch_data->bs_freq_res[ch_data->bs_num_env];
ed492b61 620 ch_data->bs_amp_res = sbr->bs_amp_res_header;
ac8d655a 621 ch_data->t_env_num_env_old = ch_data->t_env[bs_num_env_old];
ed492b61
AC
622
623 switch (ch_data->bs_frame_class = get_bits(gb, 2)) {
624 case FIXFIX:
134b8cbb
AC
625 ch_data->bs_num_env = 1 << get_bits(gb, 2);
626 num_rel_lead = ch_data->bs_num_env - 1;
ecc1f8c3 627 if (ch_data->bs_num_env == 1)
ed492b61
AC
628 ch_data->bs_amp_res = 0;
629
ecc1f8c3 630 if (ch_data->bs_num_env > 4) {
dd8871a6 631 av_log(ac->avctx, AV_LOG_ERROR,
ed1d1129 632 "Invalid bitstream, too many SBR envelopes in FIXFIX type SBR frame: %d\n",
ecc1f8c3 633 ch_data->bs_num_env);
ed1d1129
AC
634 return -1;
635 }
636
ac8d655a
AC
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
ed492b61 645 ch_data->bs_freq_res[1] = get_bits1(gb);
ecc1f8c3 646 for (i = 1; i < ch_data->bs_num_env; i++)
ed492b61
AC
647 ch_data->bs_freq_res[i + 1] = ch_data->bs_freq_res[1];
648 break;
649 case FIXVAR:
134b8cbb
AC
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;
ac8d655a 654 ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
ed492b61 655
79350786 656 for (i = 0; i < num_rel_trail; i++)
134b8cbb
AC
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;
ed492b61 659
ecc1f8c3 660 bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
ed492b61 661
ecc1f8c3
AC
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);
ed492b61
AC
664 break;
665 case VARFIX:
134b8cbb
AC
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;
ac8d655a 669 ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
ed492b61 670
79350786 671 for (i = 0; i < num_rel_lead; i++)
ac8d655a 672 ch_data->t_env[i + 1] = ch_data->t_env[i] + 2 * get_bits(gb, 2) + 2;
ed492b61 673
ecc1f8c3 674 bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
ed492b61 675
ecc1f8c3 676 get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env);
ed492b61
AC
677 break;
678 case VARVAR:
134b8cbb
AC
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;
ed492b61 684
ecc1f8c3 685 if (ch_data->bs_num_env > 5) {
dd8871a6 686 av_log(ac->avctx, AV_LOG_ERROR,
ed1d1129 687 "Invalid bitstream, too many SBR envelopes in VARVAR type SBR frame: %d\n",
ecc1f8c3 688 ch_data->bs_num_env);
ed1d1129
AC
689 return -1;
690 }
691
6ebc7240
AC
692 ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
693
79350786 694 for (i = 0; i < num_rel_lead; i++)
ac8d655a 695 ch_data->t_env[i + 1] = ch_data->t_env[i] + 2 * get_bits(gb, 2) + 2;
79350786 696 for (i = 0; i < num_rel_trail; i++)
134b8cbb
AC
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;
ed492b61 699
ecc1f8c3 700 bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
ed492b61 701
ecc1f8c3 702 get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env);
ed492b61
AC
703 break;
704 }
705
ecc1f8c3 706 if (bs_pointer > ch_data->bs_num_env + 1) {
dd8871a6 707 av_log(ac->avctx, AV_LOG_ERROR,
8a9ee4b1 708 "Invalid bitstream, bs_pointer points to a middle noise border outside the time borders table: %d\n",
79350786 709 bs_pointer);
b9c3e3b6
AC
710 return -1;
711 }
712
2d23fecd
AC
713 for (i = 1; i <= ch_data->bs_num_env; i++) {
714 if (ch_data->t_env[i-1] > ch_data->t_env[i]) {
dd8871a6 715 av_log(ac->avctx, AV_LOG_ERROR, "Non monotone time borders\n");
2d23fecd
AC
716 return -1;
717 }
718 }
719
ecc1f8c3 720 ch_data->bs_num_noise = (ch_data->bs_num_env > 1) + 1;
ed492b61 721
134b8cbb 722 ch_data->t_q[0] = ch_data->t_env[0];
f7e7888b 723 ch_data->t_q[ch_data->bs_num_noise] = ch_data->t_env[ch_data->bs_num_env];
afd96c34 724 if (ch_data->bs_num_noise > 1) {
b9c3e3b6
AC
725 unsigned int idx;
726 if (ch_data->bs_frame_class == FIXFIX) {
ecc1f8c3 727 idx = ch_data->bs_num_env >> 1;
b9c3e3b6 728 } else if (ch_data->bs_frame_class & 1) { // FIXVAR or VARVAR
ecc1f8c3 729 idx = ch_data->bs_num_env - FFMAX(bs_pointer - 1, 1);
b9c3e3b6 730 } else { // VARFIX
79350786 731 if (!bs_pointer)
b9c3e3b6 732 idx = 1;
79350786 733 else if (bs_pointer == 1)
ecc1f8c3 734 idx = ch_data->bs_num_env - 1;
b9c3e3b6 735 else // bs_pointer > 1
79350786 736 idx = bs_pointer - 1;
b9c3e3b6
AC
737 }
738 ch_data->t_q[1] = ch_data->t_env[idx];
f7e7888b 739 }
b9c3e3b6 740
ecc1f8c3 741 ch_data->e_a[0] = -(ch_data->e_a[1] != bs_num_env_old); // l_APrev
7333f849 742 ch_data->e_a[1] = -1;
79350786 743 if ((ch_data->bs_frame_class & 1) && bs_pointer) { // FIXVAR or VARVAR and bs_pointer != 0
ecc1f8c3 744 ch_data->e_a[1] = ch_data->bs_num_env + 1 - bs_pointer;
79350786
AC
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;
7333f849 747
ed492b61
AC
748 return 0;
749}
750
751static void copy_sbr_grid(SBRData *dst, const SBRData *src) {
752 //These variables are saved from the previous frame rather than copied
134b8cbb 753 dst->bs_freq_res[0] = dst->bs_freq_res[dst->bs_num_env];
ecc1f8c3 754 dst->t_env_num_env_old = dst->t_env[dst->bs_num_env];
134b8cbb 755 dst->e_a[0] = -(dst->e_a[1] != dst->bs_num_env);
ed492b61
AC
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));
b9c3e3b6
AC
759 memcpy(dst->t_env, src->t_env, sizeof(dst->t_env));
760 memcpy(dst->t_q, src->t_q, sizeof(dst->t_q));
134b8cbb
AC
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];
ed492b61
AC
766}
767
768/// Read how the envelope and noise floor data is delta coded
769static void read_sbr_dtdf(SpectralBandReplication *sbr, GetBitContext *gb,
770 SBRData *ch_data)
771{
ecc1f8c3 772 get_bits1_vector(gb, ch_data->bs_df_env, ch_data->bs_num_env);
ed492b61
AC
773 get_bits1_vector(gb, ch_data->bs_df_noise, ch_data->bs_num_noise);
774}
775
776/// Read inverse filtering data
777static 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
787static 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
ecc1f8c3 827 for (i = 0; i < ch_data->bs_num_env; i++) {
ed492b61 828 if (ch_data->bs_df_env[i]) {
ecc1f8c3 829 // bs_freq_res[0] == bs_freq_res[bs_num_env] from prev frame
ed492b61
AC
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
ecc1f8c3 852 memcpy(ch_data->env_facs[0], ch_data->env_facs[ch_data->bs_num_env],
ed492b61
AC
853 sizeof(ch_data->env_facs[0]));
854}
855
856static 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
892static void read_sbr_extension(AACContext *ac, SpectralBandReplication *sbr,
893 GetBitContext *gb,
ba659bed 894 int bs_extension_id, int *num_bits_left)
ed492b61 895{
ed492b61
AC
896 switch (bs_extension_id) {
897 case EXTENSION_ID_PS:
73c27046 898 if (!ac->m4ac.ps) {
dd8871a6 899 av_log(ac->avctx, AV_LOG_ERROR, "Parametric Stereo signaled to be not-present but was found in the bitstream.\n");
ba659bed
AC
900 skip_bits_long(gb, *num_bits_left); // bs_fill_bits
901 *num_bits_left = 0;
73c27046 902 } else {
a2063901
AC
903#if 1
904 *num_bits_left -= ff_ps_read_data(ac->avctx, gb, &sbr->ps, *num_bits_left);
ed492b61 905#else
dd8871a6 906 av_log_missing_feature(ac->avctx, "Parametric Stereo is", 0);
ba659bed
AC
907 skip_bits_long(gb, *num_bits_left); // bs_fill_bits
908 *num_bits_left = 0;
ed492b61 909#endif
73c27046 910 }
ed492b61
AC
911 break;
912 default:
dd8871a6 913 av_log_missing_feature(ac->avctx, "Reserved SBR extensions are", 1);
ed492b61
AC
914 skip_bits_long(gb, *num_bits_left); // bs_fill_bits
915 *num_bits_left = 0;
916 break;
917 }
918}
919
58b1cba0 920static int read_sbr_single_channel_element(AACContext *ac,
ed492b61
AC
921 SpectralBandReplication *sbr,
922 GetBitContext *gb)
923{
924 if (get_bits1(gb)) // bs_data_extra
925 skip_bits(gb, 4); // bs_reserved
926
58b1cba0
AC
927 if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))
928 return -1;
ed492b61
AC
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]);
bf3d904c
AC
936
937 return 0;
ed492b61
AC
938}
939
58b1cba0 940static int read_sbr_channel_pair_element(AACContext *ac,
ed492b61
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))) {
58b1cba0
AC
948 if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))
949 return -1;
ed492b61
AC
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 {
58b1cba0
AC
961 if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]) ||
962 read_sbr_grid(ac, sbr, gb, &sbr->data[1]))
963 return -1;
ed492b61
AC
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]);
bf3d904c
AC
978
979 return 0;
ed492b61
AC
980}
981
982static 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) {
58b1cba0
AC
988 if (read_sbr_single_channel_element(ac, sbr, gb)) {
989 sbr->start = 0;
990 return get_bits_count(gb) - cnt;
991 }
ed492b61 992 } else if (id_aac == TYPE_CPE) {
58b1cba0
AC
993 if (read_sbr_channel_pair_element(ac, sbr, gb)) {
994 sbr->start = 0;
995 return get_bits_count(gb) - cnt;
996 }
ed492b61 997 } else {
dd8871a6 998 av_log(ac->avctx, AV_LOG_ERROR,
ed492b61
AC
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 }
a2063901
AC
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);
ed492b61
AC
1018 }
1019
1020 return get_bits_count(gb) - cnt;
1021}
1022
1023static 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) {
dd8871a6 1030 av_log(ac->avctx, AV_LOG_ERROR,
ed492b61
AC
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 */
1044int 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) {
dd8871a6 1082 av_log(ac->avctx, AV_LOG_ERROR,
ed492b61
AC
1083 "Expected to read %d SBR bytes actually read %d.\n", cnt, bytes_read);
1084 }
1085 return cnt;
1086}
1087
ed492b61
AC
1088/// Dequantization and stereo decoding (14496-3 sp04 p203)
1089static 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;
ecc1f8c3 1097 for (e = 1; e <= sbr->data[0].bs_num_env; e++) {
ed492b61
AC
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;
ecc1f8c3 1118 for (e = 1; e <= sbr->data[ch].bs_num_env; e++)
ed492b61
AC
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 */
388c7955 1136static void sbr_qmf_analysis(DSPContext *dsp, FFTContext *mdct, const float *in, float *x,
ed492b61 1137 float z[320], float W[2][32][32][2],
f8a93a20 1138 float scale)
ed492b61
AC
1139{
1140 int i, k;
1141 memcpy(W[0], W[1], sizeof(W[0]));
1142 memcpy(x , x+1024, (320-32)*sizeof(x[0]));
f8a93a20 1143 if (scale != 1.0f)
b3e5931d 1144 dsp->vector_fmul_scalar(x+288, in, scale, 1024);
ed492b61
AC
1145 else
1146 memcpy(x+288, in, 1024*sizeof(*x));
1147 for (i = 0; i < 32; i++) { // numTimeSlots*RATE = 16*2 as 960 sample frames
1148 // are not supported
ed492b61
AC
1149 dsp->vector_fmul_reverse(z, sbr_qmf_window_ds, x, 320);
1150 for (k = 0; k < 64; k++) {
1151 float f = z[k] + z[k + 64] + z[k + 128] + z[k + 192] + z[k + 256];
932963b8 1152 z[k] = f;
ed492b61 1153 }
932963b8
AC
1154 //Shuffle to IMDCT
1155 z[64] = z[0];
ed492b61 1156 for (k = 1; k < 32; k++) {
932963b8
AC
1157 z[64+2*k-1] = z[ k];
1158 z[64+2*k ] = -z[64-k];
1159 }
1160 z[64+63] = z[32];
1161
1162 ff_imdct_half(mdct, z, z+64);
1163 for (k = 0; k < 32; k++) {
1164 W[1][i][k][0] = -z[63-k];
1165 W[1][i][k][1] = z[k];
ed492b61
AC
1166 }
1167 x += 32;
1168 }
1169}
1170
1171/**
1172 * Synthesis QMF Bank (14496-3 sp04 p206) and Downsampled Synthesis QMF Bank
1173 * (14496-3 sp04 p206)
1174 */
1175static void sbr_qmf_synthesis(DSPContext *dsp, FFTContext *mdct,
a2063901 1176 float *out, float X[2][38][64],
ed492b61
AC
1177 float mdct_buf[2][64],
1178 float *v0, int *v_off, const unsigned int div,
1179 float bias, float scale)
1180{
1181 int i, n;
1182 const float *sbr_qmf_window = div ? sbr_qmf_window_ds : sbr_qmf_window_us;
1183 int scale_and_bias = scale != 1.0f || bias != 0.0f;
1184 float *v;
1185 for (i = 0; i < 32; i++) {
1186 if (*v_off == 0) {
1187 int saved_samples = (1280 - 128) >> div;
1188 memcpy(&v0[SBR_SYNTHESIS_BUF_SIZE - saved_samples], v0, saved_samples * sizeof(float));
1189 *v_off = SBR_SYNTHESIS_BUF_SIZE - saved_samples - (128 >> div);
1190 } else {
1191 *v_off -= 128 >> div;
1192 }
1193 v = v0 + *v_off;
712209d5
AC
1194 if (div) {
1195 for (n = 0; n < 32; n++) {
1196 X[0][i][ n] = -X[0][i][n];
1197 X[0][i][32+n] = X[1][i][31-n];
1198 }
1199 ff_imdct_half(mdct, mdct_buf[0], X[0][i]);
1200 for (n = 0; n < 32; n++) {
1201 v[ n] = mdct_buf[0][63 - 2*n];
1202 v[63 - n] = -mdct_buf[0][62 - 2*n];
1203 }
1204 } else {
bc330b5f
AC
1205 for (n = 1; n < 64; n+=2) {
1206 X[1][i][n] = -X[1][i][n];
1207 }
1208 ff_imdct_half(mdct, mdct_buf[0], X[0][i]);
1209 ff_imdct_half(mdct, mdct_buf[1], X[1][i]);
ed492b61
AC
1210 for (n = 0; n < 64; n++) {
1211 v[ n] = -mdct_buf[0][63 - n] + mdct_buf[1][ n ];
1212 v[127 - n] = mdct_buf[0][63 - n] + mdct_buf[1][ n ];
1213 }
1214 }
1215 dsp->vector_fmul_add(out, v , sbr_qmf_window , zero64, 64 >> div);
1216 dsp->vector_fmul_add(out, v + ( 192 >> div), sbr_qmf_window + ( 64 >> div), out , 64 >> div);
1217 dsp->vector_fmul_add(out, v + ( 256 >> div), sbr_qmf_window + (128 >> div), out , 64 >> div);
1218 dsp->vector_fmul_add(out, v + ( 448 >> div), sbr_qmf_window + (192 >> div), out , 64 >> div);
1219 dsp->vector_fmul_add(out, v + ( 512 >> div), sbr_qmf_window + (256 >> div), out , 64 >> div);
1220 dsp->vector_fmul_add(out, v + ( 704 >> div), sbr_qmf_window + (320 >> div), out , 64 >> div);
1221 dsp->vector_fmul_add(out, v + ( 768 >> div), sbr_qmf_window + (384 >> div), out , 64 >> div);
1222 dsp->vector_fmul_add(out, v + ( 960 >> div), sbr_qmf_window + (448 >> div), out , 64 >> div);
1223 dsp->vector_fmul_add(out, v + (1024 >> div), sbr_qmf_window + (512 >> div), out , 64 >> div);
1224 dsp->vector_fmul_add(out, v + (1216 >> div), sbr_qmf_window + (576 >> div), out , 64 >> div);
1225 if (scale_and_bias)
1226 for (n = 0; n < 64 >> div; n++)
1227 out[n] = out[n] * scale + bias;
1228 out += 64 >> div;
1229 }
1230}
1231
1232static void autocorrelate(const float x[40][2], float phi[3][2][2], int lag)
1233{
1234 int i;
1235 float real_sum = 0.0f;
1236 float imag_sum = 0.0f;
1237 if (lag) {
1238 for (i = 1; i < 38; i++) {
1239 real_sum += x[i][0] * x[i+lag][0] + x[i][1] * x[i+lag][1];
1240 imag_sum += x[i][0] * x[i+lag][1] - x[i][1] * x[i+lag][0];
1241 }
1242 phi[2-lag][1][0] = real_sum + x[ 0][0] * x[lag][0] + x[ 0][1] * x[lag][1];
1243 phi[2-lag][1][1] = imag_sum + x[ 0][0] * x[lag][1] - x[ 0][1] * x[lag][0];
1244 if (lag == 1) {
1245 phi[0][0][0] = real_sum + x[38][0] * x[39][0] + x[38][1] * x[39][1];
1246 phi[0][0][1] = imag_sum + x[38][0] * x[39][1] - x[38][1] * x[39][0];
1247 }
1248 } else {
1249 for (i = 1; i < 38; i++) {
1250 real_sum += x[i][0] * x[i][0] + x[i][1] * x[i][1];
1251 }
1252 phi[2][1][0] = real_sum + x[ 0][0] * x[ 0][0] + x[ 0][1] * x[ 0][1];
1253 phi[1][0][0] = real_sum + x[38][0] * x[38][0] + x[38][1] * x[38][1];
1254 }
1255}
1256
1257/** High Frequency Generation (14496-3 sp04 p214+) and Inverse Filtering
1258 * (14496-3 sp04 p214)
1259 * Warning: This routine does not seem numerically stable.
1260 */
1261static void sbr_hf_inverse_filter(float (*alpha0)[2], float (*alpha1)[2],
1262 const float X_low[32][40][2], int k0)
1263{
1264 int k;
1265 for (k = 0; k < k0; k++) {
1266 float phi[3][2][2], dk;
1267
1268 autocorrelate(X_low[k], phi, 0);
1269 autocorrelate(X_low[k], phi, 1);
1270 autocorrelate(X_low[k], phi, 2);
1271
1272 dk = phi[2][1][0] * phi[1][0][0] -
1273 (phi[1][1][0] * phi[1][1][0] + phi[1][1][1] * phi[1][1][1]) / 1.000001f;
1274
1275 if (!dk) {
1276 alpha1[k][0] = 0;
1277 alpha1[k][1] = 0;
1278 } else {
1279 float temp_real, temp_im;
1280 temp_real = phi[0][0][0] * phi[1][1][0] -
1281 phi[0][0][1] * phi[1][1][1] -
1282 phi[0][1][0] * phi[1][0][0];
1283 temp_im = phi[0][0][0] * phi[1][1][1] +
1284 phi[0][0][1] * phi[1][1][0] -
1285 phi[0][1][1] * phi[1][0][0];
1286
1287 alpha1[k][0] = temp_real / dk;
1288 alpha1[k][1] = temp_im / dk;
1289 }
1290
1291 if (!phi[1][0][0]) {
1292 alpha0[k][0] = 0;
1293 alpha0[k][1] = 0;
1294 } else {
1295 float temp_real, temp_im;
1296 temp_real = phi[0][0][0] + alpha1[k][0] * phi[1][1][0] +
1297 alpha1[k][1] * phi[1][1][1];
1298 temp_im = phi[0][0][1] + alpha1[k][1] * phi[1][1][0] -
1299 alpha1[k][0] * phi[1][1][1];
1300
1301 alpha0[k][0] = -temp_real / phi[1][0][0];
1302 alpha0[k][1] = -temp_im / phi[1][0][0];
1303 }
1304
1305 if (alpha1[k][0] * alpha1[k][0] + alpha1[k][1] * alpha1[k][1] >= 16.0f ||
1306 alpha0[k][0] * alpha0[k][0] + alpha0[k][1] * alpha0[k][1] >= 16.0f) {
1307 alpha1[k][0] = 0;
1308 alpha1[k][1] = 0;
1309 alpha0[k][0] = 0;
1310 alpha0[k][1] = 0;
1311 }
1312 }
1313}
1314
1315/// Chirp Factors (14496-3 sp04 p214)
1316static void sbr_chirp(SpectralBandReplication *sbr, SBRData *ch_data)
1317{
1318 int i;
1319 float new_bw;
1320 static const float bw_tab[] = { 0.0f, 0.75f, 0.9f, 0.98f };
1321
1322 for (i = 0; i < sbr->n_q; i++) {
1323 if (ch_data->bs_invf_mode[0][i] + ch_data->bs_invf_mode[1][i] == 1) {
1324 new_bw = 0.6f;
1325 } else
1326 new_bw = bw_tab[ch_data->bs_invf_mode[0][i]];
1327
1328 if (new_bw < ch_data->bw_array[i]) {
1329 new_bw = 0.75f * new_bw + 0.25f * ch_data->bw_array[i];
1330 } else
1331 new_bw = 0.90625f * new_bw + 0.09375f * ch_data->bw_array[i];
1332 ch_data->bw_array[i] = new_bw < 0.015625f ? 0.0f : new_bw;
1333 }
1334}
1335
1336/// Generate the subband filtered lowband
1337static int sbr_lf_gen(AACContext *ac, SpectralBandReplication *sbr,
1338 float X_low[32][40][2], const float W[2][32][32][2])
1339{
1340 int i, k;
1341 const int t_HFGen = 8;
1342 const int i_f = 32;
1343 memset(X_low, 0, 32*sizeof(*X_low));
1344 for (k = 0; k < sbr->kx[1]; k++) {
1345 for (i = t_HFGen; i < i_f + t_HFGen; i++) {
1346 X_low[k][i][0] = W[1][i - t_HFGen][k][0];
1347 X_low[k][i][1] = W[1][i - t_HFGen][k][1];
1348 }
1349 }
1350 for (k = 0; k < sbr->kx[0]; k++) {
1351 for (i = 0; i < t_HFGen; i++) {
1352 X_low[k][i][0] = W[0][i + i_f - t_HFGen][k][0];
1353 X_low[k][i][1] = W[0][i + i_f - t_HFGen][k][1];
1354 }
1355 }
1356 return 0;
1357}
1358
1359/// High Frequency Generator (14496-3 sp04 p215)
1360static int sbr_hf_gen(AACContext *ac, SpectralBandReplication *sbr,
1361 float X_high[64][40][2], const float X_low[32][40][2],
1362 const float (*alpha0)[2], const float (*alpha1)[2],
1363 const float bw_array[5], const uint8_t *t_env,
1364 int bs_num_env)
1365{
1366 int i, j, x;
1367 int g = 0;
1368 int k = sbr->kx[1];
1369 for (j = 0; j < sbr->num_patches; j++) {
1370 for (x = 0; x < sbr->patch_num_subbands[j]; x++, k++) {
1371 float alpha[4];
1372 const int p = sbr->patch_start_subband[j] + x;
1373 while (g <= sbr->n_q && k >= sbr->f_tablenoise[g])
1374 g++;
1375 g--;
1376
1377 if (g < 0) {
dd8871a6 1378 av_log(ac->avctx, AV_LOG_ERROR,
ed492b61
AC
1379 "ERROR : no subband found for frequency %d\n", k);
1380 return -1;
1381 }
1382
1383 alpha[0] = alpha1[p][0] * bw_array[g] * bw_array[g];
1384 alpha[1] = alpha1[p][1] * bw_array[g] * bw_array[g];
1385 alpha[2] = alpha0[p][0] * bw_array[g];
1386 alpha[3] = alpha0[p][1] * bw_array[g];
1387
1388 for (i = 2 * t_env[0]; i < 2 * t_env[bs_num_env]; i++) {
1389 const int idx = i + ENVELOPE_ADJUSTMENT_OFFSET;
1390 X_high[k][idx][0] =
1391 X_low[p][idx - 2][0] * alpha[0] -
1392 X_low[p][idx - 2][1] * alpha[1] +
1393 X_low[p][idx - 1][0] * alpha[2] -
1394 X_low[p][idx - 1][1] * alpha[3] +
1395 X_low[p][idx][0];
1396 X_high[k][idx][1] =
1397 X_low[p][idx - 2][1] * alpha[0] +
1398 X_low[p][idx - 2][0] * alpha[1] +
1399 X_low[p][idx - 1][1] * alpha[2] +
1400 X_low[p][idx - 1][0] * alpha[3] +
1401 X_low[p][idx][1];
1402 }
1403 }
1404 }
1405 if (k < sbr->m[1] + sbr->kx[1])
1406 memset(X_high + k, 0, (sbr->m[1] + sbr->kx[1] - k) * sizeof(*X_high));
1407
1408 return 0;
1409}
1410
1411/// Generate the subband filtered lowband
a2063901 1412static int sbr_x_gen(SpectralBandReplication *sbr, float X[2][38][64],
ed492b61
AC
1413 const float X_low[32][40][2], const float Y[2][38][64][2],
1414 int ch)
1415{
1416 int k, i;
1417 const int i_f = 32;
1418 const int i_Temp = FFMAX(2*sbr->data[ch].t_env_num_env_old - i_f, 0);
1419 memset(X, 0, 2*sizeof(*X));
1420 for (k = 0; k < sbr->kx[0]; k++) {
1421 for (i = 0; i < i_Temp; i++) {
1422 X[0][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][0];
1423 X[1][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][1];
1424 }
1425 }
1426 for (; k < sbr->kx[0] + sbr->m[0]; k++) {
1427 for (i = 0; i < i_Temp; i++) {
1428 X[0][i][k] = Y[0][i + i_f][k][0];
1429 X[1][i][k] = Y[0][i + i_f][k][1];
1430 }
1431 }
1432
1433 for (k = 0; k < sbr->kx[1]; k++) {
a2063901 1434 for (i = i_Temp; i < 38; i++) {
ed492b61
AC
1435 X[0][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][0];
1436 X[1][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][1];
1437 }
1438 }
1439 for (; k < sbr->kx[1] + sbr->m[1]; k++) {
1440 for (i = i_Temp; i < i_f; i++) {
1441 X[0][i][k] = Y[1][i][k][0];
1442 X[1][i][k] = Y[1][i][k][1];
1443 }
1444 }
1445 return 0;
1446}
1447
1448/** High Frequency Adjustment (14496-3 sp04 p217) and Mapping
1449 * (14496-3 sp04 p217)
1450 */
1451static void sbr_mapping(AACContext *ac, SpectralBandReplication *sbr,
1452 SBRData *ch_data, int e_a[2])
1453{
1454 int e, i, m;
1455
ed492b61 1456 memset(ch_data->s_indexmapped[1], 0, 7*sizeof(ch_data->s_indexmapped[1]));
ecc1f8c3 1457 for (e = 0; e < ch_data->bs_num_env; e++) {
ed492b61
AC
1458 const unsigned int ilim = sbr->n[ch_data->bs_freq_res[e + 1]];
1459 uint16_t *table = ch_data->bs_freq_res[e + 1] ? sbr->f_tablehigh : sbr->f_tablelow;
1460 int k;
1461
1462 for (i = 0; i < ilim; i++)
1463 for (m = table[i]; m < table[i + 1]; m++)
1464 sbr->e_origmapped[e][m - sbr->kx[1]] = ch_data->env_facs[e+1][i];
1465
1466 // ch_data->bs_num_noise > 1 => 2 noise floors
1467 k = (ch_data->bs_num_noise > 1) && (ch_data->t_env[e] >= ch_data->t_q[1]);
1468 for (i = 0; i < sbr->n_q; i++)
1469 for (m = sbr->f_tablenoise[i]; m < sbr->f_tablenoise[i + 1]; m++)
1470 sbr->q_mapped[e][m - sbr->kx[1]] = ch_data->noise_facs[k+1][i];
1471
1472 for (i = 0; i < sbr->n[1]; i++) {
1473 if (ch_data->bs_add_harmonic_flag) {
1474 const unsigned int m_midpoint =
1475 (sbr->f_tablehigh[i] + sbr->f_tablehigh[i + 1]) >> 1;
1476
1477 ch_data->s_indexmapped[e + 1][m_midpoint - sbr->kx[1]] = ch_data->bs_add_harmonic[i] *
1478 (e >= e_a[1] || (ch_data->s_indexmapped[0][m_midpoint - sbr->kx[1]] == 1));
1479 }
1480 }
1481
1482 for (i = 0; i < ilim; i++) {
1483 int additional_sinusoid_present = 0;
1484 for (m = table[i]; m < table[i + 1]; m++) {
1485 if (ch_data->s_indexmapped[e + 1][m - sbr->kx[1]]) {
1486 additional_sinusoid_present = 1;
1487 break;
1488 }
1489 }
1490 memset(&sbr->s_mapped[e][table[i] - sbr->kx[1]], additional_sinusoid_present,
1491 (table[i + 1] - table[i]) * sizeof(sbr->s_mapped[e][0]));
1492 }
1493 }
1494
ecc1f8c3 1495 memcpy(ch_data->s_indexmapped[0], ch_data->s_indexmapped[ch_data->bs_num_env], sizeof(ch_data->s_indexmapped[0]));
ed492b61
AC
1496}
1497
1498/// Estimation of current envelope (14496-3 sp04 p218)
1499static void sbr_env_estimate(float (*e_curr)[48], float X_high[64][40][2],
1500 SpectralBandReplication *sbr, SBRData *ch_data)
1501{
1502 int e, i, m;
1503
1504 if (sbr->bs_interpol_freq) {
ecc1f8c3 1505 for (e = 0; e < ch_data->bs_num_env; e++) {
ed492b61
AC
1506 const float recip_env_size = 0.5f / (ch_data->t_env[e + 1] - ch_data->t_env[e]);
1507 int ilb = ch_data->t_env[e] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1508 int iub = ch_data->t_env[e + 1] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1509
1510 for (m = 0; m < sbr->m[1]; m++) {
1511 float sum = 0.0f;
1512
1513 for (i = ilb; i < iub; i++) {
1514 sum += X_high[m + sbr->kx[1]][i][0] * X_high[m + sbr->kx[1]][i][0] +
1515 X_high[m + sbr->kx[1]][i][1] * X_high[m + sbr->kx[1]][i][1];
1516 }
1517 e_curr[e][m] = sum * recip_env_size;
1518 }
1519 }
1520 } else {
1521 int k, p;
1522
ecc1f8c3 1523 for (e = 0; e < ch_data->bs_num_env; e++) {
ed492b61
AC
1524 const int env_size = 2 * (ch_data->t_env[e + 1] - ch_data->t_env[e]);
1525 int ilb = ch_data->t_env[e] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1526 int iub = ch_data->t_env[e + 1] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1527 const uint16_t *table = ch_data->bs_freq_res[e + 1] ? sbr->f_tablehigh : sbr->f_tablelow;
1528
1529 for (p = 0; p < sbr->n[ch_data->bs_freq_res[e + 1]]; p++) {
1530 float sum = 0.0f;
1531 const int den = env_size * (table[p + 1] - table[p]);
1532
1533 for (k = table[p]; k < table[p + 1]; k++) {
1534 for (i = ilb; i < iub; i++) {
1535 sum += X_high[k][i][0] * X_high[k][i][0] +
1536 X_high[k][i][1] * X_high[k][i][1];
1537 }
1538 }
1539 sum /= den;
1540 for (k = table[p]; k < table[p + 1]; k++) {
1541 e_curr[e][k - sbr->kx[1]] = sum;
1542 }
1543 }
1544 }
1545 }
1546}
1547
1548/**
1549 * Calculation of levels of additional HF signal components (14496-3 sp04 p219)
1550 * and Calculation of gain (14496-3 sp04 p219)
1551 */
1552static void sbr_gain_calc(AACContext *ac, SpectralBandReplication *sbr,
1553 SBRData *ch_data, const int e_a[2])
1554{
1555 int e, k, m;
1556 // max gain limits : -3dB, 0dB, 3dB, inf dB (limiter off)
1557 static const float limgain[4] = { 0.70795, 1.0, 1.41254, 10000000000 };
1558
ecc1f8c3 1559 for (e = 0; e < ch_data->bs_num_env; e++) {
ed492b61
AC
1560 int delta = !((e == e_a[1]) || (e == e_a[0]));
1561 for (k = 0; k < sbr->n_lim; k++) {
1562 float gain_boost, gain_max;
1563 float sum[2] = { 0.0f, 0.0f };
1564 for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1565 const float temp = sbr->e_origmapped[e][m] / (1.0f + sbr->q_mapped[e][m]);
1566 sbr->q_m[e][m] = sqrtf(temp * sbr->q_mapped[e][m]);
1567 sbr->s_m[e][m] = sqrtf(temp * ch_data->s_indexmapped[e + 1][m]);
1568 if (!sbr->s_mapped[e][m]) {
1569 sbr->gain[e][m] = sqrtf(sbr->e_origmapped[e][m] /
1570 ((1.0f + sbr->e_curr[e][m]) *
1571 (1.0f + sbr->q_mapped[e][m] * delta)));
1572 } else {
1573 sbr->gain[e][m] = sqrtf(sbr->e_origmapped[e][m] * sbr->q_mapped[e][m] /
1574 ((1.0f + sbr->e_curr[e][m]) *
1575 (1.0f + sbr->q_mapped[e][m])));
1576 }
1577 }
1578 for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1579 sum[0] += sbr->e_origmapped[e][m];
1580 sum[1] += sbr->e_curr[e][m];
1581 }
1582 gain_max = limgain[sbr->bs_limiter_gains] * sqrtf((FLT_EPSILON + sum[0]) / (FLT_EPSILON + sum[1]));
1583 gain_max = FFMIN(100000, gain_max);
1584 for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1585 float q_m_max = sbr->q_m[e][m] * gain_max / sbr->gain[e][m];
1586 sbr->q_m[e][m] = FFMIN(sbr->q_m[e][m], q_m_max);
1587 sbr->gain[e][m] = FFMIN(sbr->gain[e][m], gain_max);
1588 }
1589 sum[0] = sum[1] = 0.0f;
1590 for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1591 sum[0] += sbr->e_origmapped[e][m];
1592 sum[1] += sbr->e_curr[e][m] * sbr->gain[e][m] * sbr->gain[e][m]
1593 + sbr->s_m[e][m] * sbr->s_m[e][m]
1594 + (delta && !sbr->s_m[e][m]) * sbr->q_m[e][m] * sbr->q_m[e][m];
1595 }
1596 gain_boost = sqrtf((FLT_EPSILON + sum[0]) / (FLT_EPSILON + sum[1]));
1597 gain_boost = FFMIN(1.584893192, gain_boost);
1598 for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1599 sbr->gain[e][m] *= gain_boost;
1600 sbr->q_m[e][m] *= gain_boost;
1601 sbr->s_m[e][m] *= gain_boost;
1602 }
1603 }
1604 }
1605}
1606
1607/// Assembling HF Signals (14496-3 sp04 p220)
1608static void sbr_hf_assemble(float Y[2][38][64][2], const float X_high[64][40][2],
1609 SpectralBandReplication *sbr, SBRData *ch_data,
1610 const int e_a[2])
1611{
1612 int e, i, j, m;
1613 const int h_SL = 4 * !sbr->bs_smoothing_mode;
1614 const int kx = sbr->kx[1];
1615 const int m_max = sbr->m[1];
1616 static const float h_smooth[5] = {
1617 0.33333333333333,
1618 0.30150283239582,
1619 0.21816949906249,
1620 0.11516383427084,
1621 0.03183050093751,
1622 };
1623 static const int8_t phi[2][4] = {
1624 { 1, 0, -1, 0}, // real
1625 { 0, 1, 0, -1}, // imaginary
1626 };
1627 float (*g_temp)[48] = ch_data->g_temp, (*q_temp)[48] = ch_data->q_temp;
1628 int indexnoise = ch_data->f_indexnoise;
1629 int indexsine = ch_data->f_indexsine;
1630 memcpy(Y[0], Y[1], sizeof(Y[0]));
1631
1632 if (sbr->reset) {
1633 for (i = 0; i < h_SL; i++) {
1634 memcpy(g_temp[i + 2*ch_data->t_env[0]], sbr->gain[0], m_max * sizeof(sbr->gain[0][0]));
1635 memcpy(q_temp[i + 2*ch_data->t_env[0]], sbr->q_m[0], m_max * sizeof(sbr->q_m[0][0]));
1636 }
1637 } else if (h_SL) {
1638 memcpy(g_temp[2*ch_data->t_env[0]], g_temp[2*ch_data->t_env_num_env_old], 4*sizeof(g_temp[0]));
1639 memcpy(q_temp[2*ch_data->t_env[0]], q_temp[2*ch_data->t_env_num_env_old], 4*sizeof(q_temp[0]));
1640 }
1641
ecc1f8c3 1642 for (e = 0; e < ch_data->bs_num_env; e++) {
ed492b61
AC
1643 for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {
1644 memcpy(g_temp[h_SL + i], sbr->gain[e], m_max * sizeof(sbr->gain[0][0]));
1645 memcpy(q_temp[h_SL + i], sbr->q_m[e], m_max * sizeof(sbr->q_m[0][0]));
1646 }
1647 }
1648
ecc1f8c3 1649 for (e = 0; e < ch_data->bs_num_env; e++) {
ed492b61
AC
1650 for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {
1651 int phi_sign = (1 - 2*(kx & 1));
1652
1653 if (h_SL && e != e_a[0] && e != e_a[1]) {
1654 for (m = 0; m < m_max; m++) {
1655 const int idx1 = i + h_SL;
1656 float g_filt = 0.0f;
1657 for (j = 0; j <= h_SL; j++)
1658 g_filt += g_temp[idx1 - j][m] * h_smooth[j];
1659 Y[1][i][m + kx][0] =
1660 X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][0] * g_filt;
1661 Y[1][i][m + kx][1] =
1662 X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][1] * g_filt;
1663 }
1664 } else {
1665 for (m = 0; m < m_max; m++) {
1666 const float g_filt = g_temp[i + h_SL][m];
1667 Y[1][i][m + kx][0] =
1668 X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][0] * g_filt;
1669 Y[1][i][m + kx][1] =
1670 X_high[m + kx][i + ENVELOPE_ADJUSTMENT_OFFSET][1] * g_filt;
1671 }
1672 }
1673
1674 if (e != e_a[0] && e != e_a[1]) {
1675 for (m = 0; m < m_max; m++) {
1676 indexnoise = (indexnoise + 1) & 0x1ff;
1677 if (sbr->s_m[e][m]) {
1678 Y[1][i][m + kx][0] +=
1679 sbr->s_m[e][m] * phi[0][indexsine];
1680 Y[1][i][m + kx][1] +=
1681 sbr->s_m[e][m] * (phi[1][indexsine] * phi_sign);
1682 } else {
1683 float q_filt;
1684 if (h_SL) {
1685 const int idx1 = i + h_SL;
1686 q_filt = 0.0f;
1687 for (j = 0; j <= h_SL; j++)
1688 q_filt += q_temp[idx1 - j][m] * h_smooth[j];
1689 } else {
1690 q_filt = q_temp[i][m];
1691 }
1692 Y[1][i][m + kx][0] +=
1693 q_filt * sbr_noise_table[indexnoise][0];
1694 Y[1][i][m + kx][1] +=
1695 q_filt * sbr_noise_table[indexnoise][1];
1696 }
1697 phi_sign = -phi_sign;
1698 }
1699 } else {
1700 indexnoise = (indexnoise + m_max) & 0x1ff;
1701 for (m = 0; m < m_max; m++) {
1702 Y[1][i][m + kx][0] +=
1703 sbr->s_m[e][m] * phi[0][indexsine];
1704 Y[1][i][m + kx][1] +=
1705 sbr->s_m[e][m] * (phi[1][indexsine] * phi_sign);
1706 phi_sign = -phi_sign;
1707 }
1708 }
1709 indexsine = (indexsine + 1) & 3;
1710 }
1711 }
1712 ch_data->f_indexnoise = indexnoise;
1713 ch_data->f_indexsine = indexsine;
1714}
1715
ca6d3f23
AC
1716void ff_sbr_apply(AACContext *ac, SpectralBandReplication *sbr, int id_aac,
1717 float* L, float* R)
ed492b61 1718{
ca6d3f23
AC
1719 int downsampled = ac->m4ac.ext_sample_rate < sbr->sample_rate;
1720 int ch;
1721 int nch = (id_aac == TYPE_CPE) ? 2 : 1;
1722
ed492b61 1723 if (sbr->start) {
ed492b61
AC
1724 sbr_dequant(sbr, id_aac);
1725 }
ca6d3f23 1726 for (ch = 0; ch < nch; ch++) {
d0dedce7 1727 /* decode channel */
932963b8 1728 sbr_qmf_analysis(&ac->dsp, &sbr->mdct_ana, ch ? R : L, sbr->data[ch].analysis_filterbank_samples,
d0dedce7
AC
1729 (float*)sbr->qmf_filter_scratch,
1730 sbr->data[ch].W, 1/(-1024 * ac->sf_scale));
1731 sbr_lf_gen(ac, sbr, sbr->X_low, sbr->data[ch].W);
1732 if (sbr->start) {
1733 sbr_hf_inverse_filter(sbr->alpha0, sbr->alpha1, sbr->X_low, sbr->k[0]);
1734 sbr_chirp(sbr, &sbr->data[ch]);
1735 sbr_hf_gen(ac, sbr, sbr->X_high, sbr->X_low, sbr->alpha0, sbr->alpha1,
1736 sbr->data[ch].bw_array, sbr->data[ch].t_env,
1737 sbr->data[ch].bs_num_env);
1738
1739 // hf_adj
1740 sbr_mapping(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);
1741 sbr_env_estimate(sbr->e_curr, sbr->X_high, sbr, &sbr->data[ch]);
1742 sbr_gain_calc(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);
1743 sbr_hf_assemble(sbr->data[ch].Y, sbr->X_high, sbr, &sbr->data[ch],
1744 sbr->data[ch].e_a);
1745 }
ed492b61 1746
d0dedce7 1747 /* synthesis */
17d59599 1748 sbr_x_gen(sbr, sbr->X[ch], sbr->X_low, sbr->data[ch].Y, ch);
ca6d3f23 1749 }
a2063901
AC
1750
1751 if (ac->m4ac.ps == 1) {
1752 if (sbr->ps.start) {
1753 ff_ps_apply(ac->avctx, &sbr->ps, sbr->X[0], sbr->X[1], sbr->kx[1] + sbr->m[1]);
1754 } else {
1755 memcpy(sbr->X[1], sbr->X[0], sizeof(sbr->X[0]));
1756 }
1757 nch = 2;
1758 }
1759
17d59599 1760 sbr_qmf_synthesis(&ac->dsp, &sbr->mdct, L, sbr->X[0], sbr->qmf_filter_scratch,
ca6d3f23
AC
1761 sbr->data[0].synthesis_filterbank_samples,
1762 &sbr->data[0].synthesis_filterbank_samples_offset,
ed492b61
AC
1763 downsampled,
1764 ac->add_bias, -1024 * ac->sf_scale);
ca6d3f23 1765 if (nch == 2)
17d59599 1766 sbr_qmf_synthesis(&ac->dsp, &sbr->mdct, R, sbr->X[1], sbr->qmf_filter_scratch,
ca6d3f23
AC
1767 sbr->data[1].synthesis_filterbank_samples,
1768 &sbr->data[1].synthesis_filterbank_samples_offset,
1769 downsampled,
1770 ac->add_bias, -1024 * ac->sf_scale);
ed492b61 1771}