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             while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
00756                 sect_end += sect_len_incr;
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             for (; k < sect_end; k++) {
00769                 band_type        [idx]   = sect_band_type;
00770                 band_type_run_end[idx++] = sect_end;
00771             }
00772         }
00773     }
00774     return 0;
00775 }
00776 
00787 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
00788                                unsigned int global_gain,
00789                                IndividualChannelStream *ics,
00790                                enum BandType band_type[120],
00791                                int band_type_run_end[120])
00792 {
00793     int g, i, idx = 0;
00794     int offset[3] = { global_gain, global_gain - 90, 0 };
00795     int clipped_offset;
00796     int noise_flag = 1;
00797     static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
00798     for (g = 0; g < ics->num_window_groups; g++) {
00799         for (i = 0; i < ics->max_sfb;) {
00800             int run_end = band_type_run_end[idx];
00801             if (band_type[idx] == ZERO_BT) {
00802                 for (; i < run_end; i++, idx++)
00803                     sf[idx] = 0.;
00804             } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
00805                 for (; i < run_end; i++, idx++) {
00806                     offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
00807                     clipped_offset = av_clip(offset[2], -155, 100);
00808                     if (offset[2] != clipped_offset) {
00809                         av_log_ask_for_sample(ac->avctx, "Intensity stereo "
00810                                 "position clipped (%d -> %d).\nIf you heard an "
00811                                 "audible artifact, there may be a bug in the "
00812                                 "decoder. ", offset[2], clipped_offset);
00813                     }
00814                     sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
00815                 }
00816             } else if (band_type[idx] == NOISE_BT) {
00817                 for (; i < run_end; i++, idx++) {
00818                     if (noise_flag-- > 0)
00819                         offset[1] += get_bits(gb, 9) - 256;
00820                     else
00821                         offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
00822                     clipped_offset = av_clip(offset[1], -100, 155);
00823                     if (offset[1] != clipped_offset) {
00824                         av_log_ask_for_sample(ac->avctx, "Noise gain clipped "
00825                                 "(%d -> %d).\nIf you heard an audible "
00826                                 "artifact, there may be a bug in the decoder. ",
00827                                 offset[1], clipped_offset);
00828                     }
00829                     sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
00830                 }
00831             } else {
00832                 for (; i < run_end; i++, idx++) {
00833                     offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
00834                     if (offset[0] > 255U) {
00835                         av_log(ac->avctx, AV_LOG_ERROR,
00836                                "%s (%d) out of range.\n", sf_str[0], offset[0]);
00837                         return -1;
00838                     }
00839                     sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
00840                 }
00841             }
00842         }
00843     }
00844     return 0;
00845 }
00846 
00850 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
00851                          const uint16_t *swb_offset, int num_swb)
00852 {
00853     int i, pulse_swb;
00854     pulse->num_pulse = get_bits(gb, 2) + 1;
00855     pulse_swb        = get_bits(gb, 6);
00856     if (pulse_swb >= num_swb)
00857         return -1;
00858     pulse->pos[0]    = swb_offset[pulse_swb];
00859     pulse->pos[0]   += get_bits(gb, 5);
00860     if (pulse->pos[0] > 1023)
00861         return -1;
00862     pulse->amp[0]    = get_bits(gb, 4);
00863     for (i = 1; i < pulse->num_pulse; i++) {
00864         pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
00865         if (pulse->pos[i] > 1023)
00866             return -1;
00867         pulse->amp[i] = get_bits(gb, 4);
00868     }
00869     return 0;
00870 }
00871 
00877 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
00878                       GetBitContext *gb, const IndividualChannelStream *ics)
00879 {
00880     int w, filt, i, coef_len, coef_res, coef_compress;
00881     const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
00882     const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
00883     for (w = 0; w < ics->num_windows; w++) {
00884         if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
00885             coef_res = get_bits1(gb);
00886 
00887             for (filt = 0; filt < tns->n_filt[w]; filt++) {
00888                 int tmp2_idx;
00889                 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
00890 
00891                 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
00892                     av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
00893                            tns->order[w][filt], tns_max_order);
00894                     tns->order[w][filt] = 0;
00895                     return -1;
00896                 }
00897                 if (tns->order[w][filt]) {
00898                     tns->direction[w][filt] = get_bits1(gb);
00899                     coef_compress = get_bits1(gb);
00900                     coef_len = coef_res + 3 - coef_compress;
00901                     tmp2_idx = 2 * coef_compress + coef_res;
00902 
00903                     for (i = 0; i < tns->order[w][filt]; i++)
00904                         tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
00905                 }
00906             }
00907         }
00908     }
00909     return 0;
00910 }
00911 
00919 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
00920                                    int ms_present)
00921 {
00922     int idx;
00923     if (ms_present == 1) {
00924         for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
00925             cpe->ms_mask[idx] = get_bits1(gb);
00926     } else if (ms_present == 2) {
00927         memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
00928     }
00929 }
00930 
00931 #ifndef VMUL2
00932 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
00933                            const float *scale)
00934 {
00935     float s = *scale;
00936     *dst++ = v[idx    & 15] * s;
00937     *dst++ = v[idx>>4 & 15] * s;
00938     return dst;
00939 }
00940 #endif
00941 
00942 #ifndef VMUL4
00943 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
00944                            const float *scale)
00945 {
00946     float s = *scale;
00947     *dst++ = v[idx    & 3] * s;
00948     *dst++ = v[idx>>2 & 3] * s;
00949     *dst++ = v[idx>>4 & 3] * s;
00950     *dst++ = v[idx>>6 & 3] * s;
00951     return dst;
00952 }
00953 #endif
00954 
00955 #ifndef VMUL2S
00956 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
00957                             unsigned sign, const float *scale)
00958 {
00959     union float754 s0, s1;
00960 
00961     s0.f = s1.f = *scale;
00962     s0.i ^= sign >> 1 << 31;
00963     s1.i ^= sign      << 31;
00964 
00965     *dst++ = v[idx    & 15] * s0.f;
00966     *dst++ = v[idx>>4 & 15] * s1.f;
00967 
00968     return dst;
00969 }
00970 #endif
00971 
00972 #ifndef VMUL4S
00973 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
00974                             unsigned sign, const float *scale)
00975 {
00976     unsigned nz = idx >> 12;
00977     union float754 s = { .f = *scale };
00978     union float754 t;
00979 
00980     t.i = s.i ^ (sign & 1U<<31);
00981     *dst++ = v[idx    & 3] * t.f;
00982 
00983     sign <<= nz & 1; nz >>= 1;
00984     t.i = s.i ^ (sign & 1U<<31);
00985     *dst++ = v[idx>>2 & 3] * t.f;
00986 
00987     sign <<= nz & 1; nz >>= 1;
00988     t.i = s.i ^ (sign & 1U<<31);
00989     *dst++ = v[idx>>4 & 3] * t.f;
00990 
00991     sign <<= nz & 1; nz >>= 1;
00992     t.i = s.i ^ (sign & 1U<<31);
00993     *dst++ = v[idx>>6 & 3] * t.f;
00994 
00995     return dst;
00996 }
00997 #endif
00998 
01011 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
01012                                        GetBitContext *gb, const float sf[120],
01013                                        int pulse_present, const Pulse *pulse,
01014                                        const IndividualChannelStream *ics,
01015                                        enum BandType band_type[120])
01016 {
01017     int i, k, g, idx = 0;
01018     const int c = 1024 / ics->num_windows;
01019     const uint16_t *offsets = ics->swb_offset;
01020     float *coef_base = coef;
01021 
01022     for (g = 0; g < ics->num_windows; g++)
01023         memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
01024 
01025     for (g = 0; g < ics->num_window_groups; g++) {
01026         unsigned g_len = ics->group_len[g];
01027 
01028         for (i = 0; i < ics->max_sfb; i++, idx++) {
01029             const unsigned cbt_m1 = band_type[idx] - 1;
01030             float *cfo = coef + offsets[i];
01031             int off_len = offsets[i + 1] - offsets[i];
01032             int group;
01033 
01034             if (cbt_m1 >= INTENSITY_BT2 - 1) {
01035                 for (group = 0; group < g_len; group++, cfo+=128) {
01036                     memset(cfo, 0, off_len * sizeof(float));
01037                 }
01038             } else if (cbt_m1 == NOISE_BT - 1) {
01039                 for (group = 0; group < g_len; group++, cfo+=128) {
01040                     float scale;
01041                     float band_energy;
01042 
01043                     for (k = 0; k < off_len; k++) {
01044                         ac->random_state  = lcg_random(ac->random_state);
01045                         cfo[k] = ac->random_state;
01046                     }
01047 
01048                     band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
01049                     scale = sf[idx] / sqrtf(band_energy);
01050                     ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
01051                 }
01052             } else {
01053                 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
01054                 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
01055                 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
01056                 OPEN_READER(re, gb);
01057 
01058                 switch (cbt_m1 >> 1) {
01059                 case 0:
01060                     for (group = 0; group < g_len; group++, cfo+=128) {
01061                         float *cf = cfo;
01062                         int len = off_len;
01063 
01064                         do {
01065                             int code;
01066                             unsigned cb_idx;
01067 
01068                             UPDATE_CACHE(re, gb);
01069                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01070                             cb_idx = cb_vector_idx[code];
01071                             cf = VMUL4(cf, vq, cb_idx, sf + idx);
01072                         } while (len -= 4);
01073                     }
01074                     break;
01075 
01076                 case 1:
01077                     for (group = 0; group < g_len; group++, cfo+=128) {
01078                         float *cf = cfo;
01079                         int len = off_len;
01080 
01081                         do {
01082                             int code;
01083                             unsigned nnz;
01084                             unsigned cb_idx;
01085                             uint32_t bits;
01086 
01087                             UPDATE_CACHE(re, gb);
01088                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01089                             cb_idx = cb_vector_idx[code];
01090                             nnz = cb_idx >> 8 & 15;
01091                             bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
01092                             LAST_SKIP_BITS(re, gb, nnz);
01093                             cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
01094                         } while (len -= 4);
01095                     }
01096                     break;
01097 
01098                 case 2:
01099                     for (group = 0; group < g_len; group++, cfo+=128) {
01100                         float *cf = cfo;
01101                         int len = off_len;
01102 
01103                         do {
01104                             int code;
01105                             unsigned cb_idx;
01106 
01107                             UPDATE_CACHE(re, gb);
01108                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01109                             cb_idx = cb_vector_idx[code];
01110                             cf = VMUL2(cf, vq, cb_idx, sf + idx);
01111                         } while (len -= 2);
01112                     }
01113                     break;
01114 
01115                 case 3:
01116                 case 4:
01117                     for (group = 0; group < g_len; group++, cfo+=128) {
01118                         float *cf = cfo;
01119                         int len = off_len;
01120 
01121                         do {
01122                             int code;
01123                             unsigned nnz;
01124                             unsigned cb_idx;
01125                             unsigned sign;
01126 
01127                             UPDATE_CACHE(re, gb);
01128                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01129                             cb_idx = cb_vector_idx[code];
01130                             nnz = cb_idx >> 8 & 15;
01131                             sign = SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12);
01132                             LAST_SKIP_BITS(re, gb, nnz);
01133                             cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
01134                         } while (len -= 2);
01135                     }
01136                     break;
01137 
01138                 default:
01139                     for (group = 0; group < g_len; group++, cfo+=128) {
01140                         float *cf = cfo;
01141                         uint32_t *icf = (uint32_t *) cf;
01142                         int len = off_len;
01143 
01144                         do {
01145                             int code;
01146                             unsigned nzt, nnz;
01147                             unsigned cb_idx;
01148                             uint32_t bits;
01149                             int j;
01150 
01151                             UPDATE_CACHE(re, gb);
01152                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01153 
01154                             if (!code) {
01155                                 *icf++ = 0;
01156                                 *icf++ = 0;
01157                                 continue;
01158                             }
01159 
01160                             cb_idx = cb_vector_idx[code];
01161                             nnz = cb_idx >> 12;
01162                             nzt = cb_idx >> 8;
01163                             bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
01164                             LAST_SKIP_BITS(re, gb, nnz);
01165 
01166                             for (j = 0; j < 2; j++) {
01167                                 if (nzt & 1<<j) {
01168                                     uint32_t b;
01169                                     int n;
01170                                     /* The total length of escape_sequence must be < 22 bits according
01171                                        to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
01172                                     UPDATE_CACHE(re, gb);
01173                                     b = GET_CACHE(re, gb);
01174                                     b = 31 - av_log2(~b);
01175 
01176                                     if (b > 8) {
01177                                         av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
01178                                         return -1;
01179                                     }
01180 
01181                                     SKIP_BITS(re, gb, b + 1);
01182                                     b += 4;
01183                                     n = (1 << b) + SHOW_UBITS(re, gb, b);
01184                                     LAST_SKIP_BITS(re, gb, b);
01185                                     *icf++ = cbrt_tab[n] | (bits & 1U<<31);
01186                                     bits <<= 1;
01187                                 } else {
01188                                     unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
01189                                     *icf++ = (bits & 1U<<31) | v;
01190                                     bits <<= !!v;
01191                                 }
01192                                 cb_idx >>= 4;
01193                             }
01194                         } while (len -= 2);
01195 
01196                         ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
01197                     }
01198                 }
01199 
01200                 CLOSE_READER(re, gb);
01201             }
01202         }
01203         coef += g_len << 7;
01204     }
01205 
01206     if (pulse_present) {
01207         idx = 0;
01208         for (i = 0; i < pulse->num_pulse; i++) {
01209             float co = coef_base[ pulse->pos[i] ];
01210             while (offsets[idx + 1] <= pulse->pos[i])
01211                 idx++;
01212             if (band_type[idx] != NOISE_BT && sf[idx]) {
01213                 float ico = -pulse->amp[i];
01214                 if (co) {
01215                     co /= sf[idx];
01216                     ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
01217                 }
01218                 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
01219             }
01220         }
01221     }
01222     return 0;
01223 }
01224 
01225 static av_always_inline float flt16_round(float pf)
01226 {
01227     union float754 tmp;
01228     tmp.f = pf;
01229     tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
01230     return tmp.f;
01231 }
01232 
01233 static av_always_inline float flt16_even(float pf)
01234 {
01235     union float754 tmp;
01236     tmp.f = pf;
01237     tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
01238     return tmp.f;
01239 }
01240 
01241 static av_always_inline float flt16_trunc(float pf)
01242 {
01243     union float754 pun;
01244     pun.f = pf;
01245     pun.i &= 0xFFFF0000U;
01246     return pun.f;
01247 }
01248 
01249 static av_always_inline void predict(PredictorState *ps, float *coef,
01250                                      int output_enable)
01251 {
01252     const float a     = 0.953125; // 61.0 / 64
01253     const float alpha = 0.90625;  // 29.0 / 32
01254     float e0, e1;
01255     float pv;
01256     float k1, k2;
01257     float   r0 = ps->r0,     r1 = ps->r1;
01258     float cor0 = ps->cor0, cor1 = ps->cor1;
01259     float var0 = ps->var0, var1 = ps->var1;
01260 
01261     k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
01262     k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
01263 
01264     pv = flt16_round(k1 * r0 + k2 * r1);
01265     if (output_enable)
01266         *coef += pv;
01267 
01268     e0 = *coef;
01269     e1 = e0 - k1 * r0;
01270 
01271     ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
01272     ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
01273     ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
01274     ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
01275 
01276     ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
01277     ps->r0 = flt16_trunc(a * e0);
01278 }
01279 
01283 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
01284 {
01285     int sfb, k;
01286 
01287     if (!sce->ics.predictor_initialized) {
01288         reset_all_predictors(sce->predictor_state);
01289         sce->ics.predictor_initialized = 1;
01290     }
01291 
01292     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
01293         for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
01294             for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
01295                 predict(&sce->predictor_state[k], &sce->coeffs[k],
01296                         sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
01297             }
01298         }
01299         if (sce->ics.predictor_reset_group)
01300             reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
01301     } else
01302         reset_all_predictors(sce->predictor_state);
01303 }
01304 
01313 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
01314                       GetBitContext *gb, int common_window, int scale_flag)
01315 {
01316     Pulse pulse;
01317     TemporalNoiseShaping    *tns = &sce->tns;
01318     IndividualChannelStream *ics = &sce->ics;
01319     float *out = sce->coeffs;
01320     int global_gain, pulse_present = 0;
01321 
01322     /* This assignment is to silence a GCC warning about the variable being used
01323      * uninitialized when in fact it always is.
01324      */
01325     pulse.num_pulse = 0;
01326 
01327     global_gain = get_bits(gb, 8);
01328 
01329     if (!common_window && !scale_flag) {
01330         if (decode_ics_info(ac, ics, gb, 0) < 0)
01331             return -1;
01332     }
01333 
01334     if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
01335         return -1;
01336     if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
01337         return -1;
01338 
01339     pulse_present = 0;
01340     if (!scale_flag) {
01341         if ((pulse_present = get_bits1(gb))) {
01342             if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01343                 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
01344                 return -1;
01345             }
01346             if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
01347                 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
01348                 return -1;
01349             }
01350         }
01351         if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
01352             return -1;
01353         if (get_bits1(gb)) {
01354             av_log_missing_feature(ac->avctx, "SSR", 1);
01355             return -1;
01356         }
01357     }
01358 
01359     if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
01360         return -1;
01361 
01362     if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
01363         apply_prediction(ac, sce);
01364 
01365     return 0;
01366 }
01367 
01371 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
01372 {
01373     const IndividualChannelStream *ics = &cpe->ch[0].ics;
01374     float *ch0 = cpe->ch[0].coeffs;
01375     float *ch1 = cpe->ch[1].coeffs;
01376     int g, i, group, idx = 0;
01377     const uint16_t *offsets = ics->swb_offset;
01378     for (g = 0; g < ics->num_window_groups; g++) {
01379         for (i = 0; i < ics->max_sfb; i++, idx++) {
01380             if (cpe->ms_mask[idx] &&
01381                     cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
01382                 for (group = 0; group < ics->group_len[g]; group++) {
01383                     ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
01384                                               ch1 + group * 128 + offsets[i],
01385                                               offsets[i+1] - offsets[i]);
01386                 }
01387             }
01388         }
01389         ch0 += ics->group_len[g] * 128;
01390         ch1 += ics->group_len[g] * 128;
01391     }
01392 }
01393 
01401 static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
01402 {
01403     const IndividualChannelStream *ics = &cpe->ch[1].ics;
01404     SingleChannelElement         *sce1 = &cpe->ch[1];
01405     float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
01406     const uint16_t *offsets = ics->swb_offset;
01407     int g, group, i, idx = 0;
01408     int c;
01409     float scale;
01410     for (g = 0; g < ics->num_window_groups; g++) {
01411         for (i = 0; i < ics->max_sfb;) {
01412             if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
01413                 const int bt_run_end = sce1->band_type_run_end[idx];
01414                 for (; i < bt_run_end; i++, idx++) {
01415                     c = -1 + 2 * (sce1->band_type[idx] - 14);
01416                     if (ms_present)
01417                         c *= 1 - 2 * cpe->ms_mask[idx];
01418                     scale = c * sce1->sf[idx];
01419                     for (group = 0; group < ics->group_len[g]; group++)
01420                         ac->dsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
01421                                                    coef0 + group * 128 + offsets[i],
01422                                                    scale,
01423                                                    offsets[i + 1] - offsets[i]);
01424                 }
01425             } else {
01426                 int bt_run_end = sce1->band_type_run_end[idx];
01427                 idx += bt_run_end - i;
01428                 i    = bt_run_end;
01429             }
01430         }
01431         coef0 += ics->group_len[g] * 128;
01432         coef1 += ics->group_len[g] * 128;
01433     }
01434 }
01435 
01441 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
01442 {
01443     int i, ret, common_window, ms_present = 0;
01444 
01445     common_window = get_bits1(gb);
01446     if (common_window) {
01447         if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
01448             return -1;
01449         i = cpe->ch[1].ics.use_kb_window[0];
01450         cpe->ch[1].ics = cpe->ch[0].ics;
01451         cpe->ch[1].ics.use_kb_window[1] = i;
01452         if (cpe->ch[1].ics.predictor_present && (ac->m4ac.object_type != AOT_AAC_MAIN))
01453             if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
01454                 decode_ltp(ac, &cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
01455         ms_present = get_bits(gb, 2);
01456         if (ms_present == 3) {
01457             av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
01458             return -1;
01459         } else if (ms_present)
01460             decode_mid_side_stereo(cpe, gb, ms_present);
01461     }
01462     if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
01463         return ret;
01464     if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
01465         return ret;
01466 
01467     if (common_window) {
01468         if (ms_present)
01469             apply_mid_side_stereo(ac, cpe);
01470         if (ac->m4ac.object_type == AOT_AAC_MAIN) {
01471             apply_prediction(ac, &cpe->ch[0]);
01472             apply_prediction(ac, &cpe->ch[1]);
01473         }
01474     }
01475 
01476     apply_intensity_stereo(ac, cpe, ms_present);
01477     return 0;
01478 }
01479 
01480 static const float cce_scale[] = {
01481     1.09050773266525765921, //2^(1/8)
01482     1.18920711500272106672, //2^(1/4)
01483     M_SQRT2,
01484     2,
01485 };
01486 
01492 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
01493 {
01494     int num_gain = 0;
01495     int c, g, sfb, ret;
01496     int sign;
01497     float scale;
01498     SingleChannelElement *sce = &che->ch[0];
01499     ChannelCoupling     *coup = &che->coup;
01500 
01501     coup->coupling_point = 2 * get_bits1(gb);
01502     coup->num_coupled = get_bits(gb, 3);
01503     for (c = 0; c <= coup->num_coupled; c++) {
01504         num_gain++;
01505         coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
01506         coup->id_select[c] = get_bits(gb, 4);
01507         if (coup->type[c] == TYPE_CPE) {
01508             coup->ch_select[c] = get_bits(gb, 2);
01509             if (coup->ch_select[c] == 3)
01510                 num_gain++;
01511         } else
01512             coup->ch_select[c] = 2;
01513     }
01514     coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
01515 
01516     sign  = get_bits(gb, 1);
01517     scale = cce_scale[get_bits(gb, 2)];
01518 
01519     if ((ret = decode_ics(ac, sce, gb, 0, 0)))
01520         return ret;
01521 
01522     for (c = 0; c < num_gain; c++) {
01523         int idx  = 0;
01524         int cge  = 1;
01525         int gain = 0;
01526         float gain_cache = 1.;
01527         if (c) {
01528             cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
01529             gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
01530             gain_cache = powf(scale, -gain);
01531         }
01532         if (coup->coupling_point == AFTER_IMDCT) {
01533             coup->gain[c][0] = gain_cache;
01534         } else {
01535             for (g = 0; g < sce->ics.num_window_groups; g++) {
01536                 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
01537                     if (sce->band_type[idx] != ZERO_BT) {
01538                         if (!cge) {
01539                             int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
01540                             if (t) {
01541                                 int s = 1;
01542                                 t = gain += t;
01543                                 if (sign) {
01544                                     s  -= 2 * (t & 0x1);
01545                                     t >>= 1;
01546                                 }
01547                                 gain_cache = powf(scale, -t) * s;
01548                             }
01549                         }
01550                         coup->gain[c][idx] = gain_cache;
01551                     }
01552                 }
01553             }
01554         }
01555     }
01556     return 0;
01557 }
01558 
01564 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
01565                                          GetBitContext *gb)
01566 {
01567     int i;
01568     int num_excl_chan = 0;
01569 
01570     do {
01571         for (i = 0; i < 7; i++)
01572             che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
01573     } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
01574 
01575     return num_excl_chan / 7;
01576 }
01577 
01585 static int decode_dynamic_range(DynamicRangeControl *che_drc,
01586                                 GetBitContext *gb, int cnt)
01587 {
01588     int n             = 1;
01589     int drc_num_bands = 1;
01590     int i;
01591 
01592     /* pce_tag_present? */
01593     if (get_bits1(gb)) {
01594         che_drc->pce_instance_tag  = get_bits(gb, 4);
01595         skip_bits(gb, 4); // tag_reserved_bits
01596         n++;
01597     }
01598 
01599     /* excluded_chns_present? */
01600     if (get_bits1(gb)) {
01601         n += decode_drc_channel_exclusions(che_drc, gb);
01602     }
01603 
01604     /* drc_bands_present? */
01605     if (get_bits1(gb)) {
01606         che_drc->band_incr            = get_bits(gb, 4);
01607         che_drc->interpolation_scheme = get_bits(gb, 4);
01608         n++;
01609         drc_num_bands += che_drc->band_incr;
01610         for (i = 0; i < drc_num_bands; i++) {
01611             che_drc->band_top[i] = get_bits(gb, 8);
01612             n++;
01613         }
01614     }
01615 
01616     /* prog_ref_level_present? */
01617     if (get_bits1(gb)) {
01618         che_drc->prog_ref_level = get_bits(gb, 7);
01619         skip_bits1(gb); // prog_ref_level_reserved_bits
01620         n++;
01621     }
01622 
01623     for (i = 0; i < drc_num_bands; i++) {
01624         che_drc->dyn_rng_sgn[i] = get_bits1(gb);
01625         che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
01626         n++;
01627     }
01628 
01629     return n;
01630 }
01631 
01639 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
01640                                     ChannelElement *che, enum RawDataBlockType elem_type)
01641 {
01642     int crc_flag = 0;
01643     int res = cnt;
01644     switch (get_bits(gb, 4)) { // extension type
01645     case EXT_SBR_DATA_CRC:
01646         crc_flag++;
01647     case EXT_SBR_DATA:
01648         if (!che) {
01649             av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
01650             return res;
01651         } else if (!ac->m4ac.sbr) {
01652             av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
01653             skip_bits_long(gb, 8 * cnt - 4);
01654             return res;
01655         } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
01656             av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
01657             skip_bits_long(gb, 8 * cnt - 4);
01658             return res;
01659         } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
01660             ac->m4ac.sbr = 1;
01661             ac->m4ac.ps = 1;
01662             output_configure(ac, ac->che_pos, ac->che_pos, ac->m4ac.chan_config, ac->output_configured);
01663         } else {
01664             ac->m4ac.sbr = 1;
01665         }
01666         res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
01667         break;
01668     case EXT_DYNAMIC_RANGE:
01669         res = decode_dynamic_range(&ac->che_drc, gb, cnt);
01670         break;
01671     case EXT_FILL:
01672     case EXT_FILL_DATA:
01673     case EXT_DATA_ELEMENT:
01674     default:
01675         skip_bits_long(gb, 8 * cnt - 4);
01676         break;
01677     };
01678     return res;
01679 }
01680 
01687 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
01688                       IndividualChannelStream *ics, int decode)
01689 {
01690     const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
01691     int w, filt, m, i;
01692     int bottom, top, order, start, end, size, inc;
01693     float lpc[TNS_MAX_ORDER];
01694     float tmp[TNS_MAX_ORDER];
01695 
01696     for (w = 0; w < ics->num_windows; w++) {
01697         bottom = ics->num_swb;
01698         for (filt = 0; filt < tns->n_filt[w]; filt++) {
01699             top    = bottom;
01700             bottom = FFMAX(0, top - tns->length[w][filt]);
01701             order  = tns->order[w][filt];
01702             if (order == 0)
01703                 continue;
01704 
01705             // tns_decode_coef
01706             compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
01707 
01708             start = ics->swb_offset[FFMIN(bottom, mmm)];
01709             end   = ics->swb_offset[FFMIN(   top, mmm)];
01710             if ((size = end - start) <= 0)
01711                 continue;
01712             if (tns->direction[w][filt]) {
01713                 inc = -1;
01714                 start = end - 1;
01715             } else {
01716                 inc = 1;
01717             }
01718             start += w * 128;
01719 
01720             if (decode) {
01721                 // ar filter
01722                 for (m = 0; m < size; m++, start += inc)
01723                     for (i = 1; i <= FFMIN(m, order); i++)
01724                         coef[start] -= coef[start - i * inc] * lpc[i - 1];
01725             } else {
01726                 // ma filter
01727                 for (m = 0; m < size; m++, start += inc) {
01728                     tmp[0] = coef[start];
01729                     for (i = 1; i <= FFMIN(m, order); i++)
01730                         coef[start] += tmp[i] * lpc[i - 1];
01731                     for (i = order; i > 0; i--)
01732                         tmp[i] = tmp[i - 1];
01733                 }
01734             }
01735         }
01736     }
01737 }
01738 
01743 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
01744                                    float *in, IndividualChannelStream *ics)
01745 {
01746     const float *lwindow      = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01747     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
01748     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01749     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
01750 
01751     if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
01752         ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);
01753     } else {
01754         memset(in, 0, 448 * sizeof(float));
01755         ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
01756     }
01757     if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
01758         ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
01759     } else {
01760         ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
01761         memset(in + 1024 + 576, 0, 448 * sizeof(float));
01762     }
01763     ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
01764 }
01765 
01769 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
01770 {
01771     const LongTermPrediction *ltp = &sce->ics.ltp;
01772     const uint16_t *offsets = sce->ics.swb_offset;
01773     int i, sfb;
01774 
01775     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
01776         float *predTime = sce->ret;
01777         float *predFreq = ac->buf_mdct;
01778         int16_t num_samples = 2048;
01779 
01780         if (ltp->lag < 1024)
01781             num_samples = ltp->lag + 1024;
01782         for (i = 0; i < num_samples; i++)
01783             predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
01784         memset(&predTime[i], 0, (2048 - i) * sizeof(float));
01785 
01786         windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
01787 
01788         if (sce->tns.present)
01789             apply_tns(predFreq, &sce->tns, &sce->ics, 0);
01790 
01791         for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
01792             if (ltp->used[sfb])
01793                 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
01794                     sce->coeffs[i] += predFreq[i];
01795     }
01796 }
01797 
01801 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
01802 {
01803     IndividualChannelStream *ics = &sce->ics;
01804     float *saved     = sce->saved;
01805     float *saved_ltp = sce->coeffs;
01806     const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01807     const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
01808     int i;
01809 
01810     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01811         memcpy(saved_ltp,       saved, 512 * sizeof(float));
01812         memset(saved_ltp + 576, 0,     448 * sizeof(float));
01813         ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
01814         for (i = 0; i < 64; i++)
01815             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
01816     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
01817         memcpy(saved_ltp,       ac->buf_mdct + 512, 448 * sizeof(float));
01818         memset(saved_ltp + 576, 0,                  448 * sizeof(float));
01819         ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
01820         for (i = 0; i < 64; i++)
01821             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
01822     } else { // LONG_STOP or ONLY_LONG
01823         ac->dsp.vector_fmul_reverse(saved_ltp,       ac->buf_mdct + 512,     &lwindow[512],     512);
01824         for (i = 0; i < 512; i++)
01825             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
01826     }
01827 
01828     memcpy(sce->ltp_state,      sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
01829     memcpy(sce->ltp_state+1024, sce->ret,            1024 * sizeof(*sce->ltp_state));
01830     memcpy(sce->ltp_state+2048, saved_ltp,           1024 * sizeof(*sce->ltp_state));
01831 }
01832 
01836 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
01837 {
01838     IndividualChannelStream *ics = &sce->ics;
01839     float *in    = sce->coeffs;
01840     float *out   = sce->ret;
01841     float *saved = sce->saved;
01842     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
01843     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01844     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
01845     float *buf  = ac->buf_mdct;
01846     float *temp = ac->temp;
01847     int i;
01848 
01849     // imdct
01850     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01851         for (i = 0; i < 1024; i += 128)
01852             ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
01853     } else
01854         ac->mdct.imdct_half(&ac->mdct, buf, in);
01855 
01856     /* window overlapping
01857      * NOTE: To simplify the overlapping code, all 'meaningless' short to long
01858      * and long to short transitions are considered to be short to short
01859      * transitions. This leaves just two cases (long to long and short to short)
01860      * with a little special sauce for EIGHT_SHORT_SEQUENCE.
01861      */
01862     if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
01863             (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
01864         ac->dsp.vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 512);
01865     } else {
01866         memcpy(                        out,               saved,            448 * sizeof(float));
01867 
01868         if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01869             ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, 64);
01870             ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      64);
01871             ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      64);
01872             ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      64);
01873             ac->dsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      64);
01874             memcpy(                    out + 448 + 4*128, temp, 64 * sizeof(float));
01875         } else {
01876             ac->dsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 64);
01877             memcpy(                    out + 576,         buf + 64,         448 * sizeof(float));
01878         }
01879     }
01880 
01881     // buffer update
01882     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01883         memcpy(                    saved,       temp + 64,         64 * sizeof(float));
01884         ac->dsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 64);
01885         ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
01886         ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
01887         memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
01888     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
01889         memcpy(                    saved,       buf + 512,        448 * sizeof(float));
01890         memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
01891     } else { // LONG_STOP or ONLY_LONG
01892         memcpy(                    saved,       buf + 512,        512 * sizeof(float));
01893     }
01894 }
01895 
01901 static void apply_dependent_coupling(AACContext *ac,
01902                                      SingleChannelElement *target,
01903                                      ChannelElement *cce, int index)
01904 {
01905     IndividualChannelStream *ics = &cce->ch[0].ics;
01906     const uint16_t *offsets = ics->swb_offset;
01907     float *dest = target->coeffs;
01908     const float *src = cce->ch[0].coeffs;
01909     int g, i, group, k, idx = 0;
01910     if (ac->m4ac.object_type == AOT_AAC_LTP) {
01911         av_log(ac->avctx, AV_LOG_ERROR,
01912                "Dependent coupling is not supported together with LTP\n");
01913         return;
01914     }
01915     for (g = 0; g < ics->num_window_groups; g++) {
01916         for (i = 0; i < ics->max_sfb; i++, idx++) {
01917             if (cce->ch[0].band_type[idx] != ZERO_BT) {
01918                 const float gain = cce->coup.gain[index][idx];
01919                 for (group = 0; group < ics->group_len[g]; group++) {
01920                     for (k = offsets[i]; k < offsets[i + 1]; k++) {
01921                         // XXX dsputil-ize
01922                         dest[group * 128 + k] += gain * src[group * 128 + k];
01923                     }
01924                 }
01925             }
01926         }
01927         dest += ics->group_len[g] * 128;
01928         src  += ics->group_len[g] * 128;
01929     }
01930 }
01931 
01937 static void apply_independent_coupling(AACContext *ac,
01938                                        SingleChannelElement *target,
01939                                        ChannelElement *cce, int index)
01940 {
01941     int i;
01942     const float gain = cce->coup.gain[index][0];
01943     const float *src = cce->ch[0].ret;
01944     float *dest = target->ret;
01945     const int len = 1024 << (ac->m4ac.sbr == 1);
01946 
01947     for (i = 0; i < len; i++)
01948         dest[i] += gain * src[i];
01949 }
01950 
01956 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
01957                                    enum RawDataBlockType type, int elem_id,
01958                                    enum CouplingPoint coupling_point,
01959                                    void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
01960 {
01961     int i, c;
01962 
01963     for (i = 0; i < MAX_ELEM_ID; i++) {
01964         ChannelElement *cce = ac->che[TYPE_CCE][i];
01965         int index = 0;
01966 
01967         if (cce && cce->coup.coupling_point == coupling_point) {
01968             ChannelCoupling *coup = &cce->coup;
01969 
01970             for (c = 0; c <= coup->num_coupled; c++) {
01971                 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
01972                     if (coup->ch_select[c] != 1) {
01973                         apply_coupling_method(ac, &cc->ch[0], cce, index);
01974                         if (coup->ch_select[c] != 0)
01975                             index++;
01976                     }
01977                     if (coup->ch_select[c] != 2)
01978                         apply_coupling_method(ac, &cc->ch[1], cce, index++);
01979                 } else
01980                     index += 1 + (coup->ch_select[c] == 3);
01981             }
01982         }
01983     }
01984 }
01985 
01989 static void spectral_to_sample(AACContext *ac)
01990 {
01991     int i, type;
01992     for (type = 3; type >= 0; type--) {
01993         for (i = 0; i < MAX_ELEM_ID; i++) {
01994             ChannelElement *che = ac->che[type][i];
01995             if (che) {
01996                 if (type <= TYPE_CPE)
01997                     apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
01998                 if (ac->m4ac.object_type == AOT_AAC_LTP) {
01999                     if (che->ch[0].ics.predictor_present) {
02000                         if (che->ch[0].ics.ltp.present)
02001                             apply_ltp(ac, &che->ch[0]);
02002                         if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
02003                             apply_ltp(ac, &che->ch[1]);
02004                     }
02005                 }
02006                 if (che->ch[0].tns.present)
02007                     apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
02008                 if (che->ch[1].tns.present)
02009                     apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
02010                 if (type <= TYPE_CPE)
02011                     apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
02012                 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
02013                     imdct_and_windowing(ac, &che->ch[0]);
02014                     if (ac->m4ac.object_type == AOT_AAC_LTP)
02015                         update_ltp(ac, &che->ch[0]);
02016                     if (type == TYPE_CPE) {
02017                         imdct_and_windowing(ac, &che->ch[1]);
02018                         if (ac->m4ac.object_type == AOT_AAC_LTP)
02019                             update_ltp(ac, &che->ch[1]);
02020                     }
02021                     if (ac->m4ac.sbr > 0) {
02022                         ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
02023                     }
02024                 }
02025                 if (type <= TYPE_CCE)
02026                     apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
02027             }
02028         }
02029     }
02030 }
02031 
02032 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
02033 {
02034     int size;
02035     AACADTSHeaderInfo hdr_info;
02036 
02037     size = ff_aac_parse_header(gb, &hdr_info);
02038     if (size > 0) {
02039         if (ac->output_configured != OC_LOCKED && hdr_info.chan_config) {
02040             enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
02041             memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
02042             ac->m4ac.chan_config = hdr_info.chan_config;
02043             if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
02044                 return -7;
02045             if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config, OC_TRIAL_FRAME))
02046                 return -7;
02047         } else if (ac->output_configured != OC_LOCKED) {
02048             ac->output_configured = OC_NONE;
02049         }
02050         if (ac->output_configured != OC_LOCKED) {
02051             ac->m4ac.sbr = -1;
02052             ac->m4ac.ps  = -1;
02053         }
02054         ac->m4ac.sample_rate     = hdr_info.sample_rate;
02055         ac->m4ac.sampling_index  = hdr_info.sampling_index;
02056         ac->m4ac.object_type     = hdr_info.object_type;
02057         if (!ac->avctx->sample_rate)
02058             ac->avctx->sample_rate = hdr_info.sample_rate;
02059         if (hdr_info.num_aac_frames == 1) {
02060             if (!hdr_info.crc_absent)
02061                 skip_bits(gb, 16);
02062         } else {
02063             av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
02064             return -1;
02065         }
02066     }
02067     return size;
02068 }
02069 
02070 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
02071                                 int *data_size, GetBitContext *gb)
02072 {
02073     AACContext *ac = avctx->priv_data;
02074     ChannelElement *che = NULL, *che_prev = NULL;
02075     enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
02076     int err, elem_id, data_size_tmp;
02077     int samples = 0, multiplier, audio_found = 0;
02078 
02079     if (show_bits(gb, 12) == 0xfff) {
02080         if (parse_adts_frame_header(ac, gb) < 0) {
02081             av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
02082             return -1;
02083         }
02084         if (ac->m4ac.sampling_index > 12) {
02085             av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
02086             return -1;
02087         }
02088     }
02089 
02090     ac->tags_mapped = 0;
02091     // parse
02092     while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
02093         elem_id = get_bits(gb, 4);
02094 
02095         if (elem_type < TYPE_DSE) {
02096             if (!(che=get_che(ac, elem_type, elem_id))) {
02097                 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
02098                        elem_type, elem_id);
02099                 return -1;
02100             }
02101             samples = 1024;
02102         }
02103 
02104         switch (elem_type) {
02105 
02106         case TYPE_SCE:
02107             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
02108             audio_found = 1;
02109             break;
02110 
02111         case TYPE_CPE:
02112             err = decode_cpe(ac, gb, che);
02113             audio_found = 1;
02114             break;
02115 
02116         case TYPE_CCE:
02117             err = decode_cce(ac, gb, che);
02118             break;
02119 
02120         case TYPE_LFE:
02121             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
02122             audio_found = 1;
02123             break;
02124 
02125         case TYPE_DSE:
02126             err = skip_data_stream_element(ac, gb);
02127             break;
02128 
02129         case TYPE_PCE: {
02130             enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
02131             memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
02132             if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
02133                 break;
02134             if (ac->output_configured > OC_TRIAL_PCE)
02135                 av_log(avctx, AV_LOG_ERROR,
02136                        "Not evaluating a further program_config_element as this construct is dubious at best.\n");
02137             else
02138                 err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
02139             break;
02140         }
02141 
02142         case TYPE_FIL:
02143             if (elem_id == 15)
02144                 elem_id += get_bits(gb, 8) - 1;
02145             if (get_bits_left(gb) < 8 * elem_id) {
02146                     av_log(avctx, AV_LOG_ERROR, overread_err);
02147                     return -1;
02148             }
02149             while (elem_id > 0)
02150                 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
02151             err = 0; /* FIXME */
02152             break;
02153 
02154         default:
02155             err = -1; /* should not happen, but keeps compiler happy */
02156             break;
02157         }
02158 
02159         che_prev       = che;
02160         elem_type_prev = elem_type;
02161 
02162         if (err)
02163             return err;
02164 
02165         if (get_bits_left(gb) < 3) {
02166             av_log(avctx, AV_LOG_ERROR, overread_err);
02167             return -1;
02168         }
02169     }
02170 
02171     spectral_to_sample(ac);
02172 
02173     multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
02174     samples <<= multiplier;
02175     if (ac->output_configured < OC_LOCKED) {
02176         avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
02177         avctx->frame_size = samples;
02178     }
02179 
02180     data_size_tmp = samples * avctx->channels *
02181                     (av_get_bits_per_sample_fmt(avctx->sample_fmt) / 8);
02182     if (*data_size < data_size_tmp) {
02183         av_log(avctx, AV_LOG_ERROR,
02184                "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
02185                *data_size, data_size_tmp);
02186         return -1;
02187     }
02188     *data_size = data_size_tmp;
02189 
02190     if (samples) {
02191         if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
02192             ac->fmt_conv.float_interleave(data, (const float **)ac->output_data,
02193                                           samples, avctx->channels);
02194         else
02195             ac->fmt_conv.float_to_int16_interleave(data, (const float **)ac->output_data,
02196                                                    samples, avctx->channels);
02197     }
02198 
02199     if (ac->output_configured && audio_found)
02200         ac->output_configured = OC_LOCKED;
02201 
02202     return 0;
02203 }
02204 
02205 static int aac_decode_frame(AVCodecContext *avctx, void *data,
02206                             int *data_size, AVPacket *avpkt)
02207 {
02208     const uint8_t *buf = avpkt->data;
02209     int buf_size = avpkt->size;
02210     GetBitContext gb;
02211     int buf_consumed;
02212     int buf_offset;
02213     int err;
02214 
02215     init_get_bits(&gb, buf, buf_size * 8);
02216 
02217     if ((err = aac_decode_frame_int(avctx, data, data_size, &gb)) < 0)
02218         return err;
02219 
02220     buf_consumed = (get_bits_count(&gb) + 7) >> 3;
02221     for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
02222         if (buf[buf_offset])
02223             break;
02224 
02225     return buf_size > buf_offset ? buf_consumed : buf_size;
02226 }
02227 
02228 static av_cold int aac_decode_close(AVCodecContext *avctx)
02229 {
02230     AACContext *ac = avctx->priv_data;
02231     int i, type;
02232 
02233     for (i = 0; i < MAX_ELEM_ID; i++) {
02234         for (type = 0; type < 4; type++) {
02235             if (ac->che[type][i])
02236                 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
02237             av_freep(&ac->che[type][i]);
02238         }
02239     }
02240 
02241     ff_mdct_end(&ac->mdct);
02242     ff_mdct_end(&ac->mdct_small);
02243     ff_mdct_end(&ac->mdct_ltp);
02244     return 0;
02245 }
02246 
02247 
02248 #define LOAS_SYNC_WORD   0x2b7       ///< 11 bits LOAS sync word
02249 
02250 struct LATMContext {
02251     AACContext      aac_ctx;             
02252     int             initialized;         
02253 
02254     // parser data
02255     int             audio_mux_version_A; 
02256     int             frame_length_type;   
02257     int             frame_length;        
02258 };
02259 
02260 static inline uint32_t latm_get_value(GetBitContext *b)
02261 {
02262     int length = get_bits(b, 2);
02263 
02264     return get_bits_long(b, (length+1)*8);
02265 }
02266 
02267 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
02268                                              GetBitContext *gb)
02269 {
02270     AVCodecContext *avctx = latmctx->aac_ctx.avctx;
02271     MPEG4AudioConfig m4ac;
02272     int  config_start_bit = get_bits_count(gb);
02273     int     bits_consumed, esize;
02274 
02275     if (config_start_bit % 8) {
02276         av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
02277                                "config not byte aligned.\n", 1);
02278         return AVERROR_INVALIDDATA;
02279     } else {
02280         bits_consumed =
02281             decode_audio_specific_config(NULL, avctx, &m4ac,
02282                                          gb->buffer + (config_start_bit / 8),
02283                                          get_bits_left(gb) / 8);
02284 
02285         if (bits_consumed < 0)
02286             return AVERROR_INVALIDDATA;
02287 
02288         esize = (bits_consumed+7) / 8;
02289 
02290         if (avctx->extradata_size <= esize) {
02291             av_free(avctx->extradata);
02292             avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
02293             if (!avctx->extradata)
02294                 return AVERROR(ENOMEM);
02295         }
02296 
02297         avctx->extradata_size = esize;
02298         memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
02299         memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
02300 
02301         skip_bits_long(gb, bits_consumed);
02302     }
02303 
02304     return bits_consumed;
02305 }
02306 
02307 static int read_stream_mux_config(struct LATMContext *latmctx,
02308                                   GetBitContext *gb)
02309 {
02310     int ret, audio_mux_version = get_bits(gb, 1);
02311 
02312     latmctx->audio_mux_version_A = 0;
02313     if (audio_mux_version)
02314         latmctx->audio_mux_version_A = get_bits(gb, 1);
02315 
02316     if (!latmctx->audio_mux_version_A) {
02317 
02318         if (audio_mux_version)
02319             latm_get_value(gb);                 // taraFullness
02320 
02321         skip_bits(gb, 1);                       // allStreamSameTimeFraming
02322         skip_bits(gb, 6);                       // numSubFrames
02323         // numPrograms
02324         if (get_bits(gb, 4)) {                  // numPrograms
02325             av_log_missing_feature(latmctx->aac_ctx.avctx,
02326                                    "multiple programs are not supported\n", 1);
02327             return AVERROR_PATCHWELCOME;
02328         }
02329 
02330         // for each program (which there is only on in DVB)
02331 
02332         // for each layer (which there is only on in DVB)
02333         if (get_bits(gb, 3)) {                   // numLayer
02334             av_log_missing_feature(latmctx->aac_ctx.avctx,
02335                                    "multiple layers are not supported\n", 1);
02336             return AVERROR_PATCHWELCOME;
02337         }
02338 
02339         // for all but first stream: use_same_config = get_bits(gb, 1);
02340         if (!audio_mux_version) {
02341             if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
02342                 return ret;
02343         } else {
02344             int ascLen = latm_get_value(gb);
02345             if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
02346                 return ret;
02347             ascLen -= ret;
02348             skip_bits_long(gb, ascLen);
02349         }
02350 
02351         latmctx->frame_length_type = get_bits(gb, 3);
02352         switch (latmctx->frame_length_type) {
02353         case 0:
02354             skip_bits(gb, 8);       // latmBufferFullness
02355             break;
02356         case 1:
02357             latmctx->frame_length = get_bits(gb, 9);
02358             break;
02359         case 3:
02360         case 4:
02361         case 5:
02362             skip_bits(gb, 6);       // CELP frame length table index
02363             break;
02364         case 6:
02365         case 7:
02366             skip_bits(gb, 1);       // HVXC frame length table index
02367             break;
02368         }
02369 
02370         if (get_bits(gb, 1)) {                  // other data
02371             if (audio_mux_version) {
02372                 latm_get_value(gb);             // other_data_bits
02373             } else {
02374                 int esc;
02375                 do {
02376                     esc = get_bits(gb, 1);
02377                     skip_bits(gb, 8);
02378                 } while (esc);
02379             }
02380         }
02381 
02382         if (get_bits(gb, 1))                     // crc present
02383             skip_bits(gb, 8);                    // config_crc
02384     }
02385 
02386     return 0;
02387 }
02388 
02389 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
02390 {
02391     uint8_t tmp;
02392 
02393     if (ctx->frame_length_type == 0) {
02394         int mux_slot_length = 0;
02395         do {
02396             tmp = get_bits(gb, 8);
02397             mux_slot_length += tmp;
02398         } while (tmp == 255);
02399         return mux_slot_length;
02400     } else if (ctx->frame_length_type == 1) {
02401         return ctx->frame_length;
02402     } else if (ctx->frame_length_type == 3 ||
02403                ctx->frame_length_type == 5 ||
02404                ctx->frame_length_type == 7) {
02405         skip_bits(gb, 2);          // mux_slot_length_coded
02406     }
02407     return 0;
02408 }
02409 
02410 static int read_audio_mux_element(struct LATMContext *latmctx,
02411                                   GetBitContext *gb)
02412 {
02413     int err;
02414     uint8_t use_same_mux = get_bits(gb, 1);
02415     if (!use_same_mux) {
02416         if ((err = read_stream_mux_config(latmctx, gb)) < 0)
02417             return err;
02418     } else if (!latmctx->aac_ctx.avctx->extradata) {
02419         av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
02420                "no decoder config found\n");
02421         return AVERROR(EAGAIN);
02422     }
02423     if (latmctx->audio_mux_version_A == 0) {
02424         int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
02425         if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
02426             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
02427             return AVERROR_INVALIDDATA;
02428         } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
02429             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
02430                    "frame length mismatch %d << %d\n",
02431                    mux_slot_length_bytes * 8, get_bits_left(gb));
02432             return AVERROR_INVALIDDATA;
02433         }
02434     }
02435     return 0;
02436 }
02437 
02438 
02439 static int latm_decode_frame(AVCodecContext *avctx, void *out, int *out_size,
02440                              AVPacket *avpkt)
02441 {
02442     struct LATMContext *latmctx = avctx->priv_data;
02443     int                 muxlength, err;
02444     GetBitContext       gb;
02445 
02446     if (avpkt->size == 0)
02447         return 0;
02448 
02449     init_get_bits(&gb, avpkt->data, avpkt->size * 8);
02450 
02451     // check for LOAS sync word
02452     if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
02453         return AVERROR_INVALIDDATA;
02454 
02455     muxlength = get_bits(&gb, 13) + 3;
02456     // not enough data, the parser should have sorted this
02457     if (muxlength > avpkt->size)
02458         return AVERROR_INVALIDDATA;
02459 
02460     if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
02461         return err;
02462 
02463     if (!latmctx->initialized) {
02464         if (!avctx->extradata) {
02465             *out_size = 0;
02466             return avpkt->size;
02467         } else {
02468             aac_decode_close(avctx);
02469             if ((err = aac_decode_init(avctx)) < 0)
02470                 return err;
02471             latmctx->initialized = 1;
02472         }
02473     }
02474 
02475     if (show_bits(&gb, 12) == 0xfff) {
02476         av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
02477                "ADTS header detected, probably as result of configuration "
02478                "misparsing\n");
02479         return AVERROR_INVALIDDATA;
02480     }
02481 
02482     if ((err = aac_decode_frame_int(avctx, out, out_size, &gb)) < 0)
02483         return err;
02484 
02485     return muxlength;
02486 }
02487 
02488 av_cold static int latm_decode_init(AVCodecContext *avctx)
02489 {
02490     struct LATMContext *latmctx = avctx->priv_data;
02491     int ret;
02492 
02493     ret = aac_decode_init(avctx);
02494 
02495     if (avctx->extradata_size > 0) {
02496         latmctx->initialized = !ret;
02497     } else {
02498         latmctx->initialized = 0;
02499     }
02500 
02501     return ret;
02502 }
02503 
02504 
02505 AVCodec ff_aac_decoder = {
02506     "aac",
02507     AVMEDIA_TYPE_AUDIO,
02508     CODEC_ID_AAC,
02509     sizeof(AACContext),
02510     aac_decode_init,
02511     NULL,
02512     aac_decode_close,
02513     aac_decode_frame,
02514     .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
02515     .sample_fmts = (const enum AVSampleFormat[]) {
02516         AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
02517     },
02518     .channel_layouts = aac_channel_layout,
02519 };
02520 
02521 /*
02522     Note: This decoder filter is intended to decode LATM streams transferred
02523     in MPEG transport streams which only contain one program.
02524     To do a more complex LATM demuxing a separate LATM demuxer should be used.
02525 */
02526 AVCodec ff_aac_latm_decoder = {
02527     .name = "aac_latm",
02528     .type = AVMEDIA_TYPE_AUDIO,
02529     .id   = CODEC_ID_AAC_LATM,
02530     .priv_data_size = sizeof(struct LATMContext),
02531     .init   = latm_decode_init,
02532     .close  = aac_decode_close,
02533     .decode = latm_decode_frame,
02534     .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
02535     .sample_fmts = (const enum AVSampleFormat[]) {
02536         AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
02537     },
02538     .channel_layouts = aac_channel_layout,
02539 };