Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

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