FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
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  * Copyright (c) 2008-2013 Alex Converse <alex.converse@gmail.com>
6  *
7  * AAC LATM decoder
8  * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
9  * Copyright (c) 2010 Janne Grunau <janne-libav@jannau.net>
10  *
11  * This file is part of FFmpeg.
12  *
13  * FFmpeg is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Lesser General Public
15  * License as published by the Free Software Foundation; either
16  * version 2.1 of the License, or (at your option) any later version.
17  *
18  * FFmpeg is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21  * Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public
24  * License along with FFmpeg; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26  */
27 
28 /**
29  * @file
30  * AAC decoder
31  * @author Oded Shimon ( ods15 ods15 dyndns org )
32  * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
33  */
34 
35 /*
36  * supported tools
37  *
38  * Support? Name
39  * N (code in SoC repo) gain control
40  * Y block switching
41  * Y window shapes - standard
42  * N window shapes - Low Delay
43  * Y filterbank - standard
44  * N (code in SoC repo) filterbank - Scalable Sample Rate
45  * Y Temporal Noise Shaping
46  * Y Long Term Prediction
47  * Y intensity stereo
48  * Y channel coupling
49  * Y frequency domain prediction
50  * Y Perceptual Noise Substitution
51  * Y Mid/Side stereo
52  * N Scalable Inverse AAC Quantization
53  * N Frequency Selective Switch
54  * N upsampling filter
55  * Y quantization & coding - AAC
56  * N quantization & coding - TwinVQ
57  * N quantization & coding - BSAC
58  * N AAC Error Resilience tools
59  * N Error Resilience payload syntax
60  * N Error Protection tool
61  * N CELP
62  * N Silence Compression
63  * N HVXC
64  * N HVXC 4kbits/s VR
65  * N Structured Audio tools
66  * N Structured Audio Sample Bank Format
67  * N MIDI
68  * N Harmonic and Individual Lines plus Noise
69  * N Text-To-Speech Interface
70  * Y Spectral Band Replication
71  * Y (not in this code) Layer-1
72  * Y (not in this code) Layer-2
73  * Y (not in this code) Layer-3
74  * N SinuSoidal Coding (Transient, Sinusoid, Noise)
75  * Y Parametric Stereo
76  * N Direct Stream Transfer
77  * Y Enhanced AAC Low Delay (ER AAC ELD)
78  *
79  * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
80  * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
81  Parametric Stereo.
82  */
83 
84 #include "libavutil/float_dsp.h"
85 #include "libavutil/opt.h"
86 #include "avcodec.h"
87 #include "internal.h"
88 #include "get_bits.h"
89 #include "fft.h"
90 #include "fmtconvert.h"
91 #include "lpc.h"
92 #include "kbdwin.h"
93 #include "sinewin.h"
94 
95 #include "aac.h"
96 #include "aactab.h"
97 #include "aacdectab.h"
98 #include "cbrt_tablegen.h"
99 #include "sbr.h"
100 #include "aacsbr.h"
101 #include "mpeg4audio.h"
102 #include "aacadtsdec.h"
103 #include "libavutil/intfloat.h"
104 
105 #include <assert.h>
106 #include <errno.h>
107 #include <math.h>
108 #include <stdint.h>
109 #include <string.h>
110 
111 #if ARCH_ARM
112 # include "arm/aac.h"
113 #elif ARCH_MIPS
114 # include "mips/aacdec_mips.h"
115 #endif
116 
118 static VLC vlc_spectral[11];
119 
120 static int output_configure(AACContext *ac,
121  uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
122  enum OCStatus oc_type, int get_new_frame);
123 
124 #define overread_err "Input buffer exhausted before END element found\n"
125 
126 static int count_channels(uint8_t (*layout)[3], int tags)
127 {
128  int i, sum = 0;
129  for (i = 0; i < tags; i++) {
130  int syn_ele = layout[i][0];
131  int pos = layout[i][2];
132  sum += (1 + (syn_ele == TYPE_CPE)) *
133  (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
134  }
135  return sum;
136 }
137 
138 /**
139  * Check for the channel element in the current channel position configuration.
140  * If it exists, make sure the appropriate element is allocated and map the
141  * channel order to match the internal FFmpeg channel layout.
142  *
143  * @param che_pos current channel position configuration
144  * @param type channel element type
145  * @param id channel element id
146  * @param channels count of the number of channels in the configuration
147  *
148  * @return Returns error status. 0 - OK, !0 - error
149  */
151  enum ChannelPosition che_pos,
152  int type, int id, int *channels)
153 {
154  if (*channels >= MAX_CHANNELS)
155  return AVERROR_INVALIDDATA;
156  if (che_pos) {
157  if (!ac->che[type][id]) {
158  if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
159  return AVERROR(ENOMEM);
160  ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
161  }
162  if (type != TYPE_CCE) {
163  if (*channels >= MAX_CHANNELS - (type == TYPE_CPE || (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1))) {
164  av_log(ac->avctx, AV_LOG_ERROR, "Too many channels\n");
165  return AVERROR_INVALIDDATA;
166  }
167  ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
168  if (type == TYPE_CPE ||
169  (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
170  ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
171  }
172  }
173  } else {
174  if (ac->che[type][id])
175  ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
176  av_freep(&ac->che[type][id]);
177  }
178  return 0;
179 }
180 
182 {
183  AACContext *ac = avctx->priv_data;
184  int type, id, ch, ret;
185 
186  /* set channel pointers to internal buffers by default */
187  for (type = 0; type < 4; type++) {
188  for (id = 0; id < MAX_ELEM_ID; id++) {
189  ChannelElement *che = ac->che[type][id];
190  if (che) {
191  che->ch[0].ret = che->ch[0].ret_buf;
192  che->ch[1].ret = che->ch[1].ret_buf;
193  }
194  }
195  }
196 
197  /* get output buffer */
198  av_frame_unref(ac->frame);
199  if (!avctx->channels)
200  return 1;
201 
202  ac->frame->nb_samples = 2048;
203  if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0)
204  return ret;
205 
206  /* map output channel pointers to AVFrame data */
207  for (ch = 0; ch < avctx->channels; ch++) {
208  if (ac->output_element[ch])
209  ac->output_element[ch]->ret = (float *)ac->frame->extended_data[ch];
210  }
211 
212  return 0;
213 }
214 
216  uint64_t av_position;
220 };
221 
222 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
223  uint8_t (*layout_map)[3], int offset, uint64_t left,
224  uint64_t right, int pos)
225 {
226  if (layout_map[offset][0] == TYPE_CPE) {
227  e2c_vec[offset] = (struct elem_to_channel) {
228  .av_position = left | right,
229  .syn_ele = TYPE_CPE,
230  .elem_id = layout_map[offset][1],
231  .aac_position = pos
232  };
233  return 1;
234  } else {
235  e2c_vec[offset] = (struct elem_to_channel) {
236  .av_position = left,
237  .syn_ele = TYPE_SCE,
238  .elem_id = layout_map[offset][1],
239  .aac_position = pos
240  };
241  e2c_vec[offset + 1] = (struct elem_to_channel) {
242  .av_position = right,
243  .syn_ele = TYPE_SCE,
244  .elem_id = layout_map[offset + 1][1],
245  .aac_position = pos
246  };
247  return 2;
248  }
249 }
250 
251 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
252  int *current)
253 {
254  int num_pos_channels = 0;
255  int first_cpe = 0;
256  int sce_parity = 0;
257  int i;
258  for (i = *current; i < tags; i++) {
259  if (layout_map[i][2] != pos)
260  break;
261  if (layout_map[i][0] == TYPE_CPE) {
262  if (sce_parity) {
263  if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
264  sce_parity = 0;
265  } else {
266  return -1;
267  }
268  }
269  num_pos_channels += 2;
270  first_cpe = 1;
271  } else {
272  num_pos_channels++;
273  sce_parity ^= 1;
274  }
275  }
276  if (sce_parity &&
277  ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
278  return -1;
279  *current = i;
280  return num_pos_channels;
281 }
282 
283 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
284 {
285  int i, n, total_non_cc_elements;
286  struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
287  int num_front_channels, num_side_channels, num_back_channels;
288  uint64_t layout;
289 
290  if (FF_ARRAY_ELEMS(e2c_vec) < tags)
291  return 0;
292 
293  i = 0;
294  num_front_channels =
295  count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
296  if (num_front_channels < 0)
297  return 0;
298  num_side_channels =
299  count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
300  if (num_side_channels < 0)
301  return 0;
302  num_back_channels =
303  count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
304  if (num_back_channels < 0)
305  return 0;
306 
307  i = 0;
308  if (num_front_channels & 1) {
309  e2c_vec[i] = (struct elem_to_channel) {
311  .syn_ele = TYPE_SCE,
312  .elem_id = layout_map[i][1],
313  .aac_position = AAC_CHANNEL_FRONT
314  };
315  i++;
316  num_front_channels--;
317  }
318  if (num_front_channels >= 4) {
319  i += assign_pair(e2c_vec, layout_map, i,
323  num_front_channels -= 2;
324  }
325  if (num_front_channels >= 2) {
326  i += assign_pair(e2c_vec, layout_map, i,
330  num_front_channels -= 2;
331  }
332  while (num_front_channels >= 2) {
333  i += assign_pair(e2c_vec, layout_map, i,
334  UINT64_MAX,
335  UINT64_MAX,
337  num_front_channels -= 2;
338  }
339 
340  if (num_side_channels >= 2) {
341  i += assign_pair(e2c_vec, layout_map, i,
345  num_side_channels -= 2;
346  }
347  while (num_side_channels >= 2) {
348  i += assign_pair(e2c_vec, layout_map, i,
349  UINT64_MAX,
350  UINT64_MAX,
352  num_side_channels -= 2;
353  }
354 
355  while (num_back_channels >= 4) {
356  i += assign_pair(e2c_vec, layout_map, i,
357  UINT64_MAX,
358  UINT64_MAX,
360  num_back_channels -= 2;
361  }
362  if (num_back_channels >= 2) {
363  i += assign_pair(e2c_vec, layout_map, i,
367  num_back_channels -= 2;
368  }
369  if (num_back_channels) {
370  e2c_vec[i] = (struct elem_to_channel) {
372  .syn_ele = TYPE_SCE,
373  .elem_id = layout_map[i][1],
374  .aac_position = AAC_CHANNEL_BACK
375  };
376  i++;
377  num_back_channels--;
378  }
379 
380  if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
381  e2c_vec[i] = (struct elem_to_channel) {
383  .syn_ele = TYPE_LFE,
384  .elem_id = layout_map[i][1],
385  .aac_position = AAC_CHANNEL_LFE
386  };
387  i++;
388  }
389  while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
390  e2c_vec[i] = (struct elem_to_channel) {
391  .av_position = UINT64_MAX,
392  .syn_ele = TYPE_LFE,
393  .elem_id = layout_map[i][1],
394  .aac_position = AAC_CHANNEL_LFE
395  };
396  i++;
397  }
398 
399  // Must choose a stable sort
400  total_non_cc_elements = n = i;
401  do {
402  int next_n = 0;
403  for (i = 1; i < n; i++)
404  if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
405  FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
406  next_n = i;
407  }
408  n = next_n;
409  } while (n > 0);
410 
411  layout = 0;
412  for (i = 0; i < total_non_cc_elements; i++) {
413  layout_map[i][0] = e2c_vec[i].syn_ele;
414  layout_map[i][1] = e2c_vec[i].elem_id;
415  layout_map[i][2] = e2c_vec[i].aac_position;
416  if (e2c_vec[i].av_position != UINT64_MAX) {
417  layout |= e2c_vec[i].av_position;
418  }
419  }
420 
421  return layout;
422 }
423 
424 /**
425  * Save current output configuration if and only if it has been locked.
426  */
428  if (ac->oc[1].status == OC_LOCKED) {
429  ac->oc[0] = ac->oc[1];
430  }
431  ac->oc[1].status = OC_NONE;
432 }
433 
434 /**
435  * Restore the previous output configuration if and only if the current
436  * configuration is unlocked.
437  */
439  if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
440  ac->oc[1] = ac->oc[0];
441  ac->avctx->channels = ac->oc[1].channels;
442  ac->avctx->channel_layout = ac->oc[1].channel_layout;
443  output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
444  ac->oc[1].status, 0);
445  }
446 }
447 
448 /**
449  * Configure output channel order based on the current program
450  * configuration element.
451  *
452  * @return Returns error status. 0 - OK, !0 - error
453  */
455  uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
456  enum OCStatus oc_type, int get_new_frame)
457 {
458  AVCodecContext *avctx = ac->avctx;
459  int i, channels = 0, ret;
460  uint64_t layout = 0;
461 
462  if (ac->oc[1].layout_map != layout_map) {
463  memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
464  ac->oc[1].layout_map_tags = tags;
465  }
466 
467  // Try to sniff a reasonable channel order, otherwise output the
468  // channels in the order the PCE declared them.
470  layout = sniff_channel_order(layout_map, tags);
471  for (i = 0; i < tags; i++) {
472  int type = layout_map[i][0];
473  int id = layout_map[i][1];
474  int position = layout_map[i][2];
475  // Allocate or free elements depending on if they are in the
476  // current program configuration.
477  ret = che_configure(ac, position, type, id, &channels);
478  if (ret < 0)
479  return ret;
480  }
481  if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
482  if (layout == AV_CH_FRONT_CENTER) {
484  } else {
485  layout = 0;
486  }
487  }
488 
489  memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
490  if (layout) avctx->channel_layout = layout;
491  ac->oc[1].channel_layout = layout;
492  avctx->channels = ac->oc[1].channels = channels;
493  ac->oc[1].status = oc_type;
494 
495  if (get_new_frame) {
496  if ((ret = frame_configure_elements(ac->avctx)) < 0)
497  return ret;
498  }
499 
500  return 0;
501 }
502 
503 static void flush(AVCodecContext *avctx)
504 {
505  AACContext *ac= avctx->priv_data;
506  int type, i, j;
507 
508  for (type = 3; type >= 0; type--) {
509  for (i = 0; i < MAX_ELEM_ID; i++) {
510  ChannelElement *che = ac->che[type][i];
511  if (che) {
512  for (j = 0; j <= 1; j++) {
513  memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
514  }
515  }
516  }
517  }
518 }
519 
520 /**
521  * Set up channel positions based on a default channel configuration
522  * as specified in table 1.17.
523  *
524  * @return Returns error status. 0 - OK, !0 - error
525  */
527  uint8_t (*layout_map)[3],
528  int *tags,
529  int channel_config)
530 {
531  if (channel_config < 1 || channel_config > 7) {
532  av_log(avctx, AV_LOG_ERROR,
533  "invalid default channel configuration (%d)\n",
534  channel_config);
535  return AVERROR_INVALIDDATA;
536  }
537  *tags = tags_per_config[channel_config];
538  memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
539  *tags * sizeof(*layout_map));
540 
541  /*
542  * AAC specification has 7.1(wide) as a default layout for 8-channel streams.
543  * However, at least Nero AAC encoder encodes 7.1 streams using the default
544  * channel config 7, mapping the side channels of the original audio stream
545  * to the second AAC_CHANNEL_FRONT pair in the AAC stream. Similarly, e.g. FAAD
546  * decodes the second AAC_CHANNEL_FRONT pair as side channels, therefore decoding
547  * the incorrect streams as if they were correct (and as the encoder intended).
548  *
549  * As actual intended 7.1(wide) streams are very rare, default to assuming a
550  * 7.1 layout was intended.
551  */
552  if (channel_config == 7 && avctx->strict_std_compliance < FF_COMPLIANCE_STRICT) {
553  av_log(avctx, AV_LOG_INFO, "Assuming an incorrectly encoded 7.1 channel layout"
554  " instead of a spec-compliant 7.1(wide) layout, use -strict %d to decode"
555  " according to the specification instead.\n", FF_COMPLIANCE_STRICT);
556  layout_map[2][2] = AAC_CHANNEL_SIDE;
557  }
558 
559  return 0;
560 }
561 
562 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
563 {
564  /* For PCE based channel configurations map the channels solely based
565  * on tags. */
566  if (!ac->oc[1].m4ac.chan_config) {
567  return ac->tag_che_map[type][elem_id];
568  }
569  // Allow single CPE stereo files to be signalled with mono configuration.
570  if (!ac->tags_mapped && type == TYPE_CPE &&
571  ac->oc[1].m4ac.chan_config == 1) {
572  uint8_t layout_map[MAX_ELEM_ID*4][3];
573  int layout_map_tags;
575 
576  av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
577 
578  if (set_default_channel_config(ac->avctx, layout_map,
579  &layout_map_tags, 2) < 0)
580  return NULL;
581  if (output_configure(ac, layout_map, layout_map_tags,
582  OC_TRIAL_FRAME, 1) < 0)
583  return NULL;
584 
585  ac->oc[1].m4ac.chan_config = 2;
586  ac->oc[1].m4ac.ps = 0;
587  }
588  // And vice-versa
589  if (!ac->tags_mapped && type == TYPE_SCE &&
590  ac->oc[1].m4ac.chan_config == 2) {
591  uint8_t layout_map[MAX_ELEM_ID * 4][3];
592  int layout_map_tags;
594 
595  av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
596 
597  if (set_default_channel_config(ac->avctx, layout_map,
598  &layout_map_tags, 1) < 0)
599  return NULL;
600  if (output_configure(ac, layout_map, layout_map_tags,
601  OC_TRIAL_FRAME, 1) < 0)
602  return NULL;
603 
604  ac->oc[1].m4ac.chan_config = 1;
605  if (ac->oc[1].m4ac.sbr)
606  ac->oc[1].m4ac.ps = -1;
607  }
608  /* For indexed channel configurations map the channels solely based
609  * on position. */
610  switch (ac->oc[1].m4ac.chan_config) {
611  case 7:
612  if (ac->tags_mapped == 3 && type == TYPE_CPE) {
613  ac->tags_mapped++;
614  return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
615  }
616  case 6:
617  /* Some streams incorrectly code 5.1 audio as
618  * SCE[0] CPE[0] CPE[1] SCE[1]
619  * instead of
620  * SCE[0] CPE[0] CPE[1] LFE[0].
621  * If we seem to have encountered such a stream, transfer
622  * the LFE[0] element to the SCE[1]'s mapping */
623  if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
624  if (!ac->warned_remapping_once && (type != TYPE_LFE || elem_id != 0)) {
626  "This stream seems to incorrectly report its last channel as %s[%d], mapping to LFE[0]\n",
627  type == TYPE_SCE ? "SCE" : "LFE", elem_id);
628  ac->warned_remapping_once++;
629  }
630  ac->tags_mapped++;
631  return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
632  }
633  case 5:
634  if (ac->tags_mapped == 2 && type == TYPE_CPE) {
635  ac->tags_mapped++;
636  return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
637  }
638  case 4:
639  /* Some streams incorrectly code 4.0 audio as
640  * SCE[0] CPE[0] LFE[0]
641  * instead of
642  * SCE[0] CPE[0] SCE[1].
643  * If we seem to have encountered such a stream, transfer
644  * the SCE[1] element to the LFE[0]'s mapping */
645  if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
646  if (!ac->warned_remapping_once && (type != TYPE_SCE || elem_id != 1)) {
648  "This stream seems to incorrectly report its last channel as %s[%d], mapping to SCE[1]\n",
649  type == TYPE_SCE ? "SCE" : "LFE", elem_id);
650  ac->warned_remapping_once++;
651  }
652  ac->tags_mapped++;
653  return ac->tag_che_map[type][elem_id] = ac->che[TYPE_SCE][1];
654  }
655  if (ac->tags_mapped == 2 &&
656  ac->oc[1].m4ac.chan_config == 4 &&
657  type == TYPE_SCE) {
658  ac->tags_mapped++;
659  return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
660  }
661  case 3:
662  case 2:
663  if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
664  type == TYPE_CPE) {
665  ac->tags_mapped++;
666  return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
667  } else if (ac->oc[1].m4ac.chan_config == 2) {
668  return NULL;
669  }
670  case 1:
671  if (!ac->tags_mapped && type == TYPE_SCE) {
672  ac->tags_mapped++;
673  return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
674  }
675  default:
676  return NULL;
677  }
678 }
679 
680 /**
681  * Decode an array of 4 bit element IDs, optionally interleaved with a
682  * stereo/mono switching bit.
683  *
684  * @param type speaker type/position for these channels
685  */
686 static void decode_channel_map(uint8_t layout_map[][3],
687  enum ChannelPosition type,
688  GetBitContext *gb, int n)
689 {
690  while (n--) {
691  enum RawDataBlockType syn_ele;
692  switch (type) {
693  case AAC_CHANNEL_FRONT:
694  case AAC_CHANNEL_BACK:
695  case AAC_CHANNEL_SIDE:
696  syn_ele = get_bits1(gb);
697  break;
698  case AAC_CHANNEL_CC:
699  skip_bits1(gb);
700  syn_ele = TYPE_CCE;
701  break;
702  case AAC_CHANNEL_LFE:
703  syn_ele = TYPE_LFE;
704  break;
705  default:
706  av_assert0(0);
707  }
708  layout_map[0][0] = syn_ele;
709  layout_map[0][1] = get_bits(gb, 4);
710  layout_map[0][2] = type;
711  layout_map++;
712  }
713 }
714 
715 /**
716  * Decode program configuration element; reference: table 4.2.
717  *
718  * @return Returns error status. 0 - OK, !0 - error
719  */
720 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
721  uint8_t (*layout_map)[3],
722  GetBitContext *gb)
723 {
724  int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
725  int sampling_index;
726  int comment_len;
727  int tags;
728 
729  skip_bits(gb, 2); // object_type
730 
731  sampling_index = get_bits(gb, 4);
732  if (m4ac->sampling_index != sampling_index)
733  av_log(avctx, AV_LOG_WARNING,
734  "Sample rate index in program config element does not "
735  "match the sample rate index configured by the container.\n");
736 
737  num_front = get_bits(gb, 4);
738  num_side = get_bits(gb, 4);
739  num_back = get_bits(gb, 4);
740  num_lfe = get_bits(gb, 2);
741  num_assoc_data = get_bits(gb, 3);
742  num_cc = get_bits(gb, 4);
743 
744  if (get_bits1(gb))
745  skip_bits(gb, 4); // mono_mixdown_tag
746  if (get_bits1(gb))
747  skip_bits(gb, 4); // stereo_mixdown_tag
748 
749  if (get_bits1(gb))
750  skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
751 
752  if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
753  av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
754  return -1;
755  }
756  decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
757  tags = num_front;
758  decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
759  tags += num_side;
760  decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
761  tags += num_back;
762  decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
763  tags += num_lfe;
764 
765  skip_bits_long(gb, 4 * num_assoc_data);
766 
767  decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
768  tags += num_cc;
769 
770  align_get_bits(gb);
771 
772  /* comment field, first byte is length */
773  comment_len = get_bits(gb, 8) * 8;
774  if (get_bits_left(gb) < comment_len) {
775  av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
776  return AVERROR_INVALIDDATA;
777  }
778  skip_bits_long(gb, comment_len);
779  return tags;
780 }
781 
782 /**
783  * Decode GA "General Audio" specific configuration; reference: table 4.1.
784  *
785  * @param ac pointer to AACContext, may be null
786  * @param avctx pointer to AVCCodecContext, used for logging
787  *
788  * @return Returns error status. 0 - OK, !0 - error
789  */
791  GetBitContext *gb,
792  MPEG4AudioConfig *m4ac,
793  int channel_config)
794 {
795  int extension_flag, ret, ep_config, res_flags;
796  uint8_t layout_map[MAX_ELEM_ID*4][3];
797  int tags = 0;
798 
799  if (get_bits1(gb)) { // frameLengthFlag
800  avpriv_request_sample(avctx, "960/120 MDCT window");
801  return AVERROR_PATCHWELCOME;
802  }
803 
804  if (get_bits1(gb)) // dependsOnCoreCoder
805  skip_bits(gb, 14); // coreCoderDelay
806  extension_flag = get_bits1(gb);
807 
808  if (m4ac->object_type == AOT_AAC_SCALABLE ||
810  skip_bits(gb, 3); // layerNr
811 
812  if (channel_config == 0) {
813  skip_bits(gb, 4); // element_instance_tag
814  tags = decode_pce(avctx, m4ac, layout_map, gb);
815  if (tags < 0)
816  return tags;
817  } else {
818  if ((ret = set_default_channel_config(avctx, layout_map,
819  &tags, channel_config)))
820  return ret;
821  }
822 
823  if (count_channels(layout_map, tags) > 1) {
824  m4ac->ps = 0;
825  } else if (m4ac->sbr == 1 && m4ac->ps == -1)
826  m4ac->ps = 1;
827 
828  if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
829  return ret;
830 
831  if (extension_flag) {
832  switch (m4ac->object_type) {
833  case AOT_ER_BSAC:
834  skip_bits(gb, 5); // numOfSubFrame
835  skip_bits(gb, 11); // layer_length
836  break;
837  case AOT_ER_AAC_LC:
838  case AOT_ER_AAC_LTP:
839  case AOT_ER_AAC_SCALABLE:
840  case AOT_ER_AAC_LD:
841  res_flags = get_bits(gb, 3);
842  if (res_flags) {
844  "AAC data resilience (flags %x)",
845  res_flags);
846  return AVERROR_PATCHWELCOME;
847  }
848  break;
849  }
850  skip_bits1(gb); // extensionFlag3 (TBD in version 3)
851  }
852  switch (m4ac->object_type) {
853  case AOT_ER_AAC_LC:
854  case AOT_ER_AAC_LTP:
855  case AOT_ER_AAC_SCALABLE:
856  case AOT_ER_AAC_LD:
857  ep_config = get_bits(gb, 2);
858  if (ep_config) {
860  "epConfig %d", ep_config);
861  return AVERROR_PATCHWELCOME;
862  }
863  }
864  return 0;
865 }
866 
868  GetBitContext *gb,
869  MPEG4AudioConfig *m4ac,
870  int channel_config)
871 {
872  int ret, ep_config, res_flags;
873  uint8_t layout_map[MAX_ELEM_ID*4][3];
874  int tags = 0;
875  const int ELDEXT_TERM = 0;
876 
877  m4ac->ps = 0;
878  m4ac->sbr = 0;
879 
880  if (get_bits1(gb)) { // frameLengthFlag
881  avpriv_request_sample(avctx, "960/120 MDCT window");
882  return AVERROR_PATCHWELCOME;
883  }
884 
885  res_flags = get_bits(gb, 3);
886  if (res_flags) {
888  "AAC data resilience (flags %x)",
889  res_flags);
890  return AVERROR_PATCHWELCOME;
891  }
892 
893  if (get_bits1(gb)) { // ldSbrPresentFlag
895  "Low Delay SBR");
896  return AVERROR_PATCHWELCOME;
897  }
898 
899  while (get_bits(gb, 4) != ELDEXT_TERM) {
900  int len = get_bits(gb, 4);
901  if (len == 15)
902  len += get_bits(gb, 8);
903  if (len == 15 + 255)
904  len += get_bits(gb, 16);
905  if (get_bits_left(gb) < len * 8 + 4) {
907  return AVERROR_INVALIDDATA;
908  }
909  skip_bits_long(gb, 8 * len);
910  }
911 
912  if ((ret = set_default_channel_config(avctx, layout_map,
913  &tags, channel_config)))
914  return ret;
915 
916  if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
917  return ret;
918 
919  ep_config = get_bits(gb, 2);
920  if (ep_config) {
922  "epConfig %d", ep_config);
923  return AVERROR_PATCHWELCOME;
924  }
925  return 0;
926 }
927 
928 /**
929  * Decode audio specific configuration; reference: table 1.13.
930  *
931  * @param ac pointer to AACContext, may be null
932  * @param avctx pointer to AVCCodecContext, used for logging
933  * @param m4ac pointer to MPEG4AudioConfig, used for parsing
934  * @param data pointer to buffer holding an audio specific config
935  * @param bit_size size of audio specific config or data in bits
936  * @param sync_extension look for an appended sync extension
937  *
938  * @return Returns error status or number of consumed bits. <0 - error
939  */
941  AVCodecContext *avctx,
942  MPEG4AudioConfig *m4ac,
943  const uint8_t *data, int bit_size,
944  int sync_extension)
945 {
946  GetBitContext gb;
947  int i, ret;
948 
949  av_dlog(avctx, "audio specific config size %d\n", bit_size >> 3);
950  for (i = 0; i < bit_size >> 3; i++)
951  av_dlog(avctx, "%02x ", data[i]);
952  av_dlog(avctx, "\n");
953 
954  if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
955  return ret;
956 
957  if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
958  sync_extension)) < 0)
959  return AVERROR_INVALIDDATA;
960  if (m4ac->sampling_index > 12) {
961  av_log(avctx, AV_LOG_ERROR,
962  "invalid sampling rate index %d\n",
963  m4ac->sampling_index);
964  return AVERROR_INVALIDDATA;
965  }
966  if (m4ac->object_type == AOT_ER_AAC_LD &&
967  (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
968  av_log(avctx, AV_LOG_ERROR,
969  "invalid low delay sampling rate index %d\n",
970  m4ac->sampling_index);
971  return AVERROR_INVALIDDATA;
972  }
973 
974  skip_bits_long(&gb, i);
975 
976  switch (m4ac->object_type) {
977  case AOT_AAC_MAIN:
978  case AOT_AAC_LC:
979  case AOT_AAC_LTP:
980  case AOT_ER_AAC_LC:
981  case AOT_ER_AAC_LD:
982  if ((ret = decode_ga_specific_config(ac, avctx, &gb,
983  m4ac, m4ac->chan_config)) < 0)
984  return ret;
985  break;
986  case AOT_ER_AAC_ELD:
987  if ((ret = decode_eld_specific_config(ac, avctx, &gb,
988  m4ac, m4ac->chan_config)) < 0)
989  return ret;
990  break;
991  default:
993  "Audio object type %s%d",
994  m4ac->sbr == 1 ? "SBR+" : "",
995  m4ac->object_type);
996  return AVERROR(ENOSYS);
997  }
998 
999  av_dlog(avctx,
1000  "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
1001  m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
1002  m4ac->sample_rate, m4ac->sbr,
1003  m4ac->ps);
1004 
1005  return get_bits_count(&gb);
1006 }
1007 
1008 /**
1009  * linear congruential pseudorandom number generator
1010  *
1011  * @param previous_val pointer to the current state of the generator
1012  *
1013  * @return Returns a 32-bit pseudorandom integer
1014  */
1015 static av_always_inline int lcg_random(unsigned previous_val)
1016 {
1017  union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
1018  return v.s;
1019 }
1020 
1022 {
1023  ps->r0 = 0.0f;
1024  ps->r1 = 0.0f;
1025  ps->cor0 = 0.0f;
1026  ps->cor1 = 0.0f;
1027  ps->var0 = 1.0f;
1028  ps->var1 = 1.0f;
1029 }
1030 
1032 {
1033  int i;
1034  for (i = 0; i < MAX_PREDICTORS; i++)
1035  reset_predict_state(&ps[i]);
1036 }
1037 
1038 static int sample_rate_idx (int rate)
1039 {
1040  if (92017 <= rate) return 0;
1041  else if (75132 <= rate) return 1;
1042  else if (55426 <= rate) return 2;
1043  else if (46009 <= rate) return 3;
1044  else if (37566 <= rate) return 4;
1045  else if (27713 <= rate) return 5;
1046  else if (23004 <= rate) return 6;
1047  else if (18783 <= rate) return 7;
1048  else if (13856 <= rate) return 8;
1049  else if (11502 <= rate) return 9;
1050  else if (9391 <= rate) return 10;
1051  else return 11;
1052 }
1053 
1054 static void reset_predictor_group(PredictorState *ps, int group_num)
1055 {
1056  int i;
1057  for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1058  reset_predict_state(&ps[i]);
1059 }
1060 
1061 #define AAC_INIT_VLC_STATIC(num, size) \
1062  INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
1063  ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
1064  sizeof(ff_aac_spectral_bits[num][0]), \
1065  ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
1066  sizeof(ff_aac_spectral_codes[num][0]), \
1067  size);
1068 
1069 static void aacdec_init(AACContext *ac);
1070 
1072 {
1073  AACContext *ac = avctx->priv_data;
1074  int ret;
1075 
1076  ac->avctx = avctx;
1077  ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1078 
1079  aacdec_init(ac);
1080 
1081  avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1082 
1083  if (avctx->extradata_size > 0) {
1084  if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1085  avctx->extradata,
1086  avctx->extradata_size * 8,
1087  1)) < 0)
1088  return ret;
1089  } else {
1090  int sr, i;
1091  uint8_t layout_map[MAX_ELEM_ID*4][3];
1092  int layout_map_tags;
1093 
1094  sr = sample_rate_idx(avctx->sample_rate);
1095  ac->oc[1].m4ac.sampling_index = sr;
1096  ac->oc[1].m4ac.channels = avctx->channels;
1097  ac->oc[1].m4ac.sbr = -1;
1098  ac->oc[1].m4ac.ps = -1;
1099 
1100  for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1101  if (ff_mpeg4audio_channels[i] == avctx->channels)
1102  break;
1104  i = 0;
1105  }
1106  ac->oc[1].m4ac.chan_config = i;
1107 
1108  if (ac->oc[1].m4ac.chan_config) {
1109  int ret = set_default_channel_config(avctx, layout_map,
1110  &layout_map_tags, ac->oc[1].m4ac.chan_config);
1111  if (!ret)
1112  output_configure(ac, layout_map, layout_map_tags,
1113  OC_GLOBAL_HDR, 0);
1114  else if (avctx->err_recognition & AV_EF_EXPLODE)
1115  return AVERROR_INVALIDDATA;
1116  }
1117  }
1118 
1119  if (avctx->channels > MAX_CHANNELS) {
1120  av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1121  return AVERROR_INVALIDDATA;
1122  }
1123 
1124  AAC_INIT_VLC_STATIC( 0, 304);
1125  AAC_INIT_VLC_STATIC( 1, 270);
1126  AAC_INIT_VLC_STATIC( 2, 550);
1127  AAC_INIT_VLC_STATIC( 3, 300);
1128  AAC_INIT_VLC_STATIC( 4, 328);
1129  AAC_INIT_VLC_STATIC( 5, 294);
1130  AAC_INIT_VLC_STATIC( 6, 306);
1131  AAC_INIT_VLC_STATIC( 7, 268);
1132  AAC_INIT_VLC_STATIC( 8, 510);
1133  AAC_INIT_VLC_STATIC( 9, 366);
1134  AAC_INIT_VLC_STATIC(10, 462);
1135 
1136  ff_aac_sbr_init();
1137 
1138  ff_fmt_convert_init(&ac->fmt_conv, avctx);
1140 
1141  ac->random_state = 0x1f2e3d4c;
1142 
1143  ff_aac_tableinit();
1144 
1145  INIT_VLC_STATIC(&vlc_scalefactors, 7,
1148  sizeof(ff_aac_scalefactor_bits[0]),
1149  sizeof(ff_aac_scalefactor_bits[0]),
1151  sizeof(ff_aac_scalefactor_code[0]),
1152  sizeof(ff_aac_scalefactor_code[0]),
1153  352);
1154 
1155  ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
1156  ff_mdct_init(&ac->mdct_ld, 10, 1, 1.0 / (32768.0 * 512.0));
1157  ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
1158  ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
1159  // window initialization
1165 
1166  cbrt_tableinit();
1167 
1168  return 0;
1169 }
1170 
1171 /**
1172  * Skip data_stream_element; reference: table 4.10.
1173  */
1175 {
1176  int byte_align = get_bits1(gb);
1177  int count = get_bits(gb, 8);
1178  if (count == 255)
1179  count += get_bits(gb, 8);
1180  if (byte_align)
1181  align_get_bits(gb);
1182 
1183  if (get_bits_left(gb) < 8 * count) {
1184  av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1185  return AVERROR_INVALIDDATA;
1186  }
1187  skip_bits_long(gb, 8 * count);
1188  return 0;
1189 }
1190 
1192  GetBitContext *gb)
1193 {
1194  int sfb;
1195  if (get_bits1(gb)) {
1196  ics->predictor_reset_group = get_bits(gb, 5);
1197  if (ics->predictor_reset_group == 0 ||
1198  ics->predictor_reset_group > 30) {
1199  av_log(ac->avctx, AV_LOG_ERROR,
1200  "Invalid Predictor Reset Group.\n");
1201  return AVERROR_INVALIDDATA;
1202  }
1203  }
1204  for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1205  ics->prediction_used[sfb] = get_bits1(gb);
1206  }
1207  return 0;
1208 }
1209 
1210 /**
1211  * Decode Long Term Prediction data; reference: table 4.xx.
1212  */
1214  GetBitContext *gb, uint8_t max_sfb)
1215 {
1216  int sfb;
1217 
1218  ltp->lag = get_bits(gb, 11);
1219  ltp->coef = ltp_coef[get_bits(gb, 3)];
1220  for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1221  ltp->used[sfb] = get_bits1(gb);
1222 }
1223 
1224 /**
1225  * Decode Individual Channel Stream info; reference: table 4.6.
1226  */
1228  GetBitContext *gb)
1229 {
1230  int aot = ac->oc[1].m4ac.object_type;
1231  if (aot != AOT_ER_AAC_ELD) {
1232  if (get_bits1(gb)) {
1233  av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1234  return AVERROR_INVALIDDATA;
1235  }
1236  ics->window_sequence[1] = ics->window_sequence[0];
1237  ics->window_sequence[0] = get_bits(gb, 2);
1238  if (aot == AOT_ER_AAC_LD &&
1239  ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1240  av_log(ac->avctx, AV_LOG_ERROR,
1241  "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1242  "window sequence %d found.\n", ics->window_sequence[0]);
1244  return AVERROR_INVALIDDATA;
1245  }
1246  ics->use_kb_window[1] = ics->use_kb_window[0];
1247  ics->use_kb_window[0] = get_bits1(gb);
1248  }
1249  ics->num_window_groups = 1;
1250  ics->group_len[0] = 1;
1251  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1252  int i;
1253  ics->max_sfb = get_bits(gb, 4);
1254  for (i = 0; i < 7; i++) {
1255  if (get_bits1(gb)) {
1256  ics->group_len[ics->num_window_groups - 1]++;
1257  } else {
1258  ics->num_window_groups++;
1259  ics->group_len[ics->num_window_groups - 1] = 1;
1260  }
1261  }
1262  ics->num_windows = 8;
1266  ics->predictor_present = 0;
1267  } else {
1268  ics->max_sfb = get_bits(gb, 6);
1269  ics->num_windows = 1;
1270  if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1274  if (!ics->num_swb || !ics->swb_offset)
1275  return AVERROR_BUG;
1276  } else {
1280  }
1281  if (aot != AOT_ER_AAC_ELD) {
1282  ics->predictor_present = get_bits1(gb);
1283  ics->predictor_reset_group = 0;
1284  }
1285  if (ics->predictor_present) {
1286  if (aot == AOT_AAC_MAIN) {
1287  if (decode_prediction(ac, ics, gb)) {
1288  goto fail;
1289  }
1290  } else if (aot == AOT_AAC_LC ||
1291  aot == AOT_ER_AAC_LC) {
1292  av_log(ac->avctx, AV_LOG_ERROR,
1293  "Prediction is not allowed in AAC-LC.\n");
1294  goto fail;
1295  } else {
1296  if (aot == AOT_ER_AAC_LD) {
1297  av_log(ac->avctx, AV_LOG_ERROR,
1298  "LTP in ER AAC LD not yet implemented.\n");
1299  return AVERROR_PATCHWELCOME;
1300  }
1301  if ((ics->ltp.present = get_bits(gb, 1)))
1302  decode_ltp(&ics->ltp, gb, ics->max_sfb);
1303  }
1304  }
1305  }
1306 
1307  if (ics->max_sfb > ics->num_swb) {
1308  av_log(ac->avctx, AV_LOG_ERROR,
1309  "Number of scalefactor bands in group (%d) "
1310  "exceeds limit (%d).\n",
1311  ics->max_sfb, ics->num_swb);
1312  goto fail;
1313  }
1314 
1315  return 0;
1316 fail:
1317  ics->max_sfb = 0;
1318  return AVERROR_INVALIDDATA;
1319 }
1320 
1321 /**
1322  * Decode band types (section_data payload); reference: table 4.46.
1323  *
1324  * @param band_type array of the used band type
1325  * @param band_type_run_end array of the last scalefactor band of a band type run
1326  *
1327  * @return Returns error status. 0 - OK, !0 - error
1328  */
1329 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1330  int band_type_run_end[120], GetBitContext *gb,
1332 {
1333  int g, idx = 0;
1334  const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1335  for (g = 0; g < ics->num_window_groups; g++) {
1336  int k = 0;
1337  while (k < ics->max_sfb) {
1338  uint8_t sect_end = k;
1339  int sect_len_incr;
1340  int sect_band_type = get_bits(gb, 4);
1341  if (sect_band_type == 12) {
1342  av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1343  return AVERROR_INVALIDDATA;
1344  }
1345  do {
1346  sect_len_incr = get_bits(gb, bits);
1347  sect_end += sect_len_incr;
1348  if (get_bits_left(gb) < 0) {
1349  av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1350  return AVERROR_INVALIDDATA;
1351  }
1352  if (sect_end > ics->max_sfb) {
1353  av_log(ac->avctx, AV_LOG_ERROR,
1354  "Number of bands (%d) exceeds limit (%d).\n",
1355  sect_end, ics->max_sfb);
1356  return AVERROR_INVALIDDATA;
1357  }
1358  } while (sect_len_incr == (1 << bits) - 1);
1359  for (; k < sect_end; k++) {
1360  band_type [idx] = sect_band_type;
1361  band_type_run_end[idx++] = sect_end;
1362  }
1363  }
1364  }
1365  return 0;
1366 }
1367 
1368 /**
1369  * Decode scalefactors; reference: table 4.47.
1370  *
1371  * @param global_gain first scalefactor value as scalefactors are differentially coded
1372  * @param band_type array of the used band type
1373  * @param band_type_run_end array of the last scalefactor band of a band type run
1374  * @param sf array of scalefactors or intensity stereo positions
1375  *
1376  * @return Returns error status. 0 - OK, !0 - error
1377  */
1378 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1379  unsigned int global_gain,
1381  enum BandType band_type[120],
1382  int band_type_run_end[120])
1383 {
1384  int g, i, idx = 0;
1385  int offset[3] = { global_gain, global_gain - 90, 0 };
1386  int clipped_offset;
1387  int noise_flag = 1;
1388  for (g = 0; g < ics->num_window_groups; g++) {
1389  for (i = 0; i < ics->max_sfb;) {
1390  int run_end = band_type_run_end[idx];
1391  if (band_type[idx] == ZERO_BT) {
1392  for (; i < run_end; i++, idx++)
1393  sf[idx] = 0.0;
1394  } else if ((band_type[idx] == INTENSITY_BT) ||
1395  (band_type[idx] == INTENSITY_BT2)) {
1396  for (; i < run_end; i++, idx++) {
1397  offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1398  clipped_offset = av_clip(offset[2], -155, 100);
1399  if (offset[2] != clipped_offset) {
1401  "If you heard an audible artifact, there may be a bug in the decoder. "
1402  "Clipped intensity stereo position (%d -> %d)",
1403  offset[2], clipped_offset);
1404  }
1405  sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1406  }
1407  } else if (band_type[idx] == NOISE_BT) {
1408  for (; i < run_end; i++, idx++) {
1409  if (noise_flag-- > 0)
1410  offset[1] += get_bits(gb, 9) - 256;
1411  else
1412  offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1413  clipped_offset = av_clip(offset[1], -100, 155);
1414  if (offset[1] != clipped_offset) {
1416  "If you heard an audible artifact, there may be a bug in the decoder. "
1417  "Clipped noise gain (%d -> %d)",
1418  offset[1], clipped_offset);
1419  }
1420  sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1421  }
1422  } else {
1423  for (; i < run_end; i++, idx++) {
1424  offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1425  if (offset[0] > 255U) {
1426  av_log(ac->avctx, AV_LOG_ERROR,
1427  "Scalefactor (%d) out of range.\n", offset[0]);
1428  return AVERROR_INVALIDDATA;
1429  }
1430  sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1431  }
1432  }
1433  }
1434  }
1435  return 0;
1436 }
1437 
1438 /**
1439  * Decode pulse data; reference: table 4.7.
1440  */
1441 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1442  const uint16_t *swb_offset, int num_swb)
1443 {
1444  int i, pulse_swb;
1445  pulse->num_pulse = get_bits(gb, 2) + 1;
1446  pulse_swb = get_bits(gb, 6);
1447  if (pulse_swb >= num_swb)
1448  return -1;
1449  pulse->pos[0] = swb_offset[pulse_swb];
1450  pulse->pos[0] += get_bits(gb, 5);
1451  if (pulse->pos[0] >= swb_offset[num_swb])
1452  return -1;
1453  pulse->amp[0] = get_bits(gb, 4);
1454  for (i = 1; i < pulse->num_pulse; i++) {
1455  pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1456  if (pulse->pos[i] >= swb_offset[num_swb])
1457  return -1;
1458  pulse->amp[i] = get_bits(gb, 4);
1459  }
1460  return 0;
1461 }
1462 
1463 /**
1464  * Decode Temporal Noise Shaping data; reference: table 4.48.
1465  *
1466  * @return Returns error status. 0 - OK, !0 - error
1467  */
1469  GetBitContext *gb, const IndividualChannelStream *ics)
1470 {
1471  int w, filt, i, coef_len, coef_res, coef_compress;
1472  const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1473  const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1474  for (w = 0; w < ics->num_windows; w++) {
1475  if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1476  coef_res = get_bits1(gb);
1477 
1478  for (filt = 0; filt < tns->n_filt[w]; filt++) {
1479  int tmp2_idx;
1480  tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1481 
1482  if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1483  av_log(ac->avctx, AV_LOG_ERROR,
1484  "TNS filter order %d is greater than maximum %d.\n",
1485  tns->order[w][filt], tns_max_order);
1486  tns->order[w][filt] = 0;
1487  return AVERROR_INVALIDDATA;
1488  }
1489  if (tns->order[w][filt]) {
1490  tns->direction[w][filt] = get_bits1(gb);
1491  coef_compress = get_bits1(gb);
1492  coef_len = coef_res + 3 - coef_compress;
1493  tmp2_idx = 2 * coef_compress + coef_res;
1494 
1495  for (i = 0; i < tns->order[w][filt]; i++)
1496  tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1497  }
1498  }
1499  }
1500  }
1501  return 0;
1502 }
1503 
1504 /**
1505  * Decode Mid/Side data; reference: table 4.54.
1506  *
1507  * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1508  * [1] mask is decoded from bitstream; [2] mask is all 1s;
1509  * [3] reserved for scalable AAC
1510  */
1512  int ms_present)
1513 {
1514  int idx;
1515  if (ms_present == 1) {
1516  for (idx = 0;
1517  idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1518  idx++)
1519  cpe->ms_mask[idx] = get_bits1(gb);
1520  } else if (ms_present == 2) {
1521  memset(cpe->ms_mask, 1, sizeof(cpe->ms_mask[0]) * cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb);
1522  }
1523 }
1524 
1525 #ifndef VMUL2
1526 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1527  const float *scale)
1528 {
1529  float s = *scale;
1530  *dst++ = v[idx & 15] * s;
1531  *dst++ = v[idx>>4 & 15] * s;
1532  return dst;
1533 }
1534 #endif
1535 
1536 #ifndef VMUL4
1537 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1538  const float *scale)
1539 {
1540  float s = *scale;
1541  *dst++ = v[idx & 3] * s;
1542  *dst++ = v[idx>>2 & 3] * s;
1543  *dst++ = v[idx>>4 & 3] * s;
1544  *dst++ = v[idx>>6 & 3] * s;
1545  return dst;
1546 }
1547 #endif
1548 
1549 #ifndef VMUL2S
1550 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1551  unsigned sign, const float *scale)
1552 {
1553  union av_intfloat32 s0, s1;
1554 
1555  s0.f = s1.f = *scale;
1556  s0.i ^= sign >> 1 << 31;
1557  s1.i ^= sign << 31;
1558 
1559  *dst++ = v[idx & 15] * s0.f;
1560  *dst++ = v[idx>>4 & 15] * s1.f;
1561 
1562  return dst;
1563 }
1564 #endif
1565 
1566 #ifndef VMUL4S
1567 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1568  unsigned sign, const float *scale)
1569 {
1570  unsigned nz = idx >> 12;
1571  union av_intfloat32 s = { .f = *scale };
1572  union av_intfloat32 t;
1573 
1574  t.i = s.i ^ (sign & 1U<<31);
1575  *dst++ = v[idx & 3] * t.f;
1576 
1577  sign <<= nz & 1; nz >>= 1;
1578  t.i = s.i ^ (sign & 1U<<31);
1579  *dst++ = v[idx>>2 & 3] * t.f;
1580 
1581  sign <<= nz & 1; nz >>= 1;
1582  t.i = s.i ^ (sign & 1U<<31);
1583  *dst++ = v[idx>>4 & 3] * t.f;
1584 
1585  sign <<= nz & 1;
1586  t.i = s.i ^ (sign & 1U<<31);
1587  *dst++ = v[idx>>6 & 3] * t.f;
1588 
1589  return dst;
1590 }
1591 #endif
1592 
1593 /**
1594  * Decode spectral data; reference: table 4.50.
1595  * Dequantize and scale spectral data; reference: 4.6.3.3.
1596  *
1597  * @param coef array of dequantized, scaled spectral data
1598  * @param sf array of scalefactors or intensity stereo positions
1599  * @param pulse_present set if pulses are present
1600  * @param pulse pointer to pulse data struct
1601  * @param band_type array of the used band type
1602  *
1603  * @return Returns error status. 0 - OK, !0 - error
1604  */
1605 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1606  GetBitContext *gb, const float sf[120],
1607  int pulse_present, const Pulse *pulse,
1608  const IndividualChannelStream *ics,
1609  enum BandType band_type[120])
1610 {
1611  int i, k, g, idx = 0;
1612  const int c = 1024 / ics->num_windows;
1613  const uint16_t *offsets = ics->swb_offset;
1614  float *coef_base = coef;
1615 
1616  for (g = 0; g < ics->num_windows; g++)
1617  memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1618  sizeof(float) * (c - offsets[ics->max_sfb]));
1619 
1620  for (g = 0; g < ics->num_window_groups; g++) {
1621  unsigned g_len = ics->group_len[g];
1622 
1623  for (i = 0; i < ics->max_sfb; i++, idx++) {
1624  const unsigned cbt_m1 = band_type[idx] - 1;
1625  float *cfo = coef + offsets[i];
1626  int off_len = offsets[i + 1] - offsets[i];
1627  int group;
1628 
1629  if (cbt_m1 >= INTENSITY_BT2 - 1) {
1630  for (group = 0; group < g_len; group++, cfo+=128) {
1631  memset(cfo, 0, off_len * sizeof(float));
1632  }
1633  } else if (cbt_m1 == NOISE_BT - 1) {
1634  for (group = 0; group < g_len; group++, cfo+=128) {
1635  float scale;
1636  float band_energy;
1637 
1638  for (k = 0; k < off_len; k++) {
1640  cfo[k] = ac->random_state;
1641  }
1642 
1643  band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1644  scale = sf[idx] / sqrtf(band_energy);
1645  ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1646  }
1647  } else {
1648  const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1649  const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1650  VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1651  OPEN_READER(re, gb);
1652 
1653  switch (cbt_m1 >> 1) {
1654  case 0:
1655  for (group = 0; group < g_len; group++, cfo+=128) {
1656  float *cf = cfo;
1657  int len = off_len;
1658 
1659  do {
1660  int code;
1661  unsigned cb_idx;
1662 
1663  UPDATE_CACHE(re, gb);
1664  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1665  cb_idx = cb_vector_idx[code];
1666  cf = VMUL4(cf, vq, cb_idx, sf + idx);
1667  } while (len -= 4);
1668  }
1669  break;
1670 
1671  case 1:
1672  for (group = 0; group < g_len; group++, cfo+=128) {
1673  float *cf = cfo;
1674  int len = off_len;
1675 
1676  do {
1677  int code;
1678  unsigned nnz;
1679  unsigned cb_idx;
1680  uint32_t bits;
1681 
1682  UPDATE_CACHE(re, gb);
1683  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1684  cb_idx = cb_vector_idx[code];
1685  nnz = cb_idx >> 8 & 15;
1686  bits = nnz ? GET_CACHE(re, gb) : 0;
1687  LAST_SKIP_BITS(re, gb, nnz);
1688  cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1689  } while (len -= 4);
1690  }
1691  break;
1692 
1693  case 2:
1694  for (group = 0; group < g_len; group++, cfo+=128) {
1695  float *cf = cfo;
1696  int len = off_len;
1697 
1698  do {
1699  int code;
1700  unsigned cb_idx;
1701 
1702  UPDATE_CACHE(re, gb);
1703  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1704  cb_idx = cb_vector_idx[code];
1705  cf = VMUL2(cf, vq, cb_idx, sf + idx);
1706  } while (len -= 2);
1707  }
1708  break;
1709 
1710  case 3:
1711  case 4:
1712  for (group = 0; group < g_len; group++, cfo+=128) {
1713  float *cf = cfo;
1714  int len = off_len;
1715 
1716  do {
1717  int code;
1718  unsigned nnz;
1719  unsigned cb_idx;
1720  unsigned sign;
1721 
1722  UPDATE_CACHE(re, gb);
1723  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1724  cb_idx = cb_vector_idx[code];
1725  nnz = cb_idx >> 8 & 15;
1726  sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1727  LAST_SKIP_BITS(re, gb, nnz);
1728  cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1729  } while (len -= 2);
1730  }
1731  break;
1732 
1733  default:
1734  for (group = 0; group < g_len; group++, cfo+=128) {
1735  float *cf = cfo;
1736  uint32_t *icf = (uint32_t *) cf;
1737  int len = off_len;
1738 
1739  do {
1740  int code;
1741  unsigned nzt, nnz;
1742  unsigned cb_idx;
1743  uint32_t bits;
1744  int j;
1745 
1746  UPDATE_CACHE(re, gb);
1747  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1748 
1749  if (!code) {
1750  *icf++ = 0;
1751  *icf++ = 0;
1752  continue;
1753  }
1754 
1755  cb_idx = cb_vector_idx[code];
1756  nnz = cb_idx >> 12;
1757  nzt = cb_idx >> 8;
1758  bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1759  LAST_SKIP_BITS(re, gb, nnz);
1760 
1761  for (j = 0; j < 2; j++) {
1762  if (nzt & 1<<j) {
1763  uint32_t b;
1764  int n;
1765  /* The total length of escape_sequence must be < 22 bits according
1766  to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1767  UPDATE_CACHE(re, gb);
1768  b = GET_CACHE(re, gb);
1769  b = 31 - av_log2(~b);
1770 
1771  if (b > 8) {
1772  av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1773  return AVERROR_INVALIDDATA;
1774  }
1775 
1776  SKIP_BITS(re, gb, b + 1);
1777  b += 4;
1778  n = (1 << b) + SHOW_UBITS(re, gb, b);
1779  LAST_SKIP_BITS(re, gb, b);
1780  *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1781  bits <<= 1;
1782  } else {
1783  unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1784  *icf++ = (bits & 1U<<31) | v;
1785  bits <<= !!v;
1786  }
1787  cb_idx >>= 4;
1788  }
1789  } while (len -= 2);
1790 
1791  ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1792  }
1793  }
1794 
1795  CLOSE_READER(re, gb);
1796  }
1797  }
1798  coef += g_len << 7;
1799  }
1800 
1801  if (pulse_present) {
1802  idx = 0;
1803  for (i = 0; i < pulse->num_pulse; i++) {
1804  float co = coef_base[ pulse->pos[i] ];
1805  while (offsets[idx + 1] <= pulse->pos[i])
1806  idx++;
1807  if (band_type[idx] != NOISE_BT && sf[idx]) {
1808  float ico = -pulse->amp[i];
1809  if (co) {
1810  co /= sf[idx];
1811  ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1812  }
1813  coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1814  }
1815  }
1816  }
1817  return 0;
1818 }
1819 
1820 static av_always_inline float flt16_round(float pf)
1821 {
1822  union av_intfloat32 tmp;
1823  tmp.f = pf;
1824  tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1825  return tmp.f;
1826 }
1827 
1828 static av_always_inline float flt16_even(float pf)
1829 {
1830  union av_intfloat32 tmp;
1831  tmp.f = pf;
1832  tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1833  return tmp.f;
1834 }
1835 
1836 static av_always_inline float flt16_trunc(float pf)
1837 {
1838  union av_intfloat32 pun;
1839  pun.f = pf;
1840  pun.i &= 0xFFFF0000U;
1841  return pun.f;
1842 }
1843 
1844 static av_always_inline void predict(PredictorState *ps, float *coef,
1845  int output_enable)
1846 {
1847  const float a = 0.953125; // 61.0 / 64
1848  const float alpha = 0.90625; // 29.0 / 32
1849  float e0, e1;
1850  float pv;
1851  float k1, k2;
1852  float r0 = ps->r0, r1 = ps->r1;
1853  float cor0 = ps->cor0, cor1 = ps->cor1;
1854  float var0 = ps->var0, var1 = ps->var1;
1855 
1856  k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1857  k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1858 
1859  pv = flt16_round(k1 * r0 + k2 * r1);
1860  if (output_enable)
1861  *coef += pv;
1862 
1863  e0 = *coef;
1864  e1 = e0 - k1 * r0;
1865 
1866  ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1867  ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1868  ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1869  ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1870 
1871  ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1872  ps->r0 = flt16_trunc(a * e0);
1873 }
1874 
1875 /**
1876  * Apply AAC-Main style frequency domain prediction.
1877  */
1879 {
1880  int sfb, k;
1881 
1882  if (!sce->ics.predictor_initialized) {
1884  sce->ics.predictor_initialized = 1;
1885  }
1886 
1887  if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1888  for (sfb = 0;
1889  sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1890  sfb++) {
1891  for (k = sce->ics.swb_offset[sfb];
1892  k < sce->ics.swb_offset[sfb + 1];
1893  k++) {
1894  predict(&sce->predictor_state[k], &sce->coeffs[k],
1895  sce->ics.predictor_present &&
1896  sce->ics.prediction_used[sfb]);
1897  }
1898  }
1899  if (sce->ics.predictor_reset_group)
1901  sce->ics.predictor_reset_group);
1902  } else
1904 }
1905 
1906 /**
1907  * Decode an individual_channel_stream payload; reference: table 4.44.
1908  *
1909  * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1910  * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1911  *
1912  * @return Returns error status. 0 - OK, !0 - error
1913  */
1915  GetBitContext *gb, int common_window, int scale_flag)
1916 {
1917  Pulse pulse;
1918  TemporalNoiseShaping *tns = &sce->tns;
1919  IndividualChannelStream *ics = &sce->ics;
1920  float *out = sce->coeffs;
1921  int global_gain, eld_syntax, er_syntax, pulse_present = 0;
1922  int ret;
1923 
1924  eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1925  er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1926  ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1927  ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1928  ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1929 
1930  /* This assignment is to silence a GCC warning about the variable being used
1931  * uninitialized when in fact it always is.
1932  */
1933  pulse.num_pulse = 0;
1934 
1935  global_gain = get_bits(gb, 8);
1936 
1937  if (!common_window && !scale_flag) {
1938  if (decode_ics_info(ac, ics, gb) < 0)
1939  return AVERROR_INVALIDDATA;
1940  }
1941 
1942  if ((ret = decode_band_types(ac, sce->band_type,
1943  sce->band_type_run_end, gb, ics)) < 0)
1944  return ret;
1945  if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1946  sce->band_type, sce->band_type_run_end)) < 0)
1947  return ret;
1948 
1949  pulse_present = 0;
1950  if (!scale_flag) {
1951  if (!eld_syntax && (pulse_present = get_bits1(gb))) {
1952  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1953  av_log(ac->avctx, AV_LOG_ERROR,
1954  "Pulse tool not allowed in eight short sequence.\n");
1955  return AVERROR_INVALIDDATA;
1956  }
1957  if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1958  av_log(ac->avctx, AV_LOG_ERROR,
1959  "Pulse data corrupt or invalid.\n");
1960  return AVERROR_INVALIDDATA;
1961  }
1962  }
1963  tns->present = get_bits1(gb);
1964  if (tns->present && !er_syntax)
1965  if (decode_tns(ac, tns, gb, ics) < 0)
1966  return AVERROR_INVALIDDATA;
1967  if (!eld_syntax && get_bits1(gb)) {
1968  avpriv_request_sample(ac->avctx, "SSR");
1969  return AVERROR_PATCHWELCOME;
1970  }
1971  // I see no textual basis in the spec for this occurring after SSR gain
1972  // control, but this is what both reference and real implmentations do
1973  if (tns->present && er_syntax)
1974  if (decode_tns(ac, tns, gb, ics) < 0)
1975  return AVERROR_INVALIDDATA;
1976  }
1977 
1978  if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1979  &pulse, ics, sce->band_type) < 0)
1980  return AVERROR_INVALIDDATA;
1981 
1982  if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1983  apply_prediction(ac, sce);
1984 
1985  return 0;
1986 }
1987 
1988 /**
1989  * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1990  */
1992 {
1993  const IndividualChannelStream *ics = &cpe->ch[0].ics;
1994  float *ch0 = cpe->ch[0].coeffs;
1995  float *ch1 = cpe->ch[1].coeffs;
1996  int g, i, group, idx = 0;
1997  const uint16_t *offsets = ics->swb_offset;
1998  for (g = 0; g < ics->num_window_groups; g++) {
1999  for (i = 0; i < ics->max_sfb; i++, idx++) {
2000  if (cpe->ms_mask[idx] &&
2001  cpe->ch[0].band_type[idx] < NOISE_BT &&
2002  cpe->ch[1].band_type[idx] < NOISE_BT) {
2003  for (group = 0; group < ics->group_len[g]; group++) {
2004  ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
2005  ch1 + group * 128 + offsets[i],
2006  offsets[i+1] - offsets[i]);
2007  }
2008  }
2009  }
2010  ch0 += ics->group_len[g] * 128;
2011  ch1 += ics->group_len[g] * 128;
2012  }
2013 }
2014 
2015 /**
2016  * intensity stereo decoding; reference: 4.6.8.2.3
2017  *
2018  * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
2019  * [1] mask is decoded from bitstream; [2] mask is all 1s;
2020  * [3] reserved for scalable AAC
2021  */
2023  ChannelElement *cpe, int ms_present)
2024 {
2025  const IndividualChannelStream *ics = &cpe->ch[1].ics;
2026  SingleChannelElement *sce1 = &cpe->ch[1];
2027  float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
2028  const uint16_t *offsets = ics->swb_offset;
2029  int g, group, i, idx = 0;
2030  int c;
2031  float scale;
2032  for (g = 0; g < ics->num_window_groups; g++) {
2033  for (i = 0; i < ics->max_sfb;) {
2034  if (sce1->band_type[idx] == INTENSITY_BT ||
2035  sce1->band_type[idx] == INTENSITY_BT2) {
2036  const int bt_run_end = sce1->band_type_run_end[idx];
2037  for (; i < bt_run_end; i++, idx++) {
2038  c = -1 + 2 * (sce1->band_type[idx] - 14);
2039  if (ms_present)
2040  c *= 1 - 2 * cpe->ms_mask[idx];
2041  scale = c * sce1->sf[idx];
2042  for (group = 0; group < ics->group_len[g]; group++)
2043  ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
2044  coef0 + group * 128 + offsets[i],
2045  scale,
2046  offsets[i + 1] - offsets[i]);
2047  }
2048  } else {
2049  int bt_run_end = sce1->band_type_run_end[idx];
2050  idx += bt_run_end - i;
2051  i = bt_run_end;
2052  }
2053  }
2054  coef0 += ics->group_len[g] * 128;
2055  coef1 += ics->group_len[g] * 128;
2056  }
2057 }
2058 
2059 /**
2060  * Decode a channel_pair_element; reference: table 4.4.
2061  *
2062  * @return Returns error status. 0 - OK, !0 - error
2063  */
2065 {
2066  int i, ret, common_window, ms_present = 0;
2067  int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2068 
2069  common_window = eld_syntax || get_bits1(gb);
2070  if (common_window) {
2071  if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2072  return AVERROR_INVALIDDATA;
2073  i = cpe->ch[1].ics.use_kb_window[0];
2074  cpe->ch[1].ics = cpe->ch[0].ics;
2075  cpe->ch[1].ics.use_kb_window[1] = i;
2076  if (cpe->ch[1].ics.predictor_present &&
2077  (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2078  if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2079  decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2080  ms_present = get_bits(gb, 2);
2081  if (ms_present == 3) {
2082  av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2083  return AVERROR_INVALIDDATA;
2084  } else if (ms_present)
2085  decode_mid_side_stereo(cpe, gb, ms_present);
2086  }
2087  if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2088  return ret;
2089  if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2090  return ret;
2091 
2092  if (common_window) {
2093  if (ms_present)
2094  apply_mid_side_stereo(ac, cpe);
2095  if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2096  apply_prediction(ac, &cpe->ch[0]);
2097  apply_prediction(ac, &cpe->ch[1]);
2098  }
2099  }
2100 
2101  apply_intensity_stereo(ac, cpe, ms_present);
2102  return 0;
2103 }
2104 
2105 static const float cce_scale[] = {
2106  1.09050773266525765921, //2^(1/8)
2107  1.18920711500272106672, //2^(1/4)
2108  M_SQRT2,
2109  2,
2110 };
2111 
2112 /**
2113  * Decode coupling_channel_element; reference: table 4.8.
2114  *
2115  * @return Returns error status. 0 - OK, !0 - error
2116  */
2118 {
2119  int num_gain = 0;
2120  int c, g, sfb, ret;
2121  int sign;
2122  float scale;
2123  SingleChannelElement *sce = &che->ch[0];
2124  ChannelCoupling *coup = &che->coup;
2125 
2126  coup->coupling_point = 2 * get_bits1(gb);
2127  coup->num_coupled = get_bits(gb, 3);
2128  for (c = 0; c <= coup->num_coupled; c++) {
2129  num_gain++;
2130  coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2131  coup->id_select[c] = get_bits(gb, 4);
2132  if (coup->type[c] == TYPE_CPE) {
2133  coup->ch_select[c] = get_bits(gb, 2);
2134  if (coup->ch_select[c] == 3)
2135  num_gain++;
2136  } else
2137  coup->ch_select[c] = 2;
2138  }
2139  coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2140 
2141  sign = get_bits(gb, 1);
2142  scale = cce_scale[get_bits(gb, 2)];
2143 
2144  if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2145  return ret;
2146 
2147  for (c = 0; c < num_gain; c++) {
2148  int idx = 0;
2149  int cge = 1;
2150  int gain = 0;
2151  float gain_cache = 1.0;
2152  if (c) {
2153  cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2154  gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2155  gain_cache = powf(scale, -gain);
2156  }
2157  if (coup->coupling_point == AFTER_IMDCT) {
2158  coup->gain[c][0] = gain_cache;
2159  } else {
2160  for (g = 0; g < sce->ics.num_window_groups; g++) {
2161  for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2162  if (sce->band_type[idx] != ZERO_BT) {
2163  if (!cge) {
2164  int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2165  if (t) {
2166  int s = 1;
2167  t = gain += t;
2168  if (sign) {
2169  s -= 2 * (t & 0x1);
2170  t >>= 1;
2171  }
2172  gain_cache = powf(scale, -t) * s;
2173  }
2174  }
2175  coup->gain[c][idx] = gain_cache;
2176  }
2177  }
2178  }
2179  }
2180  }
2181  return 0;
2182 }
2183 
2184 /**
2185  * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2186  *
2187  * @return Returns number of bytes consumed.
2188  */
2190  GetBitContext *gb)
2191 {
2192  int i;
2193  int num_excl_chan = 0;
2194 
2195  do {
2196  for (i = 0; i < 7; i++)
2197  che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2198  } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2199 
2200  return num_excl_chan / 7;
2201 }
2202 
2203 /**
2204  * Decode dynamic range information; reference: table 4.52.
2205  *
2206  * @return Returns number of bytes consumed.
2207  */
2209  GetBitContext *gb)
2210 {
2211  int n = 1;
2212  int drc_num_bands = 1;
2213  int i;
2214 
2215  /* pce_tag_present? */
2216  if (get_bits1(gb)) {
2217  che_drc->pce_instance_tag = get_bits(gb, 4);
2218  skip_bits(gb, 4); // tag_reserved_bits
2219  n++;
2220  }
2221 
2222  /* excluded_chns_present? */
2223  if (get_bits1(gb)) {
2224  n += decode_drc_channel_exclusions(che_drc, gb);
2225  }
2226 
2227  /* drc_bands_present? */
2228  if (get_bits1(gb)) {
2229  che_drc->band_incr = get_bits(gb, 4);
2230  che_drc->interpolation_scheme = get_bits(gb, 4);
2231  n++;
2232  drc_num_bands += che_drc->band_incr;
2233  for (i = 0; i < drc_num_bands; i++) {
2234  che_drc->band_top[i] = get_bits(gb, 8);
2235  n++;
2236  }
2237  }
2238 
2239  /* prog_ref_level_present? */
2240  if (get_bits1(gb)) {
2241  che_drc->prog_ref_level = get_bits(gb, 7);
2242  skip_bits1(gb); // prog_ref_level_reserved_bits
2243  n++;
2244  }
2245 
2246  for (i = 0; i < drc_num_bands; i++) {
2247  che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2248  che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2249  n++;
2250  }
2251 
2252  return n;
2253 }
2254 
2255 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2256  uint8_t buf[256];
2257  int i, major, minor;
2258 
2259  if (len < 13+7*8)
2260  goto unknown;
2261 
2262  get_bits(gb, 13); len -= 13;
2263 
2264  for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2265  buf[i] = get_bits(gb, 8);
2266 
2267  buf[i] = 0;
2268  if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2269  av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2270 
2271  if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2272  ac->avctx->internal->skip_samples = 1024;
2273  }
2274 
2275 unknown:
2276  skip_bits_long(gb, len);
2277 
2278  return 0;
2279 }
2280 
2281 /**
2282  * Decode extension data (incomplete); reference: table 4.51.
2283  *
2284  * @param cnt length of TYPE_FIL syntactic element in bytes
2285  *
2286  * @return Returns number of bytes consumed
2287  */
2289  ChannelElement *che, enum RawDataBlockType elem_type)
2290 {
2291  int crc_flag = 0;
2292  int res = cnt;
2293  switch (get_bits(gb, 4)) { // extension type
2294  case EXT_SBR_DATA_CRC:
2295  crc_flag++;
2296  case EXT_SBR_DATA:
2297  if (!che) {
2298  av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2299  return res;
2300  } else if (!ac->oc[1].m4ac.sbr) {
2301  av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2302  skip_bits_long(gb, 8 * cnt - 4);
2303  return res;
2304  } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2305  av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2306  skip_bits_long(gb, 8 * cnt - 4);
2307  return res;
2308  } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2309  ac->oc[1].m4ac.sbr = 1;
2310  ac->oc[1].m4ac.ps = 1;
2312  output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2313  ac->oc[1].status, 1);
2314  } else {
2315  ac->oc[1].m4ac.sbr = 1;
2317  }
2318  res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2319  break;
2320  case EXT_DYNAMIC_RANGE:
2321  res = decode_dynamic_range(&ac->che_drc, gb);
2322  break;
2323  case EXT_FILL:
2324  decode_fill(ac, gb, 8 * cnt - 4);
2325  break;
2326  case EXT_FILL_DATA:
2327  case EXT_DATA_ELEMENT:
2328  default:
2329  skip_bits_long(gb, 8 * cnt - 4);
2330  break;
2331  };
2332  return res;
2333 }
2334 
2335 /**
2336  * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2337  *
2338  * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2339  * @param coef spectral coefficients
2340  */
2341 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2342  IndividualChannelStream *ics, int decode)
2343 {
2344  const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2345  int w, filt, m, i;
2346  int bottom, top, order, start, end, size, inc;
2347  float lpc[TNS_MAX_ORDER];
2348  float tmp[TNS_MAX_ORDER+1];
2349 
2350  for (w = 0; w < ics->num_windows; w++) {
2351  bottom = ics->num_swb;
2352  for (filt = 0; filt < tns->n_filt[w]; filt++) {
2353  top = bottom;
2354  bottom = FFMAX(0, top - tns->length[w][filt]);
2355  order = tns->order[w][filt];
2356  if (order == 0)
2357  continue;
2358 
2359  // tns_decode_coef
2360  compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2361 
2362  start = ics->swb_offset[FFMIN(bottom, mmm)];
2363  end = ics->swb_offset[FFMIN( top, mmm)];
2364  if ((size = end - start) <= 0)
2365  continue;
2366  if (tns->direction[w][filt]) {
2367  inc = -1;
2368  start = end - 1;
2369  } else {
2370  inc = 1;
2371  }
2372  start += w * 128;
2373 
2374  if (decode) {
2375  // ar filter
2376  for (m = 0; m < size; m++, start += inc)
2377  for (i = 1; i <= FFMIN(m, order); i++)
2378  coef[start] -= coef[start - i * inc] * lpc[i - 1];
2379  } else {
2380  // ma filter
2381  for (m = 0; m < size; m++, start += inc) {
2382  tmp[0] = coef[start];
2383  for (i = 1; i <= FFMIN(m, order); i++)
2384  coef[start] += tmp[i] * lpc[i - 1];
2385  for (i = order; i > 0; i--)
2386  tmp[i] = tmp[i - 1];
2387  }
2388  }
2389  }
2390  }
2391 }
2392 
2393 /**
2394  * Apply windowing and MDCT to obtain the spectral
2395  * coefficient from the predicted sample by LTP.
2396  */
2397 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2398  float *in, IndividualChannelStream *ics)
2399 {
2400  const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2401  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2402  const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2403  const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2404 
2405  if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2406  ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2407  } else {
2408  memset(in, 0, 448 * sizeof(float));
2409  ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2410  }
2411  if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2412  ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2413  } else {
2414  ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2415  memset(in + 1024 + 576, 0, 448 * sizeof(float));
2416  }
2417  ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2418 }
2419 
2420 /**
2421  * Apply the long term prediction
2422  */
2424 {
2425  const LongTermPrediction *ltp = &sce->ics.ltp;
2426  const uint16_t *offsets = sce->ics.swb_offset;
2427  int i, sfb;
2428 
2429  if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2430  float *predTime = sce->ret;
2431  float *predFreq = ac->buf_mdct;
2432  int16_t num_samples = 2048;
2433 
2434  if (ltp->lag < 1024)
2435  num_samples = ltp->lag + 1024;
2436  for (i = 0; i < num_samples; i++)
2437  predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2438  memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2439 
2440  ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2441 
2442  if (sce->tns.present)
2443  ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2444 
2445  for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2446  if (ltp->used[sfb])
2447  for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2448  sce->coeffs[i] += predFreq[i];
2449  }
2450 }
2451 
2452 /**
2453  * Update the LTP buffer for next frame
2454  */
2456 {
2457  IndividualChannelStream *ics = &sce->ics;
2458  float *saved = sce->saved;
2459  float *saved_ltp = sce->coeffs;
2460  const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2461  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2462  int i;
2463 
2464  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2465  memcpy(saved_ltp, saved, 512 * sizeof(float));
2466  memset(saved_ltp + 576, 0, 448 * sizeof(float));
2467  ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2468  for (i = 0; i < 64; i++)
2469  saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2470  } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2471  memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2472  memset(saved_ltp + 576, 0, 448 * sizeof(float));
2473  ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2474  for (i = 0; i < 64; i++)
2475  saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2476  } else { // LONG_STOP or ONLY_LONG
2477  ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2478  for (i = 0; i < 512; i++)
2479  saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2480  }
2481 
2482  memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2483  memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2484  memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2485 }
2486 
2487 /**
2488  * Conduct IMDCT and windowing.
2489  */
2491 {
2492  IndividualChannelStream *ics = &sce->ics;
2493  float *in = sce->coeffs;
2494  float *out = sce->ret;
2495  float *saved = sce->saved;
2496  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2497  const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2498  const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2499  float *buf = ac->buf_mdct;
2500  float *temp = ac->temp;
2501  int i;
2502 
2503  // imdct
2504  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2505  for (i = 0; i < 1024; i += 128)
2506  ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2507  } else
2508  ac->mdct.imdct_half(&ac->mdct, buf, in);
2509 
2510  /* window overlapping
2511  * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2512  * and long to short transitions are considered to be short to short
2513  * transitions. This leaves just two cases (long to long and short to short)
2514  * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2515  */
2516  if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2518  ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2519  } else {
2520  memcpy( out, saved, 448 * sizeof(float));
2521 
2522  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2523  ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2524  ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2525  ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2526  ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2527  ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2528  memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2529  } else {
2530  ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2531  memcpy( out + 576, buf + 64, 448 * sizeof(float));
2532  }
2533  }
2534 
2535  // buffer update
2536  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2537  memcpy( saved, temp + 64, 64 * sizeof(float));
2538  ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2539  ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2540  ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2541  memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2542  } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2543  memcpy( saved, buf + 512, 448 * sizeof(float));
2544  memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2545  } else { // LONG_STOP or ONLY_LONG
2546  memcpy( saved, buf + 512, 512 * sizeof(float));
2547  }
2548 }
2549 
2551 {
2552  IndividualChannelStream *ics = &sce->ics;
2553  float *in = sce->coeffs;
2554  float *out = sce->ret;
2555  float *saved = sce->saved;
2556  float *buf = ac->buf_mdct;
2557 
2558  // imdct
2559  ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2560 
2561  // window overlapping
2562  if (ics->use_kb_window[1]) {
2563  // AAC LD uses a low overlap sine window instead of a KBD window
2564  memcpy(out, saved, 192 * sizeof(float));
2565  ac->fdsp.vector_fmul_window(out + 192, saved + 192, buf, ff_sine_128, 64);
2566  memcpy( out + 320, buf + 64, 192 * sizeof(float));
2567  } else {
2568  ac->fdsp.vector_fmul_window(out, saved, buf, ff_sine_512, 256);
2569  }
2570 
2571  // buffer update
2572  memcpy(saved, buf + 256, 256 * sizeof(float));
2573 }
2574 
2576 {
2577  float *in = sce->coeffs;
2578  float *out = sce->ret;
2579  float *saved = sce->saved;
2580  const float *const window = ff_aac_eld_window;
2581  float *buf = ac->buf_mdct;
2582  int i;
2583  const int n = 512;
2584  const int n2 = n >> 1;
2585  const int n4 = n >> 2;
2586 
2587  // Inverse transform, mapped to the conventional IMDCT by
2588  // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2589  // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2590  // International Conference on Audio, Language and Image Processing, ICALIP 2008.
2591  // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2592  for (i = 0; i < n2; i+=2) {
2593  float temp;
2594  temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2595  temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2596  }
2597  ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2598  for (i = 0; i < n; i+=2) {
2599  buf[i] = -buf[i];
2600  }
2601  // Like with the regular IMDCT at this point we still have the middle half
2602  // of a transform but with even symmetry on the left and odd symmetry on
2603  // the right
2604 
2605  // window overlapping
2606  // The spec says to use samples [0..511] but the reference decoder uses
2607  // samples [128..639].
2608  for (i = n4; i < n2; i ++) {
2609  out[i - n4] = buf[n2 - 1 - i] * window[i - n4] +
2610  saved[ i + n2] * window[i + n - n4] +
2611  -saved[ n + n2 - 1 - i] * window[i + 2*n - n4] +
2612  -saved[2*n + n2 + i] * window[i + 3*n - n4];
2613  }
2614  for (i = 0; i < n2; i ++) {
2615  out[n4 + i] = buf[i] * window[i + n2 - n4] +
2616  -saved[ n - 1 - i] * window[i + n2 + n - n4] +
2617  -saved[ n + i] * window[i + n2 + 2*n - n4] +
2618  saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
2619  }
2620  for (i = 0; i < n4; i ++) {
2621  out[n2 + n4 + i] = buf[ i + n2] * window[i + n - n4] +
2622  -saved[ n2 - 1 - i] * window[i + 2*n - n4] +
2623  -saved[ n + n2 + i] * window[i + 3*n - n4];
2624  }
2625 
2626  // buffer update
2627  memmove(saved + n, saved, 2 * n * sizeof(float));
2628  memcpy( saved, buf, n * sizeof(float));
2629 }
2630 
2631 /**
2632  * Apply dependent channel coupling (applied before IMDCT).
2633  *
2634  * @param index index into coupling gain array
2635  */
2637  SingleChannelElement *target,
2638  ChannelElement *cce, int index)
2639 {
2640  IndividualChannelStream *ics = &cce->ch[0].ics;
2641  const uint16_t *offsets = ics->swb_offset;
2642  float *dest = target->coeffs;
2643  const float *src = cce->ch[0].coeffs;
2644  int g, i, group, k, idx = 0;
2645  if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2646  av_log(ac->avctx, AV_LOG_ERROR,
2647  "Dependent coupling is not supported together with LTP\n");
2648  return;
2649  }
2650  for (g = 0; g < ics->num_window_groups; g++) {
2651  for (i = 0; i < ics->max_sfb; i++, idx++) {
2652  if (cce->ch[0].band_type[idx] != ZERO_BT) {
2653  const float gain = cce->coup.gain[index][idx];
2654  for (group = 0; group < ics->group_len[g]; group++) {
2655  for (k = offsets[i]; k < offsets[i + 1]; k++) {
2656  // FIXME: SIMDify
2657  dest[group * 128 + k] += gain * src[group * 128 + k];
2658  }
2659  }
2660  }
2661  }
2662  dest += ics->group_len[g] * 128;
2663  src += ics->group_len[g] * 128;
2664  }
2665 }
2666 
2667 /**
2668  * Apply independent channel coupling (applied after IMDCT).
2669  *
2670  * @param index index into coupling gain array
2671  */
2673  SingleChannelElement *target,
2674  ChannelElement *cce, int index)
2675 {
2676  int i;
2677  const float gain = cce->coup.gain[index][0];
2678  const float *src = cce->ch[0].ret;
2679  float *dest = target->ret;
2680  const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2681 
2682  for (i = 0; i < len; i++)
2683  dest[i] += gain * src[i];
2684 }
2685 
2686 /**
2687  * channel coupling transformation interface
2688  *
2689  * @param apply_coupling_method pointer to (in)dependent coupling function
2690  */
2692  enum RawDataBlockType type, int elem_id,
2693  enum CouplingPoint coupling_point,
2694  void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2695 {
2696  int i, c;
2697 
2698  for (i = 0; i < MAX_ELEM_ID; i++) {
2699  ChannelElement *cce = ac->che[TYPE_CCE][i];
2700  int index = 0;
2701 
2702  if (cce && cce->coup.coupling_point == coupling_point) {
2703  ChannelCoupling *coup = &cce->coup;
2704 
2705  for (c = 0; c <= coup->num_coupled; c++) {
2706  if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2707  if (coup->ch_select[c] != 1) {
2708  apply_coupling_method(ac, &cc->ch[0], cce, index);
2709  if (coup->ch_select[c] != 0)
2710  index++;
2711  }
2712  if (coup->ch_select[c] != 2)
2713  apply_coupling_method(ac, &cc->ch[1], cce, index++);
2714  } else
2715  index += 1 + (coup->ch_select[c] == 3);
2716  }
2717  }
2718  }
2719 }
2720 
2721 /**
2722  * Convert spectral data to float samples, applying all supported tools as appropriate.
2723  */
2725 {
2726  int i, type;
2728  switch (ac->oc[1].m4ac.object_type) {
2729  case AOT_ER_AAC_LD:
2731  break;
2732  case AOT_ER_AAC_ELD:
2734  break;
2735  default:
2737  }
2738  for (type = 3; type >= 0; type--) {
2739  for (i = 0; i < MAX_ELEM_ID; i++) {
2740  ChannelElement *che = ac->che[type][i];
2741  if (che) {
2742  if (type <= TYPE_CPE)
2744  if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2745  if (che->ch[0].ics.predictor_present) {
2746  if (che->ch[0].ics.ltp.present)
2747  ac->apply_ltp(ac, &che->ch[0]);
2748  if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2749  ac->apply_ltp(ac, &che->ch[1]);
2750  }
2751  }
2752  if (che->ch[0].tns.present)
2753  ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2754  if (che->ch[1].tns.present)
2755  ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2756  if (type <= TYPE_CPE)
2758  if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2759  imdct_and_window(ac, &che->ch[0]);
2760  if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2761  ac->update_ltp(ac, &che->ch[0]);
2762  if (type == TYPE_CPE) {
2763  imdct_and_window(ac, &che->ch[1]);
2764  if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2765  ac->update_ltp(ac, &che->ch[1]);
2766  }
2767  if (ac->oc[1].m4ac.sbr > 0) {
2768  ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2769  }
2770  }
2771  if (type <= TYPE_CCE)
2773  }
2774  }
2775  }
2776 }
2777 
2779 {
2780  int size;
2781  AACADTSHeaderInfo hdr_info;
2782  uint8_t layout_map[MAX_ELEM_ID*4][3];
2783  int layout_map_tags, ret;
2784 
2785  size = avpriv_aac_parse_header(gb, &hdr_info);
2786  if (size > 0) {
2787  if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2788  // This is 2 for "VLB " audio in NSV files.
2789  // See samples/nsv/vlb_audio.
2791  "More than one AAC RDB per ADTS frame");
2792  ac->warned_num_aac_frames = 1;
2793  }
2795  if (hdr_info.chan_config) {
2796  ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2797  if ((ret = set_default_channel_config(ac->avctx,
2798  layout_map,
2799  &layout_map_tags,
2800  hdr_info.chan_config)) < 0)
2801  return ret;
2802  if ((ret = output_configure(ac, layout_map, layout_map_tags,
2803  FFMAX(ac->oc[1].status,
2804  OC_TRIAL_FRAME), 0)) < 0)
2805  return ret;
2806  } else {
2807  ac->oc[1].m4ac.chan_config = 0;
2808  /**
2809  * dual mono frames in Japanese DTV can have chan_config 0
2810  * WITHOUT specifying PCE.
2811  * thus, set dual mono as default.
2812  */
2813  if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
2814  layout_map_tags = 2;
2815  layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
2816  layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
2817  layout_map[0][1] = 0;
2818  layout_map[1][1] = 1;
2819  if (output_configure(ac, layout_map, layout_map_tags,
2820  OC_TRIAL_FRAME, 0))
2821  return -7;
2822  }
2823  }
2824  ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2825  ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2826  ac->oc[1].m4ac.object_type = hdr_info.object_type;
2827  if (ac->oc[0].status != OC_LOCKED ||
2828  ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2829  ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2830  ac->oc[1].m4ac.sbr = -1;
2831  ac->oc[1].m4ac.ps = -1;
2832  }
2833  if (!hdr_info.crc_absent)
2834  skip_bits(gb, 16);
2835  }
2836  return size;
2837 }
2838 
2839 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2840  int *got_frame_ptr, GetBitContext *gb)
2841 {
2842  AACContext *ac = avctx->priv_data;
2843  ChannelElement *che;
2844  int err, i;
2845  int samples = 1024;
2846  int chan_config = ac->oc[1].m4ac.chan_config;
2847  int aot = ac->oc[1].m4ac.object_type;
2848 
2849  if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
2850  samples >>= 1;
2851 
2852  ac->frame = data;
2853 
2854  if ((err = frame_configure_elements(avctx)) < 0)
2855  return err;
2856 
2857  // The FF_PROFILE_AAC_* defines are all object_type - 1
2858  // This may lead to an undefined profile being signaled
2859  ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2860 
2861  ac->tags_mapped = 0;
2862 
2863  if (chan_config < 0 || chan_config >= 8) {
2864  avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2865  ac->oc[1].m4ac.chan_config);
2866  return AVERROR_INVALIDDATA;
2867  }
2868  for (i = 0; i < tags_per_config[chan_config]; i++) {
2869  const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2870  const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
2871  if (!(che=get_che(ac, elem_type, elem_id))) {
2872  av_log(ac->avctx, AV_LOG_ERROR,
2873  "channel element %d.%d is not allocated\n",
2874  elem_type, elem_id);
2875  return AVERROR_INVALIDDATA;
2876  }
2877  if (aot != AOT_ER_AAC_ELD)
2878  skip_bits(gb, 4);
2879  switch (elem_type) {
2880  case TYPE_SCE:
2881  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2882  break;
2883  case TYPE_CPE:
2884  err = decode_cpe(ac, gb, che);
2885  break;
2886  case TYPE_LFE:
2887  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2888  break;
2889  }
2890  if (err < 0)
2891  return err;
2892  }
2893 
2894  spectral_to_sample(ac);
2895 
2896  ac->frame->nb_samples = samples;
2897  ac->frame->sample_rate = avctx->sample_rate;
2898  *got_frame_ptr = 1;
2899 
2900  skip_bits_long(gb, get_bits_left(gb));
2901  return 0;
2902 }
2903 
2904 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2905  int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
2906 {
2907  AACContext *ac = avctx->priv_data;
2908  ChannelElement *che = NULL, *che_prev = NULL;
2909  enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2910  int err, elem_id;
2911  int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2912  int is_dmono, sce_count = 0;
2913 
2914  ac->frame = data;
2915 
2916  if (show_bits(gb, 12) == 0xfff) {
2917  if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2918  av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2919  goto fail;
2920  }
2921  if (ac->oc[1].m4ac.sampling_index > 12) {
2922  av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2923  err = AVERROR_INVALIDDATA;
2924  goto fail;
2925  }
2926  }
2927 
2928  if ((err = frame_configure_elements(avctx)) < 0)
2929  goto fail;
2930 
2931  // The FF_PROFILE_AAC_* defines are all object_type - 1
2932  // This may lead to an undefined profile being signaled
2933  ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2934 
2935  ac->tags_mapped = 0;
2936  // parse
2937  while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2938  elem_id = get_bits(gb, 4);
2939 
2940  if (avctx->debug & FF_DEBUG_STARTCODE)
2941  av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
2942 
2943  if (elem_type < TYPE_DSE) {
2944  if (!(che=get_che(ac, elem_type, elem_id))) {
2945  av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2946  elem_type, elem_id);
2947  err = AVERROR_INVALIDDATA;
2948  goto fail;
2949  }
2950  samples = 1024;
2951  }
2952 
2953  switch (elem_type) {
2954 
2955  case TYPE_SCE:
2956  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2957  audio_found = 1;
2958  sce_count++;
2959  break;
2960 
2961  case TYPE_CPE:
2962  err = decode_cpe(ac, gb, che);
2963  audio_found = 1;
2964  break;
2965 
2966  case TYPE_CCE:
2967  err = decode_cce(ac, gb, che);
2968  break;
2969 
2970  case TYPE_LFE:
2971  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2972  audio_found = 1;
2973  break;
2974 
2975  case TYPE_DSE:
2976  err = skip_data_stream_element(ac, gb);
2977  break;
2978 
2979  case TYPE_PCE: {
2980  uint8_t layout_map[MAX_ELEM_ID*4][3];
2981  int tags;
2983  tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2984  if (tags < 0) {
2985  err = tags;
2986  break;
2987  }
2988  if (pce_found) {
2989  av_log(avctx, AV_LOG_ERROR,
2990  "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2991  } else {
2992  err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2993  if (!err)
2994  ac->oc[1].m4ac.chan_config = 0;
2995  pce_found = 1;
2996  }
2997  break;
2998  }
2999 
3000  case TYPE_FIL:
3001  if (elem_id == 15)
3002  elem_id += get_bits(gb, 8) - 1;
3003  if (get_bits_left(gb) < 8 * elem_id) {
3004  av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
3005  err = AVERROR_INVALIDDATA;
3006  goto fail;
3007  }
3008  while (elem_id > 0)
3009  elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
3010  err = 0; /* FIXME */
3011  break;
3012 
3013  default:
3014  err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
3015  break;
3016  }
3017 
3018  che_prev = che;
3019  elem_type_prev = elem_type;
3020 
3021  if (err)
3022  goto fail;
3023 
3024  if (get_bits_left(gb) < 3) {
3025  av_log(avctx, AV_LOG_ERROR, overread_err);
3026  err = AVERROR_INVALIDDATA;
3027  goto fail;
3028  }
3029  }
3030 
3031  spectral_to_sample(ac);
3032 
3033  multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
3034  samples <<= multiplier;
3035 
3036  if (ac->oc[1].status && audio_found) {
3037  avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
3038  avctx->frame_size = samples;
3039  ac->oc[1].status = OC_LOCKED;
3040  }
3041 
3042  if (multiplier) {
3043  int side_size;
3044  const uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
3045  if (side && side_size>=4)
3046  AV_WL32(side, 2*AV_RL32(side));
3047  }
3048 
3049  *got_frame_ptr = !!samples;
3050  if (samples) {
3051  ac->frame->nb_samples = samples;
3052  ac->frame->sample_rate = avctx->sample_rate;
3053  } else
3054  av_frame_unref(ac->frame);
3055  *got_frame_ptr = !!samples;
3056 
3057  /* for dual-mono audio (SCE + SCE) */
3058  is_dmono = ac->dmono_mode && sce_count == 2 &&
3060  if (is_dmono) {
3061  if (ac->dmono_mode == 1)
3062  ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
3063  else if (ac->dmono_mode == 2)
3064  ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
3065  }
3066 
3067  return 0;
3068 fail:
3070  return err;
3071 }
3072 
3073 static int aac_decode_frame(AVCodecContext *avctx, void *data,
3074  int *got_frame_ptr, AVPacket *avpkt)
3075 {
3076  AACContext *ac = avctx->priv_data;
3077  const uint8_t *buf = avpkt->data;
3078  int buf_size = avpkt->size;
3079  GetBitContext gb;
3080  int buf_consumed;
3081  int buf_offset;
3082  int err;
3083  int new_extradata_size;
3084  const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
3086  &new_extradata_size);
3087  int jp_dualmono_size;
3088  const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
3090  &jp_dualmono_size);
3091 
3092  if (new_extradata && 0) {
3093  av_free(avctx->extradata);
3094  avctx->extradata = av_mallocz(new_extradata_size +
3096  if (!avctx->extradata)
3097  return AVERROR(ENOMEM);
3098  avctx->extradata_size = new_extradata_size;
3099  memcpy(avctx->extradata, new_extradata, new_extradata_size);
3101  if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
3102  avctx->extradata,
3103  avctx->extradata_size*8, 1) < 0) {
3105  return AVERROR_INVALIDDATA;
3106  }
3107  }
3108 
3109  ac->dmono_mode = 0;
3110  if (jp_dualmono && jp_dualmono_size > 0)
3111  ac->dmono_mode = 1 + *jp_dualmono;
3112  if (ac->force_dmono_mode >= 0)
3113  ac->dmono_mode = ac->force_dmono_mode;
3114 
3115  if (INT_MAX / 8 <= buf_size)
3116  return AVERROR_INVALIDDATA;
3117 
3118  if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
3119  return err;
3120 
3121  switch (ac->oc[1].m4ac.object_type) {
3122  case AOT_ER_AAC_LC:
3123  case AOT_ER_AAC_LTP:
3124  case AOT_ER_AAC_LD:
3125  case AOT_ER_AAC_ELD:
3126  err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3127  break;
3128  default:
3129  err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
3130  }
3131  if (err < 0)
3132  return err;
3133 
3134  buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3135  for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3136  if (buf[buf_offset])
3137  break;
3138 
3139  return buf_size > buf_offset ? buf_consumed : buf_size;
3140 }
3141 
3143 {
3144  AACContext *ac = avctx->priv_data;
3145  int i, type;
3146 
3147  for (i = 0; i < MAX_ELEM_ID; i++) {
3148  for (type = 0; type < 4; type++) {
3149  if (ac->che[type][i])
3150  ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
3151  av_freep(&ac->che[type][i]);
3152  }
3153  }
3154 
3155  ff_mdct_end(&ac->mdct);
3156  ff_mdct_end(&ac->mdct_small);
3157  ff_mdct_end(&ac->mdct_ld);
3158  ff_mdct_end(&ac->mdct_ltp);
3159  return 0;
3160 }
3161 
3162 
3163 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
3164 
3165 struct LATMContext {
3166  AACContext aac_ctx; ///< containing AACContext
3167  int initialized; ///< initialized after a valid extradata was seen
3168 
3169  // parser data
3170  int audio_mux_version_A; ///< LATM syntax version
3171  int frame_length_type; ///< 0/1 variable/fixed frame length
3172  int frame_length; ///< frame length for fixed frame length
3173 };
3174 
3175 static inline uint32_t latm_get_value(GetBitContext *b)
3176 {
3177  int length = get_bits(b, 2);
3178 
3179  return get_bits_long(b, (length+1)*8);
3180 }
3181 
3183  GetBitContext *gb, int asclen)
3184 {
3185  AACContext *ac = &latmctx->aac_ctx;
3186  AVCodecContext *avctx = ac->avctx;
3187  MPEG4AudioConfig m4ac = { 0 };
3188  int config_start_bit = get_bits_count(gb);
3189  int sync_extension = 0;
3190  int bits_consumed, esize;
3191 
3192  if (asclen) {
3193  sync_extension = 1;
3194  asclen = FFMIN(asclen, get_bits_left(gb));
3195  } else
3196  asclen = get_bits_left(gb);
3197 
3198  if (config_start_bit % 8) {
3200  "Non-byte-aligned audio-specific config");
3201  return AVERROR_PATCHWELCOME;
3202  }
3203  if (asclen <= 0)
3204  return AVERROR_INVALIDDATA;
3205  bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
3206  gb->buffer + (config_start_bit / 8),
3207  asclen, sync_extension);
3208 
3209  if (bits_consumed < 0)
3210  return AVERROR_INVALIDDATA;
3211 
3212  if (!latmctx->initialized ||
3213  ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
3214  ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
3215 
3216  if(latmctx->initialized) {
3217  av_log(avctx, AV_LOG_INFO, "audio config changed\n");
3218  } else {
3219  av_log(avctx, AV_LOG_DEBUG, "initializing latmctx\n");
3220  }
3221  latmctx->initialized = 0;
3222 
3223  esize = (bits_consumed+7) / 8;
3224 
3225  if (avctx->extradata_size < esize) {
3226  av_free(avctx->extradata);
3228  if (!avctx->extradata)
3229  return AVERROR(ENOMEM);
3230  }
3231 
3232  avctx->extradata_size = esize;
3233  memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
3234  memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
3235  }
3236  skip_bits_long(gb, bits_consumed);
3237 
3238  return bits_consumed;
3239 }
3240 
3241 static int read_stream_mux_config(struct LATMContext *latmctx,
3242  GetBitContext *gb)
3243 {
3244  int ret, audio_mux_version = get_bits(gb, 1);
3245 
3246  latmctx->audio_mux_version_A = 0;
3247  if (audio_mux_version)
3248  latmctx->audio_mux_version_A = get_bits(gb, 1);
3249 
3250  if (!latmctx->audio_mux_version_A) {
3251 
3252  if (audio_mux_version)
3253  latm_get_value(gb); // taraFullness
3254 
3255  skip_bits(gb, 1); // allStreamSameTimeFraming
3256  skip_bits(gb, 6); // numSubFrames
3257  // numPrograms
3258  if (get_bits(gb, 4)) { // numPrograms
3259  avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
3260  return AVERROR_PATCHWELCOME;
3261  }
3262 
3263  // for each program (which there is only one in DVB)
3264 
3265  // for each layer (which there is only one in DVB)
3266  if (get_bits(gb, 3)) { // numLayer
3267  avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
3268  return AVERROR_PATCHWELCOME;
3269  }
3270 
3271  // for all but first stream: use_same_config = get_bits(gb, 1);
3272  if (!audio_mux_version) {
3273  if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
3274  return ret;
3275  } else {
3276  int ascLen = latm_get_value(gb);
3277  if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
3278  return ret;
3279  ascLen -= ret;
3280  skip_bits_long(gb, ascLen);
3281  }
3282 
3283  latmctx->frame_length_type = get_bits(gb, 3);
3284  switch (latmctx->frame_length_type) {
3285  case 0:
3286  skip_bits(gb, 8); // latmBufferFullness
3287  break;
3288  case 1:
3289  latmctx->frame_length = get_bits(gb, 9);
3290  break;
3291  case 3:
3292  case 4:
3293  case 5:
3294  skip_bits(gb, 6); // CELP frame length table index
3295  break;
3296  case 6:
3297  case 7:
3298  skip_bits(gb, 1); // HVXC frame length table index
3299  break;
3300  }
3301 
3302  if (get_bits(gb, 1)) { // other data
3303  if (audio_mux_version) {
3304  latm_get_value(gb); // other_data_bits
3305  } else {
3306  int esc;
3307  do {
3308  esc = get_bits(gb, 1);
3309  skip_bits(gb, 8);
3310  } while (esc);
3311  }
3312  }
3313 
3314  if (get_bits(gb, 1)) // crc present
3315  skip_bits(gb, 8); // config_crc
3316  }
3317 
3318  return 0;
3319 }
3320 
3322 {
3323  uint8_t tmp;
3324 
3325  if (ctx->frame_length_type == 0) {
3326  int mux_slot_length = 0;
3327  do {
3328  tmp = get_bits(gb, 8);
3329  mux_slot_length += tmp;
3330  } while (tmp == 255);
3331  return mux_slot_length;
3332  } else if (ctx->frame_length_type == 1) {
3333  return ctx->frame_length;
3334  } else if (ctx->frame_length_type == 3 ||
3335  ctx->frame_length_type == 5 ||
3336  ctx->frame_length_type == 7) {
3337  skip_bits(gb, 2); // mux_slot_length_coded
3338  }
3339  return 0;
3340 }
3341 
3342 static int read_audio_mux_element(struct LATMContext *latmctx,
3343  GetBitContext *gb)
3344 {
3345  int err;
3346  uint8_t use_same_mux = get_bits(gb, 1);
3347  if (!use_same_mux) {
3348  if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3349  return err;
3350  } else if (!latmctx->aac_ctx.avctx->extradata) {
3351  av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3352  "no decoder config found\n");
3353  return AVERROR(EAGAIN);
3354  }
3355  if (latmctx->audio_mux_version_A == 0) {
3356  int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3357  if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3358  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3359  return AVERROR_INVALIDDATA;
3360  } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3361  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3362  "frame length mismatch %d << %d\n",
3363  mux_slot_length_bytes * 8, get_bits_left(gb));
3364  return AVERROR_INVALIDDATA;
3365  }
3366  }
3367  return 0;
3368 }
3369 
3370 
3371 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3372  int *got_frame_ptr, AVPacket *avpkt)
3373 {
3374  struct LATMContext *latmctx = avctx->priv_data;
3375  int muxlength, err;
3376  GetBitContext gb;
3377 
3378  if ((err = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
3379  return err;
3380 
3381  // check for LOAS sync word
3382  if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3383  return AVERROR_INVALIDDATA;
3384 
3385  muxlength = get_bits(&gb, 13) + 3;
3386  // not enough data, the parser should have sorted this out
3387  if (muxlength > avpkt->size)
3388  return AVERROR_INVALIDDATA;
3389 
3390  if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3391  return err;
3392 
3393  if (!latmctx->initialized) {
3394  if (!avctx->extradata) {
3395  *got_frame_ptr = 0;
3396  return avpkt->size;
3397  } else {
3399  if ((err = decode_audio_specific_config(
3400  &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3401  avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3402  pop_output_configuration(&latmctx->aac_ctx);
3403  return err;
3404  }
3405  latmctx->initialized = 1;
3406  }
3407  }
3408 
3409  if (show_bits(&gb, 12) == 0xfff) {
3410  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3411  "ADTS header detected, probably as result of configuration "
3412  "misparsing\n");
3413  return AVERROR_INVALIDDATA;
3414  }
3415 
3416  if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb, avpkt)) < 0)
3417  return err;
3418 
3419  return muxlength;
3420 }
3421 
3423 {
3424  struct LATMContext *latmctx = avctx->priv_data;
3425  int ret = aac_decode_init(avctx);
3426 
3427  if (avctx->extradata_size > 0)
3428  latmctx->initialized = !ret;
3429 
3430  return ret;
3431 }
3432 
3433 static void aacdec_init(AACContext *c)
3434 {
3436  c->apply_ltp = apply_ltp;
3437  c->apply_tns = apply_tns;
3439  c->update_ltp = update_ltp;
3440 
3441  if(ARCH_MIPS)
3443 }
3444 /**
3445  * AVOptions for Japanese DTV specific extensions (ADTS only)
3446  */
3447 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3448 static const AVOption options[] = {
3449  {"dual_mono_mode", "Select the channel to decode for dual mono",
3450  offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3451  AACDEC_FLAGS, "dual_mono_mode"},
3452 
3453  {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3454  {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3455  {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3456  {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3457 
3458  {NULL},
3459 };
3460 
3461 static const AVClass aac_decoder_class = {
3462  .class_name = "AAC decoder",
3463  .item_name = av_default_item_name,
3464  .option = options,
3465  .version = LIBAVUTIL_VERSION_INT,
3466 };
3467 
3469  .name = "aac",
3470  .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3471  .type = AVMEDIA_TYPE_AUDIO,
3472  .id = AV_CODEC_ID_AAC,
3473  .priv_data_size = sizeof(AACContext),
3474  .init = aac_decode_init,
3477  .sample_fmts = (const enum AVSampleFormat[]) {
3479  },
3480  .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3481  .channel_layouts = aac_channel_layout,
3482  .flush = flush,
3483  .priv_class = &aac_decoder_class,
3484 };
3485 
3486 /*
3487  Note: This decoder filter is intended to decode LATM streams transferred
3488  in MPEG transport streams which only contain one program.
3489  To do a more complex LATM demuxing a separate LATM demuxer should be used.
3490 */
3492  .name = "aac_latm",
3493  .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3494  .type = AVMEDIA_TYPE_AUDIO,
3495  .id = AV_CODEC_ID_AAC_LATM,
3496  .priv_data_size = sizeof(struct LATMContext),
3497  .init = latm_decode_init,
3498  .close = aac_decode_close,
3499  .decode = latm_decode_frame,
3500  .sample_fmts = (const enum AVSampleFormat[]) {
3502  },
3503  .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3504  .channel_layouts = aac_channel_layout,
3505  .flush = flush,
3506 };