Libav 0.7.1
libavcodec/aacdec.c
Go to the documentation of this file.
00001 /*
00002  * AAC decoder
00003  * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
00004  * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
00005  *
00006  * AAC LATM decoder
00007  * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
00008  * Copyright (c) 2010      Janne Grunau <janne-ffmpeg@jannau.net>
00009  *
00010  * This file is part of Libav.
00011  *
00012  * Libav is free software; you can redistribute it and/or
00013  * modify it under the terms of the GNU Lesser General Public
00014  * License as published by the Free Software Foundation; either
00015  * version 2.1 of the License, or (at your option) any later version.
00016  *
00017  * Libav is distributed in the hope that it will be useful,
00018  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00019  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00020  * Lesser General Public License for more details.
00021  *
00022  * You should have received a copy of the GNU Lesser General Public
00023  * License along with Libav; if not, write to the Free Software
00024  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00025  */
00026 
00034 /*
00035  * supported tools
00036  *
00037  * Support?             Name
00038  * N (code in SoC repo) gain control
00039  * Y                    block switching
00040  * Y                    window shapes - standard
00041  * N                    window shapes - Low Delay
00042  * Y                    filterbank - standard
00043  * N (code in SoC repo) filterbank - Scalable Sample Rate
00044  * Y                    Temporal Noise Shaping
00045  * Y                    Long Term Prediction
00046  * Y                    intensity stereo
00047  * Y                    channel coupling
00048  * Y                    frequency domain prediction
00049  * Y                    Perceptual Noise Substitution
00050  * Y                    Mid/Side stereo
00051  * N                    Scalable Inverse AAC Quantization
00052  * N                    Frequency Selective Switch
00053  * N                    upsampling filter
00054  * Y                    quantization & coding - AAC
00055  * N                    quantization & coding - TwinVQ
00056  * N                    quantization & coding - BSAC
00057  * N                    AAC Error Resilience tools
00058  * N                    Error Resilience payload syntax
00059  * N                    Error Protection tool
00060  * N                    CELP
00061  * N                    Silence Compression
00062  * N                    HVXC
00063  * N                    HVXC 4kbits/s VR
00064  * N                    Structured Audio tools
00065  * N                    Structured Audio Sample Bank Format
00066  * N                    MIDI
00067  * N                    Harmonic and Individual Lines plus Noise
00068  * N                    Text-To-Speech Interface
00069  * Y                    Spectral Band Replication
00070  * Y (not in this code) Layer-1
00071  * Y (not in this code) Layer-2
00072  * Y (not in this code) Layer-3
00073  * N                    SinuSoidal Coding (Transient, Sinusoid, Noise)
00074  * Y                    Parametric Stereo
00075  * N                    Direct Stream Transfer
00076  *
00077  * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
00078  *       - HE AAC v2 comprises LC AAC with Spectral Band Replication and
00079            Parametric Stereo.
00080  */
00081 
00082 
00083 #include "avcodec.h"
00084 #include "internal.h"
00085 #include "get_bits.h"
00086 #include "dsputil.h"
00087 #include "fft.h"
00088 #include "fmtconvert.h"
00089 #include "lpc.h"
00090 #include "kbdwin.h"
00091 #include "sinewin.h"
00092 
00093 #include "aac.h"
00094 #include "aactab.h"
00095 #include "aacdectab.h"
00096 #include "cbrt_tablegen.h"
00097 #include "sbr.h"
00098 #include "aacsbr.h"
00099 #include "mpeg4audio.h"
00100 #include "aacadtsdec.h"
00101 
00102 #include <assert.h>
00103 #include <errno.h>
00104 #include <math.h>
00105 #include <string.h>
00106 
00107 #if ARCH_ARM
00108 #   include "arm/aac.h"
00109 #endif
00110 
00111 union float754 {
00112     float f;
00113     uint32_t i;
00114 };
00115 
00116 static VLC vlc_scalefactors;
00117 static VLC vlc_spectral[11];
00118 
00119 static const char overread_err[] = "Input buffer exhausted before END element found\n";
00120 
00121 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
00122 {
00123     // For PCE based channel configurations map the channels solely based on tags.
00124     if (!ac->m4ac.chan_config) {
00125         return ac->tag_che_map[type][elem_id];
00126     }
00127     // For indexed channel configurations map the channels solely based on position.
00128     switch (ac->m4ac.chan_config) {
00129     case 7:
00130         if (ac->tags_mapped == 3 && type == TYPE_CPE) {
00131             ac->tags_mapped++;
00132             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
00133         }
00134     case 6:
00135         /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
00136            instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
00137            encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
00138         if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
00139             ac->tags_mapped++;
00140             return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
00141         }
00142     case 5:
00143         if (ac->tags_mapped == 2 && type == TYPE_CPE) {
00144             ac->tags_mapped++;
00145             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
00146         }
00147     case 4:
00148         if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
00149             ac->tags_mapped++;
00150             return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
00151         }
00152     case 3:
00153     case 2:
00154         if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
00155             ac->tags_mapped++;
00156             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
00157         } else if (ac->m4ac.chan_config == 2) {
00158             return NULL;
00159         }
00160     case 1:
00161         if (!ac->tags_mapped && type == TYPE_SCE) {
00162             ac->tags_mapped++;
00163             return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
00164         }
00165     default:
00166         return NULL;
00167     }
00168 }
00169 
00182 static av_cold int che_configure(AACContext *ac,
00183                                  enum ChannelPosition che_pos[4][MAX_ELEM_ID],
00184                                  int type, int id, int *channels)
00185 {
00186     if (che_pos[type][id]) {
00187         if (!ac->che[type][id] && !(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
00188             return AVERROR(ENOMEM);
00189         ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
00190         if (type != TYPE_CCE) {
00191             ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
00192             if (type == TYPE_CPE ||
00193                 (type == TYPE_SCE && ac->m4ac.ps == 1)) {
00194                 ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
00195             }
00196         }
00197     } else {
00198         if (ac->che[type][id])
00199             ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
00200         av_freep(&ac->che[type][id]);
00201     }
00202     return 0;
00203 }
00204 
00213 static av_cold int output_configure(AACContext *ac,
00214                                     enum ChannelPosition che_pos[4][MAX_ELEM_ID],
00215                                     enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
00216                                     int channel_config, enum OCStatus oc_type)
00217 {
00218     AVCodecContext *avctx = ac->avctx;
00219     int i, type, channels = 0, ret;
00220 
00221     if (new_che_pos != che_pos)
00222     memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
00223 
00224     if (channel_config) {
00225         for (i = 0; i < tags_per_config[channel_config]; i++) {
00226             if ((ret = che_configure(ac, che_pos,
00227                                      aac_channel_layout_map[channel_config - 1][i][0],
00228                                      aac_channel_layout_map[channel_config - 1][i][1],
00229                                      &channels)))
00230                 return ret;
00231         }
00232 
00233         memset(ac->tag_che_map, 0, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
00234 
00235         avctx->channel_layout = aac_channel_layout[channel_config - 1];
00236     } else {
00237         /* Allocate or free elements depending on if they are in the
00238          * current program configuration.
00239          *
00240          * Set up default 1:1 output mapping.
00241          *
00242          * For a 5.1 stream the output order will be:
00243          *    [ Center ] [ Front Left ] [ Front Right ] [ LFE ] [ Surround Left ] [ Surround Right ]
00244          */
00245 
00246         for (i = 0; i < MAX_ELEM_ID; i++) {
00247             for (type = 0; type < 4; type++) {
00248                 if ((ret = che_configure(ac, che_pos, type, i, &channels)))
00249                     return ret;
00250             }
00251         }
00252 
00253         memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
00254 
00255         avctx->channel_layout = 0;
00256     }
00257 
00258     avctx->channels = channels;
00259 
00260     ac->output_configured = oc_type;
00261 
00262     return 0;
00263 }
00264 
00272 static void decode_channel_map(enum ChannelPosition *cpe_map,
00273                                enum ChannelPosition *sce_map,
00274                                enum ChannelPosition type,
00275                                GetBitContext *gb, int n)
00276 {
00277     while (n--) {
00278         enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
00279         map[get_bits(gb, 4)] = type;
00280     }
00281 }
00282 
00290 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
00291                       enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
00292                       GetBitContext *gb)
00293 {
00294     int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
00295     int comment_len;
00296 
00297     skip_bits(gb, 2);  // object_type
00298 
00299     sampling_index = get_bits(gb, 4);
00300     if (m4ac->sampling_index != sampling_index)
00301         av_log(avctx, AV_LOG_WARNING, "Sample rate index in program config element does not match the sample rate index configured by the container.\n");
00302 
00303     num_front       = get_bits(gb, 4);
00304     num_side        = get_bits(gb, 4);
00305     num_back        = get_bits(gb, 4);
00306     num_lfe         = get_bits(gb, 2);
00307     num_assoc_data  = get_bits(gb, 3);
00308     num_cc          = get_bits(gb, 4);
00309 
00310     if (get_bits1(gb))
00311         skip_bits(gb, 4); // mono_mixdown_tag
00312     if (get_bits1(gb))
00313         skip_bits(gb, 4); // stereo_mixdown_tag
00314 
00315     if (get_bits1(gb))
00316         skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
00317 
00318     decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
00319     decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE,  gb, num_side );
00320     decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK,  gb, num_back );
00321     decode_channel_map(NULL,                  new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE,   gb, num_lfe  );
00322 
00323     skip_bits_long(gb, 4 * num_assoc_data);
00324 
00325     decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC,    gb, num_cc   );
00326 
00327     align_get_bits(gb);
00328 
00329     /* comment field, first byte is length */
00330     comment_len = get_bits(gb, 8) * 8;
00331     if (get_bits_left(gb) < comment_len) {
00332         av_log(avctx, AV_LOG_ERROR, overread_err);
00333         return -1;
00334     }
00335     skip_bits_long(gb, comment_len);
00336     return 0;
00337 }
00338 
00347 static av_cold int set_default_channel_config(AVCodecContext *avctx,
00348                                               enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
00349                                               int channel_config)
00350 {
00351     if (channel_config < 1 || channel_config > 7) {
00352         av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
00353                channel_config);
00354         return -1;
00355     }
00356 
00357     /* default channel configurations:
00358      *
00359      * 1ch : front center (mono)
00360      * 2ch : L + R (stereo)
00361      * 3ch : front center + L + R
00362      * 4ch : front center + L + R + back center
00363      * 5ch : front center + L + R + back stereo
00364      * 6ch : front center + L + R + back stereo + LFE
00365      * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
00366      */
00367 
00368     if (channel_config != 2)
00369         new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
00370     if (channel_config > 1)
00371         new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
00372     if (channel_config == 4)
00373         new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK;  // back center
00374     if (channel_config > 4)
00375         new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
00376         = AAC_CHANNEL_BACK;  // back stereo
00377     if (channel_config > 5)
00378         new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE;   // LFE
00379     if (channel_config == 7)
00380         new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
00381 
00382     return 0;
00383 }
00384 
00393 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
00394                                      GetBitContext *gb,
00395                                      MPEG4AudioConfig *m4ac,
00396                                      int channel_config)
00397 {
00398     enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
00399     int extension_flag, ret;
00400 
00401     if (get_bits1(gb)) { // frameLengthFlag
00402         av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
00403         return -1;
00404     }
00405 
00406     if (get_bits1(gb))       // dependsOnCoreCoder
00407         skip_bits(gb, 14);   // coreCoderDelay
00408     extension_flag = get_bits1(gb);
00409 
00410     if (m4ac->object_type == AOT_AAC_SCALABLE ||
00411         m4ac->object_type == AOT_ER_AAC_SCALABLE)
00412         skip_bits(gb, 3);     // layerNr
00413 
00414     memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
00415     if (channel_config == 0) {
00416         skip_bits(gb, 4);  // element_instance_tag
00417         if ((ret = decode_pce(avctx, m4ac, new_che_pos, gb)))
00418             return ret;
00419     } else {
00420         if ((ret = set_default_channel_config(avctx, new_che_pos, channel_config)))
00421             return ret;
00422     }
00423     if (ac && (ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
00424         return ret;
00425 
00426     if (extension_flag) {
00427         switch (m4ac->object_type) {
00428         case AOT_ER_BSAC:
00429             skip_bits(gb, 5);    // numOfSubFrame
00430             skip_bits(gb, 11);   // layer_length
00431             break;
00432         case AOT_ER_AAC_LC:
00433         case AOT_ER_AAC_LTP:
00434         case AOT_ER_AAC_SCALABLE:
00435         case AOT_ER_AAC_LD:
00436             skip_bits(gb, 3);  /* aacSectionDataResilienceFlag
00437                                     * aacScalefactorDataResilienceFlag
00438                                     * aacSpectralDataResilienceFlag
00439                                     */
00440             break;
00441         }
00442         skip_bits1(gb);    // extensionFlag3 (TBD in version 3)
00443     }
00444     return 0;
00445 }
00446 
00458 static int decode_audio_specific_config(AACContext *ac,
00459                                         AVCodecContext *avctx,
00460                                         MPEG4AudioConfig *m4ac,
00461                                         const uint8_t *data, int data_size)
00462 {
00463     GetBitContext gb;
00464     int i;
00465 
00466     av_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
00467     for (i = 0; i < avctx->extradata_size; i++)
00468          av_dlog(avctx, "%02x ", avctx->extradata[i]);
00469     av_dlog(avctx, "\n");
00470 
00471     init_get_bits(&gb, data, data_size * 8);
00472 
00473     if ((i = ff_mpeg4audio_get_config(m4ac, data, data_size)) < 0)
00474         return -1;
00475     if (m4ac->sampling_index > 12) {
00476         av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
00477         return -1;
00478     }
00479     if (m4ac->sbr == 1 && m4ac->ps == -1)
00480         m4ac->ps = 1;
00481 
00482     skip_bits_long(&gb, i);
00483 
00484     switch (m4ac->object_type) {
00485     case AOT_AAC_MAIN:
00486     case AOT_AAC_LC:
00487     case AOT_AAC_LTP:
00488         if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
00489             return -1;
00490         break;
00491     default:
00492         av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
00493                m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
00494         return -1;
00495     }
00496 
00497     av_dlog(avctx, "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
00498             m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
00499             m4ac->sample_rate, m4ac->sbr, m4ac->ps);
00500 
00501     return get_bits_count(&gb);
00502 }
00503 
00511 static av_always_inline int lcg_random(int previous_val)
00512 {
00513     return previous_val * 1664525 + 1013904223;
00514 }
00515 
00516 static av_always_inline void reset_predict_state(PredictorState *ps)
00517 {
00518     ps->r0   = 0.0f;
00519     ps->r1   = 0.0f;
00520     ps->cor0 = 0.0f;
00521     ps->cor1 = 0.0f;
00522     ps->var0 = 1.0f;
00523     ps->var1 = 1.0f;
00524 }
00525 
00526 static void reset_all_predictors(PredictorState *ps)
00527 {
00528     int i;
00529     for (i = 0; i < MAX_PREDICTORS; i++)
00530         reset_predict_state(&ps[i]);
00531 }
00532 
00533 static void reset_predictor_group(PredictorState *ps, int group_num)
00534 {
00535     int i;
00536     for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
00537         reset_predict_state(&ps[i]);
00538 }
00539 
00540 #define AAC_INIT_VLC_STATIC(num, size) \
00541     INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
00542          ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
00543         ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
00544         size);
00545 
00546 static av_cold int aac_decode_init(AVCodecContext *avctx)
00547 {
00548     AACContext *ac = avctx->priv_data;
00549     float output_scale_factor;
00550 
00551     ac->avctx = avctx;
00552     ac->m4ac.sample_rate = avctx->sample_rate;
00553 
00554     if (avctx->extradata_size > 0) {
00555         if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
00556                                          avctx->extradata,
00557                                          avctx->extradata_size) < 0)
00558             return -1;
00559     }
00560 
00561     if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
00562         avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
00563         output_scale_factor = 1.0 / 32768.0;
00564     } else {
00565         avctx->sample_fmt = AV_SAMPLE_FMT_S16;
00566         output_scale_factor = 1.0;
00567     }
00568 
00569     AAC_INIT_VLC_STATIC( 0, 304);
00570     AAC_INIT_VLC_STATIC( 1, 270);
00571     AAC_INIT_VLC_STATIC( 2, 550);
00572     AAC_INIT_VLC_STATIC( 3, 300);
00573     AAC_INIT_VLC_STATIC( 4, 328);
00574     AAC_INIT_VLC_STATIC( 5, 294);
00575     AAC_INIT_VLC_STATIC( 6, 306);
00576     AAC_INIT_VLC_STATIC( 7, 268);
00577     AAC_INIT_VLC_STATIC( 8, 510);
00578     AAC_INIT_VLC_STATIC( 9, 366);
00579     AAC_INIT_VLC_STATIC(10, 462);
00580 
00581     ff_aac_sbr_init();
00582 
00583     dsputil_init(&ac->dsp, avctx);
00584     ff_fmt_convert_init(&ac->fmt_conv, avctx);
00585 
00586     ac->random_state = 0x1f2e3d4c;
00587 
00588     ff_aac_tableinit();
00589 
00590     INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
00591                     ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
00592                     ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
00593                     352);
00594 
00595     ff_mdct_init(&ac->mdct,       11, 1, output_scale_factor/1024.0);
00596     ff_mdct_init(&ac->mdct_small,  8, 1, output_scale_factor/128.0);
00597     ff_mdct_init(&ac->mdct_ltp,   11, 0, -2.0/output_scale_factor);
00598     // window initialization
00599     ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
00600     ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
00601     ff_init_ff_sine_windows(10);
00602     ff_init_ff_sine_windows( 7);
00603 
00604     cbrt_tableinit();
00605 
00606     return 0;
00607 }
00608 
00612 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
00613 {
00614     int byte_align = get_bits1(gb);
00615     int count = get_bits(gb, 8);
00616     if (count == 255)
00617         count += get_bits(gb, 8);
00618     if (byte_align)
00619         align_get_bits(gb);
00620 
00621     if (get_bits_left(gb) < 8 * count) {
00622         av_log(ac->avctx, AV_LOG_ERROR, overread_err);
00623         return -1;
00624     }
00625     skip_bits_long(gb, 8 * count);
00626     return 0;
00627 }
00628 
00629 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
00630                              GetBitContext *gb)
00631 {
00632     int sfb;
00633     if (get_bits1(gb)) {
00634         ics->predictor_reset_group = get_bits(gb, 5);
00635         if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
00636             av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
00637             return -1;
00638         }
00639     }
00640     for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
00641         ics->prediction_used[sfb] = get_bits1(gb);
00642     }
00643     return 0;
00644 }
00645 
00649 static void decode_ltp(AACContext *ac, LongTermPrediction *ltp,
00650                        GetBitContext *gb, uint8_t max_sfb)
00651 {
00652     int sfb;
00653 
00654     ltp->lag  = get_bits(gb, 11);
00655     ltp->coef = ltp_coef[get_bits(gb, 3)];
00656     for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
00657         ltp->used[sfb] = get_bits1(gb);
00658 }
00659 
00665 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
00666                            GetBitContext *gb, int common_window)
00667 {
00668     if (get_bits1(gb)) {
00669         av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
00670         memset(ics, 0, sizeof(IndividualChannelStream));
00671         return -1;
00672     }
00673     ics->window_sequence[1] = ics->window_sequence[0];
00674     ics->window_sequence[0] = get_bits(gb, 2);
00675     ics->use_kb_window[1]   = ics->use_kb_window[0];
00676     ics->use_kb_window[0]   = get_bits1(gb);
00677     ics->num_window_groups  = 1;
00678     ics->group_len[0]       = 1;
00679     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
00680         int i;
00681         ics->max_sfb = get_bits(gb, 4);
00682         for (i = 0; i < 7; i++) {
00683             if (get_bits1(gb)) {
00684                 ics->group_len[ics->num_window_groups - 1]++;
00685             } else {
00686                 ics->num_window_groups++;
00687                 ics->group_len[ics->num_window_groups - 1] = 1;
00688             }
00689         }
00690         ics->num_windows       = 8;
00691         ics->swb_offset        =    ff_swb_offset_128[ac->m4ac.sampling_index];
00692         ics->num_swb           =   ff_aac_num_swb_128[ac->m4ac.sampling_index];
00693         ics->tns_max_bands     = ff_tns_max_bands_128[ac->m4ac.sampling_index];
00694         ics->predictor_present = 0;
00695     } else {
00696         ics->max_sfb               = get_bits(gb, 6);
00697         ics->num_windows           = 1;
00698         ics->swb_offset            =    ff_swb_offset_1024[ac->m4ac.sampling_index];
00699         ics->num_swb               =   ff_aac_num_swb_1024[ac->m4ac.sampling_index];
00700         ics->tns_max_bands         = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
00701         ics->predictor_present     = get_bits1(gb);
00702         ics->predictor_reset_group = 0;
00703         if (ics->predictor_present) {
00704             if (ac->m4ac.object_type == AOT_AAC_MAIN) {
00705                 if (decode_prediction(ac, ics, gb)) {
00706                     memset(ics, 0, sizeof(IndividualChannelStream));
00707                     return -1;
00708                 }
00709             } else if (ac->m4ac.object_type == AOT_AAC_LC) {
00710                 av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
00711                 memset(ics, 0, sizeof(IndividualChannelStream));
00712                 return -1;
00713             } else {
00714                 if ((ics->ltp.present = get_bits(gb, 1)))
00715                     decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);
00716             }
00717         }
00718     }
00719 
00720     if (ics->max_sfb > ics->num_swb) {
00721         av_log(ac->avctx, AV_LOG_ERROR,
00722                "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
00723                ics->max_sfb, ics->num_swb);
00724         memset(ics, 0, sizeof(IndividualChannelStream));
00725         return -1;
00726     }
00727 
00728     return 0;
00729 }
00730 
00739 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
00740                              int band_type_run_end[120], GetBitContext *gb,
00741                              IndividualChannelStream *ics)
00742 {
00743     int g, idx = 0;
00744     const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
00745     for (g = 0; g < ics->num_window_groups; g++) {
00746         int k = 0;
00747         while (k < ics->max_sfb) {
00748             uint8_t sect_end = k;
00749             int sect_len_incr;
00750             int sect_band_type = get_bits(gb, 4);
00751             if (sect_band_type == 12) {
00752                 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
00753                 return -1;
00754             }
00755             do {
00756                 sect_len_incr = get_bits(gb, bits);
00757                 sect_end += sect_len_incr;
00758                 if (get_bits_left(gb) < 0) {
00759                     av_log(ac->avctx, AV_LOG_ERROR, overread_err);
00760                     return -1;
00761                 }
00762                 if (sect_end > ics->max_sfb) {
00763                     av_log(ac->avctx, AV_LOG_ERROR,
00764                            "Number of bands (%d) exceeds limit (%d).\n",
00765                            sect_end, ics->max_sfb);
00766                     return -1;
00767                 }
00768             } while (sect_len_incr == (1 << bits) - 1);
00769             for (; k < sect_end; k++) {
00770                 band_type        [idx]   = sect_band_type;
00771                 band_type_run_end[idx++] = sect_end;
00772             }
00773         }
00774     }
00775     return 0;
00776 }
00777 
00788 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
00789                                unsigned int global_gain,
00790                                IndividualChannelStream *ics,
00791                                enum BandType band_type[120],
00792                                int band_type_run_end[120])
00793 {
00794     int g, i, idx = 0;
00795     int offset[3] = { global_gain, global_gain - 90, 0 };
00796     int clipped_offset;
00797     int noise_flag = 1;
00798     static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
00799     for (g = 0; g < ics->num_window_groups; g++) {
00800         for (i = 0; i < ics->max_sfb;) {
00801             int run_end = band_type_run_end[idx];
00802             if (band_type[idx] == ZERO_BT) {
00803                 for (; i < run_end; i++, idx++)
00804                     sf[idx] = 0.;
00805             } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
00806                 for (; i < run_end; i++, idx++) {
00807                     offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
00808                     clipped_offset = av_clip(offset[2], -155, 100);
00809                     if (offset[2] != clipped_offset) {
00810                         av_log_ask_for_sample(ac->avctx, "Intensity stereo "
00811                                 "position clipped (%d -> %d).\nIf you heard an "
00812                                 "audible artifact, there may be a bug in the "
00813                                 "decoder. ", offset[2], clipped_offset);
00814                     }
00815                     sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
00816                 }
00817             } else if (band_type[idx] == NOISE_BT) {
00818                 for (; i < run_end; i++, idx++) {
00819                     if (noise_flag-- > 0)
00820                         offset[1] += get_bits(gb, 9) - 256;
00821                     else
00822                         offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
00823                     clipped_offset = av_clip(offset[1], -100, 155);
00824                     if (offset[1] != clipped_offset) {
00825                         av_log_ask_for_sample(ac->avctx, "Noise gain clipped "
00826                                 "(%d -> %d).\nIf you heard an audible "
00827                                 "artifact, there may be a bug in the decoder. ",
00828                                 offset[1], clipped_offset);
00829                     }
00830                     sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
00831                 }
00832             } else {
00833                 for (; i < run_end; i++, idx++) {
00834                     offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
00835                     if (offset[0] > 255U) {
00836                         av_log(ac->avctx, AV_LOG_ERROR,
00837                                "%s (%d) out of range.\n", sf_str[0], offset[0]);
00838                         return -1;
00839                     }
00840                     sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
00841                 }
00842             }
00843         }
00844     }
00845     return 0;
00846 }
00847 
00851 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
00852                          const uint16_t *swb_offset, int num_swb)
00853 {
00854     int i, pulse_swb;
00855     pulse->num_pulse = get_bits(gb, 2) + 1;
00856     pulse_swb        = get_bits(gb, 6);
00857     if (pulse_swb >= num_swb)
00858         return -1;
00859     pulse->pos[0]    = swb_offset[pulse_swb];
00860     pulse->pos[0]   += get_bits(gb, 5);
00861     if (pulse->pos[0] > 1023)
00862         return -1;
00863     pulse->amp[0]    = get_bits(gb, 4);
00864     for (i = 1; i < pulse->num_pulse; i++) {
00865         pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
00866         if (pulse->pos[i] > 1023)
00867             return -1;
00868         pulse->amp[i] = get_bits(gb, 4);
00869     }
00870     return 0;
00871 }
00872 
00878 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
00879                       GetBitContext *gb, const IndividualChannelStream *ics)
00880 {
00881     int w, filt, i, coef_len, coef_res, coef_compress;
00882     const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
00883     const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
00884     for (w = 0; w < ics->num_windows; w++) {
00885         if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
00886             coef_res = get_bits1(gb);
00887 
00888             for (filt = 0; filt < tns->n_filt[w]; filt++) {
00889                 int tmp2_idx;
00890                 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
00891 
00892                 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
00893                     av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
00894                            tns->order[w][filt], tns_max_order);
00895                     tns->order[w][filt] = 0;
00896                     return -1;
00897                 }
00898                 if (tns->order[w][filt]) {
00899                     tns->direction[w][filt] = get_bits1(gb);
00900                     coef_compress = get_bits1(gb);
00901                     coef_len = coef_res + 3 - coef_compress;
00902                     tmp2_idx = 2 * coef_compress + coef_res;
00903 
00904                     for (i = 0; i < tns->order[w][filt]; i++)
00905                         tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
00906                 }
00907             }
00908         }
00909     }
00910     return 0;
00911 }
00912 
00920 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
00921                                    int ms_present)
00922 {
00923     int idx;
00924     if (ms_present == 1) {
00925         for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
00926             cpe->ms_mask[idx] = get_bits1(gb);
00927     } else if (ms_present == 2) {
00928         memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
00929     }
00930 }
00931 
00932 #ifndef VMUL2
00933 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
00934                            const float *scale)
00935 {
00936     float s = *scale;
00937     *dst++ = v[idx    & 15] * s;
00938     *dst++ = v[idx>>4 & 15] * s;
00939     return dst;
00940 }
00941 #endif
00942 
00943 #ifndef VMUL4
00944 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
00945                            const float *scale)
00946 {
00947     float s = *scale;
00948     *dst++ = v[idx    & 3] * s;
00949     *dst++ = v[idx>>2 & 3] * s;
00950     *dst++ = v[idx>>4 & 3] * s;
00951     *dst++ = v[idx>>6 & 3] * s;
00952     return dst;
00953 }
00954 #endif
00955 
00956 #ifndef VMUL2S
00957 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
00958                             unsigned sign, const float *scale)
00959 {
00960     union float754 s0, s1;
00961 
00962     s0.f = s1.f = *scale;
00963     s0.i ^= sign >> 1 << 31;
00964     s1.i ^= sign      << 31;
00965 
00966     *dst++ = v[idx    & 15] * s0.f;
00967     *dst++ = v[idx>>4 & 15] * s1.f;
00968 
00969     return dst;
00970 }
00971 #endif
00972 
00973 #ifndef VMUL4S
00974 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
00975                             unsigned sign, const float *scale)
00976 {
00977     unsigned nz = idx >> 12;
00978     union float754 s = { .f = *scale };
00979     union float754 t;
00980 
00981     t.i = s.i ^ (sign & 1U<<31);
00982     *dst++ = v[idx    & 3] * t.f;
00983 
00984     sign <<= nz & 1; nz >>= 1;
00985     t.i = s.i ^ (sign & 1U<<31);
00986     *dst++ = v[idx>>2 & 3] * t.f;
00987 
00988     sign <<= nz & 1; nz >>= 1;
00989     t.i = s.i ^ (sign & 1U<<31);
00990     *dst++ = v[idx>>4 & 3] * t.f;
00991 
00992     sign <<= nz & 1; nz >>= 1;
00993     t.i = s.i ^ (sign & 1U<<31);
00994     *dst++ = v[idx>>6 & 3] * t.f;
00995 
00996     return dst;
00997 }
00998 #endif
00999 
01012 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
01013                                        GetBitContext *gb, const float sf[120],
01014                                        int pulse_present, const Pulse *pulse,
01015                                        const IndividualChannelStream *ics,
01016                                        enum BandType band_type[120])
01017 {
01018     int i, k, g, idx = 0;
01019     const int c = 1024 / ics->num_windows;
01020     const uint16_t *offsets = ics->swb_offset;
01021     float *coef_base = coef;
01022 
01023     for (g = 0; g < ics->num_windows; g++)
01024         memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
01025 
01026     for (g = 0; g < ics->num_window_groups; g++) {
01027         unsigned g_len = ics->group_len[g];
01028 
01029         for (i = 0; i < ics->max_sfb; i++, idx++) {
01030             const unsigned cbt_m1 = band_type[idx] - 1;
01031             float *cfo = coef + offsets[i];
01032             int off_len = offsets[i + 1] - offsets[i];
01033             int group;
01034 
01035             if (cbt_m1 >= INTENSITY_BT2 - 1) {
01036                 for (group = 0; group < g_len; group++, cfo+=128) {
01037                     memset(cfo, 0, off_len * sizeof(float));
01038                 }
01039             } else if (cbt_m1 == NOISE_BT - 1) {
01040                 for (group = 0; group < g_len; group++, cfo+=128) {
01041                     float scale;
01042                     float band_energy;
01043 
01044                     for (k = 0; k < off_len; k++) {
01045                         ac->random_state  = lcg_random(ac->random_state);
01046                         cfo[k] = ac->random_state;
01047                     }
01048 
01049                     band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
01050                     scale = sf[idx] / sqrtf(band_energy);
01051                     ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
01052                 }
01053             } else {
01054                 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
01055                 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
01056                 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
01057                 OPEN_READER(re, gb);
01058 
01059                 switch (cbt_m1 >> 1) {
01060                 case 0:
01061                     for (group = 0; group < g_len; group++, cfo+=128) {
01062                         float *cf = cfo;
01063                         int len = off_len;
01064 
01065                         do {
01066                             int code;
01067                             unsigned cb_idx;
01068 
01069                             UPDATE_CACHE(re, gb);
01070                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01071                             cb_idx = cb_vector_idx[code];
01072                             cf = VMUL4(cf, vq, cb_idx, sf + idx);
01073                         } while (len -= 4);
01074                     }
01075                     break;
01076 
01077                 case 1:
01078                     for (group = 0; group < g_len; group++, cfo+=128) {
01079                         float *cf = cfo;
01080                         int len = off_len;
01081 
01082                         do {
01083                             int code;
01084                             unsigned nnz;
01085                             unsigned cb_idx;
01086                             uint32_t bits;
01087 
01088                             UPDATE_CACHE(re, gb);
01089                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01090                             cb_idx = cb_vector_idx[code];
01091                             nnz = cb_idx >> 8 & 15;
01092                             bits = nnz ? GET_CACHE(re, gb) : 0;
01093                             LAST_SKIP_BITS(re, gb, nnz);
01094                             cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
01095                         } while (len -= 4);
01096                     }
01097                     break;
01098 
01099                 case 2:
01100                     for (group = 0; group < g_len; group++, cfo+=128) {
01101                         float *cf = cfo;
01102                         int len = off_len;
01103 
01104                         do {
01105                             int code;
01106                             unsigned cb_idx;
01107 
01108                             UPDATE_CACHE(re, gb);
01109                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01110                             cb_idx = cb_vector_idx[code];
01111                             cf = VMUL2(cf, vq, cb_idx, sf + idx);
01112                         } while (len -= 2);
01113                     }
01114                     break;
01115 
01116                 case 3:
01117                 case 4:
01118                     for (group = 0; group < g_len; group++, cfo+=128) {
01119                         float *cf = cfo;
01120                         int len = off_len;
01121 
01122                         do {
01123                             int code;
01124                             unsigned nnz;
01125                             unsigned cb_idx;
01126                             unsigned sign;
01127 
01128                             UPDATE_CACHE(re, gb);
01129                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01130                             cb_idx = cb_vector_idx[code];
01131                             nnz = cb_idx >> 8 & 15;
01132                             sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
01133                             LAST_SKIP_BITS(re, gb, nnz);
01134                             cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
01135                         } while (len -= 2);
01136                     }
01137                     break;
01138 
01139                 default:
01140                     for (group = 0; group < g_len; group++, cfo+=128) {
01141                         float *cf = cfo;
01142                         uint32_t *icf = (uint32_t *) cf;
01143                         int len = off_len;
01144 
01145                         do {
01146                             int code;
01147                             unsigned nzt, nnz;
01148                             unsigned cb_idx;
01149                             uint32_t bits;
01150                             int j;
01151 
01152                             UPDATE_CACHE(re, gb);
01153                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01154 
01155                             if (!code) {
01156                                 *icf++ = 0;
01157                                 *icf++ = 0;
01158                                 continue;
01159                             }
01160 
01161                             cb_idx = cb_vector_idx[code];
01162                             nnz = cb_idx >> 12;
01163                             nzt = cb_idx >> 8;
01164                             bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
01165                             LAST_SKIP_BITS(re, gb, nnz);
01166 
01167                             for (j = 0; j < 2; j++) {
01168                                 if (nzt & 1<<j) {
01169                                     uint32_t b;
01170                                     int n;
01171                                     /* The total length of escape_sequence must be < 22 bits according
01172                                        to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
01173                                     UPDATE_CACHE(re, gb);
01174                                     b = GET_CACHE(re, gb);
01175                                     b = 31 - av_log2(~b);
01176 
01177                                     if (b > 8) {
01178                                         av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
01179                                         return -1;
01180                                     }
01181 
01182                                     SKIP_BITS(re, gb, b + 1);
01183                                     b += 4;
01184                                     n = (1 << b) + SHOW_UBITS(re, gb, b);
01185                                     LAST_SKIP_BITS(re, gb, b);
01186                                     *icf++ = cbrt_tab[n] | (bits & 1U<<31);
01187                                     bits <<= 1;
01188                                 } else {
01189                                     unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
01190                                     *icf++ = (bits & 1U<<31) | v;
01191                                     bits <<= !!v;
01192                                 }
01193                                 cb_idx >>= 4;
01194                             }
01195                         } while (len -= 2);
01196 
01197                         ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
01198                     }
01199                 }
01200 
01201                 CLOSE_READER(re, gb);
01202             }
01203         }
01204         coef += g_len << 7;
01205     }
01206 
01207     if (pulse_present) {
01208         idx = 0;
01209         for (i = 0; i < pulse->num_pulse; i++) {
01210             float co = coef_base[ pulse->pos[i] ];
01211             while (offsets[idx + 1] <= pulse->pos[i])
01212                 idx++;
01213             if (band_type[idx] != NOISE_BT && sf[idx]) {
01214                 float ico = -pulse->amp[i];
01215                 if (co) {
01216                     co /= sf[idx];
01217                     ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
01218                 }
01219                 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
01220             }
01221         }
01222     }
01223     return 0;
01224 }
01225 
01226 static av_always_inline float flt16_round(float pf)
01227 {
01228     union float754 tmp;
01229     tmp.f = pf;
01230     tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
01231     return tmp.f;
01232 }
01233 
01234 static av_always_inline float flt16_even(float pf)
01235 {
01236     union float754 tmp;
01237     tmp.f = pf;
01238     tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
01239     return tmp.f;
01240 }
01241 
01242 static av_always_inline float flt16_trunc(float pf)
01243 {
01244     union float754 pun;
01245     pun.f = pf;
01246     pun.i &= 0xFFFF0000U;
01247     return pun.f;
01248 }
01249 
01250 static av_always_inline void predict(PredictorState *ps, float *coef,
01251                                      int output_enable)
01252 {
01253     const float a     = 0.953125; // 61.0 / 64
01254     const float alpha = 0.90625;  // 29.0 / 32
01255     float e0, e1;
01256     float pv;
01257     float k1, k2;
01258     float   r0 = ps->r0,     r1 = ps->r1;
01259     float cor0 = ps->cor0, cor1 = ps->cor1;
01260     float var0 = ps->var0, var1 = ps->var1;
01261 
01262     k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
01263     k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
01264 
01265     pv = flt16_round(k1 * r0 + k2 * r1);
01266     if (output_enable)
01267         *coef += pv;
01268 
01269     e0 = *coef;
01270     e1 = e0 - k1 * r0;
01271 
01272     ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
01273     ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
01274     ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
01275     ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
01276 
01277     ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
01278     ps->r0 = flt16_trunc(a * e0);
01279 }
01280 
01284 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
01285 {
01286     int sfb, k;
01287 
01288     if (!sce->ics.predictor_initialized) {
01289         reset_all_predictors(sce->predictor_state);
01290         sce->ics.predictor_initialized = 1;
01291     }
01292 
01293     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
01294         for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
01295             for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
01296                 predict(&sce->predictor_state[k], &sce->coeffs[k],
01297                         sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
01298             }
01299         }
01300         if (sce->ics.predictor_reset_group)
01301             reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
01302     } else
01303         reset_all_predictors(sce->predictor_state);
01304 }
01305 
01314 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
01315                       GetBitContext *gb, int common_window, int scale_flag)
01316 {
01317     Pulse pulse;
01318     TemporalNoiseShaping    *tns = &sce->tns;
01319     IndividualChannelStream *ics = &sce->ics;
01320     float *out = sce->coeffs;
01321     int global_gain, pulse_present = 0;
01322 
01323     /* This assignment is to silence a GCC warning about the variable being used
01324      * uninitialized when in fact it always is.
01325      */
01326     pulse.num_pulse = 0;
01327 
01328     global_gain = get_bits(gb, 8);
01329 
01330     if (!common_window && !scale_flag) {
01331         if (decode_ics_info(ac, ics, gb, 0) < 0)
01332             return -1;
01333     }
01334 
01335     if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
01336         return -1;
01337     if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
01338         return -1;
01339 
01340     pulse_present = 0;
01341     if (!scale_flag) {
01342         if ((pulse_present = get_bits1(gb))) {
01343             if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01344                 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
01345                 return -1;
01346             }
01347             if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
01348                 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
01349                 return -1;
01350             }
01351         }
01352         if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
01353             return -1;
01354         if (get_bits1(gb)) {
01355             av_log_missing_feature(ac->avctx, "SSR", 1);
01356             return -1;
01357         }
01358     }
01359 
01360     if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
01361         return -1;
01362 
01363     if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
01364         apply_prediction(ac, sce);
01365 
01366     return 0;
01367 }
01368 
01372 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
01373 {
01374     const IndividualChannelStream *ics = &cpe->ch[0].ics;
01375     float *ch0 = cpe->ch[0].coeffs;
01376     float *ch1 = cpe->ch[1].coeffs;
01377     int g, i, group, idx = 0;
01378     const uint16_t *offsets = ics->swb_offset;
01379     for (g = 0; g < ics->num_window_groups; g++) {
01380         for (i = 0; i < ics->max_sfb; i++, idx++) {
01381             if (cpe->ms_mask[idx] &&
01382                     cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
01383                 for (group = 0; group < ics->group_len[g]; group++) {
01384                     ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
01385                                               ch1 + group * 128 + offsets[i],
01386                                               offsets[i+1] - offsets[i]);
01387                 }
01388             }
01389         }
01390         ch0 += ics->group_len[g] * 128;
01391         ch1 += ics->group_len[g] * 128;
01392     }
01393 }
01394 
01402 static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
01403 {
01404     const IndividualChannelStream *ics = &cpe->ch[1].ics;
01405     SingleChannelElement         *sce1 = &cpe->ch[1];
01406     float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
01407     const uint16_t *offsets = ics->swb_offset;
01408     int g, group, i, idx = 0;
01409     int c;
01410     float scale;
01411     for (g = 0; g < ics->num_window_groups; g++) {
01412         for (i = 0; i < ics->max_sfb;) {
01413             if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
01414                 const int bt_run_end = sce1->band_type_run_end[idx];
01415                 for (; i < bt_run_end; i++, idx++) {
01416                     c = -1 + 2 * (sce1->band_type[idx] - 14);
01417                     if (ms_present)
01418                         c *= 1 - 2 * cpe->ms_mask[idx];
01419                     scale = c * sce1->sf[idx];
01420                     for (group = 0; group < ics->group_len[g]; group++)
01421                         ac->dsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
01422                                                    coef0 + group * 128 + offsets[i],
01423                                                    scale,
01424                                                    offsets[i + 1] - offsets[i]);
01425                 }
01426             } else {
01427                 int bt_run_end = sce1->band_type_run_end[idx];
01428                 idx += bt_run_end - i;
01429                 i    = bt_run_end;
01430             }
01431         }
01432         coef0 += ics->group_len[g] * 128;
01433         coef1 += ics->group_len[g] * 128;
01434     }
01435 }
01436 
01442 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
01443 {
01444     int i, ret, common_window, ms_present = 0;
01445 
01446     common_window = get_bits1(gb);
01447     if (common_window) {
01448         if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
01449             return -1;
01450         i = cpe->ch[1].ics.use_kb_window[0];
01451         cpe->ch[1].ics = cpe->ch[0].ics;
01452         cpe->ch[1].ics.use_kb_window[1] = i;
01453         if (cpe->ch[1].ics.predictor_present && (ac->m4ac.object_type != AOT_AAC_MAIN))
01454             if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
01455                 decode_ltp(ac, &cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
01456         ms_present = get_bits(gb, 2);
01457         if (ms_present == 3) {
01458             av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
01459             return -1;
01460         } else if (ms_present)
01461             decode_mid_side_stereo(cpe, gb, ms_present);
01462     }
01463     if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
01464         return ret;
01465     if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
01466         return ret;
01467 
01468     if (common_window) {
01469         if (ms_present)
01470             apply_mid_side_stereo(ac, cpe);
01471         if (ac->m4ac.object_type == AOT_AAC_MAIN) {
01472             apply_prediction(ac, &cpe->ch[0]);
01473             apply_prediction(ac, &cpe->ch[1]);
01474         }
01475     }
01476 
01477     apply_intensity_stereo(ac, cpe, ms_present);
01478     return 0;
01479 }
01480 
01481 static const float cce_scale[] = {
01482     1.09050773266525765921, //2^(1/8)
01483     1.18920711500272106672, //2^(1/4)
01484     M_SQRT2,
01485     2,
01486 };
01487 
01493 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
01494 {
01495     int num_gain = 0;
01496     int c, g, sfb, ret;
01497     int sign;
01498     float scale;
01499     SingleChannelElement *sce = &che->ch[0];
01500     ChannelCoupling     *coup = &che->coup;
01501 
01502     coup->coupling_point = 2 * get_bits1(gb);
01503     coup->num_coupled = get_bits(gb, 3);
01504     for (c = 0; c <= coup->num_coupled; c++) {
01505         num_gain++;
01506         coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
01507         coup->id_select[c] = get_bits(gb, 4);
01508         if (coup->type[c] == TYPE_CPE) {
01509             coup->ch_select[c] = get_bits(gb, 2);
01510             if (coup->ch_select[c] == 3)
01511                 num_gain++;
01512         } else
01513             coup->ch_select[c] = 2;
01514     }
01515     coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
01516 
01517     sign  = get_bits(gb, 1);
01518     scale = cce_scale[get_bits(gb, 2)];
01519 
01520     if ((ret = decode_ics(ac, sce, gb, 0, 0)))
01521         return ret;
01522 
01523     for (c = 0; c < num_gain; c++) {
01524         int idx  = 0;
01525         int cge  = 1;
01526         int gain = 0;
01527         float gain_cache = 1.;
01528         if (c) {
01529             cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
01530             gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
01531             gain_cache = powf(scale, -gain);
01532         }
01533         if (coup->coupling_point == AFTER_IMDCT) {
01534             coup->gain[c][0] = gain_cache;
01535         } else {
01536             for (g = 0; g < sce->ics.num_window_groups; g++) {
01537                 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
01538                     if (sce->band_type[idx] != ZERO_BT) {
01539                         if (!cge) {
01540                             int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
01541                             if (t) {
01542                                 int s = 1;
01543                                 t = gain += t;
01544                                 if (sign) {
01545                                     s  -= 2 * (t & 0x1);
01546                                     t >>= 1;
01547                                 }
01548                                 gain_cache = powf(scale, -t) * s;
01549                             }
01550                         }
01551                         coup->gain[c][idx] = gain_cache;
01552                     }
01553                 }
01554             }
01555         }
01556     }
01557     return 0;
01558 }
01559 
01565 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
01566                                          GetBitContext *gb)
01567 {
01568     int i;
01569     int num_excl_chan = 0;
01570 
01571     do {
01572         for (i = 0; i < 7; i++)
01573             che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
01574     } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
01575 
01576     return num_excl_chan / 7;
01577 }
01578 
01586 static int decode_dynamic_range(DynamicRangeControl *che_drc,
01587                                 GetBitContext *gb, int cnt)
01588 {
01589     int n             = 1;
01590     int drc_num_bands = 1;
01591     int i;
01592 
01593     /* pce_tag_present? */
01594     if (get_bits1(gb)) {
01595         che_drc->pce_instance_tag  = get_bits(gb, 4);
01596         skip_bits(gb, 4); // tag_reserved_bits
01597         n++;
01598     }
01599 
01600     /* excluded_chns_present? */
01601     if (get_bits1(gb)) {
01602         n += decode_drc_channel_exclusions(che_drc, gb);
01603     }
01604 
01605     /* drc_bands_present? */
01606     if (get_bits1(gb)) {
01607         che_drc->band_incr            = get_bits(gb, 4);
01608         che_drc->interpolation_scheme = get_bits(gb, 4);
01609         n++;
01610         drc_num_bands += che_drc->band_incr;
01611         for (i = 0; i < drc_num_bands; i++) {
01612             che_drc->band_top[i] = get_bits(gb, 8);
01613             n++;
01614         }
01615     }
01616 
01617     /* prog_ref_level_present? */
01618     if (get_bits1(gb)) {
01619         che_drc->prog_ref_level = get_bits(gb, 7);
01620         skip_bits1(gb); // prog_ref_level_reserved_bits
01621         n++;
01622     }
01623 
01624     for (i = 0; i < drc_num_bands; i++) {
01625         che_drc->dyn_rng_sgn[i] = get_bits1(gb);
01626         che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
01627         n++;
01628     }
01629 
01630     return n;
01631 }
01632 
01640 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
01641                                     ChannelElement *che, enum RawDataBlockType elem_type)
01642 {
01643     int crc_flag = 0;
01644     int res = cnt;
01645     switch (get_bits(gb, 4)) { // extension type
01646     case EXT_SBR_DATA_CRC:
01647         crc_flag++;
01648     case EXT_SBR_DATA:
01649         if (!che) {
01650             av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
01651             return res;
01652         } else if (!ac->m4ac.sbr) {
01653             av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
01654             skip_bits_long(gb, 8 * cnt - 4);
01655             return res;
01656         } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
01657             av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
01658             skip_bits_long(gb, 8 * cnt - 4);
01659             return res;
01660         } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
01661             ac->m4ac.sbr = 1;
01662             ac->m4ac.ps = 1;
01663             output_configure(ac, ac->che_pos, ac->che_pos, ac->m4ac.chan_config, ac->output_configured);
01664         } else {
01665             ac->m4ac.sbr = 1;
01666         }
01667         res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
01668         break;
01669     case EXT_DYNAMIC_RANGE:
01670         res = decode_dynamic_range(&ac->che_drc, gb, cnt);
01671         break;
01672     case EXT_FILL:
01673     case EXT_FILL_DATA:
01674     case EXT_DATA_ELEMENT:
01675     default:
01676         skip_bits_long(gb, 8 * cnt - 4);
01677         break;
01678     };
01679     return res;
01680 }
01681 
01688 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
01689                       IndividualChannelStream *ics, int decode)
01690 {
01691     const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
01692     int w, filt, m, i;
01693     int bottom, top, order, start, end, size, inc;
01694     float lpc[TNS_MAX_ORDER];
01695     float tmp[TNS_MAX_ORDER];
01696 
01697     for (w = 0; w < ics->num_windows; w++) {
01698         bottom = ics->num_swb;
01699         for (filt = 0; filt < tns->n_filt[w]; filt++) {
01700             top    = bottom;
01701             bottom = FFMAX(0, top - tns->length[w][filt]);
01702             order  = tns->order[w][filt];
01703             if (order == 0)
01704                 continue;
01705 
01706             // tns_decode_coef
01707             compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
01708 
01709             start = ics->swb_offset[FFMIN(bottom, mmm)];
01710             end   = ics->swb_offset[FFMIN(   top, mmm)];
01711             if ((size = end - start) <= 0)
01712                 continue;
01713             if (tns->direction[w][filt]) {
01714                 inc = -1;
01715                 start = end - 1;
01716             } else {
01717                 inc = 1;
01718             }
01719             start += w * 128;
01720 
01721             if (decode) {
01722                 // ar filter
01723                 for (m = 0; m < size; m++, start += inc)
01724                     for (i = 1; i <= FFMIN(m, order); i++)
01725                         coef[start] -= coef[start - i * inc] * lpc[i - 1];
01726             } else {
01727                 // ma filter
01728                 for (m = 0; m < size; m++, start += inc) {
01729                     tmp[0] = coef[start];
01730                     for (i = 1; i <= FFMIN(m, order); i++)
01731                         coef[start] += tmp[i] * lpc[i - 1];
01732                     for (i = order; i > 0; i--)
01733                         tmp[i] = tmp[i - 1];
01734                 }
01735             }
01736         }
01737     }
01738 }
01739 
01744 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
01745                                    float *in, IndividualChannelStream *ics)
01746 {
01747     const float *lwindow      = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01748     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
01749     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01750     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
01751 
01752     if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
01753         ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);
01754     } else {
01755         memset(in, 0, 448 * sizeof(float));
01756         ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
01757     }
01758     if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
01759         ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
01760     } else {
01761         ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
01762         memset(in + 1024 + 576, 0, 448 * sizeof(float));
01763     }
01764     ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
01765 }
01766 
01770 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
01771 {
01772     const LongTermPrediction *ltp = &sce->ics.ltp;
01773     const uint16_t *offsets = sce->ics.swb_offset;
01774     int i, sfb;
01775 
01776     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
01777         float *predTime = sce->ret;
01778         float *predFreq = ac->buf_mdct;
01779         int16_t num_samples = 2048;
01780 
01781         if (ltp->lag < 1024)
01782             num_samples = ltp->lag + 1024;
01783         for (i = 0; i < num_samples; i++)
01784             predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
01785         memset(&predTime[i], 0, (2048 - i) * sizeof(float));
01786 
01787         windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
01788 
01789         if (sce->tns.present)
01790             apply_tns(predFreq, &sce->tns, &sce->ics, 0);
01791 
01792         for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
01793             if (ltp->used[sfb])
01794                 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
01795                     sce->coeffs[i] += predFreq[i];
01796     }
01797 }
01798 
01802 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
01803 {
01804     IndividualChannelStream *ics = &sce->ics;
01805     float *saved     = sce->saved;
01806     float *saved_ltp = sce->coeffs;
01807     const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01808     const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
01809     int i;
01810 
01811     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01812         memcpy(saved_ltp,       saved, 512 * sizeof(float));
01813         memset(saved_ltp + 576, 0,     448 * sizeof(float));
01814         ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
01815         for (i = 0; i < 64; i++)
01816             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
01817     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
01818         memcpy(saved_ltp,       ac->buf_mdct + 512, 448 * sizeof(float));
01819         memset(saved_ltp + 576, 0,                  448 * sizeof(float));
01820         ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
01821         for (i = 0; i < 64; i++)
01822             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
01823     } else { // LONG_STOP or ONLY_LONG
01824         ac->dsp.vector_fmul_reverse(saved_ltp,       ac->buf_mdct + 512,     &lwindow[512],     512);
01825         for (i = 0; i < 512; i++)
01826             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
01827     }
01828 
01829     memcpy(sce->ltp_state,      sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
01830     memcpy(sce->ltp_state+1024, sce->ret,            1024 * sizeof(*sce->ltp_state));
01831     memcpy(sce->ltp_state+2048, saved_ltp,           1024 * sizeof(*sce->ltp_state));
01832 }
01833 
01837 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
01838 {
01839     IndividualChannelStream *ics = &sce->ics;
01840     float *in    = sce->coeffs;
01841     float *out   = sce->ret;
01842     float *saved = sce->saved;
01843     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
01844     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01845     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
01846     float *buf  = ac->buf_mdct;
01847     float *temp = ac->temp;
01848     int i;
01849 
01850     // imdct
01851     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01852         for (i = 0; i < 1024; i += 128)
01853             ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
01854     } else
01855         ac->mdct.imdct_half(&ac->mdct, buf, in);
01856 
01857     /* window overlapping
01858      * NOTE: To simplify the overlapping code, all 'meaningless' short to long
01859      * and long to short transitions are considered to be short to short
01860      * transitions. This leaves just two cases (long to long and short to short)
01861      * with a little special sauce for EIGHT_SHORT_SEQUENCE.
01862      */
01863     if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
01864             (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
01865         ac->dsp.vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 512);
01866     } else {
01867         memcpy(                        out,               saved,            448 * sizeof(float));
01868 
01869         if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01870             ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, 64);
01871             ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      64);
01872             ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      64);
01873             ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      64);
01874             ac->dsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      64);
01875             memcpy(                    out + 448 + 4*128, temp, 64 * sizeof(float));
01876         } else {
01877             ac->dsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 64);
01878             memcpy(                    out + 576,         buf + 64,         448 * sizeof(float));
01879         }
01880     }
01881 
01882     // buffer update
01883     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01884         memcpy(                    saved,       temp + 64,         64 * sizeof(float));
01885         ac->dsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 64);
01886         ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
01887         ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
01888         memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
01889     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
01890         memcpy(                    saved,       buf + 512,        448 * sizeof(float));
01891         memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
01892     } else { // LONG_STOP or ONLY_LONG
01893         memcpy(                    saved,       buf + 512,        512 * sizeof(float));
01894     }
01895 }
01896 
01902 static void apply_dependent_coupling(AACContext *ac,
01903                                      SingleChannelElement *target,
01904                                      ChannelElement *cce, int index)
01905 {
01906     IndividualChannelStream *ics = &cce->ch[0].ics;
01907     const uint16_t *offsets = ics->swb_offset;
01908     float *dest = target->coeffs;
01909     const float *src = cce->ch[0].coeffs;
01910     int g, i, group, k, idx = 0;
01911     if (ac->m4ac.object_type == AOT_AAC_LTP) {
01912         av_log(ac->avctx, AV_LOG_ERROR,
01913                "Dependent coupling is not supported together with LTP\n");
01914         return;
01915     }
01916     for (g = 0; g < ics->num_window_groups; g++) {
01917         for (i = 0; i < ics->max_sfb; i++, idx++) {
01918             if (cce->ch[0].band_type[idx] != ZERO_BT) {
01919                 const float gain = cce->coup.gain[index][idx];
01920                 for (group = 0; group < ics->group_len[g]; group++) {
01921                     for (k = offsets[i]; k < offsets[i + 1]; k++) {
01922                         // XXX dsputil-ize
01923                         dest[group * 128 + k] += gain * src[group * 128 + k];
01924                     }
01925                 }
01926             }
01927         }
01928         dest += ics->group_len[g] * 128;
01929         src  += ics->group_len[g] * 128;
01930     }
01931 }
01932 
01938 static void apply_independent_coupling(AACContext *ac,
01939                                        SingleChannelElement *target,
01940                                        ChannelElement *cce, int index)
01941 {
01942     int i;
01943     const float gain = cce->coup.gain[index][0];
01944     const float *src = cce->ch[0].ret;
01945     float *dest = target->ret;
01946     const int len = 1024 << (ac->m4ac.sbr == 1);
01947 
01948     for (i = 0; i < len; i++)
01949         dest[i] += gain * src[i];
01950 }
01951 
01957 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
01958                                    enum RawDataBlockType type, int elem_id,
01959                                    enum CouplingPoint coupling_point,
01960                                    void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
01961 {
01962     int i, c;
01963 
01964     for (i = 0; i < MAX_ELEM_ID; i++) {
01965         ChannelElement *cce = ac->che[TYPE_CCE][i];
01966         int index = 0;
01967 
01968         if (cce && cce->coup.coupling_point == coupling_point) {
01969             ChannelCoupling *coup = &cce->coup;
01970 
01971             for (c = 0; c <= coup->num_coupled; c++) {
01972                 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
01973                     if (coup->ch_select[c] != 1) {
01974                         apply_coupling_method(ac, &cc->ch[0], cce, index);
01975                         if (coup->ch_select[c] != 0)
01976                             index++;
01977                     }
01978                     if (coup->ch_select[c] != 2)
01979                         apply_coupling_method(ac, &cc->ch[1], cce, index++);
01980                 } else
01981                     index += 1 + (coup->ch_select[c] == 3);
01982             }
01983         }
01984     }
01985 }
01986 
01990 static void spectral_to_sample(AACContext *ac)
01991 {
01992     int i, type;
01993     for (type = 3; type >= 0; type--) {
01994         for (i = 0; i < MAX_ELEM_ID; i++) {
01995             ChannelElement *che = ac->che[type][i];
01996             if (che) {
01997                 if (type <= TYPE_CPE)
01998                     apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
01999                 if (ac->m4ac.object_type == AOT_AAC_LTP) {
02000                     if (che->ch[0].ics.predictor_present) {
02001                         if (che->ch[0].ics.ltp.present)
02002                             apply_ltp(ac, &che->ch[0]);
02003                         if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
02004                             apply_ltp(ac, &che->ch[1]);
02005                     }
02006                 }
02007                 if (che->ch[0].tns.present)
02008                     apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
02009                 if (che->ch[1].tns.present)
02010                     apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
02011                 if (type <= TYPE_CPE)
02012                     apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
02013                 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
02014                     imdct_and_windowing(ac, &che->ch[0]);
02015                     if (ac->m4ac.object_type == AOT_AAC_LTP)
02016                         update_ltp(ac, &che->ch[0]);
02017                     if (type == TYPE_CPE) {
02018                         imdct_and_windowing(ac, &che->ch[1]);
02019                         if (ac->m4ac.object_type == AOT_AAC_LTP)
02020                             update_ltp(ac, &che->ch[1]);
02021                     }
02022                     if (ac->m4ac.sbr > 0) {
02023                         ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
02024                     }
02025                 }
02026                 if (type <= TYPE_CCE)
02027                     apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
02028             }
02029         }
02030     }
02031 }
02032 
02033 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
02034 {
02035     int size;
02036     AACADTSHeaderInfo hdr_info;
02037 
02038     size = ff_aac_parse_header(gb, &hdr_info);
02039     if (size > 0) {
02040         if (ac->output_configured != OC_LOCKED && hdr_info.chan_config) {
02041             enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
02042             memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
02043             ac->m4ac.chan_config = hdr_info.chan_config;
02044             if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
02045                 return -7;
02046             if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config, OC_TRIAL_FRAME))
02047                 return -7;
02048         } else if (ac->output_configured != OC_LOCKED) {
02049             ac->output_configured = OC_NONE;
02050         }
02051         if (ac->output_configured != OC_LOCKED) {
02052             ac->m4ac.sbr = -1;
02053             ac->m4ac.ps  = -1;
02054         }
02055         ac->m4ac.sample_rate     = hdr_info.sample_rate;
02056         ac->m4ac.sampling_index  = hdr_info.sampling_index;
02057         ac->m4ac.object_type     = hdr_info.object_type;
02058         if (!ac->avctx->sample_rate)
02059             ac->avctx->sample_rate = hdr_info.sample_rate;
02060         if (hdr_info.num_aac_frames == 1) {
02061             if (!hdr_info.crc_absent)
02062                 skip_bits(gb, 16);
02063         } else {
02064             av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
02065             return -1;
02066         }
02067     }
02068     return size;
02069 }
02070 
02071 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
02072                                 int *data_size, GetBitContext *gb)
02073 {
02074     AACContext *ac = avctx->priv_data;
02075     ChannelElement *che = NULL, *che_prev = NULL;
02076     enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
02077     int err, elem_id, data_size_tmp;
02078     int samples = 0, multiplier, audio_found = 0;
02079 
02080     if (show_bits(gb, 12) == 0xfff) {
02081         if (parse_adts_frame_header(ac, gb) < 0) {
02082             av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
02083             return -1;
02084         }
02085         if (ac->m4ac.sampling_index > 12) {
02086             av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
02087             return -1;
02088         }
02089     }
02090 
02091     ac->tags_mapped = 0;
02092     // parse
02093     while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
02094         elem_id = get_bits(gb, 4);
02095 
02096         if (elem_type < TYPE_DSE) {
02097             if (!(che=get_che(ac, elem_type, elem_id))) {
02098                 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
02099                        elem_type, elem_id);
02100                 return -1;
02101             }
02102             samples = 1024;
02103         }
02104 
02105         switch (elem_type) {
02106 
02107         case TYPE_SCE:
02108             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
02109             audio_found = 1;
02110             break;
02111 
02112         case TYPE_CPE:
02113             err = decode_cpe(ac, gb, che);
02114             audio_found = 1;
02115             break;
02116 
02117         case TYPE_CCE:
02118             err = decode_cce(ac, gb, che);
02119             break;
02120 
02121         case TYPE_LFE:
02122             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
02123             audio_found = 1;
02124             break;
02125 
02126         case TYPE_DSE:
02127             err = skip_data_stream_element(ac, gb);
02128             break;
02129 
02130         case TYPE_PCE: {
02131             enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
02132             memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
02133             if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
02134                 break;
02135             if (ac->output_configured > OC_TRIAL_PCE)
02136                 av_log(avctx, AV_LOG_ERROR,
02137                        "Not evaluating a further program_config_element as this construct is dubious at best.\n");
02138             else
02139                 err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
02140             break;
02141         }
02142 
02143         case TYPE_FIL:
02144             if (elem_id == 15)
02145                 elem_id += get_bits(gb, 8) - 1;
02146             if (get_bits_left(gb) < 8 * elem_id) {
02147                     av_log(avctx, AV_LOG_ERROR, overread_err);
02148                     return -1;
02149             }
02150             while (elem_id > 0)
02151                 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
02152             err = 0; /* FIXME */
02153             break;
02154 
02155         default:
02156             err = -1; /* should not happen, but keeps compiler happy */
02157             break;
02158         }
02159 
02160         che_prev       = che;
02161         elem_type_prev = elem_type;
02162 
02163         if (err)
02164             return err;
02165 
02166         if (get_bits_left(gb) < 3) {
02167             av_log(avctx, AV_LOG_ERROR, overread_err);
02168             return -1;
02169         }
02170     }
02171 
02172     spectral_to_sample(ac);
02173 
02174     multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
02175     samples <<= multiplier;
02176     if (ac->output_configured < OC_LOCKED) {
02177         avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
02178         avctx->frame_size = samples;
02179     }
02180 
02181     data_size_tmp = samples * avctx->channels *
02182                     (av_get_bits_per_sample_fmt(avctx->sample_fmt) / 8);
02183     if (*data_size < data_size_tmp) {
02184         av_log(avctx, AV_LOG_ERROR,
02185                "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
02186                *data_size, data_size_tmp);
02187         return -1;
02188     }
02189     *data_size = data_size_tmp;
02190 
02191     if (samples) {
02192         if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
02193             ac->fmt_conv.float_interleave(data, (const float **)ac->output_data,
02194                                           samples, avctx->channels);
02195         else
02196             ac->fmt_conv.float_to_int16_interleave(data, (const float **)ac->output_data,
02197                                                    samples, avctx->channels);
02198     }
02199 
02200     if (ac->output_configured && audio_found)
02201         ac->output_configured = OC_LOCKED;
02202 
02203     return 0;
02204 }
02205 
02206 static int aac_decode_frame(AVCodecContext *avctx, void *data,
02207                             int *data_size, AVPacket *avpkt)
02208 {
02209     const uint8_t *buf = avpkt->data;
02210     int buf_size = avpkt->size;
02211     GetBitContext gb;
02212     int buf_consumed;
02213     int buf_offset;
02214     int err;
02215 
02216     init_get_bits(&gb, buf, buf_size * 8);
02217 
02218     if ((err = aac_decode_frame_int(avctx, data, data_size, &gb)) < 0)
02219         return err;
02220 
02221     buf_consumed = (get_bits_count(&gb) + 7) >> 3;
02222     for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
02223         if (buf[buf_offset])
02224             break;
02225 
02226     return buf_size > buf_offset ? buf_consumed : buf_size;
02227 }
02228 
02229 static av_cold int aac_decode_close(AVCodecContext *avctx)
02230 {
02231     AACContext *ac = avctx->priv_data;
02232     int i, type;
02233 
02234     for (i = 0; i < MAX_ELEM_ID; i++) {
02235         for (type = 0; type < 4; type++) {
02236             if (ac->che[type][i])
02237                 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
02238             av_freep(&ac->che[type][i]);
02239         }
02240     }
02241 
02242     ff_mdct_end(&ac->mdct);
02243     ff_mdct_end(&ac->mdct_small);
02244     ff_mdct_end(&ac->mdct_ltp);
02245     return 0;
02246 }
02247 
02248 
02249 #define LOAS_SYNC_WORD   0x2b7       ///< 11 bits LOAS sync word
02250 
02251 struct LATMContext {
02252     AACContext      aac_ctx;             
02253     int             initialized;         
02254 
02255     // parser data
02256     int             audio_mux_version_A; 
02257     int             frame_length_type;   
02258     int             frame_length;        
02259 };
02260 
02261 static inline uint32_t latm_get_value(GetBitContext *b)
02262 {
02263     int length = get_bits(b, 2);
02264 
02265     return get_bits_long(b, (length+1)*8);
02266 }
02267 
02268 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
02269                                              GetBitContext *gb)
02270 {
02271     AVCodecContext *avctx = latmctx->aac_ctx.avctx;
02272     MPEG4AudioConfig m4ac;
02273     int  config_start_bit = get_bits_count(gb);
02274     int     bits_consumed, esize;
02275 
02276     if (config_start_bit % 8) {
02277         av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
02278                                "config not byte aligned.\n", 1);
02279         return AVERROR_INVALIDDATA;
02280     } else {
02281         bits_consumed =
02282             decode_audio_specific_config(NULL, avctx, &m4ac,
02283                                          gb->buffer + (config_start_bit / 8),
02284                                          get_bits_left(gb) / 8);
02285 
02286         if (bits_consumed < 0)
02287             return AVERROR_INVALIDDATA;
02288 
02289         esize = (bits_consumed+7) / 8;
02290 
02291         if (avctx->extradata_size <= esize) {
02292             av_free(avctx->extradata);
02293             avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
02294             if (!avctx->extradata)
02295                 return AVERROR(ENOMEM);
02296         }
02297 
02298         avctx->extradata_size = esize;
02299         memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
02300         memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
02301 
02302         skip_bits_long(gb, bits_consumed);
02303     }
02304 
02305     return bits_consumed;
02306 }
02307 
02308 static int read_stream_mux_config(struct LATMContext *latmctx,
02309                                   GetBitContext *gb)
02310 {
02311     int ret, audio_mux_version = get_bits(gb, 1);
02312 
02313     latmctx->audio_mux_version_A = 0;
02314     if (audio_mux_version)
02315         latmctx->audio_mux_version_A = get_bits(gb, 1);
02316 
02317     if (!latmctx->audio_mux_version_A) {
02318 
02319         if (audio_mux_version)
02320             latm_get_value(gb);                 // taraFullness
02321 
02322         skip_bits(gb, 1);                       // allStreamSameTimeFraming
02323         skip_bits(gb, 6);                       // numSubFrames
02324         // numPrograms
02325         if (get_bits(gb, 4)) {                  // numPrograms
02326             av_log_missing_feature(latmctx->aac_ctx.avctx,
02327                                    "multiple programs are not supported\n", 1);
02328             return AVERROR_PATCHWELCOME;
02329         }
02330 
02331         // for each program (which there is only on in DVB)
02332 
02333         // for each layer (which there is only on in DVB)
02334         if (get_bits(gb, 3)) {                   // numLayer
02335             av_log_missing_feature(latmctx->aac_ctx.avctx,
02336                                    "multiple layers are not supported\n", 1);
02337             return AVERROR_PATCHWELCOME;
02338         }
02339 
02340         // for all but first stream: use_same_config = get_bits(gb, 1);
02341         if (!audio_mux_version) {
02342             if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
02343                 return ret;
02344         } else {
02345             int ascLen = latm_get_value(gb);
02346             if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
02347                 return ret;
02348             ascLen -= ret;
02349             skip_bits_long(gb, ascLen);
02350         }
02351 
02352         latmctx->frame_length_type = get_bits(gb, 3);
02353         switch (latmctx->frame_length_type) {
02354         case 0:
02355             skip_bits(gb, 8);       // latmBufferFullness
02356             break;
02357         case 1:
02358             latmctx->frame_length = get_bits(gb, 9);
02359             break;
02360         case 3:
02361         case 4:
02362         case 5:
02363             skip_bits(gb, 6);       // CELP frame length table index
02364             break;
02365         case 6:
02366         case 7:
02367             skip_bits(gb, 1);       // HVXC frame length table index
02368             break;
02369         }
02370 
02371         if (get_bits(gb, 1)) {                  // other data
02372             if (audio_mux_version) {
02373                 latm_get_value(gb);             // other_data_bits
02374             } else {
02375                 int esc;
02376                 do {
02377                     esc = get_bits(gb, 1);
02378                     skip_bits(gb, 8);
02379                 } while (esc);
02380             }
02381         }
02382 
02383         if (get_bits(gb, 1))                     // crc present
02384             skip_bits(gb, 8);                    // config_crc
02385     }
02386 
02387     return 0;
02388 }
02389 
02390 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
02391 {
02392     uint8_t tmp;
02393 
02394     if (ctx->frame_length_type == 0) {
02395         int mux_slot_length = 0;
02396         do {
02397             tmp = get_bits(gb, 8);
02398             mux_slot_length += tmp;
02399         } while (tmp == 255);
02400         return mux_slot_length;
02401     } else if (ctx->frame_length_type == 1) {
02402         return ctx->frame_length;
02403     } else if (ctx->frame_length_type == 3 ||
02404                ctx->frame_length_type == 5 ||
02405                ctx->frame_length_type == 7) {
02406         skip_bits(gb, 2);          // mux_slot_length_coded
02407     }
02408     return 0;
02409 }
02410 
02411 static int read_audio_mux_element(struct LATMContext *latmctx,
02412                                   GetBitContext *gb)
02413 {
02414     int err;
02415     uint8_t use_same_mux = get_bits(gb, 1);
02416     if (!use_same_mux) {
02417         if ((err = read_stream_mux_config(latmctx, gb)) < 0)
02418             return err;
02419     } else if (!latmctx->aac_ctx.avctx->extradata) {
02420         av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
02421                "no decoder config found\n");
02422         return AVERROR(EAGAIN);
02423     }
02424     if (latmctx->audio_mux_version_A == 0) {
02425         int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
02426         if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
02427             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
02428             return AVERROR_INVALIDDATA;
02429         } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
02430             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
02431                    "frame length mismatch %d << %d\n",
02432                    mux_slot_length_bytes * 8, get_bits_left(gb));
02433             return AVERROR_INVALIDDATA;
02434         }
02435     }
02436     return 0;
02437 }
02438 
02439 
02440 static int latm_decode_frame(AVCodecContext *avctx, void *out, int *out_size,
02441                              AVPacket *avpkt)
02442 {
02443     struct LATMContext *latmctx = avctx->priv_data;
02444     int                 muxlength, err;
02445     GetBitContext       gb;
02446 
02447     if (avpkt->size == 0)
02448         return 0;
02449 
02450     init_get_bits(&gb, avpkt->data, avpkt->size * 8);
02451 
02452     // check for LOAS sync word
02453     if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
02454         return AVERROR_INVALIDDATA;
02455 
02456     muxlength = get_bits(&gb, 13) + 3;
02457     // not enough data, the parser should have sorted this
02458     if (muxlength > avpkt->size)
02459         return AVERROR_INVALIDDATA;
02460 
02461     if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
02462         return err;
02463 
02464     if (!latmctx->initialized) {
02465         if (!avctx->extradata) {
02466             *out_size = 0;
02467             return avpkt->size;
02468         } else {
02469             aac_decode_close(avctx);
02470             if ((err = aac_decode_init(avctx)) < 0)
02471                 return err;
02472             latmctx->initialized = 1;
02473         }
02474     }
02475 
02476     if (show_bits(&gb, 12) == 0xfff) {
02477         av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
02478                "ADTS header detected, probably as result of configuration "
02479                "misparsing\n");
02480         return AVERROR_INVALIDDATA;
02481     }
02482 
02483     if ((err = aac_decode_frame_int(avctx, out, out_size, &gb)) < 0)
02484         return err;
02485 
02486     return muxlength;
02487 }
02488 
02489 av_cold static int latm_decode_init(AVCodecContext *avctx)
02490 {
02491     struct LATMContext *latmctx = avctx->priv_data;
02492     int ret;
02493 
02494     ret = aac_decode_init(avctx);
02495 
02496     if (avctx->extradata_size > 0) {
02497         latmctx->initialized = !ret;
02498     } else {
02499         latmctx->initialized = 0;
02500     }
02501 
02502     return ret;
02503 }
02504 
02505 
02506 AVCodec ff_aac_decoder = {
02507     "aac",
02508     AVMEDIA_TYPE_AUDIO,
02509     CODEC_ID_AAC,
02510     sizeof(AACContext),
02511     aac_decode_init,
02512     NULL,
02513     aac_decode_close,
02514     aac_decode_frame,
02515     .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
02516     .sample_fmts = (const enum AVSampleFormat[]) {
02517         AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
02518     },
02519     .channel_layouts = aac_channel_layout,
02520 };
02521 
02522 /*
02523     Note: This decoder filter is intended to decode LATM streams transferred
02524     in MPEG transport streams which only contain one program.
02525     To do a more complex LATM demuxing a separate LATM demuxer should be used.
02526 */
02527 AVCodec ff_aac_latm_decoder = {
02528     .name = "aac_latm",
02529     .type = AVMEDIA_TYPE_AUDIO,
02530     .id   = CODEC_ID_AAC_LATM,
02531     .priv_data_size = sizeof(struct LATMContext),
02532     .init   = latm_decode_init,
02533     .close  = aac_decode_close,
02534     .decode = latm_decode_frame,
02535     .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
02536     .sample_fmts = (const enum AVSampleFormat[]) {
02537         AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
02538     },
02539     .channel_layouts = aac_channel_layout,
02540 };