b1c4e73ffc5631baa4b1cef0fe3c3ce70a658fce
[libav.git] / libavcodec / aacsbr.c
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 #include "sbrdsp.h"
36 #include "libavutil/libm.h"
37
38 #include <stdint.h>
39 #include <float.h>
40
41 #define ENVELOPE_ADJUSTMENT_OFFSET 2
42 #define NOISE_FLOOR_OFFSET 6.0f
43
44 /**
45 * SBR VLC tables
46 */
47 enum {
48 T_HUFFMAN_ENV_1_5DB,
49 F_HUFFMAN_ENV_1_5DB,
50 T_HUFFMAN_ENV_BAL_1_5DB,
51 F_HUFFMAN_ENV_BAL_1_5DB,
52 T_HUFFMAN_ENV_3_0DB,
53 F_HUFFMAN_ENV_3_0DB,
54 T_HUFFMAN_ENV_BAL_3_0DB,
55 F_HUFFMAN_ENV_BAL_3_0DB,
56 T_HUFFMAN_NOISE_3_0DB,
57 T_HUFFMAN_NOISE_BAL_3_0DB,
58 };
59
60 /**
61 * bs_frame_class - frame class of current SBR frame (14496-3 sp04 p98)
62 */
63 enum {
64 FIXFIX,
65 FIXVAR,
66 VARFIX,
67 VARVAR,
68 };
69
70 enum {
71 EXTENSION_ID_PS = 2,
72 };
73
74 static VLC vlc_sbr[10];
75 static const int8_t vlc_sbr_lav[10] =
76 { 60, 60, 24, 24, 31, 31, 12, 12, 31, 12 };
77 static const DECLARE_ALIGNED(16, float, zero64)[64];
78
79 #define SBR_INIT_VLC_STATIC(num, size) \
80 INIT_VLC_STATIC(&vlc_sbr[num], 9, sbr_tmp[num].table_size / sbr_tmp[num].elem_size, \
81 sbr_tmp[num].sbr_bits , 1, 1, \
82 sbr_tmp[num].sbr_codes, sbr_tmp[num].elem_size, sbr_tmp[num].elem_size, \
83 size)
84
85 #define SBR_VLC_ROW(name) \
86 { name ## _codes, name ## _bits, sizeof(name ## _codes), sizeof(name ## _codes[0]) }
87
88 av_cold void ff_aac_sbr_init(void)
89 {
90 int n;
91 static const struct {
92 const void *sbr_codes, *sbr_bits;
93 const unsigned int table_size, elem_size;
94 } sbr_tmp[] = {
95 SBR_VLC_ROW(t_huffman_env_1_5dB),
96 SBR_VLC_ROW(f_huffman_env_1_5dB),
97 SBR_VLC_ROW(t_huffman_env_bal_1_5dB),
98 SBR_VLC_ROW(f_huffman_env_bal_1_5dB),
99 SBR_VLC_ROW(t_huffman_env_3_0dB),
100 SBR_VLC_ROW(f_huffman_env_3_0dB),
101 SBR_VLC_ROW(t_huffman_env_bal_3_0dB),
102 SBR_VLC_ROW(f_huffman_env_bal_3_0dB),
103 SBR_VLC_ROW(t_huffman_noise_3_0dB),
104 SBR_VLC_ROW(t_huffman_noise_bal_3_0dB),
105 };
106
107 // SBR VLC table initialization
108 SBR_INIT_VLC_STATIC(0, 1098);
109 SBR_INIT_VLC_STATIC(1, 1092);
110 SBR_INIT_VLC_STATIC(2, 768);
111 SBR_INIT_VLC_STATIC(3, 1026);
112 SBR_INIT_VLC_STATIC(4, 1058);
113 SBR_INIT_VLC_STATIC(5, 1052);
114 SBR_INIT_VLC_STATIC(6, 544);
115 SBR_INIT_VLC_STATIC(7, 544);
116 SBR_INIT_VLC_STATIC(8, 592);
117 SBR_INIT_VLC_STATIC(9, 512);
118
119 for (n = 1; n < 320; n++)
120 sbr_qmf_window_us[320 + n] = sbr_qmf_window_us[320 - n];
121 sbr_qmf_window_us[384] = -sbr_qmf_window_us[384];
122 sbr_qmf_window_us[512] = -sbr_qmf_window_us[512];
123
124 for (n = 0; n < 320; n++)
125 sbr_qmf_window_ds[n] = sbr_qmf_window_us[2*n];
126
127 ff_ps_init();
128 }
129
130 /** Places SBR in pure upsampling mode. */
131 static void sbr_turnoff(SpectralBandReplication *sbr) {
132 sbr->start = 0;
133 // Init defults used in pure upsampling mode
134 sbr->kx[1] = 32; //Typo in spec, kx' inits to 32
135 sbr->m[1] = 0;
136 // Reset values for first SBR header
137 sbr->data[0].e_a[1] = sbr->data[1].e_a[1] = -1;
138 memset(&sbr->spectrum_params, -1, sizeof(SpectrumParameters));
139 }
140
141 av_cold void ff_aac_sbr_ctx_init(AACContext *ac, SpectralBandReplication *sbr)
142 {
143 float mdct_scale;
144 sbr->kx[0] = sbr->kx[1];
145 sbr_turnoff(sbr);
146 sbr->data[0].synthesis_filterbank_samples_offset = SBR_SYNTHESIS_BUF_SIZE - (1280 - 128);
147 sbr->data[1].synthesis_filterbank_samples_offset = SBR_SYNTHESIS_BUF_SIZE - (1280 - 128);
148 /* SBR requires samples to be scaled to +/-32768.0 to work correctly.
149 * mdct scale factors are adjusted to scale up from +/-1.0 at analysis
150 * and scale back down at synthesis. */
151 mdct_scale = ac->avctx->sample_fmt == AV_SAMPLE_FMT_FLT ? 32768.0f : 1.0f;
152 ff_mdct_init(&sbr->mdct, 7, 1, 1.0 / (64 * mdct_scale));
153 ff_mdct_init(&sbr->mdct_ana, 7, 1, -2.0 * mdct_scale);
154 ff_ps_ctx_init(&sbr->ps);
155 ff_sbrdsp_init(&sbr->dsp);
156 }
157
158 av_cold void ff_aac_sbr_ctx_close(SpectralBandReplication *sbr)
159 {
160 ff_mdct_end(&sbr->mdct);
161 ff_mdct_end(&sbr->mdct_ana);
162 }
163
164 static int qsort_comparison_function_int16(const void *a, const void *b)
165 {
166 return *(const int16_t *)a - *(const int16_t *)b;
167 }
168
169 static inline int in_table_int16(const int16_t *table, int last_el, int16_t needle)
170 {
171 int i;
172 for (i = 0; i <= last_el; i++)
173 if (table[i] == needle)
174 return 1;
175 return 0;
176 }
177
178 /// Limiter Frequency Band Table (14496-3 sp04 p198)
179 static void sbr_make_f_tablelim(SpectralBandReplication *sbr)
180 {
181 int k;
182 if (sbr->bs_limiter_bands > 0) {
183 static const float bands_warped[3] = { 1.32715174233856803909f, //2^(0.49/1.2)
184 1.18509277094158210129f, //2^(0.49/2)
185 1.11987160404675912501f }; //2^(0.49/3)
186 const float lim_bands_per_octave_warped = bands_warped[sbr->bs_limiter_bands - 1];
187 int16_t patch_borders[7];
188 uint16_t *in = sbr->f_tablelim + 1, *out = sbr->f_tablelim;
189
190 patch_borders[0] = sbr->kx[1];
191 for (k = 1; k <= sbr->num_patches; k++)
192 patch_borders[k] = patch_borders[k-1] + sbr->patch_num_subbands[k-1];
193
194 memcpy(sbr->f_tablelim, sbr->f_tablelow,
195 (sbr->n[0] + 1) * sizeof(sbr->f_tablelow[0]));
196 if (sbr->num_patches > 1)
197 memcpy(sbr->f_tablelim + sbr->n[0] + 1, patch_borders + 1,
198 (sbr->num_patches - 1) * sizeof(patch_borders[0]));
199
200 qsort(sbr->f_tablelim, sbr->num_patches + sbr->n[0],
201 sizeof(sbr->f_tablelim[0]),
202 qsort_comparison_function_int16);
203
204 sbr->n_lim = sbr->n[0] + sbr->num_patches - 1;
205 while (out < sbr->f_tablelim + sbr->n_lim) {
206 if (*in >= *out * lim_bands_per_octave_warped) {
207 *++out = *in++;
208 } else if (*in == *out ||
209 !in_table_int16(patch_borders, sbr->num_patches, *in)) {
210 in++;
211 sbr->n_lim--;
212 } else if (!in_table_int16(patch_borders, sbr->num_patches, *out)) {
213 *out = *in++;
214 sbr->n_lim--;
215 } else {
216 *++out = *in++;
217 }
218 }
219 } else {
220 sbr->f_tablelim[0] = sbr->f_tablelow[0];
221 sbr->f_tablelim[1] = sbr->f_tablelow[sbr->n[0]];
222 sbr->n_lim = 1;
223 }
224 }
225
226 static unsigned int read_sbr_header(SpectralBandReplication *sbr, GetBitContext *gb)
227 {
228 unsigned int cnt = get_bits_count(gb);
229 uint8_t bs_header_extra_1;
230 uint8_t bs_header_extra_2;
231 int old_bs_limiter_bands = sbr->bs_limiter_bands;
232 SpectrumParameters old_spectrum_params;
233
234 sbr->start = 1;
235
236 // Save last spectrum parameters variables to compare to new ones
237 memcpy(&old_spectrum_params, &sbr->spectrum_params, sizeof(SpectrumParameters));
238
239 sbr->bs_amp_res_header = get_bits1(gb);
240 sbr->spectrum_params.bs_start_freq = get_bits(gb, 4);
241 sbr->spectrum_params.bs_stop_freq = get_bits(gb, 4);
242 sbr->spectrum_params.bs_xover_band = get_bits(gb, 3);
243 skip_bits(gb, 2); // bs_reserved
244
245 bs_header_extra_1 = get_bits1(gb);
246 bs_header_extra_2 = get_bits1(gb);
247
248 if (bs_header_extra_1) {
249 sbr->spectrum_params.bs_freq_scale = get_bits(gb, 2);
250 sbr->spectrum_params.bs_alter_scale = get_bits1(gb);
251 sbr->spectrum_params.bs_noise_bands = get_bits(gb, 2);
252 } else {
253 sbr->spectrum_params.bs_freq_scale = 2;
254 sbr->spectrum_params.bs_alter_scale = 1;
255 sbr->spectrum_params.bs_noise_bands = 2;
256 }
257
258 // Check if spectrum parameters changed
259 if (memcmp(&old_spectrum_params, &sbr->spectrum_params, sizeof(SpectrumParameters)))
260 sbr->reset = 1;
261
262 if (bs_header_extra_2) {
263 sbr->bs_limiter_bands = get_bits(gb, 2);
264 sbr->bs_limiter_gains = get_bits(gb, 2);
265 sbr->bs_interpol_freq = get_bits1(gb);
266 sbr->bs_smoothing_mode = get_bits1(gb);
267 } else {
268 sbr->bs_limiter_bands = 2;
269 sbr->bs_limiter_gains = 2;
270 sbr->bs_interpol_freq = 1;
271 sbr->bs_smoothing_mode = 1;
272 }
273
274 if (sbr->bs_limiter_bands != old_bs_limiter_bands && !sbr->reset)
275 sbr_make_f_tablelim(sbr);
276
277 return get_bits_count(gb) - cnt;
278 }
279
280 static int array_min_int16(const int16_t *array, int nel)
281 {
282 int i, min = array[0];
283 for (i = 1; i < nel; i++)
284 min = FFMIN(array[i], min);
285 return min;
286 }
287
288 static void make_bands(int16_t* bands, int start, int stop, int num_bands)
289 {
290 int k, previous, present;
291 float base, prod;
292
293 base = powf((float)stop / start, 1.0f / num_bands);
294 prod = start;
295 previous = start;
296
297 for (k = 0; k < num_bands-1; k++) {
298 prod *= base;
299 present = lrintf(prod);
300 bands[k] = present - previous;
301 previous = present;
302 }
303 bands[num_bands-1] = stop - previous;
304 }
305
306 static int check_n_master(AVCodecContext *avctx, int n_master, int bs_xover_band)
307 {
308 // Requirements (14496-3 sp04 p205)
309 if (n_master <= 0) {
310 av_log(avctx, AV_LOG_ERROR, "Invalid n_master: %d\n", n_master);
311 return -1;
312 }
313 if (bs_xover_band >= n_master) {
314 av_log(avctx, AV_LOG_ERROR,
315 "Invalid bitstream, crossover band index beyond array bounds: %d\n",
316 bs_xover_band);
317 return -1;
318 }
319 return 0;
320 }
321
322 /// Master Frequency Band Table (14496-3 sp04 p194)
323 static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,
324 SpectrumParameters *spectrum)
325 {
326 unsigned int temp, max_qmf_subbands;
327 unsigned int start_min, stop_min;
328 int k;
329 const int8_t *sbr_offset_ptr;
330 int16_t stop_dk[13];
331
332 if (sbr->sample_rate < 32000) {
333 temp = 3000;
334 } else if (sbr->sample_rate < 64000) {
335 temp = 4000;
336 } else
337 temp = 5000;
338
339 start_min = ((temp << 7) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
340 stop_min = ((temp << 8) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
341
342 switch (sbr->sample_rate) {
343 case 16000:
344 sbr_offset_ptr = sbr_offset[0];
345 break;
346 case 22050:
347 sbr_offset_ptr = sbr_offset[1];
348 break;
349 case 24000:
350 sbr_offset_ptr = sbr_offset[2];
351 break;
352 case 32000:
353 sbr_offset_ptr = sbr_offset[3];
354 break;
355 case 44100: case 48000: case 64000:
356 sbr_offset_ptr = sbr_offset[4];
357 break;
358 case 88200: case 96000: case 128000: case 176400: case 192000:
359 sbr_offset_ptr = sbr_offset[5];
360 break;
361 default:
362 av_log(ac->avctx, AV_LOG_ERROR,
363 "Unsupported sample rate for SBR: %d\n", sbr->sample_rate);
364 return -1;
365 }
366
367 sbr->k[0] = start_min + sbr_offset_ptr[spectrum->bs_start_freq];
368
369 if (spectrum->bs_stop_freq < 14) {
370 sbr->k[2] = stop_min;
371 make_bands(stop_dk, stop_min, 64, 13);
372 qsort(stop_dk, 13, sizeof(stop_dk[0]), qsort_comparison_function_int16);
373 for (k = 0; k < spectrum->bs_stop_freq; k++)
374 sbr->k[2] += stop_dk[k];
375 } else if (spectrum->bs_stop_freq == 14) {
376 sbr->k[2] = 2*sbr->k[0];
377 } else if (spectrum->bs_stop_freq == 15) {
378 sbr->k[2] = 3*sbr->k[0];
379 } else {
380 av_log(ac->avctx, AV_LOG_ERROR,
381 "Invalid bs_stop_freq: %d\n", spectrum->bs_stop_freq);
382 return -1;
383 }
384 sbr->k[2] = FFMIN(64, sbr->k[2]);
385
386 // Requirements (14496-3 sp04 p205)
387 if (sbr->sample_rate <= 32000) {
388 max_qmf_subbands = 48;
389 } else if (sbr->sample_rate == 44100) {
390 max_qmf_subbands = 35;
391 } else if (sbr->sample_rate >= 48000)
392 max_qmf_subbands = 32;
393
394 if (sbr->k[2] - sbr->k[0] > max_qmf_subbands) {
395 av_log(ac->avctx, AV_LOG_ERROR,
396 "Invalid bitstream, too many QMF subbands: %d\n", sbr->k[2] - sbr->k[0]);
397 return -1;
398 }
399
400 if (!spectrum->bs_freq_scale) {
401 int dk, k2diff;
402
403 dk = spectrum->bs_alter_scale + 1;
404 sbr->n_master = ((sbr->k[2] - sbr->k[0] + (dk&2)) >> dk) << 1;
405 if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
406 return -1;
407
408 for (k = 1; k <= sbr->n_master; k++)
409 sbr->f_master[k] = dk;
410
411 k2diff = sbr->k[2] - sbr->k[0] - sbr->n_master * dk;
412 if (k2diff < 0) {
413 sbr->f_master[1]--;
414 sbr->f_master[2]-= (k2diff < -1);
415 } else if (k2diff) {
416 sbr->f_master[sbr->n_master]++;
417 }
418
419 sbr->f_master[0] = sbr->k[0];
420 for (k = 1; k <= sbr->n_master; k++)
421 sbr->f_master[k] += sbr->f_master[k - 1];
422
423 } else {
424 int half_bands = 7 - spectrum->bs_freq_scale; // bs_freq_scale = {1,2,3}
425 int two_regions, num_bands_0;
426 int vdk0_max, vdk1_min;
427 int16_t vk0[49];
428
429 if (49 * sbr->k[2] > 110 * sbr->k[0]) {
430 two_regions = 1;
431 sbr->k[1] = 2 * sbr->k[0];
432 } else {
433 two_regions = 0;
434 sbr->k[1] = sbr->k[2];
435 }
436
437 num_bands_0 = lrintf(half_bands * log2f(sbr->k[1] / (float)sbr->k[0])) * 2;
438
439 if (num_bands_0 <= 0) { // Requirements (14496-3 sp04 p205)
440 av_log(ac->avctx, AV_LOG_ERROR, "Invalid num_bands_0: %d\n", num_bands_0);
441 return -1;
442 }
443
444 vk0[0] = 0;
445
446 make_bands(vk0+1, sbr->k[0], sbr->k[1], num_bands_0);
447
448 qsort(vk0 + 1, num_bands_0, sizeof(vk0[1]), qsort_comparison_function_int16);
449 vdk0_max = vk0[num_bands_0];
450
451 vk0[0] = sbr->k[0];
452 for (k = 1; k <= num_bands_0; k++) {
453 if (vk0[k] <= 0) { // Requirements (14496-3 sp04 p205)
454 av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk0[%d]: %d\n", k, vk0[k]);
455 return -1;
456 }
457 vk0[k] += vk0[k-1];
458 }
459
460 if (two_regions) {
461 int16_t vk1[49];
462 float invwarp = spectrum->bs_alter_scale ? 0.76923076923076923077f
463 : 1.0f; // bs_alter_scale = {0,1}
464 int num_bands_1 = lrintf(half_bands * invwarp *
465 log2f(sbr->k[2] / (float)sbr->k[1])) * 2;
466
467 make_bands(vk1+1, sbr->k[1], sbr->k[2], num_bands_1);
468
469 vdk1_min = array_min_int16(vk1 + 1, num_bands_1);
470
471 if (vdk1_min < vdk0_max) {
472 int change;
473 qsort(vk1 + 1, num_bands_1, sizeof(vk1[1]), qsort_comparison_function_int16);
474 change = FFMIN(vdk0_max - vk1[1], (vk1[num_bands_1] - vk1[1]) >> 1);
475 vk1[1] += change;
476 vk1[num_bands_1] -= change;
477 }
478
479 qsort(vk1 + 1, num_bands_1, sizeof(vk1[1]), qsort_comparison_function_int16);
480
481 vk1[0] = sbr->k[1];
482 for (k = 1; k <= num_bands_1; k++) {
483 if (vk1[k] <= 0) { // Requirements (14496-3 sp04 p205)
484 av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk1[%d]: %d\n", k, vk1[k]);
485 return -1;
486 }
487 vk1[k] += vk1[k-1];
488 }
489
490 sbr->n_master = num_bands_0 + num_bands_1;
491 if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
492 return -1;
493 memcpy(&sbr->f_master[0], vk0,
494 (num_bands_0 + 1) * sizeof(sbr->f_master[0]));
495 memcpy(&sbr->f_master[num_bands_0 + 1], vk1 + 1,
496 num_bands_1 * sizeof(sbr->f_master[0]));
497
498 } else {
499 sbr->n_master = num_bands_0;
500 if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))
501 return -1;
502 memcpy(sbr->f_master, vk0, (num_bands_0 + 1) * sizeof(sbr->f_master[0]));
503 }
504 }
505
506 return 0;
507 }
508
509 /// High Frequency Generation - Patch Construction (14496-3 sp04 p216 fig. 4.46)
510 static int sbr_hf_calc_npatches(AACContext *ac, SpectralBandReplication *sbr)
511 {
512 int i, k, sb = 0;
513 int msb = sbr->k[0];
514 int usb = sbr->kx[1];
515 int goal_sb = ((1000 << 11) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
516
517 sbr->num_patches = 0;
518
519 if (goal_sb < sbr->kx[1] + sbr->m[1]) {
520 for (k = 0; sbr->f_master[k] < goal_sb; k++) ;
521 } else
522 k = sbr->n_master;
523
524 do {
525 int odd = 0;
526 for (i = k; i == k || sb > (sbr->k[0] - 1 + msb - odd); i--) {
527 sb = sbr->f_master[i];
528 odd = (sb + sbr->k[0]) & 1;
529 }
530
531 // Requirements (14496-3 sp04 p205) sets the maximum number of patches to 5.
532 // After this check the final number of patches can still be six which is
533 // illegal however the Coding Technologies decoder check stream has a final
534 // count of 6 patches
535 if (sbr->num_patches > 5) {
536 av_log(ac->avctx, AV_LOG_ERROR, "Too many patches: %d\n", sbr->num_patches);
537 return -1;
538 }
539
540 sbr->patch_num_subbands[sbr->num_patches] = FFMAX(sb - usb, 0);
541 sbr->patch_start_subband[sbr->num_patches] = sbr->k[0] - odd - sbr->patch_num_subbands[sbr->num_patches];
542
543 if (sbr->patch_num_subbands[sbr->num_patches] > 0) {
544 usb = sb;
545 msb = sb;
546 sbr->num_patches++;
547 } else
548 msb = sbr->kx[1];
549
550 if (sbr->f_master[k] - sb < 3)
551 k = sbr->n_master;
552 } while (sb != sbr->kx[1] + sbr->m[1]);
553
554 if (sbr->patch_num_subbands[sbr->num_patches-1] < 3 && sbr->num_patches > 1)
555 sbr->num_patches--;
556
557 return 0;
558 }
559
560 /// Derived Frequency Band Tables (14496-3 sp04 p197)
561 static int sbr_make_f_derived(AACContext *ac, SpectralBandReplication *sbr)
562 {
563 int k, temp;
564
565 sbr->n[1] = sbr->n_master - sbr->spectrum_params.bs_xover_band;
566 sbr->n[0] = (sbr->n[1] + 1) >> 1;
567
568 memcpy(sbr->f_tablehigh, &sbr->f_master[sbr->spectrum_params.bs_xover_band],
569 (sbr->n[1] + 1) * sizeof(sbr->f_master[0]));
570 sbr->m[1] = sbr->f_tablehigh[sbr->n[1]] - sbr->f_tablehigh[0];
571 sbr->kx[1] = sbr->f_tablehigh[0];
572
573 // Requirements (14496-3 sp04 p205)
574 if (sbr->kx[1] + sbr->m[1] > 64) {
575 av_log(ac->avctx, AV_LOG_ERROR,
576 "Stop frequency border too high: %d\n", sbr->kx[1] + sbr->m[1]);
577 return -1;
578 }
579 if (sbr->kx[1] > 32) {
580 av_log(ac->avctx, AV_LOG_ERROR, "Start frequency border too high: %d\n", sbr->kx[1]);
581 return -1;
582 }
583
584 sbr->f_tablelow[0] = sbr->f_tablehigh[0];
585 temp = sbr->n[1] & 1;
586 for (k = 1; k <= sbr->n[0]; k++)
587 sbr->f_tablelow[k] = sbr->f_tablehigh[2 * k - temp];
588
589 sbr->n_q = FFMAX(1, lrintf(sbr->spectrum_params.bs_noise_bands *
590 log2f(sbr->k[2] / (float)sbr->kx[1]))); // 0 <= bs_noise_bands <= 3
591 if (sbr->n_q > 5) {
592 av_log(ac->avctx, AV_LOG_ERROR, "Too many noise floor scale factors: %d\n", sbr->n_q);
593 return -1;
594 }
595
596 sbr->f_tablenoise[0] = sbr->f_tablelow[0];
597 temp = 0;
598 for (k = 1; k <= sbr->n_q; k++) {
599 temp += (sbr->n[0] - temp) / (sbr->n_q + 1 - k);
600 sbr->f_tablenoise[k] = sbr->f_tablelow[temp];
601 }
602
603 if (sbr_hf_calc_npatches(ac, sbr) < 0)
604 return -1;
605
606 sbr_make_f_tablelim(sbr);
607
608 sbr->data[0].f_indexnoise = 0;
609 sbr->data[1].f_indexnoise = 0;
610
611 return 0;
612 }
613
614 static av_always_inline void get_bits1_vector(GetBitContext *gb, uint8_t *vec,
615 int elements)
616 {
617 int i;
618 for (i = 0; i < elements; i++) {
619 vec[i] = get_bits1(gb);
620 }
621 }
622
623 /** ceil(log2(index+1)) */
624 static const int8_t ceil_log2[] = {
625 0, 1, 2, 2, 3, 3,
626 };
627
628 static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,
629 GetBitContext *gb, SBRData *ch_data)
630 {
631 int i;
632 unsigned bs_pointer = 0;
633 // frameLengthFlag ? 15 : 16; 960 sample length frames unsupported; this value is numTimeSlots
634 int abs_bord_trail = 16;
635 int num_rel_lead, num_rel_trail;
636 unsigned bs_num_env_old = ch_data->bs_num_env;
637
638 ch_data->bs_freq_res[0] = ch_data->bs_freq_res[ch_data->bs_num_env];
639 ch_data->bs_amp_res = sbr->bs_amp_res_header;
640 ch_data->t_env_num_env_old = ch_data->t_env[bs_num_env_old];
641
642 switch (ch_data->bs_frame_class = get_bits(gb, 2)) {
643 case FIXFIX:
644 ch_data->bs_num_env = 1 << get_bits(gb, 2);
645 num_rel_lead = ch_data->bs_num_env - 1;
646 if (ch_data->bs_num_env == 1)
647 ch_data->bs_amp_res = 0;
648
649 if (ch_data->bs_num_env > 4) {
650 av_log(ac->avctx, AV_LOG_ERROR,
651 "Invalid bitstream, too many SBR envelopes in FIXFIX type SBR frame: %d\n",
652 ch_data->bs_num_env);
653 return -1;
654 }
655
656 ch_data->t_env[0] = 0;
657 ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
658
659 abs_bord_trail = (abs_bord_trail + (ch_data->bs_num_env >> 1)) /
660 ch_data->bs_num_env;
661 for (i = 0; i < num_rel_lead; i++)
662 ch_data->t_env[i + 1] = ch_data->t_env[i] + abs_bord_trail;
663
664 ch_data->bs_freq_res[1] = get_bits1(gb);
665 for (i = 1; i < ch_data->bs_num_env; i++)
666 ch_data->bs_freq_res[i + 1] = ch_data->bs_freq_res[1];
667 break;
668 case FIXVAR:
669 abs_bord_trail += get_bits(gb, 2);
670 num_rel_trail = get_bits(gb, 2);
671 ch_data->bs_num_env = num_rel_trail + 1;
672 ch_data->t_env[0] = 0;
673 ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
674
675 for (i = 0; i < num_rel_trail; i++)
676 ch_data->t_env[ch_data->bs_num_env - 1 - i] =
677 ch_data->t_env[ch_data->bs_num_env - i] - 2 * get_bits(gb, 2) - 2;
678
679 bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
680
681 for (i = 0; i < ch_data->bs_num_env; i++)
682 ch_data->bs_freq_res[ch_data->bs_num_env - i] = get_bits1(gb);
683 break;
684 case VARFIX:
685 ch_data->t_env[0] = get_bits(gb, 2);
686 num_rel_lead = get_bits(gb, 2);
687 ch_data->bs_num_env = num_rel_lead + 1;
688 ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
689
690 for (i = 0; i < num_rel_lead; i++)
691 ch_data->t_env[i + 1] = ch_data->t_env[i] + 2 * get_bits(gb, 2) + 2;
692
693 bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
694
695 get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env);
696 break;
697 case VARVAR:
698 ch_data->t_env[0] = get_bits(gb, 2);
699 abs_bord_trail += get_bits(gb, 2);
700 num_rel_lead = get_bits(gb, 2);
701 num_rel_trail = get_bits(gb, 2);
702 ch_data->bs_num_env = num_rel_lead + num_rel_trail + 1;
703
704 if (ch_data->bs_num_env > 5) {
705 av_log(ac->avctx, AV_LOG_ERROR,
706 "Invalid bitstream, too many SBR envelopes in VARVAR type SBR frame: %d\n",
707 ch_data->bs_num_env);
708 return -1;
709 }
710
711 ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail;
712
713 for (i = 0; i < num_rel_lead; i++)
714 ch_data->t_env[i + 1] = ch_data->t_env[i] + 2 * get_bits(gb, 2) + 2;
715 for (i = 0; i < num_rel_trail; i++)
716 ch_data->t_env[ch_data->bs_num_env - 1 - i] =
717 ch_data->t_env[ch_data->bs_num_env - i] - 2 * get_bits(gb, 2) - 2;
718
719 bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env]);
720
721 get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env);
722 break;
723 }
724
725 if (bs_pointer > ch_data->bs_num_env + 1) {
726 av_log(ac->avctx, AV_LOG_ERROR,
727 "Invalid bitstream, bs_pointer points to a middle noise border outside the time borders table: %d\n",
728 bs_pointer);
729 return -1;
730 }
731
732 for (i = 1; i <= ch_data->bs_num_env; i++) {
733 if (ch_data->t_env[i-1] > ch_data->t_env[i]) {
734 av_log(ac->avctx, AV_LOG_ERROR, "Non monotone time borders\n");
735 return -1;
736 }
737 }
738
739 ch_data->bs_num_noise = (ch_data->bs_num_env > 1) + 1;
740
741 ch_data->t_q[0] = ch_data->t_env[0];
742 ch_data->t_q[ch_data->bs_num_noise] = ch_data->t_env[ch_data->bs_num_env];
743 if (ch_data->bs_num_noise > 1) {
744 unsigned int idx;
745 if (ch_data->bs_frame_class == FIXFIX) {
746 idx = ch_data->bs_num_env >> 1;
747 } else if (ch_data->bs_frame_class & 1) { // FIXVAR or VARVAR
748 idx = ch_data->bs_num_env - FFMAX(bs_pointer - 1, 1);
749 } else { // VARFIX
750 if (!bs_pointer)
751 idx = 1;
752 else if (bs_pointer == 1)
753 idx = ch_data->bs_num_env - 1;
754 else // bs_pointer > 1
755 idx = bs_pointer - 1;
756 }
757 ch_data->t_q[1] = ch_data->t_env[idx];
758 }
759
760 ch_data->e_a[0] = -(ch_data->e_a[1] != bs_num_env_old); // l_APrev
761 ch_data->e_a[1] = -1;
762 if ((ch_data->bs_frame_class & 1) && bs_pointer) { // FIXVAR or VARVAR and bs_pointer != 0
763 ch_data->e_a[1] = ch_data->bs_num_env + 1 - bs_pointer;
764 } else if ((ch_data->bs_frame_class == 2) && (bs_pointer > 1)) // VARFIX and bs_pointer > 1
765 ch_data->e_a[1] = bs_pointer - 1;
766
767 return 0;
768 }
769
770 static void copy_sbr_grid(SBRData *dst, const SBRData *src) {
771 //These variables are saved from the previous frame rather than copied
772 dst->bs_freq_res[0] = dst->bs_freq_res[dst->bs_num_env];
773 dst->t_env_num_env_old = dst->t_env[dst->bs_num_env];
774 dst->e_a[0] = -(dst->e_a[1] != dst->bs_num_env);
775
776 //These variables are read from the bitstream and therefore copied
777 memcpy(dst->bs_freq_res+1, src->bs_freq_res+1, sizeof(dst->bs_freq_res)-sizeof(*dst->bs_freq_res));
778 memcpy(dst->t_env, src->t_env, sizeof(dst->t_env));
779 memcpy(dst->t_q, src->t_q, sizeof(dst->t_q));
780 dst->bs_num_env = src->bs_num_env;
781 dst->bs_amp_res = src->bs_amp_res;
782 dst->bs_num_noise = src->bs_num_noise;
783 dst->bs_frame_class = src->bs_frame_class;
784 dst->e_a[1] = src->e_a[1];
785 }
786
787 /// Read how the envelope and noise floor data is delta coded
788 static void read_sbr_dtdf(SpectralBandReplication *sbr, GetBitContext *gb,
789 SBRData *ch_data)
790 {
791 get_bits1_vector(gb, ch_data->bs_df_env, ch_data->bs_num_env);
792 get_bits1_vector(gb, ch_data->bs_df_noise, ch_data->bs_num_noise);
793 }
794
795 /// Read inverse filtering data
796 static void read_sbr_invf(SpectralBandReplication *sbr, GetBitContext *gb,
797 SBRData *ch_data)
798 {
799 int i;
800
801 memcpy(ch_data->bs_invf_mode[1], ch_data->bs_invf_mode[0], 5 * sizeof(uint8_t));
802 for (i = 0; i < sbr->n_q; i++)
803 ch_data->bs_invf_mode[0][i] = get_bits(gb, 2);
804 }
805
806 static void read_sbr_envelope(SpectralBandReplication *sbr, GetBitContext *gb,
807 SBRData *ch_data, int ch)
808 {
809 int bits;
810 int i, j, k;
811 VLC_TYPE (*t_huff)[2], (*f_huff)[2];
812 int t_lav, f_lav;
813 const int delta = (ch == 1 && sbr->bs_coupling == 1) + 1;
814 const int odd = sbr->n[1] & 1;
815
816 if (sbr->bs_coupling && ch) {
817 if (ch_data->bs_amp_res) {
818 bits = 5;
819 t_huff = vlc_sbr[T_HUFFMAN_ENV_BAL_3_0DB].table;
820 t_lav = vlc_sbr_lav[T_HUFFMAN_ENV_BAL_3_0DB];
821 f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_3_0DB].table;
822 f_lav = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_3_0DB];
823 } else {
824 bits = 6;
825 t_huff = vlc_sbr[T_HUFFMAN_ENV_BAL_1_5DB].table;
826 t_lav = vlc_sbr_lav[T_HUFFMAN_ENV_BAL_1_5DB];
827 f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_1_5DB].table;
828 f_lav = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_1_5DB];
829 }
830 } else {
831 if (ch_data->bs_amp_res) {
832 bits = 6;
833 t_huff = vlc_sbr[T_HUFFMAN_ENV_3_0DB].table;
834 t_lav = vlc_sbr_lav[T_HUFFMAN_ENV_3_0DB];
835 f_huff = vlc_sbr[F_HUFFMAN_ENV_3_0DB].table;
836 f_lav = vlc_sbr_lav[F_HUFFMAN_ENV_3_0DB];
837 } else {
838 bits = 7;
839 t_huff = vlc_sbr[T_HUFFMAN_ENV_1_5DB].table;
840 t_lav = vlc_sbr_lav[T_HUFFMAN_ENV_1_5DB];
841 f_huff = vlc_sbr[F_HUFFMAN_ENV_1_5DB].table;
842 f_lav = vlc_sbr_lav[F_HUFFMAN_ENV_1_5DB];
843 }
844 }
845
846 for (i = 0; i < ch_data->bs_num_env; i++) {
847 if (ch_data->bs_df_env[i]) {
848 // bs_freq_res[0] == bs_freq_res[bs_num_env] from prev frame
849 if (ch_data->bs_freq_res[i + 1] == ch_data->bs_freq_res[i]) {
850 for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++)
851 ch_data->env_facs[i + 1][j] = ch_data->env_facs[i][j] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
852 } else if (ch_data->bs_freq_res[i + 1]) {
853 for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {
854 k = (j + odd) >> 1; // find k such that f_tablelow[k] <= f_tablehigh[j] < f_tablelow[k + 1]
855 ch_data->env_facs[i + 1][j] = ch_data->env_facs[i][k] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
856 }
857 } else {
858 for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {
859 k = j ? 2*j - odd : 0; // find k such that f_tablehigh[k] == f_tablelow[j]
860 ch_data->env_facs[i + 1][j] = ch_data->env_facs[i][k] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);
861 }
862 }
863 } else {
864 ch_data->env_facs[i + 1][0] = delta * get_bits(gb, bits); // bs_env_start_value_balance
865 for (j = 1; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++)
866 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);
867 }
868 }
869
870 //assign 0th elements of env_facs from last elements
871 memcpy(ch_data->env_facs[0], ch_data->env_facs[ch_data->bs_num_env],
872 sizeof(ch_data->env_facs[0]));
873 }
874
875 static void read_sbr_noise(SpectralBandReplication *sbr, GetBitContext *gb,
876 SBRData *ch_data, int ch)
877 {
878 int i, j;
879 VLC_TYPE (*t_huff)[2], (*f_huff)[2];
880 int t_lav, f_lav;
881 int delta = (ch == 1 && sbr->bs_coupling == 1) + 1;
882
883 if (sbr->bs_coupling && ch) {
884 t_huff = vlc_sbr[T_HUFFMAN_NOISE_BAL_3_0DB].table;
885 t_lav = vlc_sbr_lav[T_HUFFMAN_NOISE_BAL_3_0DB];
886 f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_3_0DB].table;
887 f_lav = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_3_0DB];
888 } else {
889 t_huff = vlc_sbr[T_HUFFMAN_NOISE_3_0DB].table;
890 t_lav = vlc_sbr_lav[T_HUFFMAN_NOISE_3_0DB];
891 f_huff = vlc_sbr[F_HUFFMAN_ENV_3_0DB].table;
892 f_lav = vlc_sbr_lav[F_HUFFMAN_ENV_3_0DB];
893 }
894
895 for (i = 0; i < ch_data->bs_num_noise; i++) {
896 if (ch_data->bs_df_noise[i]) {
897 for (j = 0; j < sbr->n_q; j++)
898 ch_data->noise_facs[i + 1][j] = ch_data->noise_facs[i][j] + delta * (get_vlc2(gb, t_huff, 9, 2) - t_lav);
899 } else {
900 ch_data->noise_facs[i + 1][0] = delta * get_bits(gb, 5); // bs_noise_start_value_balance or bs_noise_start_value_level
901 for (j = 1; j < sbr->n_q; j++)
902 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);
903 }
904 }
905
906 //assign 0th elements of noise_facs from last elements
907 memcpy(ch_data->noise_facs[0], ch_data->noise_facs[ch_data->bs_num_noise],
908 sizeof(ch_data->noise_facs[0]));
909 }
910
911 static void read_sbr_extension(AACContext *ac, SpectralBandReplication *sbr,
912 GetBitContext *gb,
913 int bs_extension_id, int *num_bits_left)
914 {
915 switch (bs_extension_id) {
916 case EXTENSION_ID_PS:
917 if (!ac->oc[1].m4ac.ps) {
918 av_log(ac->avctx, AV_LOG_ERROR, "Parametric Stereo signaled to be not-present but was found in the bitstream.\n");
919 skip_bits_long(gb, *num_bits_left); // bs_fill_bits
920 *num_bits_left = 0;
921 } else {
922 #if 1
923 *num_bits_left -= ff_ps_read_data(ac->avctx, gb, &sbr->ps, *num_bits_left);
924 #else
925 av_log_missing_feature(ac->avctx, "Parametric Stereo", 0);
926 skip_bits_long(gb, *num_bits_left); // bs_fill_bits
927 *num_bits_left = 0;
928 #endif
929 }
930 break;
931 default:
932 av_log_missing_feature(ac->avctx, "Reserved SBR extensions", 1);
933 skip_bits_long(gb, *num_bits_left); // bs_fill_bits
934 *num_bits_left = 0;
935 break;
936 }
937 }
938
939 static int read_sbr_single_channel_element(AACContext *ac,
940 SpectralBandReplication *sbr,
941 GetBitContext *gb)
942 {
943 if (get_bits1(gb)) // bs_data_extra
944 skip_bits(gb, 4); // bs_reserved
945
946 if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))
947 return -1;
948 read_sbr_dtdf(sbr, gb, &sbr->data[0]);
949 read_sbr_invf(sbr, gb, &sbr->data[0]);
950 read_sbr_envelope(sbr, gb, &sbr->data[0], 0);
951 read_sbr_noise(sbr, gb, &sbr->data[0], 0);
952
953 if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb)))
954 get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]);
955
956 return 0;
957 }
958
959 static int read_sbr_channel_pair_element(AACContext *ac,
960 SpectralBandReplication *sbr,
961 GetBitContext *gb)
962 {
963 if (get_bits1(gb)) // bs_data_extra
964 skip_bits(gb, 8); // bs_reserved
965
966 if ((sbr->bs_coupling = get_bits1(gb))) {
967 if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))
968 return -1;
969 copy_sbr_grid(&sbr->data[1], &sbr->data[0]);
970 read_sbr_dtdf(sbr, gb, &sbr->data[0]);
971 read_sbr_dtdf(sbr, gb, &sbr->data[1]);
972 read_sbr_invf(sbr, gb, &sbr->data[0]);
973 memcpy(sbr->data[1].bs_invf_mode[1], sbr->data[1].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0]));
974 memcpy(sbr->data[1].bs_invf_mode[0], sbr->data[0].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0]));
975 read_sbr_envelope(sbr, gb, &sbr->data[0], 0);
976 read_sbr_noise(sbr, gb, &sbr->data[0], 0);
977 read_sbr_envelope(sbr, gb, &sbr->data[1], 1);
978 read_sbr_noise(sbr, gb, &sbr->data[1], 1);
979 } else {
980 if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]) ||
981 read_sbr_grid(ac, sbr, gb, &sbr->data[1]))
982 return -1;
983 read_sbr_dtdf(sbr, gb, &sbr->data[0]);
984 read_sbr_dtdf(sbr, gb, &sbr->data[1]);
985 read_sbr_invf(sbr, gb, &sbr->data[0]);
986 read_sbr_invf(sbr, gb, &sbr->data[1]);
987 read_sbr_envelope(sbr, gb, &sbr->data[0], 0);
988 read_sbr_envelope(sbr, gb, &sbr->data[1], 1);
989 read_sbr_noise(sbr, gb, &sbr->data[0], 0);
990 read_sbr_noise(sbr, gb, &sbr->data[1], 1);
991 }
992
993 if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb)))
994 get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]);
995 if ((sbr->data[1].bs_add_harmonic_flag = get_bits1(gb)))
996 get_bits1_vector(gb, sbr->data[1].bs_add_harmonic, sbr->n[1]);
997
998 return 0;
999 }
1000
1001 static unsigned int read_sbr_data(AACContext *ac, SpectralBandReplication *sbr,
1002 GetBitContext *gb, int id_aac)
1003 {
1004 unsigned int cnt = get_bits_count(gb);
1005
1006 if (id_aac == TYPE_SCE || id_aac == TYPE_CCE) {
1007 if (read_sbr_single_channel_element(ac, sbr, gb)) {
1008 sbr_turnoff(sbr);
1009 return get_bits_count(gb) - cnt;
1010 }
1011 } else if (id_aac == TYPE_CPE) {
1012 if (read_sbr_channel_pair_element(ac, sbr, gb)) {
1013 sbr_turnoff(sbr);
1014 return get_bits_count(gb) - cnt;
1015 }
1016 } else {
1017 av_log(ac->avctx, AV_LOG_ERROR,
1018 "Invalid bitstream - cannot apply SBR to element type %d\n", id_aac);
1019 sbr_turnoff(sbr);
1020 return get_bits_count(gb) - cnt;
1021 }
1022 if (get_bits1(gb)) { // bs_extended_data
1023 int num_bits_left = get_bits(gb, 4); // bs_extension_size
1024 if (num_bits_left == 15)
1025 num_bits_left += get_bits(gb, 8); // bs_esc_count
1026
1027 num_bits_left <<= 3;
1028 while (num_bits_left > 7) {
1029 num_bits_left -= 2;
1030 read_sbr_extension(ac, sbr, gb, get_bits(gb, 2), &num_bits_left); // bs_extension_id
1031 }
1032 if (num_bits_left < 0) {
1033 av_log(ac->avctx, AV_LOG_ERROR, "SBR Extension over read.\n");
1034 }
1035 if (num_bits_left > 0)
1036 skip_bits(gb, num_bits_left);
1037 }
1038
1039 return get_bits_count(gb) - cnt;
1040 }
1041
1042 static void sbr_reset(AACContext *ac, SpectralBandReplication *sbr)
1043 {
1044 int err;
1045 err = sbr_make_f_master(ac, sbr, &sbr->spectrum_params);
1046 if (err >= 0)
1047 err = sbr_make_f_derived(ac, sbr);
1048 if (err < 0) {
1049 av_log(ac->avctx, AV_LOG_ERROR,
1050 "SBR reset failed. Switching SBR to pure upsampling mode.\n");
1051 sbr_turnoff(sbr);
1052 }
1053 }
1054
1055 /**
1056 * Decode Spectral Band Replication extension data; reference: table 4.55.
1057 *
1058 * @param crc flag indicating the presence of CRC checksum
1059 * @param cnt length of TYPE_FIL syntactic element in bytes
1060 *
1061 * @return Returns number of bytes consumed from the TYPE_FIL element.
1062 */
1063 int ff_decode_sbr_extension(AACContext *ac, SpectralBandReplication *sbr,
1064 GetBitContext *gb_host, int crc, int cnt, int id_aac)
1065 {
1066 unsigned int num_sbr_bits = 0, num_align_bits;
1067 unsigned bytes_read;
1068 GetBitContext gbc = *gb_host, *gb = &gbc;
1069 skip_bits_long(gb_host, cnt*8 - 4);
1070
1071 sbr->reset = 0;
1072
1073 if (!sbr->sample_rate)
1074 sbr->sample_rate = 2 * ac->oc[1].m4ac.sample_rate; //TODO use the nominal sample rate for arbitrary sample rate support
1075 if (!ac->oc[1].m4ac.ext_sample_rate)
1076 ac->oc[1].m4ac.ext_sample_rate = 2 * ac->oc[1].m4ac.sample_rate;
1077
1078 if (crc) {
1079 skip_bits(gb, 10); // bs_sbr_crc_bits; TODO - implement CRC check
1080 num_sbr_bits += 10;
1081 }
1082
1083 //Save some state from the previous frame.
1084 sbr->kx[0] = sbr->kx[1];
1085 sbr->m[0] = sbr->m[1];
1086 sbr->kx_and_m_pushed = 1;
1087
1088 num_sbr_bits++;
1089 if (get_bits1(gb)) // bs_header_flag
1090 num_sbr_bits += read_sbr_header(sbr, gb);
1091
1092 if (sbr->reset)
1093 sbr_reset(ac, sbr);
1094
1095 if (sbr->start)
1096 num_sbr_bits += read_sbr_data(ac, sbr, gb, id_aac);
1097
1098 num_align_bits = ((cnt << 3) - 4 - num_sbr_bits) & 7;
1099 bytes_read = ((num_sbr_bits + num_align_bits + 4) >> 3);
1100
1101 if (bytes_read > cnt) {
1102 av_log(ac->avctx, AV_LOG_ERROR,
1103 "Expected to read %d SBR bytes actually read %d.\n", cnt, bytes_read);
1104 }
1105 return cnt;
1106 }
1107
1108 /// Dequantization and stereo decoding (14496-3 sp04 p203)
1109 static void sbr_dequant(SpectralBandReplication *sbr, int id_aac)
1110 {
1111 int k, e;
1112 int ch;
1113
1114 if (id_aac == TYPE_CPE && sbr->bs_coupling) {
1115 float alpha = sbr->data[0].bs_amp_res ? 1.0f : 0.5f;
1116 float pan_offset = sbr->data[0].bs_amp_res ? 12.0f : 24.0f;
1117 for (e = 1; e <= sbr->data[0].bs_num_env; e++) {
1118 for (k = 0; k < sbr->n[sbr->data[0].bs_freq_res[e]]; k++) {
1119 float temp1 = exp2f(sbr->data[0].env_facs[e][k] * alpha + 7.0f);
1120 float temp2 = exp2f((pan_offset - sbr->data[1].env_facs[e][k]) * alpha);
1121 float fac = temp1 / (1.0f + temp2);
1122 sbr->data[0].env_facs[e][k] = fac;
1123 sbr->data[1].env_facs[e][k] = fac * temp2;
1124 }
1125 }
1126 for (e = 1; e <= sbr->data[0].bs_num_noise; e++) {
1127 for (k = 0; k < sbr->n_q; k++) {
1128 float temp1 = exp2f(NOISE_FLOOR_OFFSET - sbr->data[0].noise_facs[e][k] + 1);
1129 float temp2 = exp2f(12 - sbr->data[1].noise_facs[e][k]);
1130 float fac = temp1 / (1.0f + temp2);
1131 sbr->data[0].noise_facs[e][k] = fac;
1132 sbr->data[1].noise_facs[e][k] = fac * temp2;
1133 }
1134 }
1135 } else { // SCE or one non-coupled CPE
1136 for (ch = 0; ch < (id_aac == TYPE_CPE) + 1; ch++) {
1137 float alpha = sbr->data[ch].bs_amp_res ? 1.0f : 0.5f;
1138 for (e = 1; e <= sbr->data[ch].bs_num_env; e++)
1139 for (k = 0; k < sbr->n[sbr->data[ch].bs_freq_res[e]]; k++)
1140 sbr->data[ch].env_facs[e][k] =
1141 exp2f(alpha * sbr->data[ch].env_facs[e][k] + 6.0f);
1142 for (e = 1; e <= sbr->data[ch].bs_num_noise; e++)
1143 for (k = 0; k < sbr->n_q; k++)
1144 sbr->data[ch].noise_facs[e][k] =
1145 exp2f(NOISE_FLOOR_OFFSET - sbr->data[ch].noise_facs[e][k]);
1146 }
1147 }
1148 }
1149
1150 /**
1151 * Analysis QMF Bank (14496-3 sp04 p206)
1152 *
1153 * @param x pointer to the beginning of the first sample window
1154 * @param W array of complex-valued samples split into subbands
1155 */
1156 static void sbr_qmf_analysis(DSPContext *dsp, FFTContext *mdct,
1157 SBRDSPContext *sbrdsp, const float *in, float *x,
1158 float z[320], float W[2][32][32][2])
1159 {
1160 int i;
1161 memcpy(W[0], W[1], sizeof(W[0]));
1162 memcpy(x , x+1024, (320-32)*sizeof(x[0]));
1163 memcpy(x+288, in, 1024*sizeof(x[0]));
1164 for (i = 0; i < 32; i++) { // numTimeSlots*RATE = 16*2 as 960 sample frames
1165 // are not supported
1166 dsp->vector_fmul_reverse(z, sbr_qmf_window_ds, x, 320);
1167 sbrdsp->sum64x5(z);
1168 sbrdsp->qmf_pre_shuffle(z);
1169 mdct->imdct_half(mdct, z, z+64);
1170 sbrdsp->qmf_post_shuffle(W[1][i], z);
1171 x += 32;
1172 }
1173 }
1174
1175 /**
1176 * Synthesis QMF Bank (14496-3 sp04 p206) and Downsampled Synthesis QMF Bank
1177 * (14496-3 sp04 p206)
1178 */
1179 static void sbr_qmf_synthesis(DSPContext *dsp, FFTContext *mdct,
1180 SBRDSPContext *sbrdsp,
1181 float *out, float X[2][38][64],
1182 float mdct_buf[2][64],
1183 float *v0, int *v_off, const unsigned int div)
1184 {
1185 int i, n;
1186 const float *sbr_qmf_window = div ? sbr_qmf_window_ds : sbr_qmf_window_us;
1187 const int step = 128 >> div;
1188 float *v;
1189 for (i = 0; i < 32; i++) {
1190 if (*v_off < step) {
1191 int saved_samples = (1280 - 128) >> div;
1192 memcpy(&v0[SBR_SYNTHESIS_BUF_SIZE - saved_samples], v0, saved_samples * sizeof(float));
1193 *v_off = SBR_SYNTHESIS_BUF_SIZE - saved_samples - step;
1194 } else {
1195 *v_off -= step;
1196 }
1197 v = v0 + *v_off;
1198 if (div) {
1199 for (n = 0; n < 32; n++) {
1200 X[0][i][ n] = -X[0][i][n];
1201 X[0][i][32+n] = X[1][i][31-n];
1202 }
1203 mdct->imdct_half(mdct, mdct_buf[0], X[0][i]);
1204 sbrdsp->qmf_deint_neg(v, mdct_buf[0]);
1205 } else {
1206 sbrdsp->neg_odd_64(X[1][i]);
1207 mdct->imdct_half(mdct, mdct_buf[0], X[0][i]);
1208 mdct->imdct_half(mdct, mdct_buf[1], X[1][i]);
1209 sbrdsp->qmf_deint_bfly(v, mdct_buf[1], mdct_buf[0]);
1210 }
1211 dsp->vector_fmul_add(out, v , sbr_qmf_window , zero64, 64 >> div);
1212 dsp->vector_fmul_add(out, v + ( 192 >> div), sbr_qmf_window + ( 64 >> div), out , 64 >> div);
1213 dsp->vector_fmul_add(out, v + ( 256 >> div), sbr_qmf_window + (128 >> div), out , 64 >> div);
1214 dsp->vector_fmul_add(out, v + ( 448 >> div), sbr_qmf_window + (192 >> div), out , 64 >> div);
1215 dsp->vector_fmul_add(out, v + ( 512 >> div), sbr_qmf_window + (256 >> div), out , 64 >> div);
1216 dsp->vector_fmul_add(out, v + ( 704 >> div), sbr_qmf_window + (320 >> div), out , 64 >> div);
1217 dsp->vector_fmul_add(out, v + ( 768 >> div), sbr_qmf_window + (384 >> div), out , 64 >> div);
1218 dsp->vector_fmul_add(out, v + ( 960 >> div), sbr_qmf_window + (448 >> div), out , 64 >> div);
1219 dsp->vector_fmul_add(out, v + (1024 >> div), sbr_qmf_window + (512 >> div), out , 64 >> div);
1220 dsp->vector_fmul_add(out, v + (1216 >> div), sbr_qmf_window + (576 >> div), out , 64 >> div);
1221 out += 64 >> div;
1222 }
1223 }
1224
1225 /** High Frequency Generation (14496-3 sp04 p214+) and Inverse Filtering
1226 * (14496-3 sp04 p214)
1227 * Warning: This routine does not seem numerically stable.
1228 */
1229 static void sbr_hf_inverse_filter(SBRDSPContext *dsp,
1230 float (*alpha0)[2], float (*alpha1)[2],
1231 const float X_low[32][40][2], int k0)
1232 {
1233 int k;
1234 for (k = 0; k < k0; k++) {
1235 LOCAL_ALIGNED_16(float, phi, [3], [2][2]);
1236 float dk;
1237
1238 dsp->autocorrelate(X_low[k], phi);
1239
1240 dk = phi[2][1][0] * phi[1][0][0] -
1241 (phi[1][1][0] * phi[1][1][0] + phi[1][1][1] * phi[1][1][1]) / 1.000001f;
1242
1243 if (!dk) {
1244 alpha1[k][0] = 0;
1245 alpha1[k][1] = 0;
1246 } else {
1247 float temp_real, temp_im;
1248 temp_real = phi[0][0][0] * phi[1][1][0] -
1249 phi[0][0][1] * phi[1][1][1] -
1250 phi[0][1][0] * phi[1][0][0];
1251 temp_im = phi[0][0][0] * phi[1][1][1] +
1252 phi[0][0][1] * phi[1][1][0] -
1253 phi[0][1][1] * phi[1][0][0];
1254
1255 alpha1[k][0] = temp_real / dk;
1256 alpha1[k][1] = temp_im / dk;
1257 }
1258
1259 if (!phi[1][0][0]) {
1260 alpha0[k][0] = 0;
1261 alpha0[k][1] = 0;
1262 } else {
1263 float temp_real, temp_im;
1264 temp_real = phi[0][0][0] + alpha1[k][0] * phi[1][1][0] +
1265 alpha1[k][1] * phi[1][1][1];
1266 temp_im = phi[0][0][1] + alpha1[k][1] * phi[1][1][0] -
1267 alpha1[k][0] * phi[1][1][1];
1268
1269 alpha0[k][0] = -temp_real / phi[1][0][0];
1270 alpha0[k][1] = -temp_im / phi[1][0][0];
1271 }
1272
1273 if (alpha1[k][0] * alpha1[k][0] + alpha1[k][1] * alpha1[k][1] >= 16.0f ||
1274 alpha0[k][0] * alpha0[k][0] + alpha0[k][1] * alpha0[k][1] >= 16.0f) {
1275 alpha1[k][0] = 0;
1276 alpha1[k][1] = 0;
1277 alpha0[k][0] = 0;
1278 alpha0[k][1] = 0;
1279 }
1280 }
1281 }
1282
1283 /// Chirp Factors (14496-3 sp04 p214)
1284 static void sbr_chirp(SpectralBandReplication *sbr, SBRData *ch_data)
1285 {
1286 int i;
1287 float new_bw;
1288 static const float bw_tab[] = { 0.0f, 0.75f, 0.9f, 0.98f };
1289
1290 for (i = 0; i < sbr->n_q; i++) {
1291 if (ch_data->bs_invf_mode[0][i] + ch_data->bs_invf_mode[1][i] == 1) {
1292 new_bw = 0.6f;
1293 } else
1294 new_bw = bw_tab[ch_data->bs_invf_mode[0][i]];
1295
1296 if (new_bw < ch_data->bw_array[i]) {
1297 new_bw = 0.75f * new_bw + 0.25f * ch_data->bw_array[i];
1298 } else
1299 new_bw = 0.90625f * new_bw + 0.09375f * ch_data->bw_array[i];
1300 ch_data->bw_array[i] = new_bw < 0.015625f ? 0.0f : new_bw;
1301 }
1302 }
1303
1304 /// Generate the subband filtered lowband
1305 static int sbr_lf_gen(AACContext *ac, SpectralBandReplication *sbr,
1306 float X_low[32][40][2], const float W[2][32][32][2])
1307 {
1308 int i, k;
1309 const int t_HFGen = 8;
1310 const int i_f = 32;
1311 memset(X_low, 0, 32*sizeof(*X_low));
1312 for (k = 0; k < sbr->kx[1]; k++) {
1313 for (i = t_HFGen; i < i_f + t_HFGen; i++) {
1314 X_low[k][i][0] = W[1][i - t_HFGen][k][0];
1315 X_low[k][i][1] = W[1][i - t_HFGen][k][1];
1316 }
1317 }
1318 for (k = 0; k < sbr->kx[0]; k++) {
1319 for (i = 0; i < t_HFGen; i++) {
1320 X_low[k][i][0] = W[0][i + i_f - t_HFGen][k][0];
1321 X_low[k][i][1] = W[0][i + i_f - t_HFGen][k][1];
1322 }
1323 }
1324 return 0;
1325 }
1326
1327 /// High Frequency Generator (14496-3 sp04 p215)
1328 static int sbr_hf_gen(AACContext *ac, SpectralBandReplication *sbr,
1329 float X_high[64][40][2], const float X_low[32][40][2],
1330 const float (*alpha0)[2], const float (*alpha1)[2],
1331 const float bw_array[5], const uint8_t *t_env,
1332 int bs_num_env)
1333 {
1334 int j, x;
1335 int g = 0;
1336 int k = sbr->kx[1];
1337 for (j = 0; j < sbr->num_patches; j++) {
1338 for (x = 0; x < sbr->patch_num_subbands[j]; x++, k++) {
1339 const int p = sbr->patch_start_subband[j] + x;
1340 while (g <= sbr->n_q && k >= sbr->f_tablenoise[g])
1341 g++;
1342 g--;
1343
1344 if (g < 0) {
1345 av_log(ac->avctx, AV_LOG_ERROR,
1346 "ERROR : no subband found for frequency %d\n", k);
1347 return -1;
1348 }
1349
1350 sbr->dsp.hf_gen(X_high[k] + ENVELOPE_ADJUSTMENT_OFFSET,
1351 X_low[p] + ENVELOPE_ADJUSTMENT_OFFSET,
1352 alpha0[p], alpha1[p], bw_array[g],
1353 2 * t_env[0], 2 * t_env[bs_num_env]);
1354 }
1355 }
1356 if (k < sbr->m[1] + sbr->kx[1])
1357 memset(X_high + k, 0, (sbr->m[1] + sbr->kx[1] - k) * sizeof(*X_high));
1358
1359 return 0;
1360 }
1361
1362 /// Generate the subband filtered lowband
1363 static int sbr_x_gen(SpectralBandReplication *sbr, float X[2][38][64],
1364 const float Y0[38][64][2], const float Y1[38][64][2],
1365 const float X_low[32][40][2], int ch)
1366 {
1367 int k, i;
1368 const int i_f = 32;
1369 const int i_Temp = FFMAX(2*sbr->data[ch].t_env_num_env_old - i_f, 0);
1370 memset(X, 0, 2*sizeof(*X));
1371 for (k = 0; k < sbr->kx[0]; k++) {
1372 for (i = 0; i < i_Temp; i++) {
1373 X[0][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][0];
1374 X[1][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][1];
1375 }
1376 }
1377 for (; k < sbr->kx[0] + sbr->m[0]; k++) {
1378 for (i = 0; i < i_Temp; i++) {
1379 X[0][i][k] = Y0[i + i_f][k][0];
1380 X[1][i][k] = Y0[i + i_f][k][1];
1381 }
1382 }
1383
1384 for (k = 0; k < sbr->kx[1]; k++) {
1385 for (i = i_Temp; i < 38; i++) {
1386 X[0][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][0];
1387 X[1][i][k] = X_low[k][i + ENVELOPE_ADJUSTMENT_OFFSET][1];
1388 }
1389 }
1390 for (; k < sbr->kx[1] + sbr->m[1]; k++) {
1391 for (i = i_Temp; i < i_f; i++) {
1392 X[0][i][k] = Y1[i][k][0];
1393 X[1][i][k] = Y1[i][k][1];
1394 }
1395 }
1396 return 0;
1397 }
1398
1399 /** High Frequency Adjustment (14496-3 sp04 p217) and Mapping
1400 * (14496-3 sp04 p217)
1401 */
1402 static int sbr_mapping(AACContext *ac, SpectralBandReplication *sbr,
1403 SBRData *ch_data, int e_a[2])
1404 {
1405 int e, i, m;
1406
1407 memset(ch_data->s_indexmapped[1], 0, 7*sizeof(ch_data->s_indexmapped[1]));
1408 for (e = 0; e < ch_data->bs_num_env; e++) {
1409 const unsigned int ilim = sbr->n[ch_data->bs_freq_res[e + 1]];
1410 uint16_t *table = ch_data->bs_freq_res[e + 1] ? sbr->f_tablehigh : sbr->f_tablelow;
1411 int k;
1412
1413 if (sbr->kx[1] != table[0]) {
1414 av_log(ac->avctx, AV_LOG_ERROR, "kx != f_table{high,low}[0]. "
1415 "Derived frequency tables were not regenerated.\n");
1416 sbr_turnoff(sbr);
1417 return AVERROR_BUG;
1418 }
1419 for (i = 0; i < ilim; i++)
1420 for (m = table[i]; m < table[i + 1]; m++)
1421 sbr->e_origmapped[e][m - sbr->kx[1]] = ch_data->env_facs[e+1][i];
1422
1423 // ch_data->bs_num_noise > 1 => 2 noise floors
1424 k = (ch_data->bs_num_noise > 1) && (ch_data->t_env[e] >= ch_data->t_q[1]);
1425 for (i = 0; i < sbr->n_q; i++)
1426 for (m = sbr->f_tablenoise[i]; m < sbr->f_tablenoise[i + 1]; m++)
1427 sbr->q_mapped[e][m - sbr->kx[1]] = ch_data->noise_facs[k+1][i];
1428
1429 for (i = 0; i < sbr->n[1]; i++) {
1430 if (ch_data->bs_add_harmonic_flag) {
1431 const unsigned int m_midpoint =
1432 (sbr->f_tablehigh[i] + sbr->f_tablehigh[i + 1]) >> 1;
1433
1434 ch_data->s_indexmapped[e + 1][m_midpoint - sbr->kx[1]] = ch_data->bs_add_harmonic[i] *
1435 (e >= e_a[1] || (ch_data->s_indexmapped[0][m_midpoint - sbr->kx[1]] == 1));
1436 }
1437 }
1438
1439 for (i = 0; i < ilim; i++) {
1440 int additional_sinusoid_present = 0;
1441 for (m = table[i]; m < table[i + 1]; m++) {
1442 if (ch_data->s_indexmapped[e + 1][m - sbr->kx[1]]) {
1443 additional_sinusoid_present = 1;
1444 break;
1445 }
1446 }
1447 memset(&sbr->s_mapped[e][table[i] - sbr->kx[1]], additional_sinusoid_present,
1448 (table[i + 1] - table[i]) * sizeof(sbr->s_mapped[e][0]));
1449 }
1450 }
1451
1452 memcpy(ch_data->s_indexmapped[0], ch_data->s_indexmapped[ch_data->bs_num_env], sizeof(ch_data->s_indexmapped[0]));
1453 return 0;
1454 }
1455
1456 /// Estimation of current envelope (14496-3 sp04 p218)
1457 static void sbr_env_estimate(float (*e_curr)[48], float X_high[64][40][2],
1458 SpectralBandReplication *sbr, SBRData *ch_data)
1459 {
1460 int e, m;
1461 int kx1 = sbr->kx[1];
1462
1463 if (sbr->bs_interpol_freq) {
1464 for (e = 0; e < ch_data->bs_num_env; e++) {
1465 const float recip_env_size = 0.5f / (ch_data->t_env[e + 1] - ch_data->t_env[e]);
1466 int ilb = ch_data->t_env[e] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1467 int iub = ch_data->t_env[e + 1] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1468
1469 for (m = 0; m < sbr->m[1]; m++) {
1470 float sum = sbr->dsp.sum_square(X_high[m+kx1] + ilb, iub - ilb);
1471 e_curr[e][m] = sum * recip_env_size;
1472 }
1473 }
1474 } else {
1475 int k, p;
1476
1477 for (e = 0; e < ch_data->bs_num_env; e++) {
1478 const int env_size = 2 * (ch_data->t_env[e + 1] - ch_data->t_env[e]);
1479 int ilb = ch_data->t_env[e] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1480 int iub = ch_data->t_env[e + 1] * 2 + ENVELOPE_ADJUSTMENT_OFFSET;
1481 const uint16_t *table = ch_data->bs_freq_res[e + 1] ? sbr->f_tablehigh : sbr->f_tablelow;
1482
1483 for (p = 0; p < sbr->n[ch_data->bs_freq_res[e + 1]]; p++) {
1484 float sum = 0.0f;
1485 const int den = env_size * (table[p + 1] - table[p]);
1486
1487 for (k = table[p]; k < table[p + 1]; k++) {
1488 sum += sbr->dsp.sum_square(X_high[k] + ilb, iub - ilb);
1489 }
1490 sum /= den;
1491 for (k = table[p]; k < table[p + 1]; k++) {
1492 e_curr[e][k - kx1] = sum;
1493 }
1494 }
1495 }
1496 }
1497 }
1498
1499 /**
1500 * Calculation of levels of additional HF signal components (14496-3 sp04 p219)
1501 * and Calculation of gain (14496-3 sp04 p219)
1502 */
1503 static void sbr_gain_calc(AACContext *ac, SpectralBandReplication *sbr,
1504 SBRData *ch_data, const int e_a[2])
1505 {
1506 int e, k, m;
1507 // max gain limits : -3dB, 0dB, 3dB, inf dB (limiter off)
1508 static const float limgain[4] = { 0.70795, 1.0, 1.41254, 10000000000 };
1509
1510 for (e = 0; e < ch_data->bs_num_env; e++) {
1511 int delta = !((e == e_a[1]) || (e == e_a[0]));
1512 for (k = 0; k < sbr->n_lim; k++) {
1513 float gain_boost, gain_max;
1514 float sum[2] = { 0.0f, 0.0f };
1515 for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1516 const float temp = sbr->e_origmapped[e][m] / (1.0f + sbr->q_mapped[e][m]);
1517 sbr->q_m[e][m] = sqrtf(temp * sbr->q_mapped[e][m]);
1518 sbr->s_m[e][m] = sqrtf(temp * ch_data->s_indexmapped[e + 1][m]);
1519 if (!sbr->s_mapped[e][m]) {
1520 sbr->gain[e][m] = sqrtf(sbr->e_origmapped[e][m] /
1521 ((1.0f + sbr->e_curr[e][m]) *
1522 (1.0f + sbr->q_mapped[e][m] * delta)));
1523 } else {
1524 sbr->gain[e][m] = sqrtf(sbr->e_origmapped[e][m] * sbr->q_mapped[e][m] /
1525 ((1.0f + sbr->e_curr[e][m]) *
1526 (1.0f + sbr->q_mapped[e][m])));
1527 }
1528 }
1529 for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1530 sum[0] += sbr->e_origmapped[e][m];
1531 sum[1] += sbr->e_curr[e][m];
1532 }
1533 gain_max = limgain[sbr->bs_limiter_gains] * sqrtf((FLT_EPSILON + sum[0]) / (FLT_EPSILON + sum[1]));
1534 gain_max = FFMIN(100000.f, gain_max);
1535 for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1536 float q_m_max = sbr->q_m[e][m] * gain_max / sbr->gain[e][m];
1537 sbr->q_m[e][m] = FFMIN(sbr->q_m[e][m], q_m_max);
1538 sbr->gain[e][m] = FFMIN(sbr->gain[e][m], gain_max);
1539 }
1540 sum[0] = sum[1] = 0.0f;
1541 for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1542 sum[0] += sbr->e_origmapped[e][m];
1543 sum[1] += sbr->e_curr[e][m] * sbr->gain[e][m] * sbr->gain[e][m]
1544 + sbr->s_m[e][m] * sbr->s_m[e][m]
1545 + (delta && !sbr->s_m[e][m]) * sbr->q_m[e][m] * sbr->q_m[e][m];
1546 }
1547 gain_boost = sqrtf((FLT_EPSILON + sum[0]) / (FLT_EPSILON + sum[1]));
1548 gain_boost = FFMIN(1.584893192f, gain_boost);
1549 for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {
1550 sbr->gain[e][m] *= gain_boost;
1551 sbr->q_m[e][m] *= gain_boost;
1552 sbr->s_m[e][m] *= gain_boost;
1553 }
1554 }
1555 }
1556 }
1557
1558 /// Assembling HF Signals (14496-3 sp04 p220)
1559 static void sbr_hf_assemble(float Y1[38][64][2],
1560 const float X_high[64][40][2],
1561 SpectralBandReplication *sbr, SBRData *ch_data,
1562 const int e_a[2])
1563 {
1564 int e, i, j, m;
1565 const int h_SL = 4 * !sbr->bs_smoothing_mode;
1566 const int kx = sbr->kx[1];
1567 const int m_max = sbr->m[1];
1568 static const float h_smooth[5] = {
1569 0.33333333333333,
1570 0.30150283239582,
1571 0.21816949906249,
1572 0.11516383427084,
1573 0.03183050093751,
1574 };
1575 static const int8_t phi[2][4] = {
1576 { 1, 0, -1, 0}, // real
1577 { 0, 1, 0, -1}, // imaginary
1578 };
1579 float (*g_temp)[48] = ch_data->g_temp, (*q_temp)[48] = ch_data->q_temp;
1580 int indexnoise = ch_data->f_indexnoise;
1581 int indexsine = ch_data->f_indexsine;
1582
1583 if (sbr->reset) {
1584 for (i = 0; i < h_SL; i++) {
1585 memcpy(g_temp[i + 2*ch_data->t_env[0]], sbr->gain[0], m_max * sizeof(sbr->gain[0][0]));
1586 memcpy(q_temp[i + 2*ch_data->t_env[0]], sbr->q_m[0], m_max * sizeof(sbr->q_m[0][0]));
1587 }
1588 } else if (h_SL) {
1589 memcpy(g_temp[2*ch_data->t_env[0]], g_temp[2*ch_data->t_env_num_env_old], 4*sizeof(g_temp[0]));
1590 memcpy(q_temp[2*ch_data->t_env[0]], q_temp[2*ch_data->t_env_num_env_old], 4*sizeof(q_temp[0]));
1591 }
1592
1593 for (e = 0; e < ch_data->bs_num_env; e++) {
1594 for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {
1595 memcpy(g_temp[h_SL + i], sbr->gain[e], m_max * sizeof(sbr->gain[0][0]));
1596 memcpy(q_temp[h_SL + i], sbr->q_m[e], m_max * sizeof(sbr->q_m[0][0]));
1597 }
1598 }
1599
1600 for (e = 0; e < ch_data->bs_num_env; e++) {
1601 for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {
1602 int phi_sign = (1 - 2*(kx & 1));
1603 LOCAL_ALIGNED_16(float, g_filt_tab, [48]);
1604 LOCAL_ALIGNED_16(float, q_filt_tab, [48]);
1605 float *g_filt, *q_filt;
1606
1607 if (h_SL && e != e_a[0] && e != e_a[1]) {
1608 g_filt = g_filt_tab;
1609 q_filt = q_filt_tab;
1610 for (m = 0; m < m_max; m++) {
1611 const int idx1 = i + h_SL;
1612 g_filt[m] = 0.0f;
1613 q_filt[m] = 0.0f;
1614 for (j = 0; j <= h_SL; j++) {
1615 g_filt[m] += g_temp[idx1 - j][m] * h_smooth[j];
1616 q_filt[m] += q_temp[idx1 - j][m] * h_smooth[j];
1617 }
1618 }
1619 } else {
1620 g_filt = g_temp[i + h_SL];
1621 q_filt = q_temp[i];
1622 }
1623
1624 sbr->dsp.hf_g_filt(Y1[i] + kx, X_high + kx, g_filt, m_max,
1625 i + ENVELOPE_ADJUSTMENT_OFFSET);
1626
1627 if (e != e_a[0] && e != e_a[1]) {
1628 sbr->dsp.hf_apply_noise[indexsine](Y1[i] + kx, sbr->s_m[e],
1629 q_filt, indexnoise,
1630 kx, m_max);
1631 } else {
1632 for (m = 0; m < m_max; m++) {
1633 Y1[i][m + kx][0] +=
1634 sbr->s_m[e][m] * phi[0][indexsine];
1635 Y1[i][m + kx][1] +=
1636 sbr->s_m[e][m] * (phi[1][indexsine] * phi_sign);
1637 phi_sign = -phi_sign;
1638 }
1639 }
1640 indexnoise = (indexnoise + m_max) & 0x1ff;
1641 indexsine = (indexsine + 1) & 3;
1642 }
1643 }
1644 ch_data->f_indexnoise = indexnoise;
1645 ch_data->f_indexsine = indexsine;
1646 }
1647
1648 void ff_sbr_apply(AACContext *ac, SpectralBandReplication *sbr, int id_aac,
1649 float* L, float* R)
1650 {
1651 int downsampled = ac->oc[1].m4ac.ext_sample_rate < sbr->sample_rate;
1652 int ch;
1653 int nch = (id_aac == TYPE_CPE) ? 2 : 1;
1654 int err;
1655
1656 if (!sbr->kx_and_m_pushed) {
1657 sbr->kx[0] = sbr->kx[1];
1658 sbr->m[0] = sbr->m[1];
1659 } else {
1660 sbr->kx_and_m_pushed = 0;
1661 }
1662
1663 if (sbr->start) {
1664 sbr_dequant(sbr, id_aac);
1665 }
1666 for (ch = 0; ch < nch; ch++) {
1667 /* decode channel */
1668 sbr_qmf_analysis(&ac->dsp, &sbr->mdct_ana, &sbr->dsp, ch ? R : L, sbr->data[ch].analysis_filterbank_samples,
1669 (float*)sbr->qmf_filter_scratch,
1670 sbr->data[ch].W);
1671 sbr_lf_gen(ac, sbr, sbr->X_low, sbr->data[ch].W);
1672 sbr->data[ch].Ypos ^= 1;
1673 if (sbr->start) {
1674 sbr_hf_inverse_filter(&sbr->dsp, sbr->alpha0, sbr->alpha1, sbr->X_low, sbr->k[0]);
1675 sbr_chirp(sbr, &sbr->data[ch]);
1676 sbr_hf_gen(ac, sbr, sbr->X_high, sbr->X_low, sbr->alpha0, sbr->alpha1,
1677 sbr->data[ch].bw_array, sbr->data[ch].t_env,
1678 sbr->data[ch].bs_num_env);
1679
1680 // hf_adj
1681 err = sbr_mapping(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);
1682 if (!err) {
1683 sbr_env_estimate(sbr->e_curr, sbr->X_high, sbr, &sbr->data[ch]);
1684 sbr_gain_calc(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);
1685 sbr_hf_assemble(sbr->data[ch].Y[sbr->data[ch].Ypos],
1686 sbr->X_high, sbr, &sbr->data[ch],
1687 sbr->data[ch].e_a);
1688 }
1689 }
1690
1691 /* synthesis */
1692 sbr_x_gen(sbr, sbr->X[ch],
1693 sbr->data[ch].Y[1-sbr->data[ch].Ypos],
1694 sbr->data[ch].Y[ sbr->data[ch].Ypos],
1695 sbr->X_low, ch);
1696 }
1697
1698 if (ac->oc[1].m4ac.ps == 1) {
1699 if (sbr->ps.start) {
1700 ff_ps_apply(ac->avctx, &sbr->ps, sbr->X[0], sbr->X[1], sbr->kx[1] + sbr->m[1]);
1701 } else {
1702 memcpy(sbr->X[1], sbr->X[0], sizeof(sbr->X[0]));
1703 }
1704 nch = 2;
1705 }
1706
1707 sbr_qmf_synthesis(&ac->dsp, &sbr->mdct, &sbr->dsp, L, sbr->X[0], sbr->qmf_filter_scratch,
1708 sbr->data[0].synthesis_filterbank_samples,
1709 &sbr->data[0].synthesis_filterbank_samples_offset,
1710 downsampled);
1711 if (nch == 2)
1712 sbr_qmf_synthesis(&ac->dsp, &sbr->mdct, &sbr->dsp, R, sbr->X[1], sbr->qmf_filter_scratch,
1713 sbr->data[1].synthesis_filterbank_samples,
1714 &sbr->data[1].synthesis_filterbank_samples_offset,
1715 downsampled);
1716 }