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