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  ac->tags_mapped++;
625  return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
626  }
627  case 5:
628  if (ac->tags_mapped == 2 && type == TYPE_CPE) {
629  ac->tags_mapped++;
630  return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
631  }
632  case 4:
633  /* Some streams incorrectly code 4.0 audio as
634  * SCE[0] CPE[0] LFE[0]
635  * instead of
636  * SCE[0] CPE[0] SCE[1].
637  * If we seem to have encountered such a stream, transfer
638  * the SCE[1] element to the LFE[0]'s mapping */
639  if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
640  ac->tags_mapped++;
641  return ac->tag_che_map[type][elem_id] = ac->che[TYPE_SCE][1];
642  }
643  if (ac->tags_mapped == 2 &&
644  ac->oc[1].m4ac.chan_config == 4 &&
645  type == TYPE_SCE) {
646  ac->tags_mapped++;
647  return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
648  }
649  case 3:
650  case 2:
651  if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
652  type == TYPE_CPE) {
653  ac->tags_mapped++;
654  return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
655  } else if (ac->oc[1].m4ac.chan_config == 2) {
656  return NULL;
657  }
658  case 1:
659  if (!ac->tags_mapped && type == TYPE_SCE) {
660  ac->tags_mapped++;
661  return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
662  }
663  default:
664  return NULL;
665  }
666 }
667 
668 /**
669  * Decode an array of 4 bit element IDs, optionally interleaved with a
670  * stereo/mono switching bit.
671  *
672  * @param type speaker type/position for these channels
673  */
674 static void decode_channel_map(uint8_t layout_map[][3],
675  enum ChannelPosition type,
676  GetBitContext *gb, int n)
677 {
678  while (n--) {
679  enum RawDataBlockType syn_ele;
680  switch (type) {
681  case AAC_CHANNEL_FRONT:
682  case AAC_CHANNEL_BACK:
683  case AAC_CHANNEL_SIDE:
684  syn_ele = get_bits1(gb);
685  break;
686  case AAC_CHANNEL_CC:
687  skip_bits1(gb);
688  syn_ele = TYPE_CCE;
689  break;
690  case AAC_CHANNEL_LFE:
691  syn_ele = TYPE_LFE;
692  break;
693  default:
694  av_assert0(0);
695  }
696  layout_map[0][0] = syn_ele;
697  layout_map[0][1] = get_bits(gb, 4);
698  layout_map[0][2] = type;
699  layout_map++;
700  }
701 }
702 
703 /**
704  * Decode program configuration element; reference: table 4.2.
705  *
706  * @return Returns error status. 0 - OK, !0 - error
707  */
708 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
709  uint8_t (*layout_map)[3],
710  GetBitContext *gb)
711 {
712  int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
713  int sampling_index;
714  int comment_len;
715  int tags;
716 
717  skip_bits(gb, 2); // object_type
718 
719  sampling_index = get_bits(gb, 4);
720  if (m4ac->sampling_index != sampling_index)
721  av_log(avctx, AV_LOG_WARNING,
722  "Sample rate index in program config element does not "
723  "match the sample rate index configured by the container.\n");
724 
725  num_front = get_bits(gb, 4);
726  num_side = get_bits(gb, 4);
727  num_back = get_bits(gb, 4);
728  num_lfe = get_bits(gb, 2);
729  num_assoc_data = get_bits(gb, 3);
730  num_cc = get_bits(gb, 4);
731 
732  if (get_bits1(gb))
733  skip_bits(gb, 4); // mono_mixdown_tag
734  if (get_bits1(gb))
735  skip_bits(gb, 4); // stereo_mixdown_tag
736 
737  if (get_bits1(gb))
738  skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
739 
740  if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
741  av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
742  return -1;
743  }
744  decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
745  tags = num_front;
746  decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
747  tags += num_side;
748  decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
749  tags += num_back;
750  decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
751  tags += num_lfe;
752 
753  skip_bits_long(gb, 4 * num_assoc_data);
754 
755  decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
756  tags += num_cc;
757 
758  align_get_bits(gb);
759 
760  /* comment field, first byte is length */
761  comment_len = get_bits(gb, 8) * 8;
762  if (get_bits_left(gb) < comment_len) {
763  av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
764  return AVERROR_INVALIDDATA;
765  }
766  skip_bits_long(gb, comment_len);
767  return tags;
768 }
769 
770 /**
771  * Decode GA "General Audio" specific configuration; reference: table 4.1.
772  *
773  * @param ac pointer to AACContext, may be null
774  * @param avctx pointer to AVCCodecContext, used for logging
775  *
776  * @return Returns error status. 0 - OK, !0 - error
777  */
779  GetBitContext *gb,
780  MPEG4AudioConfig *m4ac,
781  int channel_config)
782 {
783  int extension_flag, ret, ep_config, res_flags;
784  uint8_t layout_map[MAX_ELEM_ID*4][3];
785  int tags = 0;
786 
787  if (get_bits1(gb)) { // frameLengthFlag
788  avpriv_request_sample(avctx, "960/120 MDCT window");
789  return AVERROR_PATCHWELCOME;
790  }
791 
792  if (get_bits1(gb)) // dependsOnCoreCoder
793  skip_bits(gb, 14); // coreCoderDelay
794  extension_flag = get_bits1(gb);
795 
796  if (m4ac->object_type == AOT_AAC_SCALABLE ||
798  skip_bits(gb, 3); // layerNr
799 
800  if (channel_config == 0) {
801  skip_bits(gb, 4); // element_instance_tag
802  tags = decode_pce(avctx, m4ac, layout_map, gb);
803  if (tags < 0)
804  return tags;
805  } else {
806  if ((ret = set_default_channel_config(avctx, layout_map,
807  &tags, channel_config)))
808  return ret;
809  }
810 
811  if (count_channels(layout_map, tags) > 1) {
812  m4ac->ps = 0;
813  } else if (m4ac->sbr == 1 && m4ac->ps == -1)
814  m4ac->ps = 1;
815 
816  if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
817  return ret;
818 
819  if (extension_flag) {
820  switch (m4ac->object_type) {
821  case AOT_ER_BSAC:
822  skip_bits(gb, 5); // numOfSubFrame
823  skip_bits(gb, 11); // layer_length
824  break;
825  case AOT_ER_AAC_LC:
826  case AOT_ER_AAC_LTP:
827  case AOT_ER_AAC_SCALABLE:
828  case AOT_ER_AAC_LD:
829  res_flags = get_bits(gb, 3);
830  if (res_flags) {
832  "AAC data resilience (flags %x)",
833  res_flags);
834  return AVERROR_PATCHWELCOME;
835  }
836  break;
837  }
838  skip_bits1(gb); // extensionFlag3 (TBD in version 3)
839  }
840  switch (m4ac->object_type) {
841  case AOT_ER_AAC_LC:
842  case AOT_ER_AAC_LTP:
843  case AOT_ER_AAC_SCALABLE:
844  case AOT_ER_AAC_LD:
845  ep_config = get_bits(gb, 2);
846  if (ep_config) {
848  "epConfig %d", ep_config);
849  return AVERROR_PATCHWELCOME;
850  }
851  }
852  return 0;
853 }
854 
856  GetBitContext *gb,
857  MPEG4AudioConfig *m4ac,
858  int channel_config)
859 {
860  int ret, ep_config, res_flags;
861  uint8_t layout_map[MAX_ELEM_ID*4][3];
862  int tags = 0;
863  const int ELDEXT_TERM = 0;
864 
865  m4ac->ps = 0;
866  m4ac->sbr = 0;
867 
868  if (get_bits1(gb)) { // frameLengthFlag
869  avpriv_request_sample(avctx, "960/120 MDCT window");
870  return AVERROR_PATCHWELCOME;
871  }
872 
873  res_flags = get_bits(gb, 3);
874  if (res_flags) {
876  "AAC data resilience (flags %x)",
877  res_flags);
878  return AVERROR_PATCHWELCOME;
879  }
880 
881  if (get_bits1(gb)) { // ldSbrPresentFlag
883  "Low Delay SBR");
884  return AVERROR_PATCHWELCOME;
885  }
886 
887  while (get_bits(gb, 4) != ELDEXT_TERM) {
888  int len = get_bits(gb, 4);
889  if (len == 15)
890  len += get_bits(gb, 8);
891  if (len == 15 + 255)
892  len += get_bits(gb, 16);
893  if (get_bits_left(gb) < len * 8 + 4) {
895  return AVERROR_INVALIDDATA;
896  }
897  skip_bits_long(gb, 8 * len);
898  }
899 
900  if ((ret = set_default_channel_config(avctx, layout_map,
901  &tags, channel_config)))
902  return ret;
903 
904  if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
905  return ret;
906 
907  ep_config = get_bits(gb, 2);
908  if (ep_config) {
910  "epConfig %d", ep_config);
911  return AVERROR_PATCHWELCOME;
912  }
913  return 0;
914 }
915 
916 /**
917  * Decode audio specific configuration; reference: table 1.13.
918  *
919  * @param ac pointer to AACContext, may be null
920  * @param avctx pointer to AVCCodecContext, used for logging
921  * @param m4ac pointer to MPEG4AudioConfig, used for parsing
922  * @param data pointer to buffer holding an audio specific config
923  * @param bit_size size of audio specific config or data in bits
924  * @param sync_extension look for an appended sync extension
925  *
926  * @return Returns error status or number of consumed bits. <0 - error
927  */
929  AVCodecContext *avctx,
930  MPEG4AudioConfig *m4ac,
931  const uint8_t *data, int bit_size,
932  int sync_extension)
933 {
934  GetBitContext gb;
935  int i, ret;
936 
937  av_dlog(avctx, "audio specific config size %d\n", bit_size >> 3);
938  for (i = 0; i < bit_size >> 3; i++)
939  av_dlog(avctx, "%02x ", data[i]);
940  av_dlog(avctx, "\n");
941 
942  if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
943  return ret;
944 
945  if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
946  sync_extension)) < 0)
947  return AVERROR_INVALIDDATA;
948  if (m4ac->sampling_index > 12) {
949  av_log(avctx, AV_LOG_ERROR,
950  "invalid sampling rate index %d\n",
951  m4ac->sampling_index);
952  return AVERROR_INVALIDDATA;
953  }
954  if (m4ac->object_type == AOT_ER_AAC_LD &&
955  (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
956  av_log(avctx, AV_LOG_ERROR,
957  "invalid low delay sampling rate index %d\n",
958  m4ac->sampling_index);
959  return AVERROR_INVALIDDATA;
960  }
961 
962  skip_bits_long(&gb, i);
963 
964  switch (m4ac->object_type) {
965  case AOT_AAC_MAIN:
966  case AOT_AAC_LC:
967  case AOT_AAC_LTP:
968  case AOT_ER_AAC_LC:
969  case AOT_ER_AAC_LD:
970  if ((ret = decode_ga_specific_config(ac, avctx, &gb,
971  m4ac, m4ac->chan_config)) < 0)
972  return ret;
973  break;
974  case AOT_ER_AAC_ELD:
975  if ((ret = decode_eld_specific_config(ac, avctx, &gb,
976  m4ac, m4ac->chan_config)) < 0)
977  return ret;
978  break;
979  default:
981  "Audio object type %s%d",
982  m4ac->sbr == 1 ? "SBR+" : "",
983  m4ac->object_type);
984  return AVERROR(ENOSYS);
985  }
986 
987  av_dlog(avctx,
988  "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
989  m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
990  m4ac->sample_rate, m4ac->sbr,
991  m4ac->ps);
992 
993  return get_bits_count(&gb);
994 }
995 
996 /**
997  * linear congruential pseudorandom number generator
998  *
999  * @param previous_val pointer to the current state of the generator
1000  *
1001  * @return Returns a 32-bit pseudorandom integer
1002  */
1003 static av_always_inline int lcg_random(unsigned previous_val)
1004 {
1005  union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
1006  return v.s;
1007 }
1008 
1010 {
1011  ps->r0 = 0.0f;
1012  ps->r1 = 0.0f;
1013  ps->cor0 = 0.0f;
1014  ps->cor1 = 0.0f;
1015  ps->var0 = 1.0f;
1016  ps->var1 = 1.0f;
1017 }
1018 
1020 {
1021  int i;
1022  for (i = 0; i < MAX_PREDICTORS; i++)
1023  reset_predict_state(&ps[i]);
1024 }
1025 
1026 static int sample_rate_idx (int rate)
1027 {
1028  if (92017 <= rate) return 0;
1029  else if (75132 <= rate) return 1;
1030  else if (55426 <= rate) return 2;
1031  else if (46009 <= rate) return 3;
1032  else if (37566 <= rate) return 4;
1033  else if (27713 <= rate) return 5;
1034  else if (23004 <= rate) return 6;
1035  else if (18783 <= rate) return 7;
1036  else if (13856 <= rate) return 8;
1037  else if (11502 <= rate) return 9;
1038  else if (9391 <= rate) return 10;
1039  else return 11;
1040 }
1041 
1042 static void reset_predictor_group(PredictorState *ps, int group_num)
1043 {
1044  int i;
1045  for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1046  reset_predict_state(&ps[i]);
1047 }
1048 
1049 #define AAC_INIT_VLC_STATIC(num, size) \
1050  INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
1051  ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
1052  sizeof(ff_aac_spectral_bits[num][0]), \
1053  ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
1054  sizeof(ff_aac_spectral_codes[num][0]), \
1055  size);
1056 
1057 static void aacdec_init(AACContext *ac);
1058 
1060 {
1061  AACContext *ac = avctx->priv_data;
1062  int ret;
1063 
1064  ac->avctx = avctx;
1065  ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1066 
1067  aacdec_init(ac);
1068 
1069  avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1070 
1071  if (avctx->extradata_size > 0) {
1072  if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1073  avctx->extradata,
1074  avctx->extradata_size * 8,
1075  1)) < 0)
1076  return ret;
1077  } else {
1078  int sr, i;
1079  uint8_t layout_map[MAX_ELEM_ID*4][3];
1080  int layout_map_tags;
1081 
1082  sr = sample_rate_idx(avctx->sample_rate);
1083  ac->oc[1].m4ac.sampling_index = sr;
1084  ac->oc[1].m4ac.channels = avctx->channels;
1085  ac->oc[1].m4ac.sbr = -1;
1086  ac->oc[1].m4ac.ps = -1;
1087 
1088  for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1089  if (ff_mpeg4audio_channels[i] == avctx->channels)
1090  break;
1092  i = 0;
1093  }
1094  ac->oc[1].m4ac.chan_config = i;
1095 
1096  if (ac->oc[1].m4ac.chan_config) {
1097  int ret = set_default_channel_config(avctx, layout_map,
1098  &layout_map_tags, ac->oc[1].m4ac.chan_config);
1099  if (!ret)
1100  output_configure(ac, layout_map, layout_map_tags,
1101  OC_GLOBAL_HDR, 0);
1102  else if (avctx->err_recognition & AV_EF_EXPLODE)
1103  return AVERROR_INVALIDDATA;
1104  }
1105  }
1106 
1107  if (avctx->channels > MAX_CHANNELS) {
1108  av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1109  return AVERROR_INVALIDDATA;
1110  }
1111 
1112  AAC_INIT_VLC_STATIC( 0, 304);
1113  AAC_INIT_VLC_STATIC( 1, 270);
1114  AAC_INIT_VLC_STATIC( 2, 550);
1115  AAC_INIT_VLC_STATIC( 3, 300);
1116  AAC_INIT_VLC_STATIC( 4, 328);
1117  AAC_INIT_VLC_STATIC( 5, 294);
1118  AAC_INIT_VLC_STATIC( 6, 306);
1119  AAC_INIT_VLC_STATIC( 7, 268);
1120  AAC_INIT_VLC_STATIC( 8, 510);
1121  AAC_INIT_VLC_STATIC( 9, 366);
1122  AAC_INIT_VLC_STATIC(10, 462);
1123 
1124  ff_aac_sbr_init();
1125 
1126  ff_fmt_convert_init(&ac->fmt_conv, avctx);
1128 
1129  ac->random_state = 0x1f2e3d4c;
1130 
1131  ff_aac_tableinit();
1132 
1133  INIT_VLC_STATIC(&vlc_scalefactors, 7,
1136  sizeof(ff_aac_scalefactor_bits[0]),
1137  sizeof(ff_aac_scalefactor_bits[0]),
1139  sizeof(ff_aac_scalefactor_code[0]),
1140  sizeof(ff_aac_scalefactor_code[0]),
1141  352);
1142 
1143  ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
1144  ff_mdct_init(&ac->mdct_ld, 10, 1, 1.0 / (32768.0 * 512.0));
1145  ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
1146  ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
1147  // window initialization
1153 
1154  cbrt_tableinit();
1155 
1156  return 0;
1157 }
1158 
1159 /**
1160  * Skip data_stream_element; reference: table 4.10.
1161  */
1163 {
1164  int byte_align = get_bits1(gb);
1165  int count = get_bits(gb, 8);
1166  if (count == 255)
1167  count += get_bits(gb, 8);
1168  if (byte_align)
1169  align_get_bits(gb);
1170 
1171  if (get_bits_left(gb) < 8 * count) {
1172  av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1173  return AVERROR_INVALIDDATA;
1174  }
1175  skip_bits_long(gb, 8 * count);
1176  return 0;
1177 }
1178 
1180  GetBitContext *gb)
1181 {
1182  int sfb;
1183  if (get_bits1(gb)) {
1184  ics->predictor_reset_group = get_bits(gb, 5);
1185  if (ics->predictor_reset_group == 0 ||
1186  ics->predictor_reset_group > 30) {
1187  av_log(ac->avctx, AV_LOG_ERROR,
1188  "Invalid Predictor Reset Group.\n");
1189  return AVERROR_INVALIDDATA;
1190  }
1191  }
1192  for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1193  ics->prediction_used[sfb] = get_bits1(gb);
1194  }
1195  return 0;
1196 }
1197 
1198 /**
1199  * Decode Long Term Prediction data; reference: table 4.xx.
1200  */
1202  GetBitContext *gb, uint8_t max_sfb)
1203 {
1204  int sfb;
1205 
1206  ltp->lag = get_bits(gb, 11);
1207  ltp->coef = ltp_coef[get_bits(gb, 3)];
1208  for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1209  ltp->used[sfb] = get_bits1(gb);
1210 }
1211 
1212 /**
1213  * Decode Individual Channel Stream info; reference: table 4.6.
1214  */
1216  GetBitContext *gb)
1217 {
1218  int aot = ac->oc[1].m4ac.object_type;
1219  if (aot != AOT_ER_AAC_ELD) {
1220  if (get_bits1(gb)) {
1221  av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1222  return AVERROR_INVALIDDATA;
1223  }
1224  ics->window_sequence[1] = ics->window_sequence[0];
1225  ics->window_sequence[0] = get_bits(gb, 2);
1226  if (aot == AOT_ER_AAC_LD &&
1227  ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1228  av_log(ac->avctx, AV_LOG_ERROR,
1229  "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1230  "window sequence %d found.\n", ics->window_sequence[0]);
1232  return AVERROR_INVALIDDATA;
1233  }
1234  ics->use_kb_window[1] = ics->use_kb_window[0];
1235  ics->use_kb_window[0] = get_bits1(gb);
1236  }
1237  ics->num_window_groups = 1;
1238  ics->group_len[0] = 1;
1239  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1240  int i;
1241  ics->max_sfb = get_bits(gb, 4);
1242  for (i = 0; i < 7; i++) {
1243  if (get_bits1(gb)) {
1244  ics->group_len[ics->num_window_groups - 1]++;
1245  } else {
1246  ics->num_window_groups++;
1247  ics->group_len[ics->num_window_groups - 1] = 1;
1248  }
1249  }
1250  ics->num_windows = 8;
1254  ics->predictor_present = 0;
1255  } else {
1256  ics->max_sfb = get_bits(gb, 6);
1257  ics->num_windows = 1;
1258  if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1262  if (!ics->num_swb || !ics->swb_offset)
1263  return AVERROR_BUG;
1264  } else {
1268  }
1269  if (aot != AOT_ER_AAC_ELD) {
1270  ics->predictor_present = get_bits1(gb);
1271  ics->predictor_reset_group = 0;
1272  }
1273  if (ics->predictor_present) {
1274  if (aot == AOT_AAC_MAIN) {
1275  if (decode_prediction(ac, ics, gb)) {
1276  goto fail;
1277  }
1278  } else if (aot == AOT_AAC_LC ||
1279  aot == AOT_ER_AAC_LC) {
1280  av_log(ac->avctx, AV_LOG_ERROR,
1281  "Prediction is not allowed in AAC-LC.\n");
1282  goto fail;
1283  } else {
1284  if (aot == AOT_ER_AAC_LD) {
1285  av_log(ac->avctx, AV_LOG_ERROR,
1286  "LTP in ER AAC LD not yet implemented.\n");
1287  return AVERROR_PATCHWELCOME;
1288  }
1289  if ((ics->ltp.present = get_bits(gb, 1)))
1290  decode_ltp(&ics->ltp, gb, ics->max_sfb);
1291  }
1292  }
1293  }
1294 
1295  if (ics->max_sfb > ics->num_swb) {
1296  av_log(ac->avctx, AV_LOG_ERROR,
1297  "Number of scalefactor bands in group (%d) "
1298  "exceeds limit (%d).\n",
1299  ics->max_sfb, ics->num_swb);
1300  goto fail;
1301  }
1302 
1303  return 0;
1304 fail:
1305  ics->max_sfb = 0;
1306  return AVERROR_INVALIDDATA;
1307 }
1308 
1309 /**
1310  * Decode band types (section_data payload); reference: table 4.46.
1311  *
1312  * @param band_type array of the used band type
1313  * @param band_type_run_end array of the last scalefactor band of a band type run
1314  *
1315  * @return Returns error status. 0 - OK, !0 - error
1316  */
1317 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1318  int band_type_run_end[120], GetBitContext *gb,
1320 {
1321  int g, idx = 0;
1322  const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1323  for (g = 0; g < ics->num_window_groups; g++) {
1324  int k = 0;
1325  while (k < ics->max_sfb) {
1326  uint8_t sect_end = k;
1327  int sect_len_incr;
1328  int sect_band_type = get_bits(gb, 4);
1329  if (sect_band_type == 12) {
1330  av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1331  return AVERROR_INVALIDDATA;
1332  }
1333  do {
1334  sect_len_incr = get_bits(gb, bits);
1335  sect_end += sect_len_incr;
1336  if (get_bits_left(gb) < 0) {
1337  av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1338  return AVERROR_INVALIDDATA;
1339  }
1340  if (sect_end > ics->max_sfb) {
1341  av_log(ac->avctx, AV_LOG_ERROR,
1342  "Number of bands (%d) exceeds limit (%d).\n",
1343  sect_end, ics->max_sfb);
1344  return AVERROR_INVALIDDATA;
1345  }
1346  } while (sect_len_incr == (1 << bits) - 1);
1347  for (; k < sect_end; k++) {
1348  band_type [idx] = sect_band_type;
1349  band_type_run_end[idx++] = sect_end;
1350  }
1351  }
1352  }
1353  return 0;
1354 }
1355 
1356 /**
1357  * Decode scalefactors; reference: table 4.47.
1358  *
1359  * @param global_gain first scalefactor value as scalefactors are differentially coded
1360  * @param band_type array of the used band type
1361  * @param band_type_run_end array of the last scalefactor band of a band type run
1362  * @param sf array of scalefactors or intensity stereo positions
1363  *
1364  * @return Returns error status. 0 - OK, !0 - error
1365  */
1366 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1367  unsigned int global_gain,
1369  enum BandType band_type[120],
1370  int band_type_run_end[120])
1371 {
1372  int g, i, idx = 0;
1373  int offset[3] = { global_gain, global_gain - 90, 0 };
1374  int clipped_offset;
1375  int noise_flag = 1;
1376  for (g = 0; g < ics->num_window_groups; g++) {
1377  for (i = 0; i < ics->max_sfb;) {
1378  int run_end = band_type_run_end[idx];
1379  if (band_type[idx] == ZERO_BT) {
1380  for (; i < run_end; i++, idx++)
1381  sf[idx] = 0.0;
1382  } else if ((band_type[idx] == INTENSITY_BT) ||
1383  (band_type[idx] == INTENSITY_BT2)) {
1384  for (; i < run_end; i++, idx++) {
1385  offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1386  clipped_offset = av_clip(offset[2], -155, 100);
1387  if (offset[2] != clipped_offset) {
1389  "If you heard an audible artifact, there may be a bug in the decoder. "
1390  "Clipped intensity stereo position (%d -> %d)",
1391  offset[2], clipped_offset);
1392  }
1393  sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1394  }
1395  } else if (band_type[idx] == NOISE_BT) {
1396  for (; i < run_end; i++, idx++) {
1397  if (noise_flag-- > 0)
1398  offset[1] += get_bits(gb, 9) - 256;
1399  else
1400  offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1401  clipped_offset = av_clip(offset[1], -100, 155);
1402  if (offset[1] != clipped_offset) {
1404  "If you heard an audible artifact, there may be a bug in the decoder. "
1405  "Clipped noise gain (%d -> %d)",
1406  offset[1], clipped_offset);
1407  }
1408  sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1409  }
1410  } else {
1411  for (; i < run_end; i++, idx++) {
1412  offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1413  if (offset[0] > 255U) {
1414  av_log(ac->avctx, AV_LOG_ERROR,
1415  "Scalefactor (%d) out of range.\n", offset[0]);
1416  return AVERROR_INVALIDDATA;
1417  }
1418  sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1419  }
1420  }
1421  }
1422  }
1423  return 0;
1424 }
1425 
1426 /**
1427  * Decode pulse data; reference: table 4.7.
1428  */
1429 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1430  const uint16_t *swb_offset, int num_swb)
1431 {
1432  int i, pulse_swb;
1433  pulse->num_pulse = get_bits(gb, 2) + 1;
1434  pulse_swb = get_bits(gb, 6);
1435  if (pulse_swb >= num_swb)
1436  return -1;
1437  pulse->pos[0] = swb_offset[pulse_swb];
1438  pulse->pos[0] += get_bits(gb, 5);
1439  if (pulse->pos[0] >= swb_offset[num_swb])
1440  return -1;
1441  pulse->amp[0] = get_bits(gb, 4);
1442  for (i = 1; i < pulse->num_pulse; i++) {
1443  pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1444  if (pulse->pos[i] >= swb_offset[num_swb])
1445  return -1;
1446  pulse->amp[i] = get_bits(gb, 4);
1447  }
1448  return 0;
1449 }
1450 
1451 /**
1452  * Decode Temporal Noise Shaping data; reference: table 4.48.
1453  *
1454  * @return Returns error status. 0 - OK, !0 - error
1455  */
1457  GetBitContext *gb, const IndividualChannelStream *ics)
1458 {
1459  int w, filt, i, coef_len, coef_res, coef_compress;
1460  const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1461  const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1462  for (w = 0; w < ics->num_windows; w++) {
1463  if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1464  coef_res = get_bits1(gb);
1465 
1466  for (filt = 0; filt < tns->n_filt[w]; filt++) {
1467  int tmp2_idx;
1468  tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1469 
1470  if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1471  av_log(ac->avctx, AV_LOG_ERROR,
1472  "TNS filter order %d is greater than maximum %d.\n",
1473  tns->order[w][filt], tns_max_order);
1474  tns->order[w][filt] = 0;
1475  return AVERROR_INVALIDDATA;
1476  }
1477  if (tns->order[w][filt]) {
1478  tns->direction[w][filt] = get_bits1(gb);
1479  coef_compress = get_bits1(gb);
1480  coef_len = coef_res + 3 - coef_compress;
1481  tmp2_idx = 2 * coef_compress + coef_res;
1482 
1483  for (i = 0; i < tns->order[w][filt]; i++)
1484  tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1485  }
1486  }
1487  }
1488  }
1489  return 0;
1490 }
1491 
1492 /**
1493  * Decode Mid/Side data; reference: table 4.54.
1494  *
1495  * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1496  * [1] mask is decoded from bitstream; [2] mask is all 1s;
1497  * [3] reserved for scalable AAC
1498  */
1500  int ms_present)
1501 {
1502  int idx;
1503  if (ms_present == 1) {
1504  for (idx = 0;
1505  idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1506  idx++)
1507  cpe->ms_mask[idx] = get_bits1(gb);
1508  } else if (ms_present == 2) {
1509  memset(cpe->ms_mask, 1, sizeof(cpe->ms_mask[0]) * cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb);
1510  }
1511 }
1512 
1513 #ifndef VMUL2
1514 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1515  const float *scale)
1516 {
1517  float s = *scale;
1518  *dst++ = v[idx & 15] * s;
1519  *dst++ = v[idx>>4 & 15] * s;
1520  return dst;
1521 }
1522 #endif
1523 
1524 #ifndef VMUL4
1525 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1526  const float *scale)
1527 {
1528  float s = *scale;
1529  *dst++ = v[idx & 3] * s;
1530  *dst++ = v[idx>>2 & 3] * s;
1531  *dst++ = v[idx>>4 & 3] * s;
1532  *dst++ = v[idx>>6 & 3] * s;
1533  return dst;
1534 }
1535 #endif
1536 
1537 #ifndef VMUL2S
1538 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1539  unsigned sign, const float *scale)
1540 {
1541  union av_intfloat32 s0, s1;
1542 
1543  s0.f = s1.f = *scale;
1544  s0.i ^= sign >> 1 << 31;
1545  s1.i ^= sign << 31;
1546 
1547  *dst++ = v[idx & 15] * s0.f;
1548  *dst++ = v[idx>>4 & 15] * s1.f;
1549 
1550  return dst;
1551 }
1552 #endif
1553 
1554 #ifndef VMUL4S
1555 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1556  unsigned sign, const float *scale)
1557 {
1558  unsigned nz = idx >> 12;
1559  union av_intfloat32 s = { .f = *scale };
1560  union av_intfloat32 t;
1561 
1562  t.i = s.i ^ (sign & 1U<<31);
1563  *dst++ = v[idx & 3] * t.f;
1564 
1565  sign <<= nz & 1; nz >>= 1;
1566  t.i = s.i ^ (sign & 1U<<31);
1567  *dst++ = v[idx>>2 & 3] * t.f;
1568 
1569  sign <<= nz & 1; nz >>= 1;
1570  t.i = s.i ^ (sign & 1U<<31);
1571  *dst++ = v[idx>>4 & 3] * t.f;
1572 
1573  sign <<= nz & 1;
1574  t.i = s.i ^ (sign & 1U<<31);
1575  *dst++ = v[idx>>6 & 3] * t.f;
1576 
1577  return dst;
1578 }
1579 #endif
1580 
1581 /**
1582  * Decode spectral data; reference: table 4.50.
1583  * Dequantize and scale spectral data; reference: 4.6.3.3.
1584  *
1585  * @param coef array of dequantized, scaled spectral data
1586  * @param sf array of scalefactors or intensity stereo positions
1587  * @param pulse_present set if pulses are present
1588  * @param pulse pointer to pulse data struct
1589  * @param band_type array of the used band type
1590  *
1591  * @return Returns error status. 0 - OK, !0 - error
1592  */
1593 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1594  GetBitContext *gb, const float sf[120],
1595  int pulse_present, const Pulse *pulse,
1596  const IndividualChannelStream *ics,
1597  enum BandType band_type[120])
1598 {
1599  int i, k, g, idx = 0;
1600  const int c = 1024 / ics->num_windows;
1601  const uint16_t *offsets = ics->swb_offset;
1602  float *coef_base = coef;
1603 
1604  for (g = 0; g < ics->num_windows; g++)
1605  memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1606  sizeof(float) * (c - offsets[ics->max_sfb]));
1607 
1608  for (g = 0; g < ics->num_window_groups; g++) {
1609  unsigned g_len = ics->group_len[g];
1610 
1611  for (i = 0; i < ics->max_sfb; i++, idx++) {
1612  const unsigned cbt_m1 = band_type[idx] - 1;
1613  float *cfo = coef + offsets[i];
1614  int off_len = offsets[i + 1] - offsets[i];
1615  int group;
1616 
1617  if (cbt_m1 >= INTENSITY_BT2 - 1) {
1618  for (group = 0; group < g_len; group++, cfo+=128) {
1619  memset(cfo, 0, off_len * sizeof(float));
1620  }
1621  } else if (cbt_m1 == NOISE_BT - 1) {
1622  for (group = 0; group < g_len; group++, cfo+=128) {
1623  float scale;
1624  float band_energy;
1625 
1626  for (k = 0; k < off_len; k++) {
1628  cfo[k] = ac->random_state;
1629  }
1630 
1631  band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1632  scale = sf[idx] / sqrtf(band_energy);
1633  ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1634  }
1635  } else {
1636  const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1637  const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1638  VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1639  OPEN_READER(re, gb);
1640 
1641  switch (cbt_m1 >> 1) {
1642  case 0:
1643  for (group = 0; group < g_len; group++, cfo+=128) {
1644  float *cf = cfo;
1645  int len = off_len;
1646 
1647  do {
1648  int code;
1649  unsigned cb_idx;
1650 
1651  UPDATE_CACHE(re, gb);
1652  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1653  cb_idx = cb_vector_idx[code];
1654  cf = VMUL4(cf, vq, cb_idx, sf + idx);
1655  } while (len -= 4);
1656  }
1657  break;
1658 
1659  case 1:
1660  for (group = 0; group < g_len; group++, cfo+=128) {
1661  float *cf = cfo;
1662  int len = off_len;
1663 
1664  do {
1665  int code;
1666  unsigned nnz;
1667  unsigned cb_idx;
1668  uint32_t bits;
1669 
1670  UPDATE_CACHE(re, gb);
1671  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1672  cb_idx = cb_vector_idx[code];
1673  nnz = cb_idx >> 8 & 15;
1674  bits = nnz ? GET_CACHE(re, gb) : 0;
1675  LAST_SKIP_BITS(re, gb, nnz);
1676  cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1677  } while (len -= 4);
1678  }
1679  break;
1680 
1681  case 2:
1682  for (group = 0; group < g_len; group++, cfo+=128) {
1683  float *cf = cfo;
1684  int len = off_len;
1685 
1686  do {
1687  int code;
1688  unsigned cb_idx;
1689 
1690  UPDATE_CACHE(re, gb);
1691  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1692  cb_idx = cb_vector_idx[code];
1693  cf = VMUL2(cf, vq, cb_idx, sf + idx);
1694  } while (len -= 2);
1695  }
1696  break;
1697 
1698  case 3:
1699  case 4:
1700  for (group = 0; group < g_len; group++, cfo+=128) {
1701  float *cf = cfo;
1702  int len = off_len;
1703 
1704  do {
1705  int code;
1706  unsigned nnz;
1707  unsigned cb_idx;
1708  unsigned sign;
1709 
1710  UPDATE_CACHE(re, gb);
1711  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1712  cb_idx = cb_vector_idx[code];
1713  nnz = cb_idx >> 8 & 15;
1714  sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1715  LAST_SKIP_BITS(re, gb, nnz);
1716  cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1717  } while (len -= 2);
1718  }
1719  break;
1720 
1721  default:
1722  for (group = 0; group < g_len; group++, cfo+=128) {
1723  float *cf = cfo;
1724  uint32_t *icf = (uint32_t *) cf;
1725  int len = off_len;
1726 
1727  do {
1728  int code;
1729  unsigned nzt, nnz;
1730  unsigned cb_idx;
1731  uint32_t bits;
1732  int j;
1733 
1734  UPDATE_CACHE(re, gb);
1735  GET_VLC(code, re, gb, vlc_tab, 8, 2);
1736 
1737  if (!code) {
1738  *icf++ = 0;
1739  *icf++ = 0;
1740  continue;
1741  }
1742 
1743  cb_idx = cb_vector_idx[code];
1744  nnz = cb_idx >> 12;
1745  nzt = cb_idx >> 8;
1746  bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1747  LAST_SKIP_BITS(re, gb, nnz);
1748 
1749  for (j = 0; j < 2; j++) {
1750  if (nzt & 1<<j) {
1751  uint32_t b;
1752  int n;
1753  /* The total length of escape_sequence must be < 22 bits according
1754  to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1755  UPDATE_CACHE(re, gb);
1756  b = GET_CACHE(re, gb);
1757  b = 31 - av_log2(~b);
1758 
1759  if (b > 8) {
1760  av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1761  return AVERROR_INVALIDDATA;
1762  }
1763 
1764  SKIP_BITS(re, gb, b + 1);
1765  b += 4;
1766  n = (1 << b) + SHOW_UBITS(re, gb, b);
1767  LAST_SKIP_BITS(re, gb, b);
1768  *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1769  bits <<= 1;
1770  } else {
1771  unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1772  *icf++ = (bits & 1U<<31) | v;
1773  bits <<= !!v;
1774  }
1775  cb_idx >>= 4;
1776  }
1777  } while (len -= 2);
1778 
1779  ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1780  }
1781  }
1782 
1783  CLOSE_READER(re, gb);
1784  }
1785  }
1786  coef += g_len << 7;
1787  }
1788 
1789  if (pulse_present) {
1790  idx = 0;
1791  for (i = 0; i < pulse->num_pulse; i++) {
1792  float co = coef_base[ pulse->pos[i] ];
1793  while (offsets[idx + 1] <= pulse->pos[i])
1794  idx++;
1795  if (band_type[idx] != NOISE_BT && sf[idx]) {
1796  float ico = -pulse->amp[i];
1797  if (co) {
1798  co /= sf[idx];
1799  ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1800  }
1801  coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1802  }
1803  }
1804  }
1805  return 0;
1806 }
1807 
1808 static av_always_inline float flt16_round(float pf)
1809 {
1810  union av_intfloat32 tmp;
1811  tmp.f = pf;
1812  tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1813  return tmp.f;
1814 }
1815 
1816 static av_always_inline float flt16_even(float pf)
1817 {
1818  union av_intfloat32 tmp;
1819  tmp.f = pf;
1820  tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1821  return tmp.f;
1822 }
1823 
1824 static av_always_inline float flt16_trunc(float pf)
1825 {
1826  union av_intfloat32 pun;
1827  pun.f = pf;
1828  pun.i &= 0xFFFF0000U;
1829  return pun.f;
1830 }
1831 
1832 static av_always_inline void predict(PredictorState *ps, float *coef,
1833  int output_enable)
1834 {
1835  const float a = 0.953125; // 61.0 / 64
1836  const float alpha = 0.90625; // 29.0 / 32
1837  float e0, e1;
1838  float pv;
1839  float k1, k2;
1840  float r0 = ps->r0, r1 = ps->r1;
1841  float cor0 = ps->cor0, cor1 = ps->cor1;
1842  float var0 = ps->var0, var1 = ps->var1;
1843 
1844  k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1845  k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1846 
1847  pv = flt16_round(k1 * r0 + k2 * r1);
1848  if (output_enable)
1849  *coef += pv;
1850 
1851  e0 = *coef;
1852  e1 = e0 - k1 * r0;
1853 
1854  ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1855  ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1856  ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1857  ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1858 
1859  ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1860  ps->r0 = flt16_trunc(a * e0);
1861 }
1862 
1863 /**
1864  * Apply AAC-Main style frequency domain prediction.
1865  */
1867 {
1868  int sfb, k;
1869 
1870  if (!sce->ics.predictor_initialized) {
1872  sce->ics.predictor_initialized = 1;
1873  }
1874 
1875  if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1876  for (sfb = 0;
1877  sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1878  sfb++) {
1879  for (k = sce->ics.swb_offset[sfb];
1880  k < sce->ics.swb_offset[sfb + 1];
1881  k++) {
1882  predict(&sce->predictor_state[k], &sce->coeffs[k],
1883  sce->ics.predictor_present &&
1884  sce->ics.prediction_used[sfb]);
1885  }
1886  }
1887  if (sce->ics.predictor_reset_group)
1889  sce->ics.predictor_reset_group);
1890  } else
1892 }
1893 
1894 /**
1895  * Decode an individual_channel_stream payload; reference: table 4.44.
1896  *
1897  * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1898  * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1899  *
1900  * @return Returns error status. 0 - OK, !0 - error
1901  */
1903  GetBitContext *gb, int common_window, int scale_flag)
1904 {
1905  Pulse pulse;
1906  TemporalNoiseShaping *tns = &sce->tns;
1907  IndividualChannelStream *ics = &sce->ics;
1908  float *out = sce->coeffs;
1909  int global_gain, eld_syntax, er_syntax, pulse_present = 0;
1910  int ret;
1911 
1912  eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1913  er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1914  ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1915  ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1916  ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1917 
1918  /* This assignment is to silence a GCC warning about the variable being used
1919  * uninitialized when in fact it always is.
1920  */
1921  pulse.num_pulse = 0;
1922 
1923  global_gain = get_bits(gb, 8);
1924 
1925  if (!common_window && !scale_flag) {
1926  if (decode_ics_info(ac, ics, gb) < 0)
1927  return AVERROR_INVALIDDATA;
1928  }
1929 
1930  if ((ret = decode_band_types(ac, sce->band_type,
1931  sce->band_type_run_end, gb, ics)) < 0)
1932  return ret;
1933  if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1934  sce->band_type, sce->band_type_run_end)) < 0)
1935  return ret;
1936 
1937  pulse_present = 0;
1938  if (!scale_flag) {
1939  if (!eld_syntax && (pulse_present = get_bits1(gb))) {
1940  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1941  av_log(ac->avctx, AV_LOG_ERROR,
1942  "Pulse tool not allowed in eight short sequence.\n");
1943  return AVERROR_INVALIDDATA;
1944  }
1945  if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1946  av_log(ac->avctx, AV_LOG_ERROR,
1947  "Pulse data corrupt or invalid.\n");
1948  return AVERROR_INVALIDDATA;
1949  }
1950  }
1951  tns->present = get_bits1(gb);
1952  if (tns->present && !er_syntax)
1953  if (decode_tns(ac, tns, gb, ics) < 0)
1954  return AVERROR_INVALIDDATA;
1955  if (!eld_syntax && get_bits1(gb)) {
1956  avpriv_request_sample(ac->avctx, "SSR");
1957  return AVERROR_PATCHWELCOME;
1958  }
1959  // I see no textual basis in the spec for this occurring after SSR gain
1960  // control, but this is what both reference and real implmentations do
1961  if (tns->present && er_syntax)
1962  if (decode_tns(ac, tns, gb, ics) < 0)
1963  return AVERROR_INVALIDDATA;
1964  }
1965 
1966  if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1967  &pulse, ics, sce->band_type) < 0)
1968  return AVERROR_INVALIDDATA;
1969 
1970  if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1971  apply_prediction(ac, sce);
1972 
1973  return 0;
1974 }
1975 
1976 /**
1977  * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1978  */
1980 {
1981  const IndividualChannelStream *ics = &cpe->ch[0].ics;
1982  float *ch0 = cpe->ch[0].coeffs;
1983  float *ch1 = cpe->ch[1].coeffs;
1984  int g, i, group, idx = 0;
1985  const uint16_t *offsets = ics->swb_offset;
1986  for (g = 0; g < ics->num_window_groups; g++) {
1987  for (i = 0; i < ics->max_sfb; i++, idx++) {
1988  if (cpe->ms_mask[idx] &&
1989  cpe->ch[0].band_type[idx] < NOISE_BT &&
1990  cpe->ch[1].band_type[idx] < NOISE_BT) {
1991  for (group = 0; group < ics->group_len[g]; group++) {
1992  ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1993  ch1 + group * 128 + offsets[i],
1994  offsets[i+1] - offsets[i]);
1995  }
1996  }
1997  }
1998  ch0 += ics->group_len[g] * 128;
1999  ch1 += ics->group_len[g] * 128;
2000  }
2001 }
2002 
2003 /**
2004  * intensity stereo decoding; reference: 4.6.8.2.3
2005  *
2006  * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
2007  * [1] mask is decoded from bitstream; [2] mask is all 1s;
2008  * [3] reserved for scalable AAC
2009  */
2011  ChannelElement *cpe, int ms_present)
2012 {
2013  const IndividualChannelStream *ics = &cpe->ch[1].ics;
2014  SingleChannelElement *sce1 = &cpe->ch[1];
2015  float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
2016  const uint16_t *offsets = ics->swb_offset;
2017  int g, group, i, idx = 0;
2018  int c;
2019  float scale;
2020  for (g = 0; g < ics->num_window_groups; g++) {
2021  for (i = 0; i < ics->max_sfb;) {
2022  if (sce1->band_type[idx] == INTENSITY_BT ||
2023  sce1->band_type[idx] == INTENSITY_BT2) {
2024  const int bt_run_end = sce1->band_type_run_end[idx];
2025  for (; i < bt_run_end; i++, idx++) {
2026  c = -1 + 2 * (sce1->band_type[idx] - 14);
2027  if (ms_present)
2028  c *= 1 - 2 * cpe->ms_mask[idx];
2029  scale = c * sce1->sf[idx];
2030  for (group = 0; group < ics->group_len[g]; group++)
2031  ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
2032  coef0 + group * 128 + offsets[i],
2033  scale,
2034  offsets[i + 1] - offsets[i]);
2035  }
2036  } else {
2037  int bt_run_end = sce1->band_type_run_end[idx];
2038  idx += bt_run_end - i;
2039  i = bt_run_end;
2040  }
2041  }
2042  coef0 += ics->group_len[g] * 128;
2043  coef1 += ics->group_len[g] * 128;
2044  }
2045 }
2046 
2047 /**
2048  * Decode a channel_pair_element; reference: table 4.4.
2049  *
2050  * @return Returns error status. 0 - OK, !0 - error
2051  */
2053 {
2054  int i, ret, common_window, ms_present = 0;
2055  int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2056 
2057  common_window = eld_syntax || get_bits1(gb);
2058  if (common_window) {
2059  if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2060  return AVERROR_INVALIDDATA;
2061  i = cpe->ch[1].ics.use_kb_window[0];
2062  cpe->ch[1].ics = cpe->ch[0].ics;
2063  cpe->ch[1].ics.use_kb_window[1] = i;
2064  if (cpe->ch[1].ics.predictor_present &&
2065  (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2066  if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2067  decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2068  ms_present = get_bits(gb, 2);
2069  if (ms_present == 3) {
2070  av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2071  return AVERROR_INVALIDDATA;
2072  } else if (ms_present)
2073  decode_mid_side_stereo(cpe, gb, ms_present);
2074  }
2075  if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2076  return ret;
2077  if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2078  return ret;
2079 
2080  if (common_window) {
2081  if (ms_present)
2082  apply_mid_side_stereo(ac, cpe);
2083  if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2084  apply_prediction(ac, &cpe->ch[0]);
2085  apply_prediction(ac, &cpe->ch[1]);
2086  }
2087  }
2088 
2089  apply_intensity_stereo(ac, cpe, ms_present);
2090  return 0;
2091 }
2092 
2093 static const float cce_scale[] = {
2094  1.09050773266525765921, //2^(1/8)
2095  1.18920711500272106672, //2^(1/4)
2096  M_SQRT2,
2097  2,
2098 };
2099 
2100 /**
2101  * Decode coupling_channel_element; reference: table 4.8.
2102  *
2103  * @return Returns error status. 0 - OK, !0 - error
2104  */
2106 {
2107  int num_gain = 0;
2108  int c, g, sfb, ret;
2109  int sign;
2110  float scale;
2111  SingleChannelElement *sce = &che->ch[0];
2112  ChannelCoupling *coup = &che->coup;
2113 
2114  coup->coupling_point = 2 * get_bits1(gb);
2115  coup->num_coupled = get_bits(gb, 3);
2116  for (c = 0; c <= coup->num_coupled; c++) {
2117  num_gain++;
2118  coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2119  coup->id_select[c] = get_bits(gb, 4);
2120  if (coup->type[c] == TYPE_CPE) {
2121  coup->ch_select[c] = get_bits(gb, 2);
2122  if (coup->ch_select[c] == 3)
2123  num_gain++;
2124  } else
2125  coup->ch_select[c] = 2;
2126  }
2127  coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2128 
2129  sign = get_bits(gb, 1);
2130  scale = cce_scale[get_bits(gb, 2)];
2131 
2132  if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2133  return ret;
2134 
2135  for (c = 0; c < num_gain; c++) {
2136  int idx = 0;
2137  int cge = 1;
2138  int gain = 0;
2139  float gain_cache = 1.0;
2140  if (c) {
2141  cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2142  gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2143  gain_cache = powf(scale, -gain);
2144  }
2145  if (coup->coupling_point == AFTER_IMDCT) {
2146  coup->gain[c][0] = gain_cache;
2147  } else {
2148  for (g = 0; g < sce->ics.num_window_groups; g++) {
2149  for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2150  if (sce->band_type[idx] != ZERO_BT) {
2151  if (!cge) {
2152  int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2153  if (t) {
2154  int s = 1;
2155  t = gain += t;
2156  if (sign) {
2157  s -= 2 * (t & 0x1);
2158  t >>= 1;
2159  }
2160  gain_cache = powf(scale, -t) * s;
2161  }
2162  }
2163  coup->gain[c][idx] = gain_cache;
2164  }
2165  }
2166  }
2167  }
2168  }
2169  return 0;
2170 }
2171 
2172 /**
2173  * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2174  *
2175  * @return Returns number of bytes consumed.
2176  */
2178  GetBitContext *gb)
2179 {
2180  int i;
2181  int num_excl_chan = 0;
2182 
2183  do {
2184  for (i = 0; i < 7; i++)
2185  che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2186  } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2187 
2188  return num_excl_chan / 7;
2189 }
2190 
2191 /**
2192  * Decode dynamic range information; reference: table 4.52.
2193  *
2194  * @return Returns number of bytes consumed.
2195  */
2197  GetBitContext *gb)
2198 {
2199  int n = 1;
2200  int drc_num_bands = 1;
2201  int i;
2202 
2203  /* pce_tag_present? */
2204  if (get_bits1(gb)) {
2205  che_drc->pce_instance_tag = get_bits(gb, 4);
2206  skip_bits(gb, 4); // tag_reserved_bits
2207  n++;
2208  }
2209 
2210  /* excluded_chns_present? */
2211  if (get_bits1(gb)) {
2212  n += decode_drc_channel_exclusions(che_drc, gb);
2213  }
2214 
2215  /* drc_bands_present? */
2216  if (get_bits1(gb)) {
2217  che_drc->band_incr = get_bits(gb, 4);
2218  che_drc->interpolation_scheme = get_bits(gb, 4);
2219  n++;
2220  drc_num_bands += che_drc->band_incr;
2221  for (i = 0; i < drc_num_bands; i++) {
2222  che_drc->band_top[i] = get_bits(gb, 8);
2223  n++;
2224  }
2225  }
2226 
2227  /* prog_ref_level_present? */
2228  if (get_bits1(gb)) {
2229  che_drc->prog_ref_level = get_bits(gb, 7);
2230  skip_bits1(gb); // prog_ref_level_reserved_bits
2231  n++;
2232  }
2233 
2234  for (i = 0; i < drc_num_bands; i++) {
2235  che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2236  che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2237  n++;
2238  }
2239 
2240  return n;
2241 }
2242 
2243 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2244  uint8_t buf[256];
2245  int i, major, minor;
2246 
2247  if (len < 13+7*8)
2248  goto unknown;
2249 
2250  get_bits(gb, 13); len -= 13;
2251 
2252  for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2253  buf[i] = get_bits(gb, 8);
2254 
2255  buf[i] = 0;
2256  if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2257  av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2258 
2259  if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2260  ac->avctx->internal->skip_samples = 1024;
2261  }
2262 
2263 unknown:
2264  skip_bits_long(gb, len);
2265 
2266  return 0;
2267 }
2268 
2269 /**
2270  * Decode extension data (incomplete); reference: table 4.51.
2271  *
2272  * @param cnt length of TYPE_FIL syntactic element in bytes
2273  *
2274  * @return Returns number of bytes consumed
2275  */
2277  ChannelElement *che, enum RawDataBlockType elem_type)
2278 {
2279  int crc_flag = 0;
2280  int res = cnt;
2281  switch (get_bits(gb, 4)) { // extension type
2282  case EXT_SBR_DATA_CRC:
2283  crc_flag++;
2284  case EXT_SBR_DATA:
2285  if (!che) {
2286  av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2287  return res;
2288  } else if (!ac->oc[1].m4ac.sbr) {
2289  av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2290  skip_bits_long(gb, 8 * cnt - 4);
2291  return res;
2292  } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2293  av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2294  skip_bits_long(gb, 8 * cnt - 4);
2295  return res;
2296  } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2297  ac->oc[1].m4ac.sbr = 1;
2298  ac->oc[1].m4ac.ps = 1;
2300  output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2301  ac->oc[1].status, 1);
2302  } else {
2303  ac->oc[1].m4ac.sbr = 1;
2305  }
2306  res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2307  break;
2308  case EXT_DYNAMIC_RANGE:
2309  res = decode_dynamic_range(&ac->che_drc, gb);
2310  break;
2311  case EXT_FILL:
2312  decode_fill(ac, gb, 8 * cnt - 4);
2313  break;
2314  case EXT_FILL_DATA:
2315  case EXT_DATA_ELEMENT:
2316  default:
2317  skip_bits_long(gb, 8 * cnt - 4);
2318  break;
2319  };
2320  return res;
2321 }
2322 
2323 /**
2324  * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2325  *
2326  * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2327  * @param coef spectral coefficients
2328  */
2329 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2330  IndividualChannelStream *ics, int decode)
2331 {
2332  const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2333  int w, filt, m, i;
2334  int bottom, top, order, start, end, size, inc;
2335  float lpc[TNS_MAX_ORDER];
2336  float tmp[TNS_MAX_ORDER+1];
2337 
2338  for (w = 0; w < ics->num_windows; w++) {
2339  bottom = ics->num_swb;
2340  for (filt = 0; filt < tns->n_filt[w]; filt++) {
2341  top = bottom;
2342  bottom = FFMAX(0, top - tns->length[w][filt]);
2343  order = tns->order[w][filt];
2344  if (order == 0)
2345  continue;
2346 
2347  // tns_decode_coef
2348  compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2349 
2350  start = ics->swb_offset[FFMIN(bottom, mmm)];
2351  end = ics->swb_offset[FFMIN( top, mmm)];
2352  if ((size = end - start) <= 0)
2353  continue;
2354  if (tns->direction[w][filt]) {
2355  inc = -1;
2356  start = end - 1;
2357  } else {
2358  inc = 1;
2359  }
2360  start += w * 128;
2361 
2362  if (decode) {
2363  // ar filter
2364  for (m = 0; m < size; m++, start += inc)
2365  for (i = 1; i <= FFMIN(m, order); i++)
2366  coef[start] -= coef[start - i * inc] * lpc[i - 1];
2367  } else {
2368  // ma filter
2369  for (m = 0; m < size; m++, start += inc) {
2370  tmp[0] = coef[start];
2371  for (i = 1; i <= FFMIN(m, order); i++)
2372  coef[start] += tmp[i] * lpc[i - 1];
2373  for (i = order; i > 0; i--)
2374  tmp[i] = tmp[i - 1];
2375  }
2376  }
2377  }
2378  }
2379 }
2380 
2381 /**
2382  * Apply windowing and MDCT to obtain the spectral
2383  * coefficient from the predicted sample by LTP.
2384  */
2385 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2386  float *in, IndividualChannelStream *ics)
2387 {
2388  const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2389  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2390  const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2391  const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2392 
2393  if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2394  ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2395  } else {
2396  memset(in, 0, 448 * sizeof(float));
2397  ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2398  }
2399  if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2400  ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2401  } else {
2402  ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2403  memset(in + 1024 + 576, 0, 448 * sizeof(float));
2404  }
2405  ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2406 }
2407 
2408 /**
2409  * Apply the long term prediction
2410  */
2412 {
2413  const LongTermPrediction *ltp = &sce->ics.ltp;
2414  const uint16_t *offsets = sce->ics.swb_offset;
2415  int i, sfb;
2416 
2417  if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2418  float *predTime = sce->ret;
2419  float *predFreq = ac->buf_mdct;
2420  int16_t num_samples = 2048;
2421 
2422  if (ltp->lag < 1024)
2423  num_samples = ltp->lag + 1024;
2424  for (i = 0; i < num_samples; i++)
2425  predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2426  memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2427 
2428  ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2429 
2430  if (sce->tns.present)
2431  ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2432 
2433  for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2434  if (ltp->used[sfb])
2435  for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2436  sce->coeffs[i] += predFreq[i];
2437  }
2438 }
2439 
2440 /**
2441  * Update the LTP buffer for next frame
2442  */
2444 {
2445  IndividualChannelStream *ics = &sce->ics;
2446  float *saved = sce->saved;
2447  float *saved_ltp = sce->coeffs;
2448  const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2449  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2450  int i;
2451 
2452  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2453  memcpy(saved_ltp, saved, 512 * sizeof(float));
2454  memset(saved_ltp + 576, 0, 448 * sizeof(float));
2455  ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2456  for (i = 0; i < 64; i++)
2457  saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2458  } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2459  memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2460  memset(saved_ltp + 576, 0, 448 * sizeof(float));
2461  ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2462  for (i = 0; i < 64; i++)
2463  saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2464  } else { // LONG_STOP or ONLY_LONG
2465  ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2466  for (i = 0; i < 512; i++)
2467  saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2468  }
2469 
2470  memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2471  memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2472  memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2473 }
2474 
2475 /**
2476  * Conduct IMDCT and windowing.
2477  */
2479 {
2480  IndividualChannelStream *ics = &sce->ics;
2481  float *in = sce->coeffs;
2482  float *out = sce->ret;
2483  float *saved = sce->saved;
2484  const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2485  const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2486  const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2487  float *buf = ac->buf_mdct;
2488  float *temp = ac->temp;
2489  int i;
2490 
2491  // imdct
2492  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2493  for (i = 0; i < 1024; i += 128)
2494  ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2495  } else
2496  ac->mdct.imdct_half(&ac->mdct, buf, in);
2497 
2498  /* window overlapping
2499  * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2500  * and long to short transitions are considered to be short to short
2501  * transitions. This leaves just two cases (long to long and short to short)
2502  * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2503  */
2504  if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2506  ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2507  } else {
2508  memcpy( out, saved, 448 * sizeof(float));
2509 
2510  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2511  ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2512  ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2513  ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2514  ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2515  ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2516  memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2517  } else {
2518  ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2519  memcpy( out + 576, buf + 64, 448 * sizeof(float));
2520  }
2521  }
2522 
2523  // buffer update
2524  if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2525  memcpy( saved, temp + 64, 64 * sizeof(float));
2526  ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2527  ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2528  ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2529  memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2530  } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2531  memcpy( saved, buf + 512, 448 * sizeof(float));
2532  memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2533  } else { // LONG_STOP or ONLY_LONG
2534  memcpy( saved, buf + 512, 512 * sizeof(float));
2535  }
2536 }
2537 
2539 {
2540  IndividualChannelStream *ics = &sce->ics;
2541  float *in = sce->coeffs;
2542  float *out = sce->ret;
2543  float *saved = sce->saved;
2544  float *buf = ac->buf_mdct;
2545 
2546  // imdct
2547  ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2548 
2549  // window overlapping
2550  if (ics->use_kb_window[1]) {
2551  // AAC LD uses a low overlap sine window instead of a KBD window
2552  memcpy(out, saved, 192 * sizeof(float));
2553  ac->fdsp.vector_fmul_window(out + 192, saved + 192, buf, ff_sine_128, 64);
2554  memcpy( out + 320, buf + 64, 192 * sizeof(float));
2555  } else {
2556  ac->fdsp.vector_fmul_window(out, saved, buf, ff_sine_512, 256);
2557  }
2558 
2559  // buffer update
2560  memcpy(saved, buf + 256, 256 * sizeof(float));
2561 }
2562 
2564 {
2565  float *in = sce->coeffs;
2566  float *out = sce->ret;
2567  float *saved = sce->saved;
2568  const float *const window = ff_aac_eld_window;
2569  float *buf = ac->buf_mdct;
2570  int i;
2571  const int n = 512;
2572  const int n2 = n >> 1;
2573  const int n4 = n >> 2;
2574 
2575  // Inverse transform, mapped to the conventional IMDCT by
2576  // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2577  // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2578  // International Conference on Audio, Language and Image Processing, ICALIP 2008.
2579  // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2580  for (i = 0; i < n2; i+=2) {
2581  float temp;
2582  temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2583  temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2584  }
2585  ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2586  for (i = 0; i < n; i+=2) {
2587  buf[i] = -buf[i];
2588  }
2589  // Like with the regular IMDCT at this point we still have the middle half
2590  // of a transform but with even symmetry on the left and odd symmetry on
2591  // the right
2592 
2593  // window overlapping
2594  // The spec says to use samples [0..511] but the reference decoder uses
2595  // samples [128..639].
2596  for (i = n4; i < n2; i ++) {
2597  out[i - n4] = buf[n2 - 1 - i] * window[i - n4] +
2598  saved[ i + n2] * window[i + n - n4] +
2599  -saved[ n + n2 - 1 - i] * window[i + 2*n - n4] +
2600  -saved[2*n + n2 + i] * window[i + 3*n - n4];
2601  }
2602  for (i = 0; i < n2; i ++) {
2603  out[n4 + i] = buf[i] * window[i + n2 - n4] +
2604  -saved[ n - 1 - i] * window[i + n2 + n - n4] +
2605  -saved[ n + i] * window[i + n2 + 2*n - n4] +
2606  saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
2607  }
2608  for (i = 0; i < n4; i ++) {
2609  out[n2 + n4 + i] = buf[ i + n2] * window[i + n - n4] +
2610  -saved[ n2 - 1 - i] * window[i + 2*n - n4] +
2611  -saved[ n + n2 + i] * window[i + 3*n - n4];
2612  }
2613 
2614  // buffer update
2615  memmove(saved + n, saved, 2 * n * sizeof(float));
2616  memcpy( saved, buf, n * sizeof(float));
2617 }
2618 
2619 /**
2620  * Apply dependent channel coupling (applied before IMDCT).
2621  *
2622  * @param index index into coupling gain array
2623  */
2625  SingleChannelElement *target,
2626  ChannelElement *cce, int index)
2627 {
2628  IndividualChannelStream *ics = &cce->ch[0].ics;
2629  const uint16_t *offsets = ics->swb_offset;
2630  float *dest = target->coeffs;
2631  const float *src = cce->ch[0].coeffs;
2632  int g, i, group, k, idx = 0;
2633  if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2634  av_log(ac->avctx, AV_LOG_ERROR,
2635  "Dependent coupling is not supported together with LTP\n");
2636  return;
2637  }
2638  for (g = 0; g < ics->num_window_groups; g++) {
2639  for (i = 0; i < ics->max_sfb; i++, idx++) {
2640  if (cce->ch[0].band_type[idx] != ZERO_BT) {
2641  const float gain = cce->coup.gain[index][idx];
2642  for (group = 0; group < ics->group_len[g]; group++) {
2643  for (k = offsets[i]; k < offsets[i + 1]; k++) {
2644  // FIXME: SIMDify
2645  dest[group * 128 + k] += gain * src[group * 128 + k];
2646  }
2647  }
2648  }
2649  }
2650  dest += ics->group_len[g] * 128;
2651  src += ics->group_len[g] * 128;
2652  }
2653 }
2654 
2655 /**
2656  * Apply independent channel coupling (applied after IMDCT).
2657  *
2658  * @param index index into coupling gain array
2659  */
2661  SingleChannelElement *target,
2662  ChannelElement *cce, int index)
2663 {
2664  int i;
2665  const float gain = cce->coup.gain[index][0];
2666  const float *src = cce->ch[0].ret;
2667  float *dest = target->ret;
2668  const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2669 
2670  for (i = 0; i < len; i++)
2671  dest[i] += gain * src[i];
2672 }
2673 
2674 /**
2675  * channel coupling transformation interface
2676  *
2677  * @param apply_coupling_method pointer to (in)dependent coupling function
2678  */
2680  enum RawDataBlockType type, int elem_id,
2681  enum CouplingPoint coupling_point,
2682  void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2683 {
2684  int i, c;
2685 
2686  for (i = 0; i < MAX_ELEM_ID; i++) {
2687  ChannelElement *cce = ac->che[TYPE_CCE][i];
2688  int index = 0;
2689 
2690  if (cce && cce->coup.coupling_point == coupling_point) {
2691  ChannelCoupling *coup = &cce->coup;
2692 
2693  for (c = 0; c <= coup->num_coupled; c++) {
2694  if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2695  if (coup->ch_select[c] != 1) {
2696  apply_coupling_method(ac, &cc->ch[0], cce, index);
2697  if (coup->ch_select[c] != 0)
2698  index++;
2699  }
2700  if (coup->ch_select[c] != 2)
2701  apply_coupling_method(ac, &cc->ch[1], cce, index++);
2702  } else
2703  index += 1 + (coup->ch_select[c] == 3);
2704  }
2705  }
2706  }
2707 }
2708 
2709 /**
2710  * Convert spectral data to float samples, applying all supported tools as appropriate.
2711  */
2713 {
2714  int i, type;
2716  switch (ac->oc[1].m4ac.object_type) {
2717  case AOT_ER_AAC_LD:
2719  break;
2720  case AOT_ER_AAC_ELD:
2722  break;
2723  default:
2725  }
2726  for (type = 3; type >= 0; type--) {
2727  for (i = 0; i < MAX_ELEM_ID; i++) {
2728  ChannelElement *che = ac->che[type][i];
2729  if (che) {
2730  if (type <= TYPE_CPE)
2732  if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2733  if (che->ch[0].ics.predictor_present) {
2734  if (che->ch[0].ics.ltp.present)
2735  ac->apply_ltp(ac, &che->ch[0]);
2736  if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2737  ac->apply_ltp(ac, &che->ch[1]);
2738  }
2739  }
2740  if (che->ch[0].tns.present)
2741  ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2742  if (che->ch[1].tns.present)
2743  ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2744  if (type <= TYPE_CPE)
2746  if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2747  imdct_and_window(ac, &che->ch[0]);
2748  if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2749  ac->update_ltp(ac, &che->ch[0]);
2750  if (type == TYPE_CPE) {
2751  imdct_and_window(ac, &che->ch[1]);
2752  if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2753  ac->update_ltp(ac, &che->ch[1]);
2754  }
2755  if (ac->oc[1].m4ac.sbr > 0) {
2756  ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2757  }
2758  }
2759  if (type <= TYPE_CCE)
2761  }
2762  }
2763  }
2764 }
2765 
2767 {
2768  int size;
2769  AACADTSHeaderInfo hdr_info;
2770  uint8_t layout_map[MAX_ELEM_ID*4][3];
2771  int layout_map_tags, ret;
2772 
2773  size = avpriv_aac_parse_header(gb, &hdr_info);
2774  if (size > 0) {
2775  if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2776  // This is 2 for "VLB " audio in NSV files.
2777  // See samples/nsv/vlb_audio.
2779  "More than one AAC RDB per ADTS frame");
2780  ac->warned_num_aac_frames = 1;
2781  }
2783  if (hdr_info.chan_config) {
2784  ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2785  if ((ret = set_default_channel_config(ac->avctx,
2786  layout_map,
2787  &layout_map_tags,
2788  hdr_info.chan_config)) < 0)
2789  return ret;
2790  if ((ret = output_configure(ac, layout_map, layout_map_tags,
2791  FFMAX(ac->oc[1].status,
2792  OC_TRIAL_FRAME), 0)) < 0)
2793  return ret;
2794  } else {
2795  ac->oc[1].m4ac.chan_config = 0;
2796  /**
2797  * dual mono frames in Japanese DTV can have chan_config 0
2798  * WITHOUT specifying PCE.
2799  * thus, set dual mono as default.
2800  */
2801  if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
2802  layout_map_tags = 2;
2803  layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
2804  layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
2805  layout_map[0][1] = 0;
2806  layout_map[1][1] = 1;
2807  if (output_configure(ac, layout_map, layout_map_tags,
2808  OC_TRIAL_FRAME, 0))
2809  return -7;
2810  }
2811  }
2812  ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2813  ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2814  ac->oc[1].m4ac.object_type = hdr_info.object_type;
2815  if (ac->oc[0].status != OC_LOCKED ||
2816  ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2817  ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2818  ac->oc[1].m4ac.sbr = -1;
2819  ac->oc[1].m4ac.ps = -1;
2820  }
2821  if (!hdr_info.crc_absent)
2822  skip_bits(gb, 16);
2823  }
2824  return size;
2825 }
2826 
2827 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2828  int *got_frame_ptr, GetBitContext *gb)
2829 {
2830  AACContext *ac = avctx->priv_data;
2831  ChannelElement *che;
2832  int err, i;
2833  int samples = 1024;
2834  int chan_config = ac->oc[1].m4ac.chan_config;
2835  int aot = ac->oc[1].m4ac.object_type;
2836 
2837  if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
2838  samples >>= 1;
2839 
2840  ac->frame = data;
2841 
2842  if ((err = frame_configure_elements(avctx)) < 0)
2843  return err;
2844 
2845  // The FF_PROFILE_AAC_* defines are all object_type - 1
2846  // This may lead to an undefined profile being signaled
2847  ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2848 
2849  ac->tags_mapped = 0;
2850 
2851  if (chan_config < 0 || chan_config >= 8) {
2852  avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2853  ac->oc[1].m4ac.chan_config);
2854  return AVERROR_INVALIDDATA;
2855  }
2856  for (i = 0; i < tags_per_config[chan_config]; i++) {
2857  const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2858  const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
2859  if (!(che=get_che(ac, elem_type, elem_id))) {
2860  av_log(ac->avctx, AV_LOG_ERROR,
2861  "channel element %d.%d is not allocated\n",
2862  elem_type, elem_id);
2863  return AVERROR_INVALIDDATA;
2864  }
2865  if (aot != AOT_ER_AAC_ELD)
2866  skip_bits(gb, 4);
2867  switch (elem_type) {
2868  case TYPE_SCE:
2869  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2870  break;
2871  case TYPE_CPE:
2872  err = decode_cpe(ac, gb, che);
2873  break;
2874  case TYPE_LFE:
2875  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2876  break;
2877  }
2878  if (err < 0)
2879  return err;
2880  }
2881 
2882  spectral_to_sample(ac);
2883 
2884  ac->frame->nb_samples = samples;
2885  ac->frame->sample_rate = avctx->sample_rate;
2886  *got_frame_ptr = 1;
2887 
2888  skip_bits_long(gb, get_bits_left(gb));
2889  return 0;
2890 }
2891 
2892 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2893  int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
2894 {
2895  AACContext *ac = avctx->priv_data;
2896  ChannelElement *che = NULL, *che_prev = NULL;
2897  enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2898  int err, elem_id;
2899  int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2900  int is_dmono, sce_count = 0;
2901 
2902  ac->frame = data;
2903 
2904  if (show_bits(gb, 12) == 0xfff) {
2905  if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2906  av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2907  goto fail;
2908  }
2909  if (ac->oc[1].m4ac.sampling_index > 12) {
2910  av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2911  err = AVERROR_INVALIDDATA;
2912  goto fail;
2913  }
2914  }
2915 
2916  if ((err = frame_configure_elements(avctx)) < 0)
2917  goto fail;
2918 
2919  // The FF_PROFILE_AAC_* defines are all object_type - 1
2920  // This may lead to an undefined profile being signaled
2921  ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2922 
2923  ac->tags_mapped = 0;
2924  // parse
2925  while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2926  elem_id = get_bits(gb, 4);
2927 
2928  if (avctx->debug & FF_DEBUG_STARTCODE)
2929  av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
2930 
2931  if (elem_type < TYPE_DSE) {
2932  if (!(che=get_che(ac, elem_type, elem_id))) {
2933  av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2934  elem_type, elem_id);
2935  err = AVERROR_INVALIDDATA;
2936  goto fail;
2937  }
2938  samples = 1024;
2939  }
2940 
2941  switch (elem_type) {
2942 
2943  case TYPE_SCE:
2944  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2945  audio_found = 1;
2946  sce_count++;
2947  break;
2948 
2949  case TYPE_CPE:
2950  err = decode_cpe(ac, gb, che);
2951  audio_found = 1;
2952  break;
2953 
2954  case TYPE_CCE:
2955  err = decode_cce(ac, gb, che);
2956  break;
2957 
2958  case TYPE_LFE:
2959  err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2960  audio_found = 1;
2961  break;
2962 
2963  case TYPE_DSE:
2964  err = skip_data_stream_element(ac, gb);
2965  break;
2966 
2967  case TYPE_PCE: {
2968  uint8_t layout_map[MAX_ELEM_ID*4][3];
2969  int tags;
2971  tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2972  if (tags < 0) {
2973  err = tags;
2974  break;
2975  }
2976  if (pce_found) {
2977  av_log(avctx, AV_LOG_ERROR,
2978  "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2979  } else {
2980  err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2981  if (!err)
2982  ac->oc[1].m4ac.chan_config = 0;
2983  pce_found = 1;
2984  }
2985  break;
2986  }
2987 
2988  case TYPE_FIL:
2989  if (elem_id == 15)
2990  elem_id += get_bits(gb, 8) - 1;
2991  if (get_bits_left(gb) < 8 * elem_id) {
2992  av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
2993  err = AVERROR_INVALIDDATA;
2994  goto fail;
2995  }
2996  while (elem_id > 0)
2997  elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2998  err = 0; /* FIXME */
2999  break;
3000 
3001  default:
3002  err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
3003  break;
3004  }
3005 
3006  che_prev = che;
3007  elem_type_prev = elem_type;
3008 
3009  if (err)
3010  goto fail;
3011 
3012  if (get_bits_left(gb) < 3) {
3013  av_log(avctx, AV_LOG_ERROR, overread_err);
3014  err = AVERROR_INVALIDDATA;
3015  goto fail;
3016  }
3017  }
3018 
3019  spectral_to_sample(ac);
3020 
3021  multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
3022  samples <<= multiplier;
3023 
3024  if (ac->oc[1].status && audio_found) {
3025  avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
3026  avctx->frame_size = samples;
3027  ac->oc[1].status = OC_LOCKED;
3028  }
3029 
3030  if (multiplier) {
3031  int side_size;
3032  const uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
3033  if (side && side_size>=4)
3034  AV_WL32(side, 2*AV_RL32(side));
3035  }
3036 
3037  *got_frame_ptr = !!samples;
3038  if (samples) {
3039  ac->frame->nb_samples = samples;
3040  ac->frame->sample_rate = avctx->sample_rate;
3041  } else
3042  av_frame_unref(ac->frame);
3043  *got_frame_ptr = !!samples;
3044 
3045  /* for dual-mono audio (SCE + SCE) */
3046  is_dmono = ac->dmono_mode && sce_count == 2 &&
3048  if (is_dmono) {
3049  if (ac->dmono_mode == 1)
3050  ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
3051  else if (ac->dmono_mode == 2)
3052  ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
3053  }
3054 
3055  return 0;
3056 fail:
3058  return err;
3059 }
3060 
3061 static int aac_decode_frame(AVCodecContext *avctx, void *data,
3062  int *got_frame_ptr, AVPacket *avpkt)
3063 {
3064  AACContext *ac = avctx->priv_data;
3065  const uint8_t *buf = avpkt->data;
3066  int buf_size = avpkt->size;
3067  GetBitContext gb;
3068  int buf_consumed;
3069  int buf_offset;
3070  int err;
3071  int new_extradata_size;
3072  const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
3074  &new_extradata_size);
3075  int jp_dualmono_size;
3076  const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
3078  &jp_dualmono_size);
3079 
3080  if (new_extradata && 0) {
3081  av_free(avctx->extradata);
3082  avctx->extradata = av_mallocz(new_extradata_size +
3084  if (!avctx->extradata)
3085  return AVERROR(ENOMEM);
3086  avctx->extradata_size = new_extradata_size;
3087  memcpy(avctx->extradata, new_extradata, new_extradata_size);
3089  if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
3090  avctx->extradata,
3091  avctx->extradata_size*8, 1) < 0) {
3093  return AVERROR_INVALIDDATA;
3094  }
3095  }
3096 
3097  ac->dmono_mode = 0;
3098  if (jp_dualmono && jp_dualmono_size > 0)
3099  ac->dmono_mode = 1 + *jp_dualmono;
3100  if (ac->force_dmono_mode >= 0)
3101  ac->dmono_mode = ac->force_dmono_mode;
3102 
3103  if (INT_MAX / 8 <= buf_size)
3104  return AVERROR_INVALIDDATA;
3105 
3106  if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
3107  return err;
3108 
3109  switch (ac->oc[1].m4ac.object_type) {
3110  case AOT_ER_AAC_LC:
3111  case AOT_ER_AAC_LTP:
3112  case AOT_ER_AAC_LD:
3113  case AOT_ER_AAC_ELD:
3114  err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3115  break;
3116  default:
3117  err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
3118  }
3119  if (err < 0)
3120  return err;
3121 
3122  buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3123  for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3124  if (buf[buf_offset])
3125  break;
3126 
3127  return buf_size > buf_offset ? buf_consumed : buf_size;
3128 }
3129 
3131 {
3132  AACContext *ac = avctx->priv_data;
3133  int i, type;
3134 
3135  for (i = 0; i < MAX_ELEM_ID; i++) {
3136  for (type = 0; type < 4; type++) {
3137  if (ac->che[type][i])
3138  ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
3139  av_freep(&ac->che[type][i]);
3140  }
3141  }
3142 
3143  ff_mdct_end(&ac->mdct);
3144  ff_mdct_end(&ac->mdct_small);
3145  ff_mdct_end(&ac->mdct_ld);
3146  ff_mdct_end(&ac->mdct_ltp);
3147  return 0;
3148 }
3149 
3150 
3151 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
3152 
3153 struct LATMContext {
3154  AACContext aac_ctx; ///< containing AACContext
3155  int initialized; ///< initialized after a valid extradata was seen
3156 
3157  // parser data
3158  int audio_mux_version_A; ///< LATM syntax version
3159  int frame_length_type; ///< 0/1 variable/fixed frame length
3160  int frame_length; ///< frame length for fixed frame length
3161 };
3162 
3163 static inline uint32_t latm_get_value(GetBitContext *b)
3164 {
3165  int length = get_bits(b, 2);
3166 
3167  return get_bits_long(b, (length+1)*8);
3168 }
3169 
3171  GetBitContext *gb, int asclen)
3172 {
3173  AACContext *ac = &latmctx->aac_ctx;
3174  AVCodecContext *avctx = ac->avctx;
3175  MPEG4AudioConfig m4ac = { 0 };
3176  int config_start_bit = get_bits_count(gb);
3177  int sync_extension = 0;
3178  int bits_consumed, esize;
3179 
3180  if (asclen) {
3181  sync_extension = 1;
3182  asclen = FFMIN(asclen, get_bits_left(gb));
3183  } else
3184  asclen = get_bits_left(gb);
3185 
3186  if (config_start_bit % 8) {
3188  "Non-byte-aligned audio-specific config");
3189  return AVERROR_PATCHWELCOME;
3190  }
3191  if (asclen <= 0)
3192  return AVERROR_INVALIDDATA;
3193  bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
3194  gb->buffer + (config_start_bit / 8),
3195  asclen, sync_extension);
3196 
3197  if (bits_consumed < 0)
3198  return AVERROR_INVALIDDATA;
3199 
3200  if (!latmctx->initialized ||
3201  ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
3202  ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
3203 
3204  if(latmctx->initialized) {
3205  av_log(avctx, AV_LOG_INFO, "audio config changed\n");
3206  } else {
3207  av_log(avctx, AV_LOG_DEBUG, "initializing latmctx\n");
3208  }
3209  latmctx->initialized = 0;
3210 
3211  esize = (bits_consumed+7) / 8;
3212 
3213  if (avctx->extradata_size < esize) {
3214  av_free(avctx->extradata);
3216  if (!avctx->extradata)
3217  return AVERROR(ENOMEM);
3218  }
3219 
3220  avctx->extradata_size = esize;
3221  memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
3222  memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
3223  }
3224  skip_bits_long(gb, bits_consumed);
3225 
3226  return bits_consumed;
3227 }
3228 
3229 static int read_stream_mux_config(struct LATMContext *latmctx,
3230  GetBitContext *gb)
3231 {
3232  int ret, audio_mux_version = get_bits(gb, 1);
3233 
3234  latmctx->audio_mux_version_A = 0;
3235  if (audio_mux_version)
3236  latmctx->audio_mux_version_A = get_bits(gb, 1);
3237 
3238  if (!latmctx->audio_mux_version_A) {
3239 
3240  if (audio_mux_version)
3241  latm_get_value(gb); // taraFullness
3242 
3243  skip_bits(gb, 1); // allStreamSameTimeFraming
3244  skip_bits(gb, 6); // numSubFrames
3245  // numPrograms
3246  if (get_bits(gb, 4)) { // numPrograms
3247  avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
3248  return AVERROR_PATCHWELCOME;
3249  }
3250 
3251  // for each program (which there is only one in DVB)
3252 
3253  // for each layer (which there is only one in DVB)
3254  if (get_bits(gb, 3)) { // numLayer
3255  avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
3256  return AVERROR_PATCHWELCOME;
3257  }
3258 
3259  // for all but first stream: use_same_config = get_bits(gb, 1);
3260  if (!audio_mux_version) {
3261  if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
3262  return ret;
3263  } else {
3264  int ascLen = latm_get_value(gb);
3265  if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
3266  return ret;
3267  ascLen -= ret;
3268  skip_bits_long(gb, ascLen);
3269  }
3270 
3271  latmctx->frame_length_type = get_bits(gb, 3);
3272  switch (latmctx->frame_length_type) {
3273  case 0:
3274  skip_bits(gb, 8); // latmBufferFullness
3275  break;
3276  case 1:
3277  latmctx->frame_length = get_bits(gb, 9);
3278  break;
3279  case 3:
3280  case 4:
3281  case 5:
3282  skip_bits(gb, 6); // CELP frame length table index
3283  break;
3284  case 6:
3285  case 7:
3286  skip_bits(gb, 1); // HVXC frame length table index
3287  break;
3288  }
3289 
3290  if (get_bits(gb, 1)) { // other data
3291  if (audio_mux_version) {
3292  latm_get_value(gb); // other_data_bits
3293  } else {
3294  int esc;
3295  do {
3296  esc = get_bits(gb, 1);
3297  skip_bits(gb, 8);
3298  } while (esc);
3299  }
3300  }
3301 
3302  if (get_bits(gb, 1)) // crc present
3303  skip_bits(gb, 8); // config_crc
3304  }
3305 
3306  return 0;
3307 }
3308 
3310 {
3311  uint8_t tmp;
3312 
3313  if (ctx->frame_length_type == 0) {
3314  int mux_slot_length = 0;
3315  do {
3316  tmp = get_bits(gb, 8);
3317  mux_slot_length += tmp;
3318  } while (tmp == 255);
3319  return mux_slot_length;
3320  } else if (ctx->frame_length_type == 1) {
3321  return ctx->frame_length;
3322  } else if (ctx->frame_length_type == 3 ||
3323  ctx->frame_length_type == 5 ||
3324  ctx->frame_length_type == 7) {
3325  skip_bits(gb, 2); // mux_slot_length_coded
3326  }
3327  return 0;
3328 }
3329 
3330 static int read_audio_mux_element(struct LATMContext *latmctx,
3331  GetBitContext *gb)
3332 {
3333  int err;
3334  uint8_t use_same_mux = get_bits(gb, 1);
3335  if (!use_same_mux) {
3336  if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3337  return err;
3338  } else if (!latmctx->aac_ctx.avctx->extradata) {
3339  av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3340  "no decoder config found\n");
3341  return AVERROR(EAGAIN);
3342  }
3343  if (latmctx->audio_mux_version_A == 0) {
3344  int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3345  if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3346  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3347  return AVERROR_INVALIDDATA;
3348  } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3349  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3350  "frame length mismatch %d << %d\n",
3351  mux_slot_length_bytes * 8, get_bits_left(gb));
3352  return AVERROR_INVALIDDATA;
3353  }
3354  }
3355  return 0;
3356 }
3357 
3358 
3359 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3360  int *got_frame_ptr, AVPacket *avpkt)
3361 {
3362  struct LATMContext *latmctx = avctx->priv_data;
3363  int muxlength, err;
3364  GetBitContext gb;
3365 
3366  if ((err = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
3367  return err;
3368 
3369  // check for LOAS sync word
3370  if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3371  return AVERROR_INVALIDDATA;
3372 
3373  muxlength = get_bits(&gb, 13) + 3;
3374  // not enough data, the parser should have sorted this out
3375  if (muxlength > avpkt->size)
3376  return AVERROR_INVALIDDATA;
3377 
3378  if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3379  return err;
3380 
3381  if (!latmctx->initialized) {
3382  if (!avctx->extradata) {
3383  *got_frame_ptr = 0;
3384  return avpkt->size;
3385  } else {
3387  if ((err = decode_audio_specific_config(
3388  &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3389  avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3390  pop_output_configuration(&latmctx->aac_ctx);
3391  return err;
3392  }
3393  latmctx->initialized = 1;
3394  }
3395  }
3396 
3397  if (show_bits(&gb, 12) == 0xfff) {
3398  av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3399  "ADTS header detected, probably as result of configuration "
3400  "misparsing\n");
3401  return AVERROR_INVALIDDATA;
3402  }
3403 
3404  if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb, avpkt)) < 0)
3405  return err;
3406 
3407  return muxlength;
3408 }
3409 
3411 {
3412  struct LATMContext *latmctx = avctx->priv_data;
3413  int ret = aac_decode_init(avctx);
3414 
3415  if (avctx->extradata_size > 0)
3416  latmctx->initialized = !ret;
3417 
3418  return ret;
3419 }
3420 
3421 static void aacdec_init(AACContext *c)
3422 {
3424  c->apply_ltp = apply_ltp;
3425  c->apply_tns = apply_tns;
3427  c->update_ltp = update_ltp;
3428 
3429  if(ARCH_MIPS)
3431 }
3432 /**
3433  * AVOptions for Japanese DTV specific extensions (ADTS only)
3434  */
3435 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3436 static const AVOption options[] = {
3437  {"dual_mono_mode", "Select the channel to decode for dual mono",
3438  offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3439  AACDEC_FLAGS, "dual_mono_mode"},
3440 
3441  {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3442  {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3443  {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3444  {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3445 
3446  {NULL},
3447 };
3448 
3449 static const AVClass aac_decoder_class = {
3450  .class_name = "AAC decoder",
3451  .item_name = av_default_item_name,
3452  .option = options,
3453  .version = LIBAVUTIL_VERSION_INT,
3454 };
3455 
3457  .name = "aac",
3458  .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3459  .type = AVMEDIA_TYPE_AUDIO,
3460  .id = AV_CODEC_ID_AAC,
3461  .priv_data_size = sizeof(AACContext),
3462  .init = aac_decode_init,
3465  .sample_fmts = (const enum AVSampleFormat[]) {
3467  },
3468  .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3469  .channel_layouts = aac_channel_layout,
3470  .flush = flush,
3471  .priv_class = &aac_decoder_class,
3472 };
3473 
3474 /*
3475  Note: This decoder filter is intended to decode LATM streams transferred
3476  in MPEG transport streams which only contain one program.
3477  To do a more complex LATM demuxing a separate LATM demuxer should be used.
3478 */
3480  .name = "aac_latm",
3481  .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3482  .type = AVMEDIA_TYPE_AUDIO,
3483  .id = AV_CODEC_ID_AAC_LATM,
3484  .priv_data_size = sizeof(struct LATMContext),
3485  .init = latm_decode_init,
3486  .close = aac_decode_close,
3487  .decode = latm_decode_frame,
3488  .sample_fmts = (const enum AVSampleFormat[]) {
3490  },
3491  .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3492  .channel_layouts = aac_channel_layout,
3493  .flush = flush,
3494 };