aacdec.c
Go to the documentation of this file.
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  * AAC LATM decoder
7  * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
8  * Copyright (c) 2010 Janne Grunau <janne-ffmpeg@jannau.net>
9  *
10  * This file is part of Libav.
11  *
12  * Libav is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * Libav is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with Libav; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25  */
26 
34 /*
35  * supported tools
36  *
37  * Support? Name
38  * N (code in SoC repo) gain control
39  * Y block switching
40  * Y window shapes - standard
41  * N window shapes - Low Delay
42  * Y filterbank - standard
43  * N (code in SoC repo) filterbank - Scalable Sample Rate
44  * Y Temporal Noise Shaping
45  * Y Long Term Prediction
46  * Y intensity stereo
47  * Y channel coupling
48  * Y frequency domain prediction
49  * Y Perceptual Noise Substitution
50  * Y Mid/Side stereo
51  * N Scalable Inverse AAC Quantization
52  * N Frequency Selective Switch
53  * N upsampling filter
54  * Y quantization & coding - AAC
55  * N quantization & coding - TwinVQ
56  * N quantization & coding - BSAC
57  * N AAC Error Resilience tools
58  * N Error Resilience payload syntax
59  * N Error Protection tool
60  * N CELP
61  * N Silence Compression
62  * N HVXC
63  * N HVXC 4kbits/s VR
64  * N Structured Audio tools
65  * N Structured Audio Sample Bank Format
66  * N MIDI
67  * N Harmonic and Individual Lines plus Noise
68  * N Text-To-Speech Interface
69  * Y Spectral Band Replication
70  * Y (not in this code) Layer-1
71  * Y (not in this code) Layer-2
72  * Y (not in this code) Layer-3
73  * N SinuSoidal Coding (Transient, Sinusoid, Noise)
74  * Y Parametric Stereo
75  * N Direct Stream Transfer
76  *
77  * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
78  * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
79  Parametric Stereo.
80  */
81 
82 
83 #include "avcodec.h"
84 #include "internal.h"
85 #include "get_bits.h"
86 #include "dsputil.h"
87 #include "fft.h"
88 #include "fmtconvert.h"
89 #include "lpc.h"
90 #include "kbdwin.h"
91 #include "sinewin.h"
92 
93 #include "aac.h"
94 #include "aactab.h"
95 #include "aacdectab.h"
96 #include "cbrt_tablegen.h"
97 #include "sbr.h"
98 #include "aacsbr.h"
99 #include "mpeg4audio.h"
100 #include "aacadtsdec.h"
101 #include "libavutil/intfloat.h"
102 
103 #include <assert.h>
104 #include <errno.h>
105 #include <math.h>
106 #include <string.h>
107 
108 #if ARCH_ARM
109 # include "arm/aac.h"
110 #endif
111 
113 static VLC vlc_spectral[11];
114 
115 static const char overread_err[] = "Input buffer exhausted before END element found\n";
116 
117 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
118 {
119  // For PCE based channel configurations map the channels solely based on tags.
120  if (!ac->m4ac.chan_config) {
121  return ac->tag_che_map[type][elem_id];
122  }
123  // For indexed channel configurations map the channels solely based on position.
124  switch (ac->m4ac.chan_config) {
125  case 7:
126  if (ac->tags_mapped == 3 && type == TYPE_CPE) {
127  ac->tags_mapped++;
128  return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
129  }
130  case 6:
131  /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
132  instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
133  encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
134  if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
135  ac->tags_mapped++;
136  return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
137  }
138  case 5:
139  if (ac->tags_mapped == 2 && type == TYPE_CPE) {
140  ac->tags_mapped++;
141  return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
142  }
143  case 4:
144  if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
145  ac->tags_mapped++;
146  return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
147  }
148  case 3:
149  case 2:
150  if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
151  ac->tags_mapped++;
152  return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
153  } else if (ac->m4ac.chan_config == 2) {
154  return NULL;
155  }
156  case 1:
157  if (!ac->tags_mapped && type == TYPE_SCE) {
158  ac->tags_mapped++;
159  return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
160  }
161  default:
162  return NULL;
163  }
164 }
165 
166 static int count_channels(enum ChannelPosition che_pos[4][MAX_ELEM_ID])
167 {
168  int i, type, sum = 0;
169  for (i = 0; i < MAX_ELEM_ID; i++) {
170  for (type = 0; type < 4; type++) {
171  sum += (1 + (type == TYPE_CPE)) *
172  (che_pos[type][i] != AAC_CHANNEL_OFF &&
173  che_pos[type][i] != AAC_CHANNEL_CC);
174  }
175  }
176  return sum;
177 }
178 
192  enum ChannelPosition che_pos[4][MAX_ELEM_ID],
193  int type, int id, int *channels)
194 {
195  if (*channels >= MAX_CHANNELS)
196  return AVERROR_INVALIDDATA;
197  if (che_pos[type][id]) {
198  if (!ac->che[type][id]) {
199  if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
200  return AVERROR(ENOMEM);
201  ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
202  }
203  if (type != TYPE_CCE) {
204  ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
205  if (type == TYPE_CPE ||
206  (type == TYPE_SCE && ac->m4ac.ps == 1)) {
207  ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
208  }
209  }
210  } else {
211  if (ac->che[type][id])
212  ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
213  av_freep(&ac->che[type][id]);
214  }
215  return 0;
216 }
217 
227  enum ChannelPosition che_pos[4][MAX_ELEM_ID],
228  enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
229  int channel_config, enum OCStatus oc_type)
230 {
231  AVCodecContext *avctx = ac->avctx;
232  int i, type, channels = 0, ret;
233 
234  if (new_che_pos != che_pos)
235  memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
236 
237  if (channel_config) {
238  for (i = 0; i < tags_per_config[channel_config]; i++) {
239  if ((ret = che_configure(ac, che_pos,
240  aac_channel_layout_map[channel_config - 1][i][0],
241  aac_channel_layout_map[channel_config - 1][i][1],
242  &channels)))
243  return ret;
244  }
245 
246  memset(ac->tag_che_map, 0, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
247 
248  avctx->channel_layout = aac_channel_layout[channel_config - 1];
249  } else {
250  /* Allocate or free elements depending on if they are in the
251  * current program configuration.
252  *
253  * Set up default 1:1 output mapping.
254  *
255  * For a 5.1 stream the output order will be:
256  * [ Center ] [ Front Left ] [ Front Right ] [ LFE ] [ Surround Left ] [ Surround Right ]
257  */
258 
259  for (i = 0; i < MAX_ELEM_ID; i++) {
260  for (type = 0; type < 4; type++) {
261  if ((ret = che_configure(ac, che_pos, type, i, &channels)))
262  return ret;
263  }
264  }
265 
266  memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
267 
268  avctx->channel_layout = 0;
269  }
270 
271  avctx->channels = channels;
272 
273  ac->output_configured = oc_type;
274 
275  return 0;
276 }
277 
285 static void decode_channel_map(enum ChannelPosition *cpe_map,
286  enum ChannelPosition *sce_map,
287  enum ChannelPosition type,
288  GetBitContext *gb, int n)
289 {
290  while (n--) {
291  enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
292  map[get_bits(gb, 4)] = type;
293  }
294 }
295 
303 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
304  enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
305  GetBitContext *gb)
306 {
307  int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
308  int comment_len;
309 
310  skip_bits(gb, 2); // object_type
311 
312  sampling_index = get_bits(gb, 4);
313  if (m4ac->sampling_index != sampling_index)
314  av_log(avctx, AV_LOG_WARNING, "Sample rate index in program config element does not match the sample rate index configured by the container.\n");
315 
316  num_front = get_bits(gb, 4);
317  num_side = get_bits(gb, 4);
318  num_back = get_bits(gb, 4);
319  num_lfe = get_bits(gb, 2);
320  num_assoc_data = get_bits(gb, 3);
321  num_cc = get_bits(gb, 4);
322 
323  if (get_bits1(gb))
324  skip_bits(gb, 4); // mono_mixdown_tag
325  if (get_bits1(gb))
326  skip_bits(gb, 4); // stereo_mixdown_tag
327 
328  if (get_bits1(gb))
329  skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
330 
331  decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
332  decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE, gb, num_side );
333  decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK, gb, num_back );
334  decode_channel_map(NULL, new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE, gb, num_lfe );
335 
336  skip_bits_long(gb, 4 * num_assoc_data);
337 
338  decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC, gb, num_cc );
339 
340  align_get_bits(gb);
341 
342  /* comment field, first byte is length */
343  comment_len = get_bits(gb, 8) * 8;
344  if (get_bits_left(gb) < comment_len) {
346  return AVERROR_INVALIDDATA;
347  }
348  skip_bits_long(gb, comment_len);
349  return 0;
350 }
351 
361  enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
362  int channel_config)
363 {
364  if (channel_config < 1 || channel_config > 7) {
365  av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
366  channel_config);
367  return AVERROR_INVALIDDATA;
368  }
369 
370  /* default channel configurations:
371  *
372  * 1ch : front center (mono)
373  * 2ch : L + R (stereo)
374  * 3ch : front center + L + R
375  * 4ch : front center + L + R + back center
376  * 5ch : front center + L + R + back stereo
377  * 6ch : front center + L + R + back stereo + LFE
378  * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
379  */
380 
381  if (channel_config != 2)
382  new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
383  if (channel_config > 1)
384  new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
385  if (channel_config == 4)
386  new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK; // back center
387  if (channel_config > 4)
388  new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
389  = AAC_CHANNEL_BACK; // back stereo
390  if (channel_config > 5)
391  new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE; // LFE
392  if (channel_config == 7)
393  new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
394 
395  return 0;
396 }
397 
407  GetBitContext *gb,
408  MPEG4AudioConfig *m4ac,
409  int channel_config)
410 {
411  enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
412  int extension_flag, ret;
413 
414  if (get_bits1(gb)) { // frameLengthFlag
415  av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
416  return -1;
417  }
418 
419  if (get_bits1(gb)) // dependsOnCoreCoder
420  skip_bits(gb, 14); // coreCoderDelay
421  extension_flag = get_bits1(gb);
422 
423  if (m4ac->object_type == AOT_AAC_SCALABLE ||
425  skip_bits(gb, 3); // layerNr
426 
427  memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
428  if (channel_config == 0) {
429  skip_bits(gb, 4); // element_instance_tag
430  if ((ret = decode_pce(avctx, m4ac, new_che_pos, gb)))
431  return ret;
432  } else {
433  if ((ret = set_default_channel_config(avctx, new_che_pos, channel_config)))
434  return ret;
435  }
436 
437  if (count_channels(new_che_pos) > 1) {
438  m4ac->ps = 0;
439  } else if (m4ac->sbr == 1 && m4ac->ps == -1)
440  m4ac->ps = 1;
441 
442  if (ac && (ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
443  return ret;
444 
445  if (extension_flag) {
446  switch (m4ac->object_type) {
447  case AOT_ER_BSAC:
448  skip_bits(gb, 5); // numOfSubFrame
449  skip_bits(gb, 11); // layer_length
450  break;
451  case AOT_ER_AAC_LC:
452  case AOT_ER_AAC_LTP:
453  case AOT_ER_AAC_SCALABLE:
454  case AOT_ER_AAC_LD:
455  skip_bits(gb, 3); /* aacSectionDataResilienceFlag
456  * aacScalefactorDataResilienceFlag
457  * aacSpectralDataResilienceFlag
458  */
459  break;
460  }
461  skip_bits1(gb); // extensionFlag3 (TBD in version 3)
462  }
463  return 0;
464 }
465 
479  AVCodecContext *avctx,
480  MPEG4AudioConfig *m4ac,
481  const uint8_t *data, int bit_size,
482  int sync_extension)
483 {
484  GetBitContext gb;
485  int i, ret;
486 
487  av_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
488  for (i = 0; i < avctx->extradata_size; i++)
489  av_dlog(avctx, "%02x ", avctx->extradata[i]);
490  av_dlog(avctx, "\n");
491 
492  if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
493  return ret;
494 
495  if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size, sync_extension)) < 0)
496  return AVERROR_INVALIDDATA;
497  if (m4ac->sampling_index > 12) {
498  av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
499  return AVERROR_INVALIDDATA;
500  }
501 
502  skip_bits_long(&gb, i);
503 
504  switch (m4ac->object_type) {
505  case AOT_AAC_MAIN:
506  case AOT_AAC_LC:
507  case AOT_AAC_LTP:
508  if ((ret = decode_ga_specific_config(ac, avctx, &gb,
509  m4ac, m4ac->chan_config)) < 0)
510  return ret;
511  break;
512  default:
513  av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
514  m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
515  return AVERROR(ENOSYS);
516  }
517 
518  av_dlog(avctx, "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
519  m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
520  m4ac->sample_rate, m4ac->sbr, m4ac->ps);
521 
522  return get_bits_count(&gb);
523 }
524 
532 static av_always_inline int lcg_random(int previous_val)
533 {
534  return previous_val * 1664525 + 1013904223;
535 }
536 
538 {
539  ps->r0 = 0.0f;
540  ps->r1 = 0.0f;
541  ps->cor0 = 0.0f;
542  ps->cor1 = 0.0f;
543  ps->var0 = 1.0f;
544  ps->var1 = 1.0f;
545 }
546 
548 {
549  int i;
550  for (i = 0; i < MAX_PREDICTORS; i++)
551  reset_predict_state(&ps[i]);
552 }
553 
554 static int sample_rate_idx (int rate)
555 {
556  if (92017 <= rate) return 0;
557  else if (75132 <= rate) return 1;
558  else if (55426 <= rate) return 2;
559  else if (46009 <= rate) return 3;
560  else if (37566 <= rate) return 4;
561  else if (27713 <= rate) return 5;
562  else if (23004 <= rate) return 6;
563  else if (18783 <= rate) return 7;
564  else if (13856 <= rate) return 8;
565  else if (11502 <= rate) return 9;
566  else if (9391 <= rate) return 10;
567  else return 11;
568 }
569 
570 static void reset_predictor_group(PredictorState *ps, int group_num)
571 {
572  int i;
573  for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
574  reset_predict_state(&ps[i]);
575 }
576 
577 #define AAC_INIT_VLC_STATIC(num, size) \
578  INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
579  ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
580  ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
581  size);
582 
584 {
585  AACContext *ac = avctx->priv_data;
586  int ret;
587  float output_scale_factor;
588 
589  ac->avctx = avctx;
590  ac->m4ac.sample_rate = avctx->sample_rate;
591 
592  if (avctx->extradata_size > 0) {
593  if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
594  avctx->extradata,
595  avctx->extradata_size*8, 1)) < 0)
596  return ret;
597  } else {
598  int sr, i;
599  enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
600 
601  sr = sample_rate_idx(avctx->sample_rate);
602  ac->m4ac.sampling_index = sr;
603  ac->m4ac.channels = avctx->channels;
604  ac->m4ac.sbr = -1;
605  ac->m4ac.ps = -1;
606 
607  for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
608  if (ff_mpeg4audio_channels[i] == avctx->channels)
609  break;
611  i = 0;
612  }
613  ac->m4ac.chan_config = i;
614 
615  if (ac->m4ac.chan_config) {
616  int ret = set_default_channel_config(avctx, new_che_pos, ac->m4ac.chan_config);
617  if (!ret)
618  output_configure(ac, ac->che_pos, new_che_pos, ac->m4ac.chan_config, OC_GLOBAL_HDR);
619  else if (avctx->err_recognition & AV_EF_EXPLODE)
620  return AVERROR_INVALIDDATA;
621  }
622  }
623 
624  if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
625  avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
626  output_scale_factor = 1.0 / 32768.0;
627  } else {
628  avctx->sample_fmt = AV_SAMPLE_FMT_S16;
629  output_scale_factor = 1.0;
630  }
631 
632  AAC_INIT_VLC_STATIC( 0, 304);
633  AAC_INIT_VLC_STATIC( 1, 270);
634  AAC_INIT_VLC_STATIC( 2, 550);
635  AAC_INIT_VLC_STATIC( 3, 300);
636  AAC_INIT_VLC_STATIC( 4, 328);
637  AAC_INIT_VLC_STATIC( 5, 294);
638  AAC_INIT_VLC_STATIC( 6, 306);
639  AAC_INIT_VLC_STATIC( 7, 268);
640  AAC_INIT_VLC_STATIC( 8, 510);
641  AAC_INIT_VLC_STATIC( 9, 366);
642  AAC_INIT_VLC_STATIC(10, 462);
643 
644  ff_aac_sbr_init();
645 
646  dsputil_init(&ac->dsp, avctx);
647  ff_fmt_convert_init(&ac->fmt_conv, avctx);
648 
649  ac->random_state = 0x1f2e3d4c;
650 
652 
656  352);
657 
658  ff_mdct_init(&ac->mdct, 11, 1, output_scale_factor/1024.0);
659  ff_mdct_init(&ac->mdct_small, 8, 1, output_scale_factor/128.0);
660  ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0/output_scale_factor);
661  // window initialization
666 
667  cbrt_tableinit();
668 
670  avctx->coded_frame = &ac->frame;
671 
672  return 0;
673 }
674 
679 {
680  int byte_align = get_bits1(gb);
681  int count = get_bits(gb, 8);
682  if (count == 255)
683  count += get_bits(gb, 8);
684  if (byte_align)
685  align_get_bits(gb);
686 
687  if (get_bits_left(gb) < 8 * count) {
689  return AVERROR_INVALIDDATA;
690  }
691  skip_bits_long(gb, 8 * count);
692  return 0;
693 }
694 
696  GetBitContext *gb)
697 {
698  int sfb;
699  if (get_bits1(gb)) {
700  ics->predictor_reset_group = get_bits(gb, 5);
701  if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
702  av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
703  return AVERROR_INVALIDDATA;
704  }
705  }
706  for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
707  ics->prediction_used[sfb] = get_bits1(gb);
708  }
709  return 0;
710 }
711 
716  GetBitContext *gb, uint8_t max_sfb)
717 {
718  int sfb;
719 
720  ltp->lag = get_bits(gb, 11);
721  ltp->coef = ltp_coef[get_bits(gb, 3)];
722  for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
723  ltp->used[sfb] = get_bits1(gb);
724 }
725 
730  GetBitContext *gb)
731 {
732  if (get_bits1(gb)) {
733  av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
734  return AVERROR_INVALIDDATA;
735  }
736  ics->window_sequence[1] = ics->window_sequence[0];
737  ics->window_sequence[0] = get_bits(gb, 2);
738  ics->use_kb_window[1] = ics->use_kb_window[0];
739  ics->use_kb_window[0] = get_bits1(gb);
740  ics->num_window_groups = 1;
741  ics->group_len[0] = 1;
742  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
743  int i;
744  ics->max_sfb = get_bits(gb, 4);
745  for (i = 0; i < 7; i++) {
746  if (get_bits1(gb)) {
747  ics->group_len[ics->num_window_groups - 1]++;
748  } else {
749  ics->num_window_groups++;
750  ics->group_len[ics->num_window_groups - 1] = 1;
751  }
752  }
753  ics->num_windows = 8;
757  ics->predictor_present = 0;
758  } else {
759  ics->max_sfb = get_bits(gb, 6);
760  ics->num_windows = 1;
764  ics->predictor_present = get_bits1(gb);
765  ics->predictor_reset_group = 0;
766  if (ics->predictor_present) {
767  if (ac->m4ac.object_type == AOT_AAC_MAIN) {
768  if (decode_prediction(ac, ics, gb)) {
769  return AVERROR_INVALIDDATA;
770  }
771  } else if (ac->m4ac.object_type == AOT_AAC_LC) {
772  av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
773  return AVERROR_INVALIDDATA;
774  } else {
775  if ((ics->ltp.present = get_bits(gb, 1)))
776  decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);
777  }
778  }
779  }
780 
781  if (ics->max_sfb > ics->num_swb) {
783  "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
784  ics->max_sfb, ics->num_swb);
785  return AVERROR_INVALIDDATA;
786  }
787 
788  return 0;
789 }
790 
799 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
800  int band_type_run_end[120], GetBitContext *gb,
802 {
803  int g, idx = 0;
804  const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
805  for (g = 0; g < ics->num_window_groups; g++) {
806  int k = 0;
807  while (k < ics->max_sfb) {
808  uint8_t sect_end = k;
809  int sect_len_incr;
810  int sect_band_type = get_bits(gb, 4);
811  if (sect_band_type == 12) {
812  av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
813  return AVERROR_INVALIDDATA;
814  }
815  do {
816  sect_len_incr = get_bits(gb, bits);
817  sect_end += sect_len_incr;
818  if (get_bits_left(gb) < 0) {
820  return AVERROR_INVALIDDATA;
821  }
822  if (sect_end > ics->max_sfb) {
824  "Number of bands (%d) exceeds limit (%d).\n",
825  sect_end, ics->max_sfb);
826  return AVERROR_INVALIDDATA;
827  }
828  } while (sect_len_incr == (1 << bits) - 1);
829  for (; k < sect_end; k++) {
830  band_type [idx] = sect_band_type;
831  band_type_run_end[idx++] = sect_end;
832  }
833  }
834  }
835  return 0;
836 }
837 
848 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
849  unsigned int global_gain,
851  enum BandType band_type[120],
852  int band_type_run_end[120])
853 {
854  int g, i, idx = 0;
855  int offset[3] = { global_gain, global_gain - 90, 0 };
856  int clipped_offset;
857  int noise_flag = 1;
858  static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
859  for (g = 0; g < ics->num_window_groups; g++) {
860  for (i = 0; i < ics->max_sfb;) {
861  int run_end = band_type_run_end[idx];
862  if (band_type[idx] == ZERO_BT) {
863  for (; i < run_end; i++, idx++)
864  sf[idx] = 0.;
865  } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
866  for (; i < run_end; i++, idx++) {
867  offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
868  clipped_offset = av_clip(offset[2], -155, 100);
869  if (offset[2] != clipped_offset) {
870  av_log_ask_for_sample(ac->avctx, "Intensity stereo "
871  "position clipped (%d -> %d).\nIf you heard an "
872  "audible artifact, there may be a bug in the "
873  "decoder. ", offset[2], clipped_offset);
874  }
875  sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
876  }
877  } else if (band_type[idx] == NOISE_BT) {
878  for (; i < run_end; i++, idx++) {
879  if (noise_flag-- > 0)
880  offset[1] += get_bits(gb, 9) - 256;
881  else
882  offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
883  clipped_offset = av_clip(offset[1], -100, 155);
884  if (offset[1] != clipped_offset) {
885  av_log_ask_for_sample(ac->avctx, "Noise gain clipped "
886  "(%d -> %d).\nIf you heard an audible "
887  "artifact, there may be a bug in the decoder. ",
888  offset[1], clipped_offset);
889  }
890  sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
891  }
892  } else {
893  for (; i < run_end; i++, idx++) {
894  offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
895  if (offset[0] > 255U) {
897  "%s (%d) out of range.\n", sf_str[0], offset[0]);
898  return AVERROR_INVALIDDATA;
899  }
900  sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
901  }
902  }
903  }
904  }
905  return 0;
906 }
907 
911 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
912  const uint16_t *swb_offset, int num_swb)
913 {
914  int i, pulse_swb;
915  pulse->num_pulse = get_bits(gb, 2) + 1;
916  pulse_swb = get_bits(gb, 6);
917  if (pulse_swb >= num_swb)
918  return -1;
919  pulse->pos[0] = swb_offset[pulse_swb];
920  pulse->pos[0] += get_bits(gb, 5);
921  if (pulse->pos[0] > 1023)
922  return -1;
923  pulse->amp[0] = get_bits(gb, 4);
924  for (i = 1; i < pulse->num_pulse; i++) {
925  pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
926  if (pulse->pos[i] > 1023)
927  return -1;
928  pulse->amp[i] = get_bits(gb, 4);
929  }
930  return 0;
931 }
932 
939  GetBitContext *gb, const IndividualChannelStream *ics)
940 {
941  int w, filt, i, coef_len, coef_res, coef_compress;
942  const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
943  const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
944  for (w = 0; w < ics->num_windows; w++) {
945  if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
946  coef_res = get_bits1(gb);
947 
948  for (filt = 0; filt < tns->n_filt[w]; filt++) {
949  int tmp2_idx;
950  tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
951 
952  if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
953  av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
954  tns->order[w][filt], tns_max_order);
955  tns->order[w][filt] = 0;
956  return AVERROR_INVALIDDATA;
957  }
958  if (tns->order[w][filt]) {
959  tns->direction[w][filt] = get_bits1(gb);
960  coef_compress = get_bits1(gb);
961  coef_len = coef_res + 3 - coef_compress;
962  tmp2_idx = 2 * coef_compress + coef_res;
963 
964  for (i = 0; i < tns->order[w][filt]; i++)
965  tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
966  }
967  }
968  }
969  }
970  return 0;
971 }
972 
981  int ms_present)
982 {
983  int idx;
984  if (ms_present == 1) {
985  for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
986  cpe->ms_mask[idx] = get_bits1(gb);
987  } else if (ms_present == 2) {
988  memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
989  }
990 }
991 
992 #ifndef VMUL2
993 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
994  const float *scale)
995 {
996  float s = *scale;
997  *dst++ = v[idx & 15] * s;
998  *dst++ = v[idx>>4 & 15] * s;
999  return dst;
1000 }
1001 #endif
1002 
1003 #ifndef VMUL4
1004 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1005  const float *scale)
1006 {
1007  float s = *scale;
1008  *dst++ = v[idx & 3] * s;
1009  *dst++ = v[idx>>2 & 3] * s;
1010  *dst++ = v[idx>>4 & 3] * s;
1011  *dst++ = v[idx>>6 & 3] * s;
1012  return dst;
1013 }
1014 #endif
1015 
1016 #ifndef VMUL2S
1017 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1018  unsigned sign, const float *scale)
1019 {
1020  union av_intfloat32 s0, s1;
1021 
1022  s0.f = s1.f = *scale;
1023  s0.i ^= sign >> 1 << 31;
1024  s1.i ^= sign << 31;
1025 
1026  *dst++ = v[idx & 15] * s0.f;
1027  *dst++ = v[idx>>4 & 15] * s1.f;
1028 
1029  return dst;
1030 }
1031 #endif
1032 
1033 #ifndef VMUL4S
1034 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1035  unsigned sign, const float *scale)
1036 {
1037  unsigned nz = idx >> 12;
1038  union av_intfloat32 s = { .f = *scale };
1039  union av_intfloat32 t;
1040 
1041  t.i = s.i ^ (sign & 1U<<31);
1042  *dst++ = v[idx & 3] * t.f;
1043 
1044  sign <<= nz & 1; nz >>= 1;
1045  t.i = s.i ^ (sign & 1U<<31);
1046  *dst++ = v[idx>>2 & 3] * t.f;
1047 
1048  sign <<= nz & 1; nz >>= 1;
1049  t.i = s.i ^ (sign & 1U<<31);
1050  *dst++ = v[idx>>4 & 3] * t.f;
1051 
1052  sign <<= nz & 1; nz >>= 1;
1053  t.i = s.i ^ (sign & 1U<<31);
1054  *dst++ = v[idx>>6 & 3] * t.f;
1055 
1056  return dst;
1057 }
1058 #endif
1059 
1072 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1073  GetBitContext *gb, const float sf[120],
1074  int pulse_present, const Pulse *pulse,
1075  const IndividualChannelStream *ics,
1076  enum BandType band_type[120])
1077 {
1078  int i, k, g, idx = 0;
1079  const int c = 1024 / ics->num_windows;
1080  const uint16_t *offsets = ics->swb_offset;
1081  float *coef_base = coef;
1082 
1083  for (g = 0; g < ics->num_windows; g++)
1084  memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
1085 
1086  for (g = 0; g < ics->num_window_groups; g++) {
1087  unsigned g_len = ics->group_len[g];
1088 
1089  for (i = 0; i < ics->max_sfb; i++, idx++) {
1090  const unsigned cbt_m1 = band_type[idx] - 1;
1091  float *cfo = coef + offsets[i];
1092  int off_len = offsets[i + 1] - offsets[i];
1093  int group;
1094 
1095  if (cbt_m1 >= INTENSITY_BT2 - 1) {
1096  for (group = 0; group < g_len; group++, cfo+=128) {
1097  memset(cfo, 0, off_len * sizeof(float));
1098  }
1099  } else if (cbt_m1 == NOISE_BT - 1) {
1100  for (group = 0; group < g_len; group++, cfo+=128) {
1101  float scale;
1102  float band_energy;
1103 
1104  for (k = 0; k < off_len; k++) {
1106  cfo[k] = ac->random_state;
1107  }
1108 
1109  band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
1110  scale = sf[idx] / sqrtf(band_energy);
1111  ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1112  }
1113  } else {
1114  const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1115  const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1116  VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1117  OPEN_READER(re, gb);
1118 
1119  switch (cbt_m1 >> 1) {
1120  case 0:
1121  for (group = 0; group < g_len; group++, cfo+=128) {
1122  float *cf = cfo;
1123  int len = off_len;
1124 
1125  do {
1126  int code;
1127  unsigned cb_idx;
1128 
1129  UPDATE_CACHE(re, gb);
1130  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1131  cb_idx = cb_vector_idx[code];
1132  cf = VMUL4(cf, vq, cb_idx, sf + idx);
1133  } while (len -= 4);
1134  }
1135  break;
1136 
1137  case 1:
1138  for (group = 0; group < g_len; group++, cfo+=128) {
1139  float *cf = cfo;
1140  int len = off_len;
1141 
1142  do {
1143  int code;
1144  unsigned nnz;
1145  unsigned cb_idx;
1146  uint32_t bits;
1147 
1148  UPDATE_CACHE(re, gb);
1149  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1150  cb_idx = cb_vector_idx[code];
1151  nnz = cb_idx >> 8 & 15;
1152  bits = nnz ? GET_CACHE(re, gb) : 0;
1153  LAST_SKIP_BITS(re, gb, nnz);
1154  cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1155  } while (len -= 4);
1156  }
1157  break;
1158 
1159  case 2:
1160  for (group = 0; group < g_len; group++, cfo+=128) {
1161  float *cf = cfo;
1162  int len = off_len;
1163 
1164  do {
1165  int code;
1166  unsigned cb_idx;
1167 
1168  UPDATE_CACHE(re, gb);
1169  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1170  cb_idx = cb_vector_idx[code];
1171  cf = VMUL2(cf, vq, cb_idx, sf + idx);
1172  } while (len -= 2);
1173  }
1174  break;
1175 
1176  case 3:
1177  case 4:
1178  for (group = 0; group < g_len; group++, cfo+=128) {
1179  float *cf = cfo;
1180  int len = off_len;
1181 
1182  do {
1183  int code;
1184  unsigned nnz;
1185  unsigned cb_idx;
1186  unsigned sign;
1187 
1188  UPDATE_CACHE(re, gb);
1189  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1190  cb_idx = cb_vector_idx[code];
1191  nnz = cb_idx >> 8 & 15;
1192  sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1193  LAST_SKIP_BITS(re, gb, nnz);
1194  cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1195  } while (len -= 2);
1196  }
1197  break;
1198 
1199  default:
1200  for (group = 0; group < g_len; group++, cfo+=128) {
1201  float *cf = cfo;
1202  uint32_t *icf = (uint32_t *) cf;
1203  int len = off_len;
1204 
1205  do {
1206  int code;
1207  unsigned nzt, nnz;
1208  unsigned cb_idx;
1209  uint32_t bits;
1210  int j;
1211 
1212  UPDATE_CACHE(re, gb);
1213  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1214 
1215  if (!code) {
1216  *icf++ = 0;
1217  *icf++ = 0;
1218  continue;
1219  }
1220 
1221  cb_idx = cb_vector_idx[code];
1222  nnz = cb_idx >> 12;
1223  nzt = cb_idx >> 8;
1224  bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1225  LAST_SKIP_BITS(re, gb, nnz);
1226 
1227  for (j = 0; j < 2; j++) {
1228  if (nzt & 1<<j) {
1229  uint32_t b;
1230  int n;
1231  /* The total length of escape_sequence must be < 22 bits according
1232  to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1233  UPDATE_CACHE(re, gb);
1234  b = GET_CACHE(re, gb);
1235  b = 31 - av_log2(~b);
1236 
1237  if (b > 8) {
1238  av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1239  return AVERROR_INVALIDDATA;
1240  }
1241 
1242  SKIP_BITS(re, gb, b + 1);
1243  b += 4;
1244  n = (1 << b) + SHOW_UBITS(re, gb, b);
1245  LAST_SKIP_BITS(re, gb, b);
1246  *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1247  bits <<= 1;
1248  } else {
1249  unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1250  *icf++ = (bits & 1U<<31) | v;
1251  bits <<= !!v;
1252  }
1253  cb_idx >>= 4;
1254  }
1255  } while (len -= 2);
1256 
1257  ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1258  }
1259  }
1260 
1261  CLOSE_READER(re, gb);
1262  }
1263  }
1264  coef += g_len << 7;
1265  }
1266 
1267  if (pulse_present) {
1268  idx = 0;
1269  for (i = 0; i < pulse->num_pulse; i++) {
1270  float co = coef_base[ pulse->pos[i] ];
1271  while (offsets[idx + 1] <= pulse->pos[i])
1272  idx++;
1273  if (band_type[idx] != NOISE_BT && sf[idx]) {
1274  float ico = -pulse->amp[i];
1275  if (co) {
1276  co /= sf[idx];
1277  ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1278  }
1279  coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1280  }
1281  }
1282  }
1283  return 0;
1284 }
1285 
1286 static av_always_inline float flt16_round(float pf)
1287 {
1288  union av_intfloat32 tmp;
1289  tmp.f = pf;
1290  tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1291  return tmp.f;
1292 }
1293 
1294 static av_always_inline float flt16_even(float pf)
1295 {
1296  union av_intfloat32 tmp;
1297  tmp.f = pf;
1298  tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1299  return tmp.f;
1300 }
1301 
1302 static av_always_inline float flt16_trunc(float pf)
1303 {
1304  union av_intfloat32 pun;
1305  pun.f = pf;
1306  pun.i &= 0xFFFF0000U;
1307  return pun.f;
1308 }
1309 
1310 static av_always_inline void predict(PredictorState *ps, float *coef,
1311  int output_enable)
1312 {
1313  const float a = 0.953125; // 61.0 / 64
1314  const float alpha = 0.90625; // 29.0 / 32
1315  float e0, e1;
1316  float pv;
1317  float k1, k2;
1318  float r0 = ps->r0, r1 = ps->r1;
1319  float cor0 = ps->cor0, cor1 = ps->cor1;
1320  float var0 = ps->var0, var1 = ps->var1;
1321 
1322  k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1323  k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1324 
1325  pv = flt16_round(k1 * r0 + k2 * r1);
1326  if (output_enable)
1327  *coef += pv;
1328 
1329  e0 = *coef;
1330  e1 = e0 - k1 * r0;
1331 
1332  ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1333  ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1334  ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1335  ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1336 
1337  ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1338  ps->r0 = flt16_trunc(a * e0);
1339 }
1340 
1345 {
1346  int sfb, k;
1347 
1348  if (!sce->ics.predictor_initialized) {
1350  sce->ics.predictor_initialized = 1;
1351  }
1352 
1353  if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1354  for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
1355  for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
1356  predict(&sce->predictor_state[k], &sce->coeffs[k],
1357  sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
1358  }
1359  }
1360  if (sce->ics.predictor_reset_group)
1362  } else
1364 }
1365 
1375  GetBitContext *gb, int common_window, int scale_flag)
1376 {
1377  Pulse pulse;
1378  TemporalNoiseShaping *tns = &sce->tns;
1379  IndividualChannelStream *ics = &sce->ics;
1380  float *out = sce->coeffs;
1381  int global_gain, pulse_present = 0;
1382  int ret;
1383 
1384  /* This assignment is to silence a GCC warning about the variable being used
1385  * uninitialized when in fact it always is.
1386  */
1387  pulse.num_pulse = 0;
1388 
1389  global_gain = get_bits(gb, 8);
1390 
1391  if (!common_window && !scale_flag) {
1392  if (decode_ics_info(ac, ics, gb) < 0)
1393  return AVERROR_INVALIDDATA;
1394  }
1395 
1396  if ((ret = decode_band_types(ac, sce->band_type,
1397  sce->band_type_run_end, gb, ics)) < 0)
1398  return ret;
1399  if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1400  sce->band_type, sce->band_type_run_end)) < 0)
1401  return ret;
1402 
1403  pulse_present = 0;
1404  if (!scale_flag) {
1405  if ((pulse_present = get_bits1(gb))) {
1406  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1407  av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
1408  return AVERROR_INVALIDDATA;
1409  }
1410  if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1411  av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
1412  return AVERROR_INVALIDDATA;
1413  }
1414  }
1415  if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1416  return AVERROR_INVALIDDATA;
1417  if (get_bits1(gb)) {
1418  av_log_missing_feature(ac->avctx, "SSR", 1);
1419  return -1;
1420  }
1421  }
1422 
1423  if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1424  return AVERROR_INVALIDDATA;
1425 
1426  if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
1427  apply_prediction(ac, sce);
1428 
1429  return 0;
1430 }
1431 
1436 {
1437  const IndividualChannelStream *ics = &cpe->ch[0].ics;
1438  float *ch0 = cpe->ch[0].coeffs;
1439  float *ch1 = cpe->ch[1].coeffs;
1440  int g, i, group, idx = 0;
1441  const uint16_t *offsets = ics->swb_offset;
1442  for (g = 0; g < ics->num_window_groups; g++) {
1443  for (i = 0; i < ics->max_sfb; i++, idx++) {
1444  if (cpe->ms_mask[idx] &&
1445  cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
1446  for (group = 0; group < ics->group_len[g]; group++) {
1447  ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
1448  ch1 + group * 128 + offsets[i],
1449  offsets[i+1] - offsets[i]);
1450  }
1451  }
1452  }
1453  ch0 += ics->group_len[g] * 128;
1454  ch1 += ics->group_len[g] * 128;
1455  }
1456 }
1457 
1465 static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
1466 {
1467  const IndividualChannelStream *ics = &cpe->ch[1].ics;
1468  SingleChannelElement *sce1 = &cpe->ch[1];
1469  float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1470  const uint16_t *offsets = ics->swb_offset;
1471  int g, group, i, idx = 0;
1472  int c;
1473  float scale;
1474  for (g = 0; g < ics->num_window_groups; g++) {
1475  for (i = 0; i < ics->max_sfb;) {
1476  if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1477  const int bt_run_end = sce1->band_type_run_end[idx];
1478  for (; i < bt_run_end; i++, idx++) {
1479  c = -1 + 2 * (sce1->band_type[idx] - 14);
1480  if (ms_present)
1481  c *= 1 - 2 * cpe->ms_mask[idx];
1482  scale = c * sce1->sf[idx];
1483  for (group = 0; group < ics->group_len[g]; group++)
1484  ac->dsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1485  coef0 + group * 128 + offsets[i],
1486  scale,
1487  offsets[i + 1] - offsets[i]);
1488  }
1489  } else {
1490  int bt_run_end = sce1->band_type_run_end[idx];
1491  idx += bt_run_end - i;
1492  i = bt_run_end;
1493  }
1494  }
1495  coef0 += ics->group_len[g] * 128;
1496  coef1 += ics->group_len[g] * 128;
1497  }
1498 }
1499 
1506 {
1507  int i, ret, common_window, ms_present = 0;
1508 
1509  common_window = get_bits1(gb);
1510  if (common_window) {
1511  if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1512  return AVERROR_INVALIDDATA;
1513  i = cpe->ch[1].ics.use_kb_window[0];
1514  cpe->ch[1].ics = cpe->ch[0].ics;
1515  cpe->ch[1].ics.use_kb_window[1] = i;
1516  if (cpe->ch[1].ics.predictor_present && (ac->m4ac.object_type != AOT_AAC_MAIN))
1517  if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1518  decode_ltp(ac, &cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1519  ms_present = get_bits(gb, 2);
1520  if (ms_present == 3) {
1521  av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1522  return AVERROR_INVALIDDATA;
1523  } else if (ms_present)
1524  decode_mid_side_stereo(cpe, gb, ms_present);
1525  }
1526  if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1527  return ret;
1528  if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1529  return ret;
1530 
1531  if (common_window) {
1532  if (ms_present)
1533  apply_mid_side_stereo(ac, cpe);
1534  if (ac->m4ac.object_type == AOT_AAC_MAIN) {
1535  apply_prediction(ac, &cpe->ch[0]);
1536  apply_prediction(ac, &cpe->ch[1]);
1537  }
1538  }
1539 
1540  apply_intensity_stereo(ac, cpe, ms_present);
1541  return 0;
1542 }
1543 
1544 static const float cce_scale[] = {
1545  1.09050773266525765921, //2^(1/8)
1546  1.18920711500272106672, //2^(1/4)
1547  M_SQRT2,
1548  2,
1549 };
1550 
1557 {
1558  int num_gain = 0;
1559  int c, g, sfb, ret;
1560  int sign;
1561  float scale;
1562  SingleChannelElement *sce = &che->ch[0];
1563  ChannelCoupling *coup = &che->coup;
1564 
1565  coup->coupling_point = 2 * get_bits1(gb);
1566  coup->num_coupled = get_bits(gb, 3);
1567  for (c = 0; c <= coup->num_coupled; c++) {
1568  num_gain++;
1569  coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1570  coup->id_select[c] = get_bits(gb, 4);
1571  if (coup->type[c] == TYPE_CPE) {
1572  coup->ch_select[c] = get_bits(gb, 2);
1573  if (coup->ch_select[c] == 3)
1574  num_gain++;
1575  } else
1576  coup->ch_select[c] = 2;
1577  }
1578  coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1579 
1580  sign = get_bits(gb, 1);
1581  scale = cce_scale[get_bits(gb, 2)];
1582 
1583  if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1584  return ret;
1585 
1586  for (c = 0; c < num_gain; c++) {
1587  int idx = 0;
1588  int cge = 1;
1589  int gain = 0;
1590  float gain_cache = 1.;
1591  if (c) {
1592  cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1593  gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1594  gain_cache = powf(scale, -gain);
1595  }
1596  if (coup->coupling_point == AFTER_IMDCT) {
1597  coup->gain[c][0] = gain_cache;
1598  } else {
1599  for (g = 0; g < sce->ics.num_window_groups; g++) {
1600  for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1601  if (sce->band_type[idx] != ZERO_BT) {
1602  if (!cge) {
1603  int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1604  if (t) {
1605  int s = 1;
1606  t = gain += t;
1607  if (sign) {
1608  s -= 2 * (t & 0x1);
1609  t >>= 1;
1610  }
1611  gain_cache = powf(scale, -t) * s;
1612  }
1613  }
1614  coup->gain[c][idx] = gain_cache;
1615  }
1616  }
1617  }
1618  }
1619  }
1620  return 0;
1621 }
1622 
1629  GetBitContext *gb)
1630 {
1631  int i;
1632  int num_excl_chan = 0;
1633 
1634  do {
1635  for (i = 0; i < 7; i++)
1636  che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1637  } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1638 
1639  return num_excl_chan / 7;
1640 }
1641 
1650  GetBitContext *gb, int cnt)
1651 {
1652  int n = 1;
1653  int drc_num_bands = 1;
1654  int i;
1655 
1656  /* pce_tag_present? */
1657  if (get_bits1(gb)) {
1658  che_drc->pce_instance_tag = get_bits(gb, 4);
1659  skip_bits(gb, 4); // tag_reserved_bits
1660  n++;
1661  }
1662 
1663  /* excluded_chns_present? */
1664  if (get_bits1(gb)) {
1665  n += decode_drc_channel_exclusions(che_drc, gb);
1666  }
1667 
1668  /* drc_bands_present? */
1669  if (get_bits1(gb)) {
1670  che_drc->band_incr = get_bits(gb, 4);
1671  che_drc->interpolation_scheme = get_bits(gb, 4);
1672  n++;
1673  drc_num_bands += che_drc->band_incr;
1674  for (i = 0; i < drc_num_bands; i++) {
1675  che_drc->band_top[i] = get_bits(gb, 8);
1676  n++;
1677  }
1678  }
1679 
1680  /* prog_ref_level_present? */
1681  if (get_bits1(gb)) {
1682  che_drc->prog_ref_level = get_bits(gb, 7);
1683  skip_bits1(gb); // prog_ref_level_reserved_bits
1684  n++;
1685  }
1686 
1687  for (i = 0; i < drc_num_bands; i++) {
1688  che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1689  che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1690  n++;
1691  }
1692 
1693  return n;
1694 }
1695 
1704  ChannelElement *che, enum RawDataBlockType elem_type)
1705 {
1706  int crc_flag = 0;
1707  int res = cnt;
1708  switch (get_bits(gb, 4)) { // extension type
1709  case EXT_SBR_DATA_CRC:
1710  crc_flag++;
1711  case EXT_SBR_DATA:
1712  if (!che) {
1713  av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
1714  return res;
1715  } else if (!ac->m4ac.sbr) {
1716  av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
1717  skip_bits_long(gb, 8 * cnt - 4);
1718  return res;
1719  } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
1720  av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
1721  skip_bits_long(gb, 8 * cnt - 4);
1722  return res;
1723  } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
1724  ac->m4ac.sbr = 1;
1725  ac->m4ac.ps = 1;
1727  } else {
1728  ac->m4ac.sbr = 1;
1729  }
1730  res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
1731  break;
1732  case EXT_DYNAMIC_RANGE:
1733  res = decode_dynamic_range(&ac->che_drc, gb, cnt);
1734  break;
1735  case EXT_FILL:
1736  case EXT_FILL_DATA:
1737  case EXT_DATA_ELEMENT:
1738  default:
1739  skip_bits_long(gb, 8 * cnt - 4);
1740  break;
1741  };
1742  return res;
1743 }
1744 
1751 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1752  IndividualChannelStream *ics, int decode)
1753 {
1754  const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1755  int w, filt, m, i;
1756  int bottom, top, order, start, end, size, inc;
1757  float lpc[TNS_MAX_ORDER];
1758  float tmp[TNS_MAX_ORDER + 1];
1759 
1760  for (w = 0; w < ics->num_windows; w++) {
1761  bottom = ics->num_swb;
1762  for (filt = 0; filt < tns->n_filt[w]; filt++) {
1763  top = bottom;
1764  bottom = FFMAX(0, top - tns->length[w][filt]);
1765  order = tns->order[w][filt];
1766  if (order == 0)
1767  continue;
1768 
1769  // tns_decode_coef
1770  compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
1771 
1772  start = ics->swb_offset[FFMIN(bottom, mmm)];
1773  end = ics->swb_offset[FFMIN( top, mmm)];
1774  if ((size = end - start) <= 0)
1775  continue;
1776  if (tns->direction[w][filt]) {
1777  inc = -1;
1778  start = end - 1;
1779  } else {
1780  inc = 1;
1781  }
1782  start += w * 128;
1783 
1784  if (decode) {
1785  // ar filter
1786  for (m = 0; m < size; m++, start += inc)
1787  for (i = 1; i <= FFMIN(m, order); i++)
1788  coef[start] -= coef[start - i * inc] * lpc[i - 1];
1789  } else {
1790  // ma filter
1791  for (m = 0; m < size; m++, start += inc) {
1792  tmp[0] = coef[start];
1793  for (i = 1; i <= FFMIN(m, order); i++)
1794  coef[start] += tmp[i] * lpc[i - 1];
1795  for (i = order; i > 0; i--)
1796  tmp[i] = tmp[i - 1];
1797  }
1798  }
1799  }
1800  }
1801 }
1802 
1807 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
1808  float *in, IndividualChannelStream *ics)
1809 {
1810  const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1811  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1812  const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1813  const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1814 
1815  if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
1816  ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);
1817  } else {
1818  memset(in, 0, 448 * sizeof(float));
1819  ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
1820  }
1821  if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
1822  ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
1823  } else {
1824  ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
1825  memset(in + 1024 + 576, 0, 448 * sizeof(float));
1826  }
1827  ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
1828 }
1829 
1834 {
1835  const LongTermPrediction *ltp = &sce->ics.ltp;
1836  const uint16_t *offsets = sce->ics.swb_offset;
1837  int i, sfb;
1838 
1839  if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1840  float *predTime = sce->ret;
1841  float *predFreq = ac->buf_mdct;
1842  int16_t num_samples = 2048;
1843 
1844  if (ltp->lag < 1024)
1845  num_samples = ltp->lag + 1024;
1846  for (i = 0; i < num_samples; i++)
1847  predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
1848  memset(&predTime[i], 0, (2048 - i) * sizeof(float));
1849 
1850  windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
1851 
1852  if (sce->tns.present)
1853  apply_tns(predFreq, &sce->tns, &sce->ics, 0);
1854 
1855  for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
1856  if (ltp->used[sfb])
1857  for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
1858  sce->coeffs[i] += predFreq[i];
1859  }
1860 }
1861 
1866 {
1867  IndividualChannelStream *ics = &sce->ics;
1868  float *saved = sce->saved;
1869  float *saved_ltp = sce->coeffs;
1870  const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1871  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1872  int i;
1873 
1874  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1875  memcpy(saved_ltp, saved, 512 * sizeof(float));
1876  memset(saved_ltp + 576, 0, 448 * sizeof(float));
1877  ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
1878  for (i = 0; i < 64; i++)
1879  saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
1880  } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1881  memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
1882  memset(saved_ltp + 576, 0, 448 * sizeof(float));
1883  ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
1884  for (i = 0; i < 64; i++)
1885  saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
1886  } else { // LONG_STOP or ONLY_LONG
1887  ac->dsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
1888  for (i = 0; i < 512; i++)
1889  saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
1890  }
1891 
1892  memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
1893  memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
1894  memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
1895 }
1896 
1901 {
1902  IndividualChannelStream *ics = &sce->ics;
1903  float *in = sce->coeffs;
1904  float *out = sce->ret;
1905  float *saved = sce->saved;
1906  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1907  const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1908  const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1909  float *buf = ac->buf_mdct;
1910  float *temp = ac->temp;
1911  int i;
1912 
1913  // imdct
1914  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1915  for (i = 0; i < 1024; i += 128)
1916  ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
1917  } else
1918  ac->mdct.imdct_half(&ac->mdct, buf, in);
1919 
1920  /* window overlapping
1921  * NOTE: To simplify the overlapping code, all 'meaningless' short to long
1922  * and long to short transitions are considered to be short to short
1923  * transitions. This leaves just two cases (long to long and short to short)
1924  * with a little special sauce for EIGHT_SHORT_SEQUENCE.
1925  */
1926  if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
1928  ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
1929  } else {
1930  memcpy( out, saved, 448 * sizeof(float));
1931 
1932  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1933  ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
1934  ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
1935  ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
1936  ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
1937  ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
1938  memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
1939  } else {
1940  ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
1941  memcpy( out + 576, buf + 64, 448 * sizeof(float));
1942  }
1943  }
1944 
1945  // buffer update
1946  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1947  memcpy( saved, temp + 64, 64 * sizeof(float));
1948  ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
1949  ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
1950  ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
1951  memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1952  } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1953  memcpy( saved, buf + 512, 448 * sizeof(float));
1954  memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1955  } else { // LONG_STOP or ONLY_LONG
1956  memcpy( saved, buf + 512, 512 * sizeof(float));
1957  }
1958 }
1959 
1966  SingleChannelElement *target,
1967  ChannelElement *cce, int index)
1968 {
1969  IndividualChannelStream *ics = &cce->ch[0].ics;
1970  const uint16_t *offsets = ics->swb_offset;
1971  float *dest = target->coeffs;
1972  const float *src = cce->ch[0].coeffs;
1973  int g, i, group, k, idx = 0;
1974  if (ac->m4ac.object_type == AOT_AAC_LTP) {
1975  av_log(ac->avctx, AV_LOG_ERROR,
1976  "Dependent coupling is not supported together with LTP\n");
1977  return;
1978  }
1979  for (g = 0; g < ics->num_window_groups; g++) {
1980  for (i = 0; i < ics->max_sfb; i++, idx++) {
1981  if (cce->ch[0].band_type[idx] != ZERO_BT) {
1982  const float gain = cce->coup.gain[index][idx];
1983  for (group = 0; group < ics->group_len[g]; group++) {
1984  for (k = offsets[i]; k < offsets[i + 1]; k++) {
1985  // XXX dsputil-ize
1986  dest[group * 128 + k] += gain * src[group * 128 + k];
1987  }
1988  }
1989  }
1990  }
1991  dest += ics->group_len[g] * 128;
1992  src += ics->group_len[g] * 128;
1993  }
1994 }
1995 
2002  SingleChannelElement *target,
2003  ChannelElement *cce, int index)
2004 {
2005  int i;
2006  const float gain = cce->coup.gain[index][0];
2007  const float *src = cce->ch[0].ret;
2008  float *dest = target->ret;
2009  const int len = 1024 << (ac->m4ac.sbr == 1);
2010 
2011  for (i = 0; i < len; i++)
2012  dest[i] += gain * src[i];
2013 }
2014 
2021  enum RawDataBlockType type, int elem_id,
2022  enum CouplingPoint coupling_point,
2023  void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2024 {
2025  int i, c;
2026 
2027  for (i = 0; i < MAX_ELEM_ID; i++) {
2028  ChannelElement *cce = ac->che[TYPE_CCE][i];
2029  int index = 0;
2030 
2031  if (cce && cce->coup.coupling_point == coupling_point) {
2032  ChannelCoupling *coup = &cce->coup;
2033 
2034  for (c = 0; c <= coup->num_coupled; c++) {
2035  if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2036  if (coup->ch_select[c] != 1) {
2037  apply_coupling_method(ac, &cc->ch[0], cce, index);
2038  if (coup->ch_select[c] != 0)
2039  index++;
2040  }
2041  if (coup->ch_select[c] != 2)
2042  apply_coupling_method(ac, &cc->ch[1], cce, index++);
2043  } else
2044  index += 1 + (coup->ch_select[c] == 3);
2045  }
2046  }
2047  }
2048 }
2049 
2054 {
2055  int i, type;
2056  for (type = 3; type >= 0; type--) {
2057  for (i = 0; i < MAX_ELEM_ID; i++) {
2058  ChannelElement *che = ac->che[type][i];
2059  if (che) {
2060  if (type <= TYPE_CPE)
2062  if (ac->m4ac.object_type == AOT_AAC_LTP) {
2063  if (che->ch[0].ics.predictor_present) {
2064  if (che->ch[0].ics.ltp.present)
2065  apply_ltp(ac, &che->ch[0]);
2066  if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2067  apply_ltp(ac, &che->ch[1]);
2068  }
2069  }
2070  if (che->ch[0].tns.present)
2071  apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2072  if (che->ch[1].tns.present)
2073  apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2074  if (type <= TYPE_CPE)
2076  if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2077  imdct_and_windowing(ac, &che->ch[0]);
2078  if (ac->m4ac.object_type == AOT_AAC_LTP)
2079  update_ltp(ac, &che->ch[0]);
2080  if (type == TYPE_CPE) {
2081  imdct_and_windowing(ac, &che->ch[1]);
2082  if (ac->m4ac.object_type == AOT_AAC_LTP)
2083  update_ltp(ac, &che->ch[1]);
2084  }
2085  if (ac->m4ac.sbr > 0) {
2086  ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2087  }
2088  }
2089  if (type <= TYPE_CCE)
2091  }
2092  }
2093  }
2094 }
2095 
2097 {
2098  int size;
2099  AACADTSHeaderInfo hdr_info;
2100 
2101  size = avpriv_aac_parse_header(gb, &hdr_info);
2102  if (size > 0) {
2103  if (hdr_info.chan_config) {
2104  enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
2105  memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
2106  ac->m4ac.chan_config = hdr_info.chan_config;
2107  if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
2108  return -7;
2109  if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config,
2111  return -7;
2112  } else if (ac->output_configured != OC_LOCKED) {
2113  ac->m4ac.chan_config = 0;
2114  ac->output_configured = OC_NONE;
2115  }
2116  if (ac->output_configured != OC_LOCKED) {
2117  ac->m4ac.sbr = -1;
2118  ac->m4ac.ps = -1;
2119  ac->m4ac.sample_rate = hdr_info.sample_rate;
2120  ac->m4ac.sampling_index = hdr_info.sampling_index;
2121  ac->m4ac.object_type = hdr_info.object_type;
2122  }
2123  if (!ac->avctx->sample_rate)
2124  ac->avctx->sample_rate = hdr_info.sample_rate;
2125  if (hdr_info.num_aac_frames == 1) {
2126  if (!hdr_info.crc_absent)
2127  skip_bits(gb, 16);
2128  } else {
2129  av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
2130  return -1;
2131  }
2132  }
2133  return size;
2134 }
2135 
2136 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2137  int *got_frame_ptr, GetBitContext *gb)
2138 {
2139  AACContext *ac = avctx->priv_data;
2140  ChannelElement *che = NULL, *che_prev = NULL;
2141  enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2142  int err, elem_id;
2143  int samples = 0, multiplier, audio_found = 0;
2144 
2145  if (show_bits(gb, 12) == 0xfff) {
2146  if (parse_adts_frame_header(ac, gb) < 0) {
2147  av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2148  return -1;
2149  }
2150  if (ac->m4ac.sampling_index > 12) {
2151  av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
2152  return -1;
2153  }
2154  }
2155 
2156  ac->tags_mapped = 0;
2157  // parse
2158  while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2159  elem_id = get_bits(gb, 4);
2160 
2161  if (elem_type < TYPE_DSE) {
2162  if (!(che=get_che(ac, elem_type, elem_id))) {
2163  av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2164  elem_type, elem_id);
2165  return -1;
2166  }
2167  samples = 1024;
2168  }
2169 
2170  switch (elem_type) {
2171 
2172  case TYPE_SCE:
2173  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2174  audio_found = 1;
2175  break;
2176 
2177  case TYPE_CPE:
2178  err = decode_cpe(ac, gb, che);
2179  audio_found = 1;
2180  break;
2181 
2182  case TYPE_CCE:
2183  err = decode_cce(ac, gb, che);
2184  break;
2185 
2186  case TYPE_LFE:
2187  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2188  audio_found = 1;
2189  break;
2190 
2191  case TYPE_DSE:
2192  err = skip_data_stream_element(ac, gb);
2193  break;
2194 
2195  case TYPE_PCE: {
2196  enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
2197  memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
2198  if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
2199  break;
2200  if (ac->output_configured > OC_TRIAL_PCE)
2201  av_log(avctx, AV_LOG_ERROR,
2202  "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2203  else
2204  err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
2205  break;
2206  }
2207 
2208  case TYPE_FIL:
2209  if (elem_id == 15)
2210  elem_id += get_bits(gb, 8) - 1;
2211  if (get_bits_left(gb) < 8 * elem_id) {
2212  av_log(avctx, AV_LOG_ERROR, overread_err);
2213  return -1;
2214  }
2215  while (elem_id > 0)
2216  elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2217  err = 0; /* FIXME */
2218  break;
2219 
2220  default:
2221  err = -1; /* should not happen, but keeps compiler happy */
2222  break;
2223  }
2224 
2225  che_prev = che;
2226  elem_type_prev = elem_type;
2227 
2228  if (err)
2229  return err;
2230 
2231  if (get_bits_left(gb) < 3) {
2232  av_log(avctx, AV_LOG_ERROR, overread_err);
2233  return -1;
2234  }
2235  }
2236 
2237  spectral_to_sample(ac);
2238 
2239  multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
2240  samples <<= multiplier;
2241  if (ac->output_configured < OC_LOCKED) {
2242  avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
2243  avctx->frame_size = samples;
2244  }
2245 
2246  if (samples) {
2247  /* get output buffer */
2248  ac->frame.nb_samples = samples;
2249  if ((err = ff_get_buffer(avctx, &ac->frame)) < 0) {
2250  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
2251  return err;
2252  }
2253 
2254  if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
2255  ac->fmt_conv.float_interleave((float *)ac->frame.data[0],
2256  (const float **)ac->output_data,
2257  samples, avctx->channels);
2258  else
2259  ac->fmt_conv.float_to_int16_interleave((int16_t *)ac->frame.data[0],
2260  (const float **)ac->output_data,
2261  samples, avctx->channels);
2262 
2263  *(AVFrame *)data = ac->frame;
2264  }
2265  *got_frame_ptr = !!samples;
2266 
2267  if (ac->output_configured && audio_found)
2269 
2270  return 0;
2271 }
2272 
2273 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2274  int *got_frame_ptr, AVPacket *avpkt)
2275 {
2276  AACContext *ac = avctx->priv_data;
2277  const uint8_t *buf = avpkt->data;
2278  int buf_size = avpkt->size;
2279  GetBitContext gb;
2280  int buf_consumed;
2281  int buf_offset;
2282  int err;
2283  int new_extradata_size;
2284  const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2286  &new_extradata_size);
2287 
2288  if (new_extradata) {
2289  av_free(avctx->extradata);
2290  avctx->extradata = av_mallocz(new_extradata_size +
2292  if (!avctx->extradata)
2293  return AVERROR(ENOMEM);
2294  avctx->extradata_size = new_extradata_size;
2295  memcpy(avctx->extradata, new_extradata, new_extradata_size);
2296  if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
2297  avctx->extradata,
2298  avctx->extradata_size*8, 1) < 0)
2299  return AVERROR_INVALIDDATA;
2300  }
2301 
2302  if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
2303  return err;
2304 
2305  if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb)) < 0)
2306  return err;
2307 
2308  buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2309  for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2310  if (buf[buf_offset])
2311  break;
2312 
2313  return buf_size > buf_offset ? buf_consumed : buf_size;
2314 }
2315 
2317 {
2318  AACContext *ac = avctx->priv_data;
2319  int i, type;
2320 
2321  for (i = 0; i < MAX_ELEM_ID; i++) {
2322  for (type = 0; type < 4; type++) {
2323  if (ac->che[type][i])
2324  ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2325  av_freep(&ac->che[type][i]);
2326  }
2327  }
2328 
2329  ff_mdct_end(&ac->mdct);
2330  ff_mdct_end(&ac->mdct_small);
2331  ff_mdct_end(&ac->mdct_ltp);
2332  return 0;
2333 }
2334 
2335 
2336 #define LOAS_SYNC_WORD 0x2b7
2337 
2338 struct LATMContext {
2341 
2342  // parser data
2346 };
2347 
2348 static inline uint32_t latm_get_value(GetBitContext *b)
2349 {
2350  int length = get_bits(b, 2);
2351 
2352  return get_bits_long(b, (length+1)*8);
2353 }
2354 
2356  GetBitContext *gb, int asclen)
2357 {
2358  AACContext *ac = &latmctx->aac_ctx;
2359  AVCodecContext *avctx = ac->avctx;
2360  MPEG4AudioConfig m4ac = {0};
2361  int config_start_bit = get_bits_count(gb);
2362  int sync_extension = 0;
2363  int bits_consumed, esize;
2364 
2365  if (asclen) {
2366  sync_extension = 1;
2367  asclen = FFMIN(asclen, get_bits_left(gb));
2368  } else
2369  asclen = get_bits_left(gb);
2370 
2371  if (config_start_bit % 8) {
2372  av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
2373  "config not byte aligned.\n", 1);
2374  return AVERROR_INVALIDDATA;
2375  }
2376  if (asclen <= 0)
2377  return AVERROR_INVALIDDATA;
2378  bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
2379  gb->buffer + (config_start_bit / 8),
2380  asclen, sync_extension);
2381 
2382  if (bits_consumed < 0)
2383  return AVERROR_INVALIDDATA;
2384 
2385  if (ac->m4ac.sample_rate != m4ac.sample_rate ||
2386  ac->m4ac.chan_config != m4ac.chan_config) {
2387 
2388  av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2389  latmctx->initialized = 0;
2390 
2391  esize = (bits_consumed+7) / 8;
2392 
2393  if (avctx->extradata_size < esize) {
2394  av_free(avctx->extradata);
2396  if (!avctx->extradata)
2397  return AVERROR(ENOMEM);
2398  }
2399 
2400  avctx->extradata_size = esize;
2401  memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2402  memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2403  }
2404  skip_bits_long(gb, bits_consumed);
2405 
2406  return bits_consumed;
2407 }
2408 
2409 static int read_stream_mux_config(struct LATMContext *latmctx,
2410  GetBitContext *gb)
2411 {
2412  int ret, audio_mux_version = get_bits(gb, 1);
2413 
2414  latmctx->audio_mux_version_A = 0;
2415  if (audio_mux_version)
2416  latmctx->audio_mux_version_A = get_bits(gb, 1);
2417 
2418  if (!latmctx->audio_mux_version_A) {
2419 
2420  if (audio_mux_version)
2421  latm_get_value(gb); // taraFullness
2422 
2423  skip_bits(gb, 1); // allStreamSameTimeFraming
2424  skip_bits(gb, 6); // numSubFrames
2425  // numPrograms
2426  if (get_bits(gb, 4)) { // numPrograms
2428  "multiple programs are not supported\n", 1);
2429  return AVERROR_PATCHWELCOME;
2430  }
2431 
2432  // for each program (which there is only on in DVB)
2433 
2434  // for each layer (which there is only on in DVB)
2435  if (get_bits(gb, 3)) { // numLayer
2437  "multiple layers are not supported\n", 1);
2438  return AVERROR_PATCHWELCOME;
2439  }
2440 
2441  // for all but first stream: use_same_config = get_bits(gb, 1);
2442  if (!audio_mux_version) {
2443  if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
2444  return ret;
2445  } else {
2446  int ascLen = latm_get_value(gb);
2447  if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
2448  return ret;
2449  ascLen -= ret;
2450  skip_bits_long(gb, ascLen);
2451  }
2452 
2453  latmctx->frame_length_type = get_bits(gb, 3);
2454  switch (latmctx->frame_length_type) {
2455  case 0:
2456  skip_bits(gb, 8); // latmBufferFullness
2457  break;
2458  case 1:
2459  latmctx->frame_length = get_bits(gb, 9);
2460  break;
2461  case 3:
2462  case 4:
2463  case 5:
2464  skip_bits(gb, 6); // CELP frame length table index
2465  break;
2466  case 6:
2467  case 7:
2468  skip_bits(gb, 1); // HVXC frame length table index
2469  break;
2470  }
2471 
2472  if (get_bits(gb, 1)) { // other data
2473  if (audio_mux_version) {
2474  latm_get_value(gb); // other_data_bits
2475  } else {
2476  int esc;
2477  do {
2478  esc = get_bits(gb, 1);
2479  skip_bits(gb, 8);
2480  } while (esc);
2481  }
2482  }
2483 
2484  if (get_bits(gb, 1)) // crc present
2485  skip_bits(gb, 8); // config_crc
2486  }
2487 
2488  return 0;
2489 }
2490 
2492 {
2493  uint8_t tmp;
2494 
2495  if (ctx->frame_length_type == 0) {
2496  int mux_slot_length = 0;
2497  do {
2498  tmp = get_bits(gb, 8);
2499  mux_slot_length += tmp;
2500  } while (tmp == 255);
2501  return mux_slot_length;
2502  } else if (ctx->frame_length_type == 1) {
2503  return ctx->frame_length;
2504  } else if (ctx->frame_length_type == 3 ||
2505  ctx->frame_length_type == 5 ||
2506  ctx->frame_length_type == 7) {
2507  skip_bits(gb, 2); // mux_slot_length_coded
2508  }
2509  return 0;
2510 }
2511 
2512 static int read_audio_mux_element(struct LATMContext *latmctx,
2513  GetBitContext *gb)
2514 {
2515  int err;
2516  uint8_t use_same_mux = get_bits(gb, 1);
2517  if (!use_same_mux) {
2518  if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2519  return err;
2520  } else if (!latmctx->aac_ctx.avctx->extradata) {
2521  av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2522  "no decoder config found\n");
2523  return AVERROR(EAGAIN);
2524  }
2525  if (latmctx->audio_mux_version_A == 0) {
2526  int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2527  if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2528  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2529  return AVERROR_INVALIDDATA;
2530  } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2531  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2532  "frame length mismatch %d << %d\n",
2533  mux_slot_length_bytes * 8, get_bits_left(gb));
2534  return AVERROR_INVALIDDATA;
2535  }
2536  }
2537  return 0;
2538 }
2539 
2540 
2541 static int latm_decode_frame(AVCodecContext *avctx, void *out,
2542  int *got_frame_ptr, AVPacket *avpkt)
2543 {
2544  struct LATMContext *latmctx = avctx->priv_data;
2545  int muxlength, err;
2546  GetBitContext gb;
2547 
2548  if ((err = init_get_bits(&gb, avpkt->data, avpkt->size * 8)) < 0)
2549  return err;
2550 
2551  // check for LOAS sync word
2552  if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2553  return AVERROR_INVALIDDATA;
2554 
2555  muxlength = get_bits(&gb, 13) + 3;
2556  // not enough data, the parser should have sorted this
2557  if (muxlength > avpkt->size)
2558  return AVERROR_INVALIDDATA;
2559 
2560  if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2561  return err;
2562 
2563  if (!latmctx->initialized) {
2564  if (!avctx->extradata) {
2565  *got_frame_ptr = 0;
2566  return avpkt->size;
2567  } else {
2568  if ((err = decode_audio_specific_config(
2569  &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.m4ac,
2570  avctx->extradata, avctx->extradata_size*8, 1)) < 0)
2571  return err;
2572  latmctx->initialized = 1;
2573  }
2574  }
2575 
2576  if (show_bits(&gb, 12) == 0xfff) {
2577  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2578  "ADTS header detected, probably as result of configuration "
2579  "misparsing\n");
2580  return AVERROR_INVALIDDATA;
2581  }
2582 
2583  if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
2584  return err;
2585 
2586  return muxlength;
2587 }
2588 
2590 {
2591  struct LATMContext *latmctx = avctx->priv_data;
2592  int ret = aac_decode_init(avctx);
2593 
2594  if (avctx->extradata_size > 0)
2595  latmctx->initialized = !ret;
2596 
2597  return ret;
2598 }
2599 
2600 
2602  .name = "aac",
2603  .type = AVMEDIA_TYPE_AUDIO,
2604  .id = CODEC_ID_AAC,
2605  .priv_data_size = sizeof(AACContext),
2606  .init = aac_decode_init,
2609  .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
2610  .sample_fmts = (const enum AVSampleFormat[]) {
2612  },
2613  .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2614  .channel_layouts = aac_channel_layout,
2615 };
2616 
2617 /*
2618  Note: This decoder filter is intended to decode LATM streams transferred
2619  in MPEG transport streams which only contain one program.
2620  To do a more complex LATM demuxing a separate LATM demuxer should be used.
2621 */
2623  .name = "aac_latm",
2624  .type = AVMEDIA_TYPE_AUDIO,
2625  .id = CODEC_ID_AAC_LATM,
2626  .priv_data_size = sizeof(struct LATMContext),
2627  .init = latm_decode_init,
2628  .close = aac_decode_close,
2629  .decode = latm_decode_frame,
2630  .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
2631  .sample_fmts = (const enum AVSampleFormat[]) {
2633  },
2634  .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2635  .channel_layouts = aac_channel_layout,
2636 };