Fixing the units in DV50 tables (both coordinates are
[libav.git] / libavcodec / aac.c
CommitLineData
71e9a1b8
RS
1/*
2 * AAC decoder
3 * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
4 * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23/**
24 * @file aac.c
25 * AAC decoder
26 * @author Oded Shimon ( ods15 ods15 dyndns org )
27 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
28 */
29
30/*
31 * supported tools
32 *
33 * Support? Name
34 * N (code in SoC repo) gain control
35 * Y block switching
36 * Y window shapes - standard
37 * N window shapes - Low Delay
38 * Y filterbank - standard
39 * N (code in SoC repo) filterbank - Scalable Sample Rate
40 * Y Temporal Noise Shaping
41 * N (code in SoC repo) Long Term Prediction
42 * Y intensity stereo
43 * Y channel coupling
44 * N frequency domain prediction
45 * Y Perceptual Noise Substitution
46 * Y Mid/Side stereo
47 * N Scalable Inverse AAC Quantization
48 * N Frequency Selective Switch
49 * N upsampling filter
50 * Y quantization & coding - AAC
51 * N quantization & coding - TwinVQ
52 * N quantization & coding - BSAC
53 * N AAC Error Resilience tools
54 * N Error Resilience payload syntax
55 * N Error Protection tool
56 * N CELP
57 * N Silence Compression
58 * N HVXC
59 * N HVXC 4kbits/s VR
60 * N Structured Audio tools
61 * N Structured Audio Sample Bank Format
62 * N MIDI
63 * N Harmonic and Individual Lines plus Noise
64 * N Text-To-Speech Interface
65 * N (in progress) Spectral Band Replication
66 * Y (not in this code) Layer-1
67 * Y (not in this code) Layer-2
68 * Y (not in this code) Layer-3
69 * N SinuSoidal Coding (Transient, Sinusoid, Noise)
70 * N (planned) Parametric Stereo
71 * N Direct Stream Transfer
72 *
73 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
74 * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
75 Parametric Stereo.
76 */
77
78
79#include "avcodec.h"
80#include "bitstream.h"
81#include "dsputil.h"
82
83#include "aac.h"
84#include "aactab.h"
cc0591da 85#include "aacdectab.h"
71e9a1b8
RS
86#include "mpeg4audio.h"
87
88#include <assert.h>
89#include <errno.h>
90#include <math.h>
91#include <string.h>
92
93#ifndef CONFIG_HARDCODED_TABLES
94 static float ff_aac_ivquant_tab[IVQUANT_SIZE];
cc0591da 95 static float ff_aac_pow2sf_tab[316];
71e9a1b8
RS
96#endif /* CONFIG_HARDCODED_TABLES */
97
98static VLC vlc_scalefactors;
99static VLC vlc_spectral[11];
100
101
102 num_front = get_bits(gb, 4);
103 num_side = get_bits(gb, 4);
104 num_back = get_bits(gb, 4);
105 num_lfe = get_bits(gb, 2);
106 num_assoc_data = get_bits(gb, 3);
107 num_cc = get_bits(gb, 4);
108
cc0591da
RS
109 if (get_bits1(gb))
110 skip_bits(gb, 4); // mono_mixdown_tag
111 if (get_bits1(gb))
112 skip_bits(gb, 4); // stereo_mixdown_tag
71e9a1b8 113
cc0591da
RS
114 if (get_bits1(gb))
115 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
71e9a1b8 116
cc0591da
RS
117 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
118 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE, gb, num_side );
119 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK, gb, num_back );
120 decode_channel_map(NULL, new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE, gb, num_lfe );
71e9a1b8
RS
121
122 skip_bits_long(gb, 4 * num_assoc_data);
123
cc0591da 124 decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC, gb, num_cc );
71e9a1b8
RS
125
126 align_get_bits(gb);
127
128 /* comment field, first byte is length */
129 skip_bits_long(gb, 8 * get_bits(gb, 8));
cc0591da
RS
130 return 0;
131}
71e9a1b8
RS
132
133static av_cold int aac_decode_init(AVCodecContext * avccontext) {
134 AACContext * ac = avccontext->priv_data;
135 int i;
136
137 ac->avccontext = avccontext;
138
cc0591da
RS
139 if (avccontext->extradata_size <= 0 ||
140 decode_audio_specific_config(ac, avccontext->extradata, avccontext->extradata_size))
141 return -1;
142
71e9a1b8
RS
143 avccontext->sample_rate = ac->m4ac.sample_rate;
144 avccontext->frame_size = 1024;
145
146 AAC_INIT_VLC_STATIC( 0, 144);
147 AAC_INIT_VLC_STATIC( 1, 114);
148 AAC_INIT_VLC_STATIC( 2, 188);
149 AAC_INIT_VLC_STATIC( 3, 180);
150 AAC_INIT_VLC_STATIC( 4, 172);
151 AAC_INIT_VLC_STATIC( 5, 140);
152 AAC_INIT_VLC_STATIC( 6, 168);
153 AAC_INIT_VLC_STATIC( 7, 114);
154 AAC_INIT_VLC_STATIC( 8, 262);
155 AAC_INIT_VLC_STATIC( 9, 248);
156 AAC_INIT_VLC_STATIC(10, 384);
157
158 dsputil_init(&ac->dsp, avccontext);
159
160 // -1024 - Compensate wrong IMDCT method.
161 // 32768 - Required to scale values to the correct range for the bias method
162 // for float to int16 conversion.
163
164 if(ac->dsp.float_to_int16 == ff_float_to_int16_c) {
165 ac->add_bias = 385.0f;
166 ac->sf_scale = 1. / (-1024. * 32768.);
167 ac->sf_offset = 0;
168 } else {
169 ac->add_bias = 0.0f;
170 ac->sf_scale = 1. / -1024.;
171 ac->sf_offset = 60;
172 }
173
174#ifndef CONFIG_HARDCODED_TABLES
175 for (i = 1 - IVQUANT_SIZE/2; i < IVQUANT_SIZE/2; i++)
176 ff_aac_ivquant_tab[i + IVQUANT_SIZE/2 - 1] = cbrt(fabs(i)) * i;
cc0591da
RS
177 for (i = 0; i < 316; i++)
178 ff_aac_pow2sf_tab[i] = pow(2, (i - 200)/4.);
71e9a1b8
RS
179#endif /* CONFIG_HARDCODED_TABLES */
180
181 INIT_VLC_STATIC(&vlc_scalefactors, 7, sizeof(ff_aac_scalefactor_code)/sizeof(ff_aac_scalefactor_code[0]),
182 ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
183 ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
184 352);
185
186 ff_mdct_init(&ac->mdct, 11, 1);
187 ff_mdct_init(&ac->mdct_small, 8, 1);
188 return 0;
189}
190
191 int byte_align = get_bits1(gb);
192 int count = get_bits(gb, 8);
193 if (count == 255)
194 count += get_bits(gb, 8);
195 if (byte_align)
196 align_get_bits(gb);
197 skip_bits_long(gb, 8 * count);
198}
199
200/**
201 * inverse quantization
202 *
203 * @param a quantized value to be dequantized
204 * @return Returns dequantized value.
205 */
206static inline float ivquant(int a) {
207 if (a + (unsigned int)IVQUANT_SIZE/2 - 1 < (unsigned int)IVQUANT_SIZE - 1)
208 return ff_aac_ivquant_tab[a + IVQUANT_SIZE/2 - 1];
209 else
210 return cbrtf(fabsf(a)) * a;
211}
212
cc0591da
RS
213 int band_type_run_end[120], GetBitContext * gb, IndividualChannelStream * ics) {
214 int g, idx = 0;
215 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
216 for (g = 0; g < ics->num_window_groups; g++) {
217 int k = 0;
218 while (k < ics->max_sfb) {
219 uint8_t sect_len = k;
220 int sect_len_incr;
221 int sect_band_type = get_bits(gb, 4);
222 if (sect_band_type == 12) {
223 av_log(ac->avccontext, AV_LOG_ERROR, "invalid band type\n");
224 return -1;
225 }
226 while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits)-1)
227 sect_len += sect_len_incr;
228 sect_len += sect_len_incr;
229 if (sect_len > ics->max_sfb) {
230 av_log(ac->avccontext, AV_LOG_ERROR,
231 "Number of bands (%d) exceeds limit (%d).\n",
232 sect_len, ics->max_sfb);
233 return -1;
234 }
235
236 *
237 * @param mix_gain channel gain (Not used by AAC bitstream.)
238 * @param global_gain first scalefactor value as scalefactors are differentially coded
239 * @param band_type array of the used band type
240 * @param band_type_run_end array of the last scalefactor band of a band type run
241 * @param sf array of scalefactors or intensity stereo positions
242 *
243 * @return Returns error status. 0 - OK, !0 - error
244 */
245static int decode_scalefactors(AACContext * ac, float sf[120], GetBitContext * gb,
246 float mix_gain, unsigned int global_gain, IndividualChannelStream * ics,
247 enum BandType band_type[120], int band_type_run_end[120]) {
248 const int sf_offset = ac->sf_offset + (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE ? 12 : 0);
249 int g, i, idx = 0;
250 int offset[3] = { global_gain, global_gain - 90, 100 };
251 int noise_flag = 1;
252 static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
253 ics->intensity_present = 0;
254 for (g = 0; g < ics->num_window_groups; g++) {
255 for (i = 0; i < ics->max_sfb;) {
256 int run_end = band_type_run_end[idx];
257 if (band_type[idx] == ZERO_BT) {
258 for(; i < run_end; i++, idx++)
259 sf[idx] = 0.;
260 }else if((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
261 ics->intensity_present = 1;
262 for(; i < run_end; i++, idx++) {
263 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
264 if(offset[2] > 255U) {
265 av_log(ac->avccontext, AV_LOG_ERROR,
266 "%s (%d) out of range.\n", sf_str[2], offset[2]);
267 return -1;
268 }
269 sf[idx] = ff_aac_pow2sf_tab[-offset[2] + 300];
270 sf[idx] *= mix_gain;
271 }
272 }else if(band_type[idx] == NOISE_BT) {
273 for(; i < run_end; i++, idx++) {
274 if(noise_flag-- > 0)
275 offset[1] += get_bits(gb, 9) - 256;
276 else
277 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
278 if(offset[1] > 255U) {
279 av_log(ac->avccontext, AV_LOG_ERROR,
280 "%s (%d) out of range.\n", sf_str[1], offset[1]);
281 return -1;
282 }
283 sf[idx] = -ff_aac_pow2sf_tab[ offset[1] + sf_offset];
284 sf[idx] *= mix_gain;
285 }
286 }else {
287 for(; i < run_end; i++, idx++) {
288 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
289 if(offset[0] > 255U) {
290 av_log(ac->avccontext, AV_LOG_ERROR,
291 "%s (%d) out of range.\n", sf_str[0], offset[0]);
292 return -1;
293 }
294 sf[idx] = -ff_aac_pow2sf_tab[ offset[0] + sf_offset];
295 sf[idx] *= mix_gain;
296 }
297 }
298 }
299 }
300 return 0;
301}
302
303/**
304 * Decode pulse data; reference: table 4.7.
305 */
306static void decode_pulses(Pulse * pulse, GetBitContext * gb) {
307 int i;
308 pulse->num_pulse = get_bits(gb, 2) + 1;
309 pulse->start = get_bits(gb, 6);
310 for (i = 0; i < pulse->num_pulse; i++) {
311 pulse->offset[i] = get_bits(gb, 5);
312 pulse->amp [i] = get_bits(gb, 4);
313 }
314}
315
316/**
317 * Add pulses with particular amplitudes to the quantized spectral data; reference: 4.6.3.3.
318 *
71e9a1b8
RS
319 * @param pulse pointer to pulse data struct
320 * @param icoef array of quantized spectral data
321 */
322static void add_pulses(int icoef[1024], const Pulse * pulse, const IndividualChannelStream * ics) {
323 int i, off = ics->swb_offset[pulse->start];
324 for (i = 0; i < pulse->num_pulse; i++) {
325 int ic;
326 off += pulse->offset[i];
327 ic = (icoef[off] - 1)>>31;
328 icoef[off] += (pulse->amp[i]^ic) - ic;
329 }
330}
331
cc0591da
RS
332/**
333 * Parse Spectral Band Replication extension data; reference: table 4.55.
334 *
335 * @param crc flag indicating the presence of CRC checksum
336 * @param cnt length of TYPE_FIL syntactic element in bytes
337 * @return Returns number of bytes consumed from the TYPE_FIL element.
338 */
339static int decode_sbr_extension(AACContext * ac, GetBitContext * gb, int crc, int cnt) {
340 // TODO : sbr_extension implementation
341 av_log(ac->avccontext, AV_LOG_DEBUG, "aac: SBR not yet supported.\n");
342 skip_bits_long(gb, 8*cnt - 4); // -4 due to reading extension type
343 return cnt;
344}
345
346 int crc_flag = 0;
347 int res = cnt;
348 switch (get_bits(gb, 4)) { // extension type
349 case EXT_SBR_DATA_CRC:
350 crc_flag++;
351 case EXT_SBR_DATA:
352 res = decode_sbr_extension(ac, gb, crc_flag, cnt);
353 break;
354 case EXT_DYNAMIC_RANGE:
355 res = decode_dynamic_range(&ac->che_drc, gb, cnt);
356 break;
357 case EXT_FILL:
358 case EXT_FILL_DATA:
359 case EXT_DATA_ELEMENT:
360 default:
361 skip_bits_long(gb, 8*cnt - 4);
362 break;
363 };
364 return res;
365}
366
367/**
368 * Apply dependent channel coupling (applied before IMDCT).
369 *
370 * @param index index into coupling gain array
371 */
372static void apply_dependent_coupling(AACContext * ac, SingleChannelElement * sce, ChannelElement * cc, int index) {
373 IndividualChannelStream * ics = &cc->ch[0].ics;
374 const uint16_t * offsets = ics->swb_offset;
375 float * dest = sce->coeffs;
376 const float * src = cc->ch[0].coeffs;
377 int g, i, group, k, idx = 0;
378 if(ac->m4ac.object_type == AOT_AAC_LTP) {
379 av_log(ac->avccontext, AV_LOG_ERROR,
380 "Dependent coupling is not supported together with LTP\n");
381 return;
382 }
383 for (g = 0; g < ics->num_window_groups; g++) {
384 for (i = 0; i < ics->max_sfb; i++, idx++) {
385 if (cc->ch[0].band_type[idx] != ZERO_BT) {
386 float gain = cc->coup.gain[index][idx] * sce->mixing_gain;
387 for (group = 0; group < ics->group_len[g]; group++) {
388 for (k = offsets[i]; k < offsets[i+1]; k++) {
389 // XXX dsputil-ize
390 dest[group*128+k] += gain * src[group*128+k];
391 }
392 }
393 }
394 }
395 dest += ics->group_len[g]*128;
396 src += ics->group_len[g]*128;
397 }
398}
399
400/**
401 * Apply independent channel coupling (applied after IMDCT).
402 *
403 * @param index index into coupling gain array
404 */
405static void apply_independent_coupling(AACContext * ac, SingleChannelElement * sce, ChannelElement * cc, int index) {
406 int i;
407 float gain = cc->coup.gain[index][0] * sce->mixing_gain;
408 for (i = 0; i < 1024; i++)
409 sce->ret[i] += gain * (cc->ch[0].ret[i] - ac->add_bias);
410}
411
71e9a1b8
RS
412static av_cold int aac_decode_close(AVCodecContext * avccontext) {
413 AACContext * ac = avccontext->priv_data;
414 int i, j;
415
cc0591da 416 for (i = 0; i < MAX_ELEM_ID; i++) {
71e9a1b8
RS
417 for(j = 0; j < 4; j++)
418 av_freep(&ac->che[j][i]);
419 }
420
421 ff_mdct_end(&ac->mdct);
422 ff_mdct_end(&ac->mdct_small);
71e9a1b8
RS
423 return 0 ;
424}
425
426AVCodec aac_decoder = {
427 "aac",
428 CODEC_TYPE_AUDIO,
429 CODEC_ID_AAC,
430 sizeof(AACContext),
431 aac_decode_init,
432 NULL,
433 aac_decode_close,
434 aac_decode_frame,
435 .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
cc0591da 436 .sample_fmts = (enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
71e9a1b8 437};