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 -1;
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 -1;
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;
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  init_get_bits(&gb, data, bit_size);
493 
494  if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size, sync_extension)) < 0)
495  return -1;
496  if (m4ac->sampling_index > 12) {
497  av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
498  return -1;
499  }
500 
501  skip_bits_long(&gb, i);
502 
503  switch (m4ac->object_type) {
504  case AOT_AAC_MAIN:
505  case AOT_AAC_LC:
506  case AOT_AAC_LTP:
507  if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
508  return -1;
509  break;
510  default:
511  av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
512  m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
513  return -1;
514  }
515 
516  av_dlog(avctx, "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
517  m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
518  m4ac->sample_rate, m4ac->sbr, m4ac->ps);
519 
520  return get_bits_count(&gb);
521 }
522 
530 static av_always_inline int lcg_random(int previous_val)
531 {
532  return previous_val * 1664525 + 1013904223;
533 }
534 
536 {
537  ps->r0 = 0.0f;
538  ps->r1 = 0.0f;
539  ps->cor0 = 0.0f;
540  ps->cor1 = 0.0f;
541  ps->var0 = 1.0f;
542  ps->var1 = 1.0f;
543 }
544 
546 {
547  int i;
548  for (i = 0; i < MAX_PREDICTORS; i++)
549  reset_predict_state(&ps[i]);
550 }
551 
552 static int sample_rate_idx (int rate)
553 {
554  if (92017 <= rate) return 0;
555  else if (75132 <= rate) return 1;
556  else if (55426 <= rate) return 2;
557  else if (46009 <= rate) return 3;
558  else if (37566 <= rate) return 4;
559  else if (27713 <= rate) return 5;
560  else if (23004 <= rate) return 6;
561  else if (18783 <= rate) return 7;
562  else if (13856 <= rate) return 8;
563  else if (11502 <= rate) return 9;
564  else if (9391 <= rate) return 10;
565  else return 11;
566 }
567 
568 static void reset_predictor_group(PredictorState *ps, int group_num)
569 {
570  int i;
571  for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
572  reset_predict_state(&ps[i]);
573 }
574 
575 #define AAC_INIT_VLC_STATIC(num, size) \
576  INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
577  ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
578  ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
579  size);
580 
582 {
583  AACContext *ac = avctx->priv_data;
584  float output_scale_factor;
585 
586  ac->avctx = avctx;
587  ac->m4ac.sample_rate = avctx->sample_rate;
588 
589  if (avctx->extradata_size > 0) {
590  if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
591  avctx->extradata,
592  avctx->extradata_size*8, 1) < 0)
593  return -1;
594  } else {
595  int sr, i;
596  enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
597 
598  sr = sample_rate_idx(avctx->sample_rate);
599  ac->m4ac.sampling_index = sr;
600  ac->m4ac.channels = avctx->channels;
601  ac->m4ac.sbr = -1;
602  ac->m4ac.ps = -1;
603 
604  for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
605  if (ff_mpeg4audio_channels[i] == avctx->channels)
606  break;
608  i = 0;
609  }
610  ac->m4ac.chan_config = i;
611 
612  if (ac->m4ac.chan_config) {
613  int ret = set_default_channel_config(avctx, new_che_pos, ac->m4ac.chan_config);
614  if (!ret)
615  output_configure(ac, ac->che_pos, new_che_pos, ac->m4ac.chan_config, OC_GLOBAL_HDR);
616  else if (avctx->err_recognition & AV_EF_EXPLODE)
617  return AVERROR_INVALIDDATA;
618  }
619  }
620 
621  if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
622  avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
623  output_scale_factor = 1.0 / 32768.0;
624  } else {
625  avctx->sample_fmt = AV_SAMPLE_FMT_S16;
626  output_scale_factor = 1.0;
627  }
628 
629  AAC_INIT_VLC_STATIC( 0, 304);
630  AAC_INIT_VLC_STATIC( 1, 270);
631  AAC_INIT_VLC_STATIC( 2, 550);
632  AAC_INIT_VLC_STATIC( 3, 300);
633  AAC_INIT_VLC_STATIC( 4, 328);
634  AAC_INIT_VLC_STATIC( 5, 294);
635  AAC_INIT_VLC_STATIC( 6, 306);
636  AAC_INIT_VLC_STATIC( 7, 268);
637  AAC_INIT_VLC_STATIC( 8, 510);
638  AAC_INIT_VLC_STATIC( 9, 366);
639  AAC_INIT_VLC_STATIC(10, 462);
640 
641  ff_aac_sbr_init();
642 
643  dsputil_init(&ac->dsp, avctx);
644  ff_fmt_convert_init(&ac->fmt_conv, avctx);
645 
646  ac->random_state = 0x1f2e3d4c;
647 
649 
653  352);
654 
655  ff_mdct_init(&ac->mdct, 11, 1, output_scale_factor/1024.0);
656  ff_mdct_init(&ac->mdct_small, 8, 1, output_scale_factor/128.0);
657  ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0/output_scale_factor);
658  // window initialization
663 
664  cbrt_tableinit();
665 
667  avctx->coded_frame = &ac->frame;
668 
669  return 0;
670 }
671 
676 {
677  int byte_align = get_bits1(gb);
678  int count = get_bits(gb, 8);
679  if (count == 255)
680  count += get_bits(gb, 8);
681  if (byte_align)
682  align_get_bits(gb);
683 
684  if (get_bits_left(gb) < 8 * count) {
686  return -1;
687  }
688  skip_bits_long(gb, 8 * count);
689  return 0;
690 }
691 
693  GetBitContext *gb)
694 {
695  int sfb;
696  if (get_bits1(gb)) {
697  ics->predictor_reset_group = get_bits(gb, 5);
698  if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
699  av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
700  return -1;
701  }
702  }
703  for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
704  ics->prediction_used[sfb] = get_bits1(gb);
705  }
706  return 0;
707 }
708 
713  GetBitContext *gb, uint8_t max_sfb)
714 {
715  int sfb;
716 
717  ltp->lag = get_bits(gb, 11);
718  ltp->coef = ltp_coef[get_bits(gb, 3)];
719  for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
720  ltp->used[sfb] = get_bits1(gb);
721 }
722 
727  GetBitContext *gb)
728 {
729  if (get_bits1(gb)) {
730  av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
731  return AVERROR_INVALIDDATA;
732  }
733  ics->window_sequence[1] = ics->window_sequence[0];
734  ics->window_sequence[0] = get_bits(gb, 2);
735  ics->use_kb_window[1] = ics->use_kb_window[0];
736  ics->use_kb_window[0] = get_bits1(gb);
737  ics->num_window_groups = 1;
738  ics->group_len[0] = 1;
739  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
740  int i;
741  ics->max_sfb = get_bits(gb, 4);
742  for (i = 0; i < 7; i++) {
743  if (get_bits1(gb)) {
744  ics->group_len[ics->num_window_groups - 1]++;
745  } else {
746  ics->num_window_groups++;
747  ics->group_len[ics->num_window_groups - 1] = 1;
748  }
749  }
750  ics->num_windows = 8;
754  ics->predictor_present = 0;
755  } else {
756  ics->max_sfb = get_bits(gb, 6);
757  ics->num_windows = 1;
761  ics->predictor_present = get_bits1(gb);
762  ics->predictor_reset_group = 0;
763  if (ics->predictor_present) {
764  if (ac->m4ac.object_type == AOT_AAC_MAIN) {
765  if (decode_prediction(ac, ics, gb)) {
766  return AVERROR_INVALIDDATA;
767  }
768  } else if (ac->m4ac.object_type == AOT_AAC_LC) {
769  av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
770  return AVERROR_INVALIDDATA;
771  } else {
772  if ((ics->ltp.present = get_bits(gb, 1)))
773  decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);
774  }
775  }
776  }
777 
778  if (ics->max_sfb > ics->num_swb) {
780  "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
781  ics->max_sfb, ics->num_swb);
782  return AVERROR_INVALIDDATA;
783  }
784 
785  return 0;
786 }
787 
796 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
797  int band_type_run_end[120], GetBitContext *gb,
799 {
800  int g, idx = 0;
801  const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
802  for (g = 0; g < ics->num_window_groups; g++) {
803  int k = 0;
804  while (k < ics->max_sfb) {
805  uint8_t sect_end = k;
806  int sect_len_incr;
807  int sect_band_type = get_bits(gb, 4);
808  if (sect_band_type == 12) {
809  av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
810  return -1;
811  }
812  do {
813  sect_len_incr = get_bits(gb, bits);
814  sect_end += sect_len_incr;
815  if (get_bits_left(gb) < 0) {
817  return -1;
818  }
819  if (sect_end > ics->max_sfb) {
821  "Number of bands (%d) exceeds limit (%d).\n",
822  sect_end, ics->max_sfb);
823  return -1;
824  }
825  } while (sect_len_incr == (1 << bits) - 1);
826  for (; k < sect_end; k++) {
827  band_type [idx] = sect_band_type;
828  band_type_run_end[idx++] = sect_end;
829  }
830  }
831  }
832  return 0;
833 }
834 
845 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
846  unsigned int global_gain,
848  enum BandType band_type[120],
849  int band_type_run_end[120])
850 {
851  int g, i, idx = 0;
852  int offset[3] = { global_gain, global_gain - 90, 0 };
853  int clipped_offset;
854  int noise_flag = 1;
855  static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
856  for (g = 0; g < ics->num_window_groups; g++) {
857  for (i = 0; i < ics->max_sfb;) {
858  int run_end = band_type_run_end[idx];
859  if (band_type[idx] == ZERO_BT) {
860  for (; i < run_end; i++, idx++)
861  sf[idx] = 0.;
862  } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
863  for (; i < run_end; i++, idx++) {
864  offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
865  clipped_offset = av_clip(offset[2], -155, 100);
866  if (offset[2] != clipped_offset) {
867  av_log_ask_for_sample(ac->avctx, "Intensity stereo "
868  "position clipped (%d -> %d).\nIf you heard an "
869  "audible artifact, there may be a bug in the "
870  "decoder. ", offset[2], clipped_offset);
871  }
872  sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
873  }
874  } else if (band_type[idx] == NOISE_BT) {
875  for (; i < run_end; i++, idx++) {
876  if (noise_flag-- > 0)
877  offset[1] += get_bits(gb, 9) - 256;
878  else
879  offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
880  clipped_offset = av_clip(offset[1], -100, 155);
881  if (offset[1] != clipped_offset) {
882  av_log_ask_for_sample(ac->avctx, "Noise gain clipped "
883  "(%d -> %d).\nIf you heard an audible "
884  "artifact, there may be a bug in the decoder. ",
885  offset[1], clipped_offset);
886  }
887  sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
888  }
889  } else {
890  for (; i < run_end; i++, idx++) {
891  offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
892  if (offset[0] > 255U) {
894  "%s (%d) out of range.\n", sf_str[0], offset[0]);
895  return -1;
896  }
897  sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
898  }
899  }
900  }
901  }
902  return 0;
903 }
904 
908 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
909  const uint16_t *swb_offset, int num_swb)
910 {
911  int i, pulse_swb;
912  pulse->num_pulse = get_bits(gb, 2) + 1;
913  pulse_swb = get_bits(gb, 6);
914  if (pulse_swb >= num_swb)
915  return -1;
916  pulse->pos[0] = swb_offset[pulse_swb];
917  pulse->pos[0] += get_bits(gb, 5);
918  if (pulse->pos[0] > 1023)
919  return -1;
920  pulse->amp[0] = get_bits(gb, 4);
921  for (i = 1; i < pulse->num_pulse; i++) {
922  pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
923  if (pulse->pos[i] > 1023)
924  return -1;
925  pulse->amp[i] = get_bits(gb, 4);
926  }
927  return 0;
928 }
929 
936  GetBitContext *gb, const IndividualChannelStream *ics)
937 {
938  int w, filt, i, coef_len, coef_res, coef_compress;
939  const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
940  const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
941  for (w = 0; w < ics->num_windows; w++) {
942  if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
943  coef_res = get_bits1(gb);
944 
945  for (filt = 0; filt < tns->n_filt[w]; filt++) {
946  int tmp2_idx;
947  tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
948 
949  if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
950  av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
951  tns->order[w][filt], tns_max_order);
952  tns->order[w][filt] = 0;
953  return -1;
954  }
955  if (tns->order[w][filt]) {
956  tns->direction[w][filt] = get_bits1(gb);
957  coef_compress = get_bits1(gb);
958  coef_len = coef_res + 3 - coef_compress;
959  tmp2_idx = 2 * coef_compress + coef_res;
960 
961  for (i = 0; i < tns->order[w][filt]; i++)
962  tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
963  }
964  }
965  }
966  }
967  return 0;
968 }
969 
978  int ms_present)
979 {
980  int idx;
981  if (ms_present == 1) {
982  for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
983  cpe->ms_mask[idx] = get_bits1(gb);
984  } else if (ms_present == 2) {
985  memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
986  }
987 }
988 
989 #ifndef VMUL2
990 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
991  const float *scale)
992 {
993  float s = *scale;
994  *dst++ = v[idx & 15] * s;
995  *dst++ = v[idx>>4 & 15] * s;
996  return dst;
997 }
998 #endif
999 
1000 #ifndef VMUL4
1001 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1002  const float *scale)
1003 {
1004  float s = *scale;
1005  *dst++ = v[idx & 3] * s;
1006  *dst++ = v[idx>>2 & 3] * s;
1007  *dst++ = v[idx>>4 & 3] * s;
1008  *dst++ = v[idx>>6 & 3] * s;
1009  return dst;
1010 }
1011 #endif
1012 
1013 #ifndef VMUL2S
1014 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1015  unsigned sign, const float *scale)
1016 {
1017  union av_intfloat32 s0, s1;
1018 
1019  s0.f = s1.f = *scale;
1020  s0.i ^= sign >> 1 << 31;
1021  s1.i ^= sign << 31;
1022 
1023  *dst++ = v[idx & 15] * s0.f;
1024  *dst++ = v[idx>>4 & 15] * s1.f;
1025 
1026  return dst;
1027 }
1028 #endif
1029 
1030 #ifndef VMUL4S
1031 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1032  unsigned sign, const float *scale)
1033 {
1034  unsigned nz = idx >> 12;
1035  union av_intfloat32 s = { .f = *scale };
1036  union av_intfloat32 t;
1037 
1038  t.i = s.i ^ (sign & 1U<<31);
1039  *dst++ = v[idx & 3] * t.f;
1040 
1041  sign <<= nz & 1; nz >>= 1;
1042  t.i = s.i ^ (sign & 1U<<31);
1043  *dst++ = v[idx>>2 & 3] * t.f;
1044 
1045  sign <<= nz & 1; nz >>= 1;
1046  t.i = s.i ^ (sign & 1U<<31);
1047  *dst++ = v[idx>>4 & 3] * t.f;
1048 
1049  sign <<= nz & 1; nz >>= 1;
1050  t.i = s.i ^ (sign & 1U<<31);
1051  *dst++ = v[idx>>6 & 3] * t.f;
1052 
1053  return dst;
1054 }
1055 #endif
1056 
1069 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1070  GetBitContext *gb, const float sf[120],
1071  int pulse_present, const Pulse *pulse,
1072  const IndividualChannelStream *ics,
1073  enum BandType band_type[120])
1074 {
1075  int i, k, g, idx = 0;
1076  const int c = 1024 / ics->num_windows;
1077  const uint16_t *offsets = ics->swb_offset;
1078  float *coef_base = coef;
1079 
1080  for (g = 0; g < ics->num_windows; g++)
1081  memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
1082 
1083  for (g = 0; g < ics->num_window_groups; g++) {
1084  unsigned g_len = ics->group_len[g];
1085 
1086  for (i = 0; i < ics->max_sfb; i++, idx++) {
1087  const unsigned cbt_m1 = band_type[idx] - 1;
1088  float *cfo = coef + offsets[i];
1089  int off_len = offsets[i + 1] - offsets[i];
1090  int group;
1091 
1092  if (cbt_m1 >= INTENSITY_BT2 - 1) {
1093  for (group = 0; group < g_len; group++, cfo+=128) {
1094  memset(cfo, 0, off_len * sizeof(float));
1095  }
1096  } else if (cbt_m1 == NOISE_BT - 1) {
1097  for (group = 0; group < g_len; group++, cfo+=128) {
1098  float scale;
1099  float band_energy;
1100 
1101  for (k = 0; k < off_len; k++) {
1103  cfo[k] = ac->random_state;
1104  }
1105 
1106  band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
1107  scale = sf[idx] / sqrtf(band_energy);
1108  ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1109  }
1110  } else {
1111  const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1112  const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1113  VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1114  OPEN_READER(re, gb);
1115 
1116  switch (cbt_m1 >> 1) {
1117  case 0:
1118  for (group = 0; group < g_len; group++, cfo+=128) {
1119  float *cf = cfo;
1120  int len = off_len;
1121 
1122  do {
1123  int code;
1124  unsigned cb_idx;
1125 
1126  UPDATE_CACHE(re, gb);
1127  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1128  cb_idx = cb_vector_idx[code];
1129  cf = VMUL4(cf, vq, cb_idx, sf + idx);
1130  } while (len -= 4);
1131  }
1132  break;
1133 
1134  case 1:
1135  for (group = 0; group < g_len; group++, cfo+=128) {
1136  float *cf = cfo;
1137  int len = off_len;
1138 
1139  do {
1140  int code;
1141  unsigned nnz;
1142  unsigned cb_idx;
1143  uint32_t bits;
1144 
1145  UPDATE_CACHE(re, gb);
1146  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1147  cb_idx = cb_vector_idx[code];
1148  nnz = cb_idx >> 8 & 15;
1149  bits = nnz ? GET_CACHE(re, gb) : 0;
1150  LAST_SKIP_BITS(re, gb, nnz);
1151  cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1152  } while (len -= 4);
1153  }
1154  break;
1155 
1156  case 2:
1157  for (group = 0; group < g_len; group++, cfo+=128) {
1158  float *cf = cfo;
1159  int len = off_len;
1160 
1161  do {
1162  int code;
1163  unsigned cb_idx;
1164 
1165  UPDATE_CACHE(re, gb);
1166  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1167  cb_idx = cb_vector_idx[code];
1168  cf = VMUL2(cf, vq, cb_idx, sf + idx);
1169  } while (len -= 2);
1170  }
1171  break;
1172 
1173  case 3:
1174  case 4:
1175  for (group = 0; group < g_len; group++, cfo+=128) {
1176  float *cf = cfo;
1177  int len = off_len;
1178 
1179  do {
1180  int code;
1181  unsigned nnz;
1182  unsigned cb_idx;
1183  unsigned sign;
1184 
1185  UPDATE_CACHE(re, gb);
1186  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1187  cb_idx = cb_vector_idx[code];
1188  nnz = cb_idx >> 8 & 15;
1189  sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1190  LAST_SKIP_BITS(re, gb, nnz);
1191  cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1192  } while (len -= 2);
1193  }
1194  break;
1195 
1196  default:
1197  for (group = 0; group < g_len; group++, cfo+=128) {
1198  float *cf = cfo;
1199  uint32_t *icf = (uint32_t *) cf;
1200  int len = off_len;
1201 
1202  do {
1203  int code;
1204  unsigned nzt, nnz;
1205  unsigned cb_idx;
1206  uint32_t bits;
1207  int j;
1208 
1209  UPDATE_CACHE(re, gb);
1210  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1211 
1212  if (!code) {
1213  *icf++ = 0;
1214  *icf++ = 0;
1215  continue;
1216  }
1217 
1218  cb_idx = cb_vector_idx[code];
1219  nnz = cb_idx >> 12;
1220  nzt = cb_idx >> 8;
1221  bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1222  LAST_SKIP_BITS(re, gb, nnz);
1223 
1224  for (j = 0; j < 2; j++) {
1225  if (nzt & 1<<j) {
1226  uint32_t b;
1227  int n;
1228  /* The total length of escape_sequence must be < 22 bits according
1229  to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1230  UPDATE_CACHE(re, gb);
1231  b = GET_CACHE(re, gb);
1232  b = 31 - av_log2(~b);
1233 
1234  if (b > 8) {
1235  av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1236  return -1;
1237  }
1238 
1239  SKIP_BITS(re, gb, b + 1);
1240  b += 4;
1241  n = (1 << b) + SHOW_UBITS(re, gb, b);
1242  LAST_SKIP_BITS(re, gb, b);
1243  *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1244  bits <<= 1;
1245  } else {
1246  unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1247  *icf++ = (bits & 1U<<31) | v;
1248  bits <<= !!v;
1249  }
1250  cb_idx >>= 4;
1251  }
1252  } while (len -= 2);
1253 
1254  ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1255  }
1256  }
1257 
1258  CLOSE_READER(re, gb);
1259  }
1260  }
1261  coef += g_len << 7;
1262  }
1263 
1264  if (pulse_present) {
1265  idx = 0;
1266  for (i = 0; i < pulse->num_pulse; i++) {
1267  float co = coef_base[ pulse->pos[i] ];
1268  while (offsets[idx + 1] <= pulse->pos[i])
1269  idx++;
1270  if (band_type[idx] != NOISE_BT && sf[idx]) {
1271  float ico = -pulse->amp[i];
1272  if (co) {
1273  co /= sf[idx];
1274  ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1275  }
1276  coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1277  }
1278  }
1279  }
1280  return 0;
1281 }
1282 
1283 static av_always_inline float flt16_round(float pf)
1284 {
1285  union av_intfloat32 tmp;
1286  tmp.f = pf;
1287  tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1288  return tmp.f;
1289 }
1290 
1291 static av_always_inline float flt16_even(float pf)
1292 {
1293  union av_intfloat32 tmp;
1294  tmp.f = pf;
1295  tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1296  return tmp.f;
1297 }
1298 
1299 static av_always_inline float flt16_trunc(float pf)
1300 {
1301  union av_intfloat32 pun;
1302  pun.f = pf;
1303  pun.i &= 0xFFFF0000U;
1304  return pun.f;
1305 }
1306 
1307 static av_always_inline void predict(PredictorState *ps, float *coef,
1308  int output_enable)
1309 {
1310  const float a = 0.953125; // 61.0 / 64
1311  const float alpha = 0.90625; // 29.0 / 32
1312  float e0, e1;
1313  float pv;
1314  float k1, k2;
1315  float r0 = ps->r0, r1 = ps->r1;
1316  float cor0 = ps->cor0, cor1 = ps->cor1;
1317  float var0 = ps->var0, var1 = ps->var1;
1318 
1319  k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1320  k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1321 
1322  pv = flt16_round(k1 * r0 + k2 * r1);
1323  if (output_enable)
1324  *coef += pv;
1325 
1326  e0 = *coef;
1327  e1 = e0 - k1 * r0;
1328 
1329  ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1330  ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1331  ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1332  ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1333 
1334  ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1335  ps->r0 = flt16_trunc(a * e0);
1336 }
1337 
1342 {
1343  int sfb, k;
1344 
1345  if (!sce->ics.predictor_initialized) {
1347  sce->ics.predictor_initialized = 1;
1348  }
1349 
1350  if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1351  for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
1352  for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
1353  predict(&sce->predictor_state[k], &sce->coeffs[k],
1354  sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
1355  }
1356  }
1357  if (sce->ics.predictor_reset_group)
1359  } else
1361 }
1362 
1372  GetBitContext *gb, int common_window, int scale_flag)
1373 {
1374  Pulse pulse;
1375  TemporalNoiseShaping *tns = &sce->tns;
1376  IndividualChannelStream *ics = &sce->ics;
1377  float *out = sce->coeffs;
1378  int global_gain, pulse_present = 0;
1379 
1380  /* This assignment is to silence a GCC warning about the variable being used
1381  * uninitialized when in fact it always is.
1382  */
1383  pulse.num_pulse = 0;
1384 
1385  global_gain = get_bits(gb, 8);
1386 
1387  if (!common_window && !scale_flag) {
1388  if (decode_ics_info(ac, ics, gb) < 0)
1389  return AVERROR_INVALIDDATA;
1390  }
1391 
1392  if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1393  return -1;
1394  if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1395  return -1;
1396 
1397  pulse_present = 0;
1398  if (!scale_flag) {
1399  if ((pulse_present = get_bits1(gb))) {
1400  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1401  av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
1402  return -1;
1403  }
1404  if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1405  av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
1406  return -1;
1407  }
1408  }
1409  if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1410  return -1;
1411  if (get_bits1(gb)) {
1412  av_log_missing_feature(ac->avctx, "SSR", 1);
1413  return -1;
1414  }
1415  }
1416 
1417  if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1418  return -1;
1419 
1420  if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
1421  apply_prediction(ac, sce);
1422 
1423  return 0;
1424 }
1425 
1430 {
1431  const IndividualChannelStream *ics = &cpe->ch[0].ics;
1432  float *ch0 = cpe->ch[0].coeffs;
1433  float *ch1 = cpe->ch[1].coeffs;
1434  int g, i, group, idx = 0;
1435  const uint16_t *offsets = ics->swb_offset;
1436  for (g = 0; g < ics->num_window_groups; g++) {
1437  for (i = 0; i < ics->max_sfb; i++, idx++) {
1438  if (cpe->ms_mask[idx] &&
1439  cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
1440  for (group = 0; group < ics->group_len[g]; group++) {
1441  ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
1442  ch1 + group * 128 + offsets[i],
1443  offsets[i+1] - offsets[i]);
1444  }
1445  }
1446  }
1447  ch0 += ics->group_len[g] * 128;
1448  ch1 += ics->group_len[g] * 128;
1449  }
1450 }
1451 
1459 static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
1460 {
1461  const IndividualChannelStream *ics = &cpe->ch[1].ics;
1462  SingleChannelElement *sce1 = &cpe->ch[1];
1463  float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1464  const uint16_t *offsets = ics->swb_offset;
1465  int g, group, i, idx = 0;
1466  int c;
1467  float scale;
1468  for (g = 0; g < ics->num_window_groups; g++) {
1469  for (i = 0; i < ics->max_sfb;) {
1470  if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1471  const int bt_run_end = sce1->band_type_run_end[idx];
1472  for (; i < bt_run_end; i++, idx++) {
1473  c = -1 + 2 * (sce1->band_type[idx] - 14);
1474  if (ms_present)
1475  c *= 1 - 2 * cpe->ms_mask[idx];
1476  scale = c * sce1->sf[idx];
1477  for (group = 0; group < ics->group_len[g]; group++)
1478  ac->dsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1479  coef0 + group * 128 + offsets[i],
1480  scale,
1481  offsets[i + 1] - offsets[i]);
1482  }
1483  } else {
1484  int bt_run_end = sce1->band_type_run_end[idx];
1485  idx += bt_run_end - i;
1486  i = bt_run_end;
1487  }
1488  }
1489  coef0 += ics->group_len[g] * 128;
1490  coef1 += ics->group_len[g] * 128;
1491  }
1492 }
1493 
1500 {
1501  int i, ret, common_window, ms_present = 0;
1502 
1503  common_window = get_bits1(gb);
1504  if (common_window) {
1505  if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1506  return AVERROR_INVALIDDATA;
1507  i = cpe->ch[1].ics.use_kb_window[0];
1508  cpe->ch[1].ics = cpe->ch[0].ics;
1509  cpe->ch[1].ics.use_kb_window[1] = i;
1510  if (cpe->ch[1].ics.predictor_present && (ac->m4ac.object_type != AOT_AAC_MAIN))
1511  if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1512  decode_ltp(ac, &cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1513  ms_present = get_bits(gb, 2);
1514  if (ms_present == 3) {
1515  av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1516  return -1;
1517  } else if (ms_present)
1518  decode_mid_side_stereo(cpe, gb, ms_present);
1519  }
1520  if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1521  return ret;
1522  if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1523  return ret;
1524 
1525  if (common_window) {
1526  if (ms_present)
1527  apply_mid_side_stereo(ac, cpe);
1528  if (ac->m4ac.object_type == AOT_AAC_MAIN) {
1529  apply_prediction(ac, &cpe->ch[0]);
1530  apply_prediction(ac, &cpe->ch[1]);
1531  }
1532  }
1533 
1534  apply_intensity_stereo(ac, cpe, ms_present);
1535  return 0;
1536 }
1537 
1538 static const float cce_scale[] = {
1539  1.09050773266525765921, //2^(1/8)
1540  1.18920711500272106672, //2^(1/4)
1541  M_SQRT2,
1542  2,
1543 };
1544 
1551 {
1552  int num_gain = 0;
1553  int c, g, sfb, ret;
1554  int sign;
1555  float scale;
1556  SingleChannelElement *sce = &che->ch[0];
1557  ChannelCoupling *coup = &che->coup;
1558 
1559  coup->coupling_point = 2 * get_bits1(gb);
1560  coup->num_coupled = get_bits(gb, 3);
1561  for (c = 0; c <= coup->num_coupled; c++) {
1562  num_gain++;
1563  coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1564  coup->id_select[c] = get_bits(gb, 4);
1565  if (coup->type[c] == TYPE_CPE) {
1566  coup->ch_select[c] = get_bits(gb, 2);
1567  if (coup->ch_select[c] == 3)
1568  num_gain++;
1569  } else
1570  coup->ch_select[c] = 2;
1571  }
1572  coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1573 
1574  sign = get_bits(gb, 1);
1575  scale = cce_scale[get_bits(gb, 2)];
1576 
1577  if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1578  return ret;
1579 
1580  for (c = 0; c < num_gain; c++) {
1581  int idx = 0;
1582  int cge = 1;
1583  int gain = 0;
1584  float gain_cache = 1.;
1585  if (c) {
1586  cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1587  gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1588  gain_cache = powf(scale, -gain);
1589  }
1590  if (coup->coupling_point == AFTER_IMDCT) {
1591  coup->gain[c][0] = gain_cache;
1592  } else {
1593  for (g = 0; g < sce->ics.num_window_groups; g++) {
1594  for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1595  if (sce->band_type[idx] != ZERO_BT) {
1596  if (!cge) {
1597  int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1598  if (t) {
1599  int s = 1;
1600  t = gain += t;
1601  if (sign) {
1602  s -= 2 * (t & 0x1);
1603  t >>= 1;
1604  }
1605  gain_cache = powf(scale, -t) * s;
1606  }
1607  }
1608  coup->gain[c][idx] = gain_cache;
1609  }
1610  }
1611  }
1612  }
1613  }
1614  return 0;
1615 }
1616 
1623  GetBitContext *gb)
1624 {
1625  int i;
1626  int num_excl_chan = 0;
1627 
1628  do {
1629  for (i = 0; i < 7; i++)
1630  che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1631  } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1632 
1633  return num_excl_chan / 7;
1634 }
1635 
1644  GetBitContext *gb, int cnt)
1645 {
1646  int n = 1;
1647  int drc_num_bands = 1;
1648  int i;
1649 
1650  /* pce_tag_present? */
1651  if (get_bits1(gb)) {
1652  che_drc->pce_instance_tag = get_bits(gb, 4);
1653  skip_bits(gb, 4); // tag_reserved_bits
1654  n++;
1655  }
1656 
1657  /* excluded_chns_present? */
1658  if (get_bits1(gb)) {
1659  n += decode_drc_channel_exclusions(che_drc, gb);
1660  }
1661 
1662  /* drc_bands_present? */
1663  if (get_bits1(gb)) {
1664  che_drc->band_incr = get_bits(gb, 4);
1665  che_drc->interpolation_scheme = get_bits(gb, 4);
1666  n++;
1667  drc_num_bands += che_drc->band_incr;
1668  for (i = 0; i < drc_num_bands; i++) {
1669  che_drc->band_top[i] = get_bits(gb, 8);
1670  n++;
1671  }
1672  }
1673 
1674  /* prog_ref_level_present? */
1675  if (get_bits1(gb)) {
1676  che_drc->prog_ref_level = get_bits(gb, 7);
1677  skip_bits1(gb); // prog_ref_level_reserved_bits
1678  n++;
1679  }
1680 
1681  for (i = 0; i < drc_num_bands; i++) {
1682  che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1683  che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1684  n++;
1685  }
1686 
1687  return n;
1688 }
1689 
1698  ChannelElement *che, enum RawDataBlockType elem_type)
1699 {
1700  int crc_flag = 0;
1701  int res = cnt;
1702  switch (get_bits(gb, 4)) { // extension type
1703  case EXT_SBR_DATA_CRC:
1704  crc_flag++;
1705  case EXT_SBR_DATA:
1706  if (!che) {
1707  av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
1708  return res;
1709  } else if (!ac->m4ac.sbr) {
1710  av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
1711  skip_bits_long(gb, 8 * cnt - 4);
1712  return res;
1713  } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
1714  av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
1715  skip_bits_long(gb, 8 * cnt - 4);
1716  return res;
1717  } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
1718  ac->m4ac.sbr = 1;
1719  ac->m4ac.ps = 1;
1721  } else {
1722  ac->m4ac.sbr = 1;
1723  }
1724  res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
1725  break;
1726  case EXT_DYNAMIC_RANGE:
1727  res = decode_dynamic_range(&ac->che_drc, gb, cnt);
1728  break;
1729  case EXT_FILL:
1730  case EXT_FILL_DATA:
1731  case EXT_DATA_ELEMENT:
1732  default:
1733  skip_bits_long(gb, 8 * cnt - 4);
1734  break;
1735  };
1736  return res;
1737 }
1738 
1745 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1746  IndividualChannelStream *ics, int decode)
1747 {
1748  const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1749  int w, filt, m, i;
1750  int bottom, top, order, start, end, size, inc;
1751  float lpc[TNS_MAX_ORDER];
1752  float tmp[TNS_MAX_ORDER + 1];
1753 
1754  for (w = 0; w < ics->num_windows; w++) {
1755  bottom = ics->num_swb;
1756  for (filt = 0; filt < tns->n_filt[w]; filt++) {
1757  top = bottom;
1758  bottom = FFMAX(0, top - tns->length[w][filt]);
1759  order = tns->order[w][filt];
1760  if (order == 0)
1761  continue;
1762 
1763  // tns_decode_coef
1764  compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
1765 
1766  start = ics->swb_offset[FFMIN(bottom, mmm)];
1767  end = ics->swb_offset[FFMIN( top, mmm)];
1768  if ((size = end - start) <= 0)
1769  continue;
1770  if (tns->direction[w][filt]) {
1771  inc = -1;
1772  start = end - 1;
1773  } else {
1774  inc = 1;
1775  }
1776  start += w * 128;
1777 
1778  if (decode) {
1779  // ar filter
1780  for (m = 0; m < size; m++, start += inc)
1781  for (i = 1; i <= FFMIN(m, order); i++)
1782  coef[start] -= coef[start - i * inc] * lpc[i - 1];
1783  } else {
1784  // ma filter
1785  for (m = 0; m < size; m++, start += inc) {
1786  tmp[0] = coef[start];
1787  for (i = 1; i <= FFMIN(m, order); i++)
1788  coef[start] += tmp[i] * lpc[i - 1];
1789  for (i = order; i > 0; i--)
1790  tmp[i] = tmp[i - 1];
1791  }
1792  }
1793  }
1794  }
1795 }
1796 
1801 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
1802  float *in, IndividualChannelStream *ics)
1803 {
1804  const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1805  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1806  const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1807  const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1808 
1809  if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
1810  ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);
1811  } else {
1812  memset(in, 0, 448 * sizeof(float));
1813  ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
1814  }
1815  if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
1816  ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
1817  } else {
1818  ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
1819  memset(in + 1024 + 576, 0, 448 * sizeof(float));
1820  }
1821  ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
1822 }
1823 
1828 {
1829  const LongTermPrediction *ltp = &sce->ics.ltp;
1830  const uint16_t *offsets = sce->ics.swb_offset;
1831  int i, sfb;
1832 
1833  if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1834  float *predTime = sce->ret;
1835  float *predFreq = ac->buf_mdct;
1836  int16_t num_samples = 2048;
1837 
1838  if (ltp->lag < 1024)
1839  num_samples = ltp->lag + 1024;
1840  for (i = 0; i < num_samples; i++)
1841  predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
1842  memset(&predTime[i], 0, (2048 - i) * sizeof(float));
1843 
1844  windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
1845 
1846  if (sce->tns.present)
1847  apply_tns(predFreq, &sce->tns, &sce->ics, 0);
1848 
1849  for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
1850  if (ltp->used[sfb])
1851  for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
1852  sce->coeffs[i] += predFreq[i];
1853  }
1854 }
1855 
1860 {
1861  IndividualChannelStream *ics = &sce->ics;
1862  float *saved = sce->saved;
1863  float *saved_ltp = sce->coeffs;
1864  const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1865  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1866  int i;
1867 
1868  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1869  memcpy(saved_ltp, saved, 512 * sizeof(float));
1870  memset(saved_ltp + 576, 0, 448 * sizeof(float));
1871  ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
1872  for (i = 0; i < 64; i++)
1873  saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
1874  } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1875  memcpy(saved_ltp, ac->buf_mdct + 512, 448 * 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 { // LONG_STOP or ONLY_LONG
1881  ac->dsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
1882  for (i = 0; i < 512; i++)
1883  saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
1884  }
1885 
1886  memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
1887  memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
1888  memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
1889 }
1890 
1895 {
1896  IndividualChannelStream *ics = &sce->ics;
1897  float *in = sce->coeffs;
1898  float *out = sce->ret;
1899  float *saved = sce->saved;
1900  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1901  const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1902  const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1903  float *buf = ac->buf_mdct;
1904  float *temp = ac->temp;
1905  int i;
1906 
1907  // imdct
1908  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1909  for (i = 0; i < 1024; i += 128)
1910  ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
1911  } else
1912  ac->mdct.imdct_half(&ac->mdct, buf, in);
1913 
1914  /* window overlapping
1915  * NOTE: To simplify the overlapping code, all 'meaningless' short to long
1916  * and long to short transitions are considered to be short to short
1917  * transitions. This leaves just two cases (long to long and short to short)
1918  * with a little special sauce for EIGHT_SHORT_SEQUENCE.
1919  */
1920  if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
1922  ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
1923  } else {
1924  memcpy( out, saved, 448 * sizeof(float));
1925 
1926  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1927  ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
1928  ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
1929  ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
1930  ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
1931  ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
1932  memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
1933  } else {
1934  ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
1935  memcpy( out + 576, buf + 64, 448 * sizeof(float));
1936  }
1937  }
1938 
1939  // buffer update
1940  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1941  memcpy( saved, temp + 64, 64 * sizeof(float));
1942  ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
1943  ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
1944  ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
1945  memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1946  } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1947  memcpy( saved, buf + 512, 448 * sizeof(float));
1948  memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1949  } else { // LONG_STOP or ONLY_LONG
1950  memcpy( saved, buf + 512, 512 * sizeof(float));
1951  }
1952 }
1953 
1960  SingleChannelElement *target,
1961  ChannelElement *cce, int index)
1962 {
1963  IndividualChannelStream *ics = &cce->ch[0].ics;
1964  const uint16_t *offsets = ics->swb_offset;
1965  float *dest = target->coeffs;
1966  const float *src = cce->ch[0].coeffs;
1967  int g, i, group, k, idx = 0;
1968  if (ac->m4ac.object_type == AOT_AAC_LTP) {
1969  av_log(ac->avctx, AV_LOG_ERROR,
1970  "Dependent coupling is not supported together with LTP\n");
1971  return;
1972  }
1973  for (g = 0; g < ics->num_window_groups; g++) {
1974  for (i = 0; i < ics->max_sfb; i++, idx++) {
1975  if (cce->ch[0].band_type[idx] != ZERO_BT) {
1976  const float gain = cce->coup.gain[index][idx];
1977  for (group = 0; group < ics->group_len[g]; group++) {
1978  for (k = offsets[i]; k < offsets[i + 1]; k++) {
1979  // XXX dsputil-ize
1980  dest[group * 128 + k] += gain * src[group * 128 + k];
1981  }
1982  }
1983  }
1984  }
1985  dest += ics->group_len[g] * 128;
1986  src += ics->group_len[g] * 128;
1987  }
1988 }
1989 
1996  SingleChannelElement *target,
1997  ChannelElement *cce, int index)
1998 {
1999  int i;
2000  const float gain = cce->coup.gain[index][0];
2001  const float *src = cce->ch[0].ret;
2002  float *dest = target->ret;
2003  const int len = 1024 << (ac->m4ac.sbr == 1);
2004 
2005  for (i = 0; i < len; i++)
2006  dest[i] += gain * src[i];
2007 }
2008 
2015  enum RawDataBlockType type, int elem_id,
2016  enum CouplingPoint coupling_point,
2017  void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2018 {
2019  int i, c;
2020 
2021  for (i = 0; i < MAX_ELEM_ID; i++) {
2022  ChannelElement *cce = ac->che[TYPE_CCE][i];
2023  int index = 0;
2024 
2025  if (cce && cce->coup.coupling_point == coupling_point) {
2026  ChannelCoupling *coup = &cce->coup;
2027 
2028  for (c = 0; c <= coup->num_coupled; c++) {
2029  if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2030  if (coup->ch_select[c] != 1) {
2031  apply_coupling_method(ac, &cc->ch[0], cce, index);
2032  if (coup->ch_select[c] != 0)
2033  index++;
2034  }
2035  if (coup->ch_select[c] != 2)
2036  apply_coupling_method(ac, &cc->ch[1], cce, index++);
2037  } else
2038  index += 1 + (coup->ch_select[c] == 3);
2039  }
2040  }
2041  }
2042 }
2043 
2048 {
2049  int i, type;
2050  for (type = 3; type >= 0; type--) {
2051  for (i = 0; i < MAX_ELEM_ID; i++) {
2052  ChannelElement *che = ac->che[type][i];
2053  if (che) {
2054  if (type <= TYPE_CPE)
2056  if (ac->m4ac.object_type == AOT_AAC_LTP) {
2057  if (che->ch[0].ics.predictor_present) {
2058  if (che->ch[0].ics.ltp.present)
2059  apply_ltp(ac, &che->ch[0]);
2060  if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2061  apply_ltp(ac, &che->ch[1]);
2062  }
2063  }
2064  if (che->ch[0].tns.present)
2065  apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2066  if (che->ch[1].tns.present)
2067  apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2068  if (type <= TYPE_CPE)
2070  if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2071  imdct_and_windowing(ac, &che->ch[0]);
2072  if (ac->m4ac.object_type == AOT_AAC_LTP)
2073  update_ltp(ac, &che->ch[0]);
2074  if (type == TYPE_CPE) {
2075  imdct_and_windowing(ac, &che->ch[1]);
2076  if (ac->m4ac.object_type == AOT_AAC_LTP)
2077  update_ltp(ac, &che->ch[1]);
2078  }
2079  if (ac->m4ac.sbr > 0) {
2080  ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2081  }
2082  }
2083  if (type <= TYPE_CCE)
2085  }
2086  }
2087  }
2088 }
2089 
2091 {
2092  int size;
2093  AACADTSHeaderInfo hdr_info;
2094 
2095  size = avpriv_aac_parse_header(gb, &hdr_info);
2096  if (size > 0) {
2097  if (hdr_info.chan_config) {
2098  enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
2099  memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
2100  ac->m4ac.chan_config = hdr_info.chan_config;
2101  if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
2102  return -7;
2103  if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config,
2105  return -7;
2106  } else if (ac->output_configured != OC_LOCKED) {
2107  ac->m4ac.chan_config = 0;
2108  ac->output_configured = OC_NONE;
2109  }
2110  if (ac->output_configured != OC_LOCKED) {
2111  ac->m4ac.sbr = -1;
2112  ac->m4ac.ps = -1;
2113  ac->m4ac.sample_rate = hdr_info.sample_rate;
2114  ac->m4ac.sampling_index = hdr_info.sampling_index;
2115  ac->m4ac.object_type = hdr_info.object_type;
2116  }
2117  if (!ac->avctx->sample_rate)
2118  ac->avctx->sample_rate = hdr_info.sample_rate;
2119  if (hdr_info.num_aac_frames == 1) {
2120  if (!hdr_info.crc_absent)
2121  skip_bits(gb, 16);
2122  } else {
2123  av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
2124  return -1;
2125  }
2126  }
2127  return size;
2128 }
2129 
2130 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2131  int *got_frame_ptr, GetBitContext *gb)
2132 {
2133  AACContext *ac = avctx->priv_data;
2134  ChannelElement *che = NULL, *che_prev = NULL;
2135  enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2136  int err, elem_id;
2137  int samples = 0, multiplier, audio_found = 0;
2138 
2139  if (show_bits(gb, 12) == 0xfff) {
2140  if (parse_adts_frame_header(ac, gb) < 0) {
2141  av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2142  return -1;
2143  }
2144  if (ac->m4ac.sampling_index > 12) {
2145  av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
2146  return -1;
2147  }
2148  }
2149 
2150  ac->tags_mapped = 0;
2151  // parse
2152  while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2153  elem_id = get_bits(gb, 4);
2154 
2155  if (elem_type < TYPE_DSE) {
2156  if (!(che=get_che(ac, elem_type, elem_id))) {
2157  av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2158  elem_type, elem_id);
2159  return -1;
2160  }
2161  samples = 1024;
2162  }
2163 
2164  switch (elem_type) {
2165 
2166  case TYPE_SCE:
2167  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2168  audio_found = 1;
2169  break;
2170 
2171  case TYPE_CPE:
2172  err = decode_cpe(ac, gb, che);
2173  audio_found = 1;
2174  break;
2175 
2176  case TYPE_CCE:
2177  err = decode_cce(ac, gb, che);
2178  break;
2179 
2180  case TYPE_LFE:
2181  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2182  audio_found = 1;
2183  break;
2184 
2185  case TYPE_DSE:
2186  err = skip_data_stream_element(ac, gb);
2187  break;
2188 
2189  case TYPE_PCE: {
2190  enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
2191  memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
2192  if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
2193  break;
2194  if (ac->output_configured > OC_TRIAL_PCE)
2195  av_log(avctx, AV_LOG_ERROR,
2196  "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2197  else
2198  err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
2199  break;
2200  }
2201 
2202  case TYPE_FIL:
2203  if (elem_id == 15)
2204  elem_id += get_bits(gb, 8) - 1;
2205  if (get_bits_left(gb) < 8 * elem_id) {
2206  av_log(avctx, AV_LOG_ERROR, overread_err);
2207  return -1;
2208  }
2209  while (elem_id > 0)
2210  elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2211  err = 0; /* FIXME */
2212  break;
2213 
2214  default:
2215  err = -1; /* should not happen, but keeps compiler happy */
2216  break;
2217  }
2218 
2219  che_prev = che;
2220  elem_type_prev = elem_type;
2221 
2222  if (err)
2223  return err;
2224 
2225  if (get_bits_left(gb) < 3) {
2226  av_log(avctx, AV_LOG_ERROR, overread_err);
2227  return -1;
2228  }
2229  }
2230 
2231  spectral_to_sample(ac);
2232 
2233  multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
2234  samples <<= multiplier;
2235  if (ac->output_configured < OC_LOCKED) {
2236  avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
2237  avctx->frame_size = samples;
2238  }
2239 
2240  if (samples) {
2241  /* get output buffer */
2242  ac->frame.nb_samples = samples;
2243  if ((err = avctx->get_buffer(avctx, &ac->frame)) < 0) {
2244  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
2245  return err;
2246  }
2247 
2248  if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
2249  ac->fmt_conv.float_interleave((float *)ac->frame.data[0],
2250  (const float **)ac->output_data,
2251  samples, avctx->channels);
2252  else
2253  ac->fmt_conv.float_to_int16_interleave((int16_t *)ac->frame.data[0],
2254  (const float **)ac->output_data,
2255  samples, avctx->channels);
2256 
2257  *(AVFrame *)data = ac->frame;
2258  }
2259  *got_frame_ptr = !!samples;
2260 
2261  if (ac->output_configured && audio_found)
2263 
2264  return 0;
2265 }
2266 
2267 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2268  int *got_frame_ptr, AVPacket *avpkt)
2269 {
2270  AACContext *ac = avctx->priv_data;
2271  const uint8_t *buf = avpkt->data;
2272  int buf_size = avpkt->size;
2273  GetBitContext gb;
2274  int buf_consumed;
2275  int buf_offset;
2276  int err;
2277  int new_extradata_size;
2278  const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2280  &new_extradata_size);
2281 
2282  if (new_extradata) {
2283  av_free(avctx->extradata);
2284  avctx->extradata = av_mallocz(new_extradata_size +
2286  if (!avctx->extradata)
2287  return AVERROR(ENOMEM);
2288  avctx->extradata_size = new_extradata_size;
2289  memcpy(avctx->extradata, new_extradata, new_extradata_size);
2290  if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
2291  avctx->extradata,
2292  avctx->extradata_size*8, 1) < 0)
2293  return AVERROR_INVALIDDATA;
2294  }
2295 
2296  init_get_bits(&gb, buf, buf_size * 8);
2297 
2298  if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb)) < 0)
2299  return err;
2300 
2301  buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2302  for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2303  if (buf[buf_offset])
2304  break;
2305 
2306  return buf_size > buf_offset ? buf_consumed : buf_size;
2307 }
2308 
2310 {
2311  AACContext *ac = avctx->priv_data;
2312  int i, type;
2313 
2314  for (i = 0; i < MAX_ELEM_ID; i++) {
2315  for (type = 0; type < 4; type++) {
2316  if (ac->che[type][i])
2317  ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2318  av_freep(&ac->che[type][i]);
2319  }
2320  }
2321 
2322  ff_mdct_end(&ac->mdct);
2323  ff_mdct_end(&ac->mdct_small);
2324  ff_mdct_end(&ac->mdct_ltp);
2325  return 0;
2326 }
2327 
2328 
2329 #define LOAS_SYNC_WORD 0x2b7
2330 
2331 struct LATMContext {
2334 
2335  // parser data
2339 };
2340 
2341 static inline uint32_t latm_get_value(GetBitContext *b)
2342 {
2343  int length = get_bits(b, 2);
2344 
2345  return get_bits_long(b, (length+1)*8);
2346 }
2347 
2349  GetBitContext *gb, int asclen)
2350 {
2351  AACContext *ac = &latmctx->aac_ctx;
2352  AVCodecContext *avctx = ac->avctx;
2353  MPEG4AudioConfig m4ac = {0};
2354  int config_start_bit = get_bits_count(gb);
2355  int sync_extension = 0;
2356  int bits_consumed, esize;
2357 
2358  if (asclen) {
2359  sync_extension = 1;
2360  asclen = FFMIN(asclen, get_bits_left(gb));
2361  } else
2362  asclen = get_bits_left(gb);
2363 
2364  if (config_start_bit % 8) {
2365  av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
2366  "config not byte aligned.\n", 1);
2367  return AVERROR_INVALIDDATA;
2368  }
2369  if (asclen <= 0)
2370  return AVERROR_INVALIDDATA;
2371  bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
2372  gb->buffer + (config_start_bit / 8),
2373  asclen, sync_extension);
2374 
2375  if (bits_consumed < 0)
2376  return AVERROR_INVALIDDATA;
2377 
2378  if (ac->m4ac.sample_rate != m4ac.sample_rate ||
2379  ac->m4ac.chan_config != m4ac.chan_config) {
2380 
2381  av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2382  latmctx->initialized = 0;
2383 
2384  esize = (bits_consumed+7) / 8;
2385 
2386  if (avctx->extradata_size < esize) {
2387  av_free(avctx->extradata);
2389  if (!avctx->extradata)
2390  return AVERROR(ENOMEM);
2391  }
2392 
2393  avctx->extradata_size = esize;
2394  memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2395  memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2396  }
2397  skip_bits_long(gb, bits_consumed);
2398 
2399  return bits_consumed;
2400 }
2401 
2402 static int read_stream_mux_config(struct LATMContext *latmctx,
2403  GetBitContext *gb)
2404 {
2405  int ret, audio_mux_version = get_bits(gb, 1);
2406 
2407  latmctx->audio_mux_version_A = 0;
2408  if (audio_mux_version)
2409  latmctx->audio_mux_version_A = get_bits(gb, 1);
2410 
2411  if (!latmctx->audio_mux_version_A) {
2412 
2413  if (audio_mux_version)
2414  latm_get_value(gb); // taraFullness
2415 
2416  skip_bits(gb, 1); // allStreamSameTimeFraming
2417  skip_bits(gb, 6); // numSubFrames
2418  // numPrograms
2419  if (get_bits(gb, 4)) { // numPrograms
2421  "multiple programs are not supported\n", 1);
2422  return AVERROR_PATCHWELCOME;
2423  }
2424 
2425  // for each program (which there is only on in DVB)
2426 
2427  // for each layer (which there is only on in DVB)
2428  if (get_bits(gb, 3)) { // numLayer
2430  "multiple layers are not supported\n", 1);
2431  return AVERROR_PATCHWELCOME;
2432  }
2433 
2434  // for all but first stream: use_same_config = get_bits(gb, 1);
2435  if (!audio_mux_version) {
2436  if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
2437  return ret;
2438  } else {
2439  int ascLen = latm_get_value(gb);
2440  if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
2441  return ret;
2442  ascLen -= ret;
2443  skip_bits_long(gb, ascLen);
2444  }
2445 
2446  latmctx->frame_length_type = get_bits(gb, 3);
2447  switch (latmctx->frame_length_type) {
2448  case 0:
2449  skip_bits(gb, 8); // latmBufferFullness
2450  break;
2451  case 1:
2452  latmctx->frame_length = get_bits(gb, 9);
2453  break;
2454  case 3:
2455  case 4:
2456  case 5:
2457  skip_bits(gb, 6); // CELP frame length table index
2458  break;
2459  case 6:
2460  case 7:
2461  skip_bits(gb, 1); // HVXC frame length table index
2462  break;
2463  }
2464 
2465  if (get_bits(gb, 1)) { // other data
2466  if (audio_mux_version) {
2467  latm_get_value(gb); // other_data_bits
2468  } else {
2469  int esc;
2470  do {
2471  esc = get_bits(gb, 1);
2472  skip_bits(gb, 8);
2473  } while (esc);
2474  }
2475  }
2476 
2477  if (get_bits(gb, 1)) // crc present
2478  skip_bits(gb, 8); // config_crc
2479  }
2480 
2481  return 0;
2482 }
2483 
2485 {
2486  uint8_t tmp;
2487 
2488  if (ctx->frame_length_type == 0) {
2489  int mux_slot_length = 0;
2490  do {
2491  tmp = get_bits(gb, 8);
2492  mux_slot_length += tmp;
2493  } while (tmp == 255);
2494  return mux_slot_length;
2495  } else if (ctx->frame_length_type == 1) {
2496  return ctx->frame_length;
2497  } else if (ctx->frame_length_type == 3 ||
2498  ctx->frame_length_type == 5 ||
2499  ctx->frame_length_type == 7) {
2500  skip_bits(gb, 2); // mux_slot_length_coded
2501  }
2502  return 0;
2503 }
2504 
2505 static int read_audio_mux_element(struct LATMContext *latmctx,
2506  GetBitContext *gb)
2507 {
2508  int err;
2509  uint8_t use_same_mux = get_bits(gb, 1);
2510  if (!use_same_mux) {
2511  if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2512  return err;
2513  } else if (!latmctx->aac_ctx.avctx->extradata) {
2514  av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2515  "no decoder config found\n");
2516  return AVERROR(EAGAIN);
2517  }
2518  if (latmctx->audio_mux_version_A == 0) {
2519  int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2520  if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2521  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2522  return AVERROR_INVALIDDATA;
2523  } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2524  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2525  "frame length mismatch %d << %d\n",
2526  mux_slot_length_bytes * 8, get_bits_left(gb));
2527  return AVERROR_INVALIDDATA;
2528  }
2529  }
2530  return 0;
2531 }
2532 
2533 
2534 static int latm_decode_frame(AVCodecContext *avctx, void *out,
2535  int *got_frame_ptr, AVPacket *avpkt)
2536 {
2537  struct LATMContext *latmctx = avctx->priv_data;
2538  int muxlength, err;
2539  GetBitContext gb;
2540 
2541  init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2542 
2543  // check for LOAS sync word
2544  if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2545  return AVERROR_INVALIDDATA;
2546 
2547  muxlength = get_bits(&gb, 13) + 3;
2548  // not enough data, the parser should have sorted this
2549  if (muxlength > avpkt->size)
2550  return AVERROR_INVALIDDATA;
2551 
2552  if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2553  return err;
2554 
2555  if (!latmctx->initialized) {
2556  if (!avctx->extradata) {
2557  *got_frame_ptr = 0;
2558  return avpkt->size;
2559  } else {
2560  if ((err = decode_audio_specific_config(
2561  &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.m4ac,
2562  avctx->extradata, avctx->extradata_size*8, 1)) < 0)
2563  return err;
2564  latmctx->initialized = 1;
2565  }
2566  }
2567 
2568  if (show_bits(&gb, 12) == 0xfff) {
2569  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2570  "ADTS header detected, probably as result of configuration "
2571  "misparsing\n");
2572  return AVERROR_INVALIDDATA;
2573  }
2574 
2575  if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
2576  return err;
2577 
2578  return muxlength;
2579 }
2580 
2582 {
2583  struct LATMContext *latmctx = avctx->priv_data;
2584  int ret = aac_decode_init(avctx);
2585 
2586  if (avctx->extradata_size > 0)
2587  latmctx->initialized = !ret;
2588 
2589  return ret;
2590 }
2591 
2592 
2594  .name = "aac",
2595  .type = AVMEDIA_TYPE_AUDIO,
2596  .id = CODEC_ID_AAC,
2597  .priv_data_size = sizeof(AACContext),
2598  .init = aac_decode_init,
2601  .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
2602  .sample_fmts = (const enum AVSampleFormat[]) {
2604  },
2605  .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2606  .channel_layouts = aac_channel_layout,
2607 };
2608 
2609 /*
2610  Note: This decoder filter is intended to decode LATM streams transferred
2611  in MPEG transport streams which only contain one program.
2612  To do a more complex LATM demuxing a separate LATM demuxer should be used.
2613 */
2615  .name = "aac_latm",
2616  .type = AVMEDIA_TYPE_AUDIO,
2617  .id = CODEC_ID_AAC_LATM,
2618  .priv_data_size = sizeof(struct LATMContext),
2619  .init = latm_decode_init,
2620  .close = aac_decode_close,
2621  .decode = latm_decode_frame,
2622  .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
2623  .sample_fmts = (const enum AVSampleFormat[]) {
2625  },
2626  .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2627  .channel_layouts = aac_channel_layout,
2628 };