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