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