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 FFmpeg.
00011  *
00012  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 #include "libavutil/intfloat.h"
00102 
00103 #include <assert.h>
00104 #include <errno.h>
00105 #include <math.h>
00106 #include <string.h>
00107 
00108 #if ARCH_ARM
00109 #   include "arm/aac.h"
00110 #endif
00111 
00112 static VLC vlc_scalefactors;
00113 static VLC vlc_spectral[11];
00114 
00115 static const char overread_err[] = "Input buffer exhausted before END element found\n";
00116 
00117 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
00118 {
00119     // For PCE based channel configurations map the channels solely based on tags.
00120     if (!ac->m4ac.chan_config) {
00121         return ac->tag_che_map[type][elem_id];
00122     }
00123     // For indexed channel configurations map the channels solely based on position.
00124     switch (ac->m4ac.chan_config) {
00125     case 7:
00126         if (ac->tags_mapped == 3 && type == TYPE_CPE) {
00127             ac->tags_mapped++;
00128             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
00129         }
00130     case 6:
00131         /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
00132            instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
00133            encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
00134         if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
00135             ac->tags_mapped++;
00136             return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
00137         }
00138     case 5:
00139         if (ac->tags_mapped == 2 && type == TYPE_CPE) {
00140             ac->tags_mapped++;
00141             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
00142         }
00143     case 4:
00144         if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
00145             ac->tags_mapped++;
00146             return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
00147         }
00148     case 3:
00149     case 2:
00150         if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
00151             ac->tags_mapped++;
00152             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
00153         } else if (ac->m4ac.chan_config == 2) {
00154             return NULL;
00155         }
00156     case 1:
00157         if (!ac->tags_mapped && type == TYPE_SCE) {
00158             ac->tags_mapped++;
00159             return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
00160         }
00161     default:
00162         return NULL;
00163     }
00164 }
00165 
00166 static int count_channels(enum ChannelPosition che_pos[4][MAX_ELEM_ID])
00167 {
00168     int i, type, sum = 0;
00169     for (i = 0; i < MAX_ELEM_ID; i++) {
00170         for (type = 0; type < 4; type++) {
00171             sum += (1 + (type == TYPE_CPE)) *
00172                 (che_pos[type][i] != AAC_CHANNEL_OFF &&
00173                  che_pos[type][i] != AAC_CHANNEL_CC);
00174         }
00175     }
00176     return sum;
00177 }
00178 
00191 static av_cold int che_configure(AACContext *ac,
00192                                  enum ChannelPosition che_pos[4][MAX_ELEM_ID],
00193                                  int type, int id, int *channels)
00194 {
00195     if (che_pos[type][id]) {
00196         if (!ac->che[type][id]) {
00197             if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
00198                 return AVERROR(ENOMEM);
00199             ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
00200         }
00201         if (type != TYPE_CCE) {
00202             ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
00203             if (type == TYPE_CPE ||
00204                 (type == TYPE_SCE && ac->m4ac.ps == 1)) {
00205                 ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
00206             }
00207         }
00208     } else {
00209         if (ac->che[type][id])
00210             ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
00211         av_freep(&ac->che[type][id]);
00212     }
00213     return 0;
00214 }
00215 
00224 static av_cold int output_configure(AACContext *ac,
00225                                     enum ChannelPosition che_pos[4][MAX_ELEM_ID],
00226                                     enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
00227                                     int channel_config, enum OCStatus oc_type)
00228 {
00229     AVCodecContext *avctx = ac->avctx;
00230     int i, type, channels = 0, ret;
00231 
00232     if (new_che_pos != che_pos)
00233     memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
00234 
00235     if (channel_config) {
00236         for (i = 0; i < tags_per_config[channel_config]; i++) {
00237             if ((ret = che_configure(ac, che_pos,
00238                                      aac_channel_layout_map[channel_config - 1][i][0],
00239                                      aac_channel_layout_map[channel_config - 1][i][1],
00240                                      &channels)))
00241                 return ret;
00242         }
00243 
00244         memset(ac->tag_che_map, 0, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
00245 
00246         avctx->channel_layout = aac_channel_layout[channel_config - 1];
00247     } else {
00248         /* Allocate or free elements depending on if they are in the
00249          * current program configuration.
00250          *
00251          * Set up default 1:1 output mapping.
00252          *
00253          * For a 5.1 stream the output order will be:
00254          *    [ Center ] [ Front Left ] [ Front Right ] [ LFE ] [ Surround Left ] [ Surround Right ]
00255          */
00256 
00257         for (i = 0; i < MAX_ELEM_ID; i++) {
00258             for (type = 0; type < 4; type++) {
00259                 if ((ret = che_configure(ac, che_pos, type, i, &channels)))
00260                     return ret;
00261             }
00262         }
00263 
00264         memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
00265     }
00266 
00267     avctx->channels = channels;
00268 
00269     ac->output_configured = oc_type;
00270 
00271     return 0;
00272 }
00273 
00274 static void flush(AVCodecContext *avctx)
00275 {
00276     AACContext *ac= avctx->priv_data;
00277     int type, i, j;
00278 
00279     for (type = 3; type >= 0; type--) {
00280         for (i = 0; i < MAX_ELEM_ID; i++) {
00281             ChannelElement *che = ac->che[type][i];
00282             if (che) {
00283                 for (j = 0; j <= 1; j++) {
00284                     memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
00285                 }
00286             }
00287         }
00288     }
00289 }
00290 
00298 static void decode_channel_map(enum ChannelPosition *cpe_map,
00299                                enum ChannelPosition *sce_map,
00300                                enum ChannelPosition type,
00301                                GetBitContext *gb, int n)
00302 {
00303     while (n--) {
00304         enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
00305         map[get_bits(gb, 4)] = type;
00306     }
00307 }
00308 
00316 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
00317                       enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
00318                       GetBitContext *gb)
00319 {
00320     int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
00321     int comment_len;
00322 
00323     skip_bits(gb, 2);  // object_type
00324 
00325     sampling_index = get_bits(gb, 4);
00326     if (m4ac->sampling_index != sampling_index)
00327         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");
00328 
00329     num_front       = get_bits(gb, 4);
00330     num_side        = get_bits(gb, 4);
00331     num_back        = get_bits(gb, 4);
00332     num_lfe         = get_bits(gb, 2);
00333     num_assoc_data  = get_bits(gb, 3);
00334     num_cc          = get_bits(gb, 4);
00335 
00336     if (get_bits1(gb))
00337         skip_bits(gb, 4); // mono_mixdown_tag
00338     if (get_bits1(gb))
00339         skip_bits(gb, 4); // stereo_mixdown_tag
00340 
00341     if (get_bits1(gb))
00342         skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
00343 
00344     if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
00345         av_log(avctx, AV_LOG_ERROR, overread_err);
00346         return -1;
00347     }
00348     decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
00349     decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE,  gb, num_side );
00350     decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK,  gb, num_back );
00351     decode_channel_map(NULL,                  new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE,   gb, num_lfe  );
00352 
00353     skip_bits_long(gb, 4 * num_assoc_data);
00354 
00355     decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC,    gb, num_cc   );
00356 
00357     align_get_bits(gb);
00358 
00359     /* comment field, first byte is length */
00360     comment_len = get_bits(gb, 8) * 8;
00361     if (get_bits_left(gb) < comment_len) {
00362         av_log(avctx, AV_LOG_ERROR, overread_err);
00363         return -1;
00364     }
00365     skip_bits_long(gb, comment_len);
00366     return 0;
00367 }
00368 
00377 static av_cold int set_default_channel_config(AVCodecContext *avctx,
00378                                               enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
00379                                               int channel_config)
00380 {
00381     if (channel_config < 1 || channel_config > 7) {
00382         av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
00383                channel_config);
00384         return -1;
00385     }
00386 
00387     /* default channel configurations:
00388      *
00389      * 1ch : front center (mono)
00390      * 2ch : L + R (stereo)
00391      * 3ch : front center + L + R
00392      * 4ch : front center + L + R + back center
00393      * 5ch : front center + L + R + back stereo
00394      * 6ch : front center + L + R + back stereo + LFE
00395      * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
00396      */
00397 
00398     if (channel_config != 2)
00399         new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
00400     if (channel_config > 1)
00401         new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
00402     if (channel_config == 4)
00403         new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK;  // back center
00404     if (channel_config > 4)
00405         new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
00406         = AAC_CHANNEL_BACK;  // back stereo
00407     if (channel_config > 5)
00408         new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE;   // LFE
00409     if (channel_config == 7)
00410         new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
00411 
00412     return 0;
00413 }
00414 
00423 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
00424                                      GetBitContext *gb,
00425                                      MPEG4AudioConfig *m4ac,
00426                                      int channel_config)
00427 {
00428     enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
00429     int extension_flag, ret;
00430 
00431     if (get_bits1(gb)) { // frameLengthFlag
00432         av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
00433         return -1;
00434     }
00435 
00436     if (get_bits1(gb))       // dependsOnCoreCoder
00437         skip_bits(gb, 14);   // coreCoderDelay
00438     extension_flag = get_bits1(gb);
00439 
00440     if (m4ac->object_type == AOT_AAC_SCALABLE ||
00441         m4ac->object_type == AOT_ER_AAC_SCALABLE)
00442         skip_bits(gb, 3);     // layerNr
00443 
00444     memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
00445     if (channel_config == 0) {
00446         skip_bits(gb, 4);  // element_instance_tag
00447         if ((ret = decode_pce(avctx, m4ac, new_che_pos, gb)))
00448             return ret;
00449     } else {
00450         if ((ret = set_default_channel_config(avctx, new_che_pos, channel_config)))
00451             return ret;
00452     }
00453 
00454     if (count_channels(new_che_pos) > 1) {
00455         m4ac->ps = 0;
00456     } else if (m4ac->sbr == 1 && m4ac->ps == -1)
00457         m4ac->ps = 1;
00458 
00459     if (ac && (ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
00460         return ret;
00461 
00462     if (extension_flag) {
00463         switch (m4ac->object_type) {
00464         case AOT_ER_BSAC:
00465             skip_bits(gb, 5);    // numOfSubFrame
00466             skip_bits(gb, 11);   // layer_length
00467             break;
00468         case AOT_ER_AAC_LC:
00469         case AOT_ER_AAC_LTP:
00470         case AOT_ER_AAC_SCALABLE:
00471         case AOT_ER_AAC_LD:
00472             skip_bits(gb, 3);  /* aacSectionDataResilienceFlag
00473                                     * aacScalefactorDataResilienceFlag
00474                                     * aacSpectralDataResilienceFlag
00475                                     */
00476             break;
00477         }
00478         skip_bits1(gb);    // extensionFlag3 (TBD in version 3)
00479     }
00480     return 0;
00481 }
00482 
00495 static int decode_audio_specific_config(AACContext *ac,
00496                                         AVCodecContext *avctx,
00497                                         MPEG4AudioConfig *m4ac,
00498                                         const uint8_t *data, int bit_size,
00499                                         int sync_extension)
00500 {
00501     GetBitContext gb;
00502     int i;
00503 
00504     av_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
00505     for (i = 0; i < avctx->extradata_size; i++)
00506          av_dlog(avctx, "%02x ", avctx->extradata[i]);
00507     av_dlog(avctx, "\n");
00508 
00509     init_get_bits(&gb, data, bit_size);
00510 
00511     if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size, sync_extension)) < 0)
00512         return -1;
00513     if (m4ac->sampling_index > 12) {
00514         av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
00515         return -1;
00516     }
00517 
00518     skip_bits_long(&gb, i);
00519 
00520     switch (m4ac->object_type) {
00521     case AOT_AAC_MAIN:
00522     case AOT_AAC_LC:
00523     case AOT_AAC_LTP:
00524         if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
00525             return -1;
00526         break;
00527     default:
00528         av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
00529                m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
00530         return -1;
00531     }
00532 
00533     av_dlog(avctx, "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
00534             m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
00535             m4ac->sample_rate, m4ac->sbr, m4ac->ps);
00536 
00537     return get_bits_count(&gb);
00538 }
00539 
00547 static av_always_inline int lcg_random(int previous_val)
00548 {
00549     return previous_val * 1664525 + 1013904223;
00550 }
00551 
00552 static av_always_inline void reset_predict_state(PredictorState *ps)
00553 {
00554     ps->r0   = 0.0f;
00555     ps->r1   = 0.0f;
00556     ps->cor0 = 0.0f;
00557     ps->cor1 = 0.0f;
00558     ps->var0 = 1.0f;
00559     ps->var1 = 1.0f;
00560 }
00561 
00562 static void reset_all_predictors(PredictorState *ps)
00563 {
00564     int i;
00565     for (i = 0; i < MAX_PREDICTORS; i++)
00566         reset_predict_state(&ps[i]);
00567 }
00568 
00569 static int sample_rate_idx (int rate)
00570 {
00571          if (92017 <= rate) return 0;
00572     else if (75132 <= rate) return 1;
00573     else if (55426 <= rate) return 2;
00574     else if (46009 <= rate) return 3;
00575     else if (37566 <= rate) return 4;
00576     else if (27713 <= rate) return 5;
00577     else if (23004 <= rate) return 6;
00578     else if (18783 <= rate) return 7;
00579     else if (13856 <= rate) return 8;
00580     else if (11502 <= rate) return 9;
00581     else if (9391  <= rate) return 10;
00582     else                    return 11;
00583 }
00584 
00585 static void reset_predictor_group(PredictorState *ps, int group_num)
00586 {
00587     int i;
00588     for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
00589         reset_predict_state(&ps[i]);
00590 }
00591 
00592 #define AAC_INIT_VLC_STATIC(num, size) \
00593     INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
00594          ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
00595         ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
00596         size);
00597 
00598 static av_cold int aac_decode_init(AVCodecContext *avctx)
00599 {
00600     AACContext *ac = avctx->priv_data;
00601     float output_scale_factor;
00602 
00603     ac->avctx = avctx;
00604     ac->m4ac.sample_rate = avctx->sample_rate;
00605 
00606     if (avctx->extradata_size > 0) {
00607         if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
00608                                          avctx->extradata,
00609                                          avctx->extradata_size*8, 1) < 0)
00610             return -1;
00611     } else {
00612         int sr, i;
00613         enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
00614 
00615         sr = sample_rate_idx(avctx->sample_rate);
00616         ac->m4ac.sampling_index = sr;
00617         ac->m4ac.channels = avctx->channels;
00618         ac->m4ac.sbr = -1;
00619         ac->m4ac.ps = -1;
00620 
00621         for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
00622             if (ff_mpeg4audio_channels[i] == avctx->channels)
00623                 break;
00624         if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
00625             i = 0;
00626         }
00627         ac->m4ac.chan_config = i;
00628 
00629         if (ac->m4ac.chan_config) {
00630             int ret = set_default_channel_config(avctx, new_che_pos, ac->m4ac.chan_config);
00631             if (!ret)
00632                 output_configure(ac, ac->che_pos, new_che_pos, ac->m4ac.chan_config, OC_GLOBAL_HDR);
00633             else if (avctx->err_recognition & AV_EF_EXPLODE)
00634                 return AVERROR_INVALIDDATA;
00635         }
00636     }
00637 
00638     if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
00639         avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
00640         output_scale_factor = 1.0 / 32768.0;
00641     } else {
00642         avctx->sample_fmt = AV_SAMPLE_FMT_S16;
00643         output_scale_factor = 1.0;
00644     }
00645 
00646     AAC_INIT_VLC_STATIC( 0, 304);
00647     AAC_INIT_VLC_STATIC( 1, 270);
00648     AAC_INIT_VLC_STATIC( 2, 550);
00649     AAC_INIT_VLC_STATIC( 3, 300);
00650     AAC_INIT_VLC_STATIC( 4, 328);
00651     AAC_INIT_VLC_STATIC( 5, 294);
00652     AAC_INIT_VLC_STATIC( 6, 306);
00653     AAC_INIT_VLC_STATIC( 7, 268);
00654     AAC_INIT_VLC_STATIC( 8, 510);
00655     AAC_INIT_VLC_STATIC( 9, 366);
00656     AAC_INIT_VLC_STATIC(10, 462);
00657 
00658     ff_aac_sbr_init();
00659 
00660     dsputil_init(&ac->dsp, avctx);
00661     ff_fmt_convert_init(&ac->fmt_conv, avctx);
00662 
00663     ac->random_state = 0x1f2e3d4c;
00664 
00665     ff_aac_tableinit();
00666 
00667     INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
00668                     ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
00669                     ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
00670                     352);
00671 
00672     ff_mdct_init(&ac->mdct,       11, 1, output_scale_factor/1024.0);
00673     ff_mdct_init(&ac->mdct_small,  8, 1, output_scale_factor/128.0);
00674     ff_mdct_init(&ac->mdct_ltp,   11, 0, -2.0/output_scale_factor);
00675     // window initialization
00676     ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
00677     ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
00678     ff_init_ff_sine_windows(10);
00679     ff_init_ff_sine_windows( 7);
00680 
00681     cbrt_tableinit();
00682 
00683     avcodec_get_frame_defaults(&ac->frame);
00684     avctx->coded_frame = &ac->frame;
00685 
00686     return 0;
00687 }
00688 
00692 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
00693 {
00694     int byte_align = get_bits1(gb);
00695     int count = get_bits(gb, 8);
00696     if (count == 255)
00697         count += get_bits(gb, 8);
00698     if (byte_align)
00699         align_get_bits(gb);
00700 
00701     if (get_bits_left(gb) < 8 * count) {
00702         av_log(ac->avctx, AV_LOG_ERROR, overread_err);
00703         return -1;
00704     }
00705     skip_bits_long(gb, 8 * count);
00706     return 0;
00707 }
00708 
00709 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
00710                              GetBitContext *gb)
00711 {
00712     int sfb;
00713     if (get_bits1(gb)) {
00714         ics->predictor_reset_group = get_bits(gb, 5);
00715         if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
00716             av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
00717             return -1;
00718         }
00719     }
00720     for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
00721         ics->prediction_used[sfb] = get_bits1(gb);
00722     }
00723     return 0;
00724 }
00725 
00729 static void decode_ltp(AACContext *ac, LongTermPrediction *ltp,
00730                        GetBitContext *gb, uint8_t max_sfb)
00731 {
00732     int sfb;
00733 
00734     ltp->lag  = get_bits(gb, 11);
00735     ltp->coef = ltp_coef[get_bits(gb, 3)];
00736     for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
00737         ltp->used[sfb] = get_bits1(gb);
00738 }
00739 
00743 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
00744                            GetBitContext *gb)
00745 {
00746     if (get_bits1(gb)) {
00747         av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
00748         return AVERROR_INVALIDDATA;
00749     }
00750     ics->window_sequence[1] = ics->window_sequence[0];
00751     ics->window_sequence[0] = get_bits(gb, 2);
00752     ics->use_kb_window[1]   = ics->use_kb_window[0];
00753     ics->use_kb_window[0]   = get_bits1(gb);
00754     ics->num_window_groups  = 1;
00755     ics->group_len[0]       = 1;
00756     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
00757         int i;
00758         ics->max_sfb = get_bits(gb, 4);
00759         for (i = 0; i < 7; i++) {
00760             if (get_bits1(gb)) {
00761                 ics->group_len[ics->num_window_groups - 1]++;
00762             } else {
00763                 ics->num_window_groups++;
00764                 ics->group_len[ics->num_window_groups - 1] = 1;
00765             }
00766         }
00767         ics->num_windows       = 8;
00768         ics->swb_offset        =    ff_swb_offset_128[ac->m4ac.sampling_index];
00769         ics->num_swb           =   ff_aac_num_swb_128[ac->m4ac.sampling_index];
00770         ics->tns_max_bands     = ff_tns_max_bands_128[ac->m4ac.sampling_index];
00771         ics->predictor_present = 0;
00772     } else {
00773         ics->max_sfb               = get_bits(gb, 6);
00774         ics->num_windows           = 1;
00775         ics->swb_offset            =    ff_swb_offset_1024[ac->m4ac.sampling_index];
00776         ics->num_swb               =   ff_aac_num_swb_1024[ac->m4ac.sampling_index];
00777         ics->tns_max_bands         = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
00778         ics->predictor_present     = get_bits1(gb);
00779         ics->predictor_reset_group = 0;
00780         if (ics->predictor_present) {
00781             if (ac->m4ac.object_type == AOT_AAC_MAIN) {
00782                 if (decode_prediction(ac, ics, gb)) {
00783                     return AVERROR_INVALIDDATA;
00784                 }
00785             } else if (ac->m4ac.object_type == AOT_AAC_LC) {
00786                 av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
00787                 return AVERROR_INVALIDDATA;
00788             } else {
00789                 if ((ics->ltp.present = get_bits(gb, 1)))
00790                     decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);
00791             }
00792         }
00793     }
00794 
00795     if (ics->max_sfb > ics->num_swb) {
00796         av_log(ac->avctx, AV_LOG_ERROR,
00797                "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
00798                ics->max_sfb, ics->num_swb);
00799         return AVERROR_INVALIDDATA;
00800     }
00801 
00802     return 0;
00803 }
00804 
00813 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
00814                              int band_type_run_end[120], GetBitContext *gb,
00815                              IndividualChannelStream *ics)
00816 {
00817     int g, idx = 0;
00818     const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
00819     for (g = 0; g < ics->num_window_groups; g++) {
00820         int k = 0;
00821         while (k < ics->max_sfb) {
00822             uint8_t sect_end = k;
00823             int sect_len_incr;
00824             int sect_band_type = get_bits(gb, 4);
00825             if (sect_band_type == 12) {
00826                 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
00827                 return -1;
00828             }
00829             do {
00830                 sect_len_incr = get_bits(gb, bits);
00831                 sect_end += sect_len_incr;
00832                 if (get_bits_left(gb) < 0) {
00833                     av_log(ac->avctx, AV_LOG_ERROR, overread_err);
00834                     return -1;
00835                 }
00836                 if (sect_end > ics->max_sfb) {
00837                     av_log(ac->avctx, AV_LOG_ERROR,
00838                            "Number of bands (%d) exceeds limit (%d).\n",
00839                            sect_end, ics->max_sfb);
00840                     return -1;
00841                 }
00842             } while (sect_len_incr == (1 << bits) - 1);
00843             for (; k < sect_end; k++) {
00844                 band_type        [idx]   = sect_band_type;
00845                 band_type_run_end[idx++] = sect_end;
00846             }
00847         }
00848     }
00849     return 0;
00850 }
00851 
00862 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
00863                                unsigned int global_gain,
00864                                IndividualChannelStream *ics,
00865                                enum BandType band_type[120],
00866                                int band_type_run_end[120])
00867 {
00868     int g, i, idx = 0;
00869     int offset[3] = { global_gain, global_gain - 90, 0 };
00870     int clipped_offset;
00871     int noise_flag = 1;
00872     static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
00873     for (g = 0; g < ics->num_window_groups; g++) {
00874         for (i = 0; i < ics->max_sfb;) {
00875             int run_end = band_type_run_end[idx];
00876             if (band_type[idx] == ZERO_BT) {
00877                 for (; i < run_end; i++, idx++)
00878                     sf[idx] = 0.;
00879             } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
00880                 for (; i < run_end; i++, idx++) {
00881                     offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
00882                     clipped_offset = av_clip(offset[2], -155, 100);
00883                     if (offset[2] != clipped_offset) {
00884                         av_log_ask_for_sample(ac->avctx, "Intensity stereo "
00885                                 "position clipped (%d -> %d).\nIf you heard an "
00886                                 "audible artifact, there may be a bug in the "
00887                                 "decoder. ", offset[2], clipped_offset);
00888                     }
00889                     sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
00890                 }
00891             } else if (band_type[idx] == NOISE_BT) {
00892                 for (; i < run_end; i++, idx++) {
00893                     if (noise_flag-- > 0)
00894                         offset[1] += get_bits(gb, 9) - 256;
00895                     else
00896                         offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
00897                     clipped_offset = av_clip(offset[1], -100, 155);
00898                     if (offset[1] != clipped_offset) {
00899                         av_log_ask_for_sample(ac->avctx, "Noise gain clipped "
00900                                 "(%d -> %d).\nIf you heard an audible "
00901                                 "artifact, there may be a bug in the decoder. ",
00902                                 offset[1], clipped_offset);
00903                     }
00904                     sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
00905                 }
00906             } else {
00907                 for (; i < run_end; i++, idx++) {
00908                     offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
00909                     if (offset[0] > 255U) {
00910                         av_log(ac->avctx, AV_LOG_ERROR,
00911                                "%s (%d) out of range.\n", sf_str[0], offset[0]);
00912                         return -1;
00913                     }
00914                     sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
00915                 }
00916             }
00917         }
00918     }
00919     return 0;
00920 }
00921 
00925 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
00926                          const uint16_t *swb_offset, int num_swb)
00927 {
00928     int i, pulse_swb;
00929     pulse->num_pulse = get_bits(gb, 2) + 1;
00930     pulse_swb        = get_bits(gb, 6);
00931     if (pulse_swb >= num_swb)
00932         return -1;
00933     pulse->pos[0]    = swb_offset[pulse_swb];
00934     pulse->pos[0]   += get_bits(gb, 5);
00935     if (pulse->pos[0] > 1023)
00936         return -1;
00937     pulse->amp[0]    = get_bits(gb, 4);
00938     for (i = 1; i < pulse->num_pulse; i++) {
00939         pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
00940         if (pulse->pos[i] > 1023)
00941             return -1;
00942         pulse->amp[i] = get_bits(gb, 4);
00943     }
00944     return 0;
00945 }
00946 
00952 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
00953                       GetBitContext *gb, const IndividualChannelStream *ics)
00954 {
00955     int w, filt, i, coef_len, coef_res, coef_compress;
00956     const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
00957     const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
00958     for (w = 0; w < ics->num_windows; w++) {
00959         if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
00960             coef_res = get_bits1(gb);
00961 
00962             for (filt = 0; filt < tns->n_filt[w]; filt++) {
00963                 int tmp2_idx;
00964                 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
00965 
00966                 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
00967                     av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
00968                            tns->order[w][filt], tns_max_order);
00969                     tns->order[w][filt] = 0;
00970                     return -1;
00971                 }
00972                 if (tns->order[w][filt]) {
00973                     tns->direction[w][filt] = get_bits1(gb);
00974                     coef_compress = get_bits1(gb);
00975                     coef_len = coef_res + 3 - coef_compress;
00976                     tmp2_idx = 2 * coef_compress + coef_res;
00977 
00978                     for (i = 0; i < tns->order[w][filt]; i++)
00979                         tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
00980                 }
00981             }
00982         }
00983     }
00984     return 0;
00985 }
00986 
00994 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
00995                                    int ms_present)
00996 {
00997     int idx;
00998     if (ms_present == 1) {
00999         for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
01000             cpe->ms_mask[idx] = get_bits1(gb);
01001     } else if (ms_present == 2) {
01002         memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
01003     }
01004 }
01005 
01006 #ifndef VMUL2
01007 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
01008                            const float *scale)
01009 {
01010     float s = *scale;
01011     *dst++ = v[idx    & 15] * s;
01012     *dst++ = v[idx>>4 & 15] * s;
01013     return dst;
01014 }
01015 #endif
01016 
01017 #ifndef VMUL4
01018 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
01019                            const float *scale)
01020 {
01021     float s = *scale;
01022     *dst++ = v[idx    & 3] * s;
01023     *dst++ = v[idx>>2 & 3] * s;
01024     *dst++ = v[idx>>4 & 3] * s;
01025     *dst++ = v[idx>>6 & 3] * s;
01026     return dst;
01027 }
01028 #endif
01029 
01030 #ifndef VMUL2S
01031 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
01032                             unsigned sign, const float *scale)
01033 {
01034     union av_intfloat32 s0, s1;
01035 
01036     s0.f = s1.f = *scale;
01037     s0.i ^= sign >> 1 << 31;
01038     s1.i ^= sign      << 31;
01039 
01040     *dst++ = v[idx    & 15] * s0.f;
01041     *dst++ = v[idx>>4 & 15] * s1.f;
01042 
01043     return dst;
01044 }
01045 #endif
01046 
01047 #ifndef VMUL4S
01048 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
01049                             unsigned sign, const float *scale)
01050 {
01051     unsigned nz = idx >> 12;
01052     union av_intfloat32 s = { .f = *scale };
01053     union av_intfloat32 t;
01054 
01055     t.i = s.i ^ (sign & 1U<<31);
01056     *dst++ = v[idx    & 3] * t.f;
01057 
01058     sign <<= nz & 1; nz >>= 1;
01059     t.i = s.i ^ (sign & 1U<<31);
01060     *dst++ = v[idx>>2 & 3] * t.f;
01061 
01062     sign <<= nz & 1; nz >>= 1;
01063     t.i = s.i ^ (sign & 1U<<31);
01064     *dst++ = v[idx>>4 & 3] * t.f;
01065 
01066     sign <<= nz & 1; nz >>= 1;
01067     t.i = s.i ^ (sign & 1U<<31);
01068     *dst++ = v[idx>>6 & 3] * t.f;
01069 
01070     return dst;
01071 }
01072 #endif
01073 
01086 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
01087                                        GetBitContext *gb, const float sf[120],
01088                                        int pulse_present, const Pulse *pulse,
01089                                        const IndividualChannelStream *ics,
01090                                        enum BandType band_type[120])
01091 {
01092     int i, k, g, idx = 0;
01093     const int c = 1024 / ics->num_windows;
01094     const uint16_t *offsets = ics->swb_offset;
01095     float *coef_base = coef;
01096 
01097     for (g = 0; g < ics->num_windows; g++)
01098         memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
01099 
01100     for (g = 0; g < ics->num_window_groups; g++) {
01101         unsigned g_len = ics->group_len[g];
01102 
01103         for (i = 0; i < ics->max_sfb; i++, idx++) {
01104             const unsigned cbt_m1 = band_type[idx] - 1;
01105             float *cfo = coef + offsets[i];
01106             int off_len = offsets[i + 1] - offsets[i];
01107             int group;
01108 
01109             if (cbt_m1 >= INTENSITY_BT2 - 1) {
01110                 for (group = 0; group < g_len; group++, cfo+=128) {
01111                     memset(cfo, 0, off_len * sizeof(float));
01112                 }
01113             } else if (cbt_m1 == NOISE_BT - 1) {
01114                 for (group = 0; group < g_len; group++, cfo+=128) {
01115                     float scale;
01116                     float band_energy;
01117 
01118                     for (k = 0; k < off_len; k++) {
01119                         ac->random_state  = lcg_random(ac->random_state);
01120                         cfo[k] = ac->random_state;
01121                     }
01122 
01123                     band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
01124                     scale = sf[idx] / sqrtf(band_energy);
01125                     ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
01126                 }
01127             } else {
01128                 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
01129                 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
01130                 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
01131                 OPEN_READER(re, gb);
01132 
01133                 switch (cbt_m1 >> 1) {
01134                 case 0:
01135                     for (group = 0; group < g_len; group++, cfo+=128) {
01136                         float *cf = cfo;
01137                         int len = off_len;
01138 
01139                         do {
01140                             int code;
01141                             unsigned cb_idx;
01142 
01143                             UPDATE_CACHE(re, gb);
01144                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01145                             cb_idx = cb_vector_idx[code];
01146                             cf = VMUL4(cf, vq, cb_idx, sf + idx);
01147                         } while (len -= 4);
01148                     }
01149                     break;
01150 
01151                 case 1:
01152                     for (group = 0; group < g_len; group++, cfo+=128) {
01153                         float *cf = cfo;
01154                         int len = off_len;
01155 
01156                         do {
01157                             int code;
01158                             unsigned nnz;
01159                             unsigned cb_idx;
01160                             uint32_t bits;
01161 
01162                             UPDATE_CACHE(re, gb);
01163                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01164                             cb_idx = cb_vector_idx[code];
01165                             nnz = cb_idx >> 8 & 15;
01166                             bits = nnz ? GET_CACHE(re, gb) : 0;
01167                             LAST_SKIP_BITS(re, gb, nnz);
01168                             cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
01169                         } while (len -= 4);
01170                     }
01171                     break;
01172 
01173                 case 2:
01174                     for (group = 0; group < g_len; group++, cfo+=128) {
01175                         float *cf = cfo;
01176                         int len = off_len;
01177 
01178                         do {
01179                             int code;
01180                             unsigned cb_idx;
01181 
01182                             UPDATE_CACHE(re, gb);
01183                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01184                             cb_idx = cb_vector_idx[code];
01185                             cf = VMUL2(cf, vq, cb_idx, sf + idx);
01186                         } while (len -= 2);
01187                     }
01188                     break;
01189 
01190                 case 3:
01191                 case 4:
01192                     for (group = 0; group < g_len; group++, cfo+=128) {
01193                         float *cf = cfo;
01194                         int len = off_len;
01195 
01196                         do {
01197                             int code;
01198                             unsigned nnz;
01199                             unsigned cb_idx;
01200                             unsigned sign;
01201 
01202                             UPDATE_CACHE(re, gb);
01203                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01204                             cb_idx = cb_vector_idx[code];
01205                             nnz = cb_idx >> 8 & 15;
01206                             sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
01207                             LAST_SKIP_BITS(re, gb, nnz);
01208                             cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
01209                         } while (len -= 2);
01210                     }
01211                     break;
01212 
01213                 default:
01214                     for (group = 0; group < g_len; group++, cfo+=128) {
01215                         float *cf = cfo;
01216                         uint32_t *icf = (uint32_t *) cf;
01217                         int len = off_len;
01218 
01219                         do {
01220                             int code;
01221                             unsigned nzt, nnz;
01222                             unsigned cb_idx;
01223                             uint32_t bits;
01224                             int j;
01225 
01226                             UPDATE_CACHE(re, gb);
01227                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
01228 
01229                             if (!code) {
01230                                 *icf++ = 0;
01231                                 *icf++ = 0;
01232                                 continue;
01233                             }
01234 
01235                             cb_idx = cb_vector_idx[code];
01236                             nnz = cb_idx >> 12;
01237                             nzt = cb_idx >> 8;
01238                             bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
01239                             LAST_SKIP_BITS(re, gb, nnz);
01240 
01241                             for (j = 0; j < 2; j++) {
01242                                 if (nzt & 1<<j) {
01243                                     uint32_t b;
01244                                     int n;
01245                                     /* The total length of escape_sequence must be < 22 bits according
01246                                        to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
01247                                     UPDATE_CACHE(re, gb);
01248                                     b = GET_CACHE(re, gb);
01249                                     b = 31 - av_log2(~b);
01250 
01251                                     if (b > 8) {
01252                                         av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
01253                                         return -1;
01254                                     }
01255 
01256                                     SKIP_BITS(re, gb, b + 1);
01257                                     b += 4;
01258                                     n = (1 << b) + SHOW_UBITS(re, gb, b);
01259                                     LAST_SKIP_BITS(re, gb, b);
01260                                     *icf++ = cbrt_tab[n] | (bits & 1U<<31);
01261                                     bits <<= 1;
01262                                 } else {
01263                                     unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
01264                                     *icf++ = (bits & 1U<<31) | v;
01265                                     bits <<= !!v;
01266                                 }
01267                                 cb_idx >>= 4;
01268                             }
01269                         } while (len -= 2);
01270 
01271                         ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
01272                     }
01273                 }
01274 
01275                 CLOSE_READER(re, gb);
01276             }
01277         }
01278         coef += g_len << 7;
01279     }
01280 
01281     if (pulse_present) {
01282         idx = 0;
01283         for (i = 0; i < pulse->num_pulse; i++) {
01284             float co = coef_base[ pulse->pos[i] ];
01285             while (offsets[idx + 1] <= pulse->pos[i])
01286                 idx++;
01287             if (band_type[idx] != NOISE_BT && sf[idx]) {
01288                 float ico = -pulse->amp[i];
01289                 if (co) {
01290                     co /= sf[idx];
01291                     ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
01292                 }
01293                 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
01294             }
01295         }
01296     }
01297     return 0;
01298 }
01299 
01300 static av_always_inline float flt16_round(float pf)
01301 {
01302     union av_intfloat32 tmp;
01303     tmp.f = pf;
01304     tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
01305     return tmp.f;
01306 }
01307 
01308 static av_always_inline float flt16_even(float pf)
01309 {
01310     union av_intfloat32 tmp;
01311     tmp.f = pf;
01312     tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
01313     return tmp.f;
01314 }
01315 
01316 static av_always_inline float flt16_trunc(float pf)
01317 {
01318     union av_intfloat32 pun;
01319     pun.f = pf;
01320     pun.i &= 0xFFFF0000U;
01321     return pun.f;
01322 }
01323 
01324 static av_always_inline void predict(PredictorState *ps, float *coef,
01325                                      int output_enable)
01326 {
01327     const float a     = 0.953125; // 61.0 / 64
01328     const float alpha = 0.90625;  // 29.0 / 32
01329     float e0, e1;
01330     float pv;
01331     float k1, k2;
01332     float   r0 = ps->r0,     r1 = ps->r1;
01333     float cor0 = ps->cor0, cor1 = ps->cor1;
01334     float var0 = ps->var0, var1 = ps->var1;
01335 
01336     k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
01337     k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
01338 
01339     pv = flt16_round(k1 * r0 + k2 * r1);
01340     if (output_enable)
01341         *coef += pv;
01342 
01343     e0 = *coef;
01344     e1 = e0 - k1 * r0;
01345 
01346     ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
01347     ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
01348     ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
01349     ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
01350 
01351     ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
01352     ps->r0 = flt16_trunc(a * e0);
01353 }
01354 
01358 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
01359 {
01360     int sfb, k;
01361 
01362     if (!sce->ics.predictor_initialized) {
01363         reset_all_predictors(sce->predictor_state);
01364         sce->ics.predictor_initialized = 1;
01365     }
01366 
01367     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
01368         for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
01369             for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
01370                 predict(&sce->predictor_state[k], &sce->coeffs[k],
01371                         sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
01372             }
01373         }
01374         if (sce->ics.predictor_reset_group)
01375             reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
01376     } else
01377         reset_all_predictors(sce->predictor_state);
01378 }
01379 
01388 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
01389                       GetBitContext *gb, int common_window, int scale_flag)
01390 {
01391     Pulse pulse;
01392     TemporalNoiseShaping    *tns = &sce->tns;
01393     IndividualChannelStream *ics = &sce->ics;
01394     float *out = sce->coeffs;
01395     int global_gain, pulse_present = 0;
01396 
01397     /* This assignment is to silence a GCC warning about the variable being used
01398      * uninitialized when in fact it always is.
01399      */
01400     pulse.num_pulse = 0;
01401 
01402     global_gain = get_bits(gb, 8);
01403 
01404     if (!common_window && !scale_flag) {
01405         if (decode_ics_info(ac, ics, gb) < 0)
01406             return AVERROR_INVALIDDATA;
01407     }
01408 
01409     if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
01410         return -1;
01411     if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
01412         return -1;
01413 
01414     pulse_present = 0;
01415     if (!scale_flag) {
01416         if ((pulse_present = get_bits1(gb))) {
01417             if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01418                 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
01419                 return -1;
01420             }
01421             if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
01422                 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
01423                 return -1;
01424             }
01425         }
01426         if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
01427             return -1;
01428         if (get_bits1(gb)) {
01429             av_log_missing_feature(ac->avctx, "SSR", 1);
01430             return -1;
01431         }
01432     }
01433 
01434     if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
01435         return -1;
01436 
01437     if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
01438         apply_prediction(ac, sce);
01439 
01440     return 0;
01441 }
01442 
01446 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
01447 {
01448     const IndividualChannelStream *ics = &cpe->ch[0].ics;
01449     float *ch0 = cpe->ch[0].coeffs;
01450     float *ch1 = cpe->ch[1].coeffs;
01451     int g, i, group, idx = 0;
01452     const uint16_t *offsets = ics->swb_offset;
01453     for (g = 0; g < ics->num_window_groups; g++) {
01454         for (i = 0; i < ics->max_sfb; i++, idx++) {
01455             if (cpe->ms_mask[idx] &&
01456                     cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
01457                 for (group = 0; group < ics->group_len[g]; group++) {
01458                     ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
01459                                               ch1 + group * 128 + offsets[i],
01460                                               offsets[i+1] - offsets[i]);
01461                 }
01462             }
01463         }
01464         ch0 += ics->group_len[g] * 128;
01465         ch1 += ics->group_len[g] * 128;
01466     }
01467 }
01468 
01476 static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
01477 {
01478     const IndividualChannelStream *ics = &cpe->ch[1].ics;
01479     SingleChannelElement         *sce1 = &cpe->ch[1];
01480     float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
01481     const uint16_t *offsets = ics->swb_offset;
01482     int g, group, i, idx = 0;
01483     int c;
01484     float scale;
01485     for (g = 0; g < ics->num_window_groups; g++) {
01486         for (i = 0; i < ics->max_sfb;) {
01487             if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
01488                 const int bt_run_end = sce1->band_type_run_end[idx];
01489                 for (; i < bt_run_end; i++, idx++) {
01490                     c = -1 + 2 * (sce1->band_type[idx] - 14);
01491                     if (ms_present)
01492                         c *= 1 - 2 * cpe->ms_mask[idx];
01493                     scale = c * sce1->sf[idx];
01494                     for (group = 0; group < ics->group_len[g]; group++)
01495                         ac->dsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
01496                                                    coef0 + group * 128 + offsets[i],
01497                                                    scale,
01498                                                    offsets[i + 1] - offsets[i]);
01499                 }
01500             } else {
01501                 int bt_run_end = sce1->band_type_run_end[idx];
01502                 idx += bt_run_end - i;
01503                 i    = bt_run_end;
01504             }
01505         }
01506         coef0 += ics->group_len[g] * 128;
01507         coef1 += ics->group_len[g] * 128;
01508     }
01509 }
01510 
01516 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
01517 {
01518     int i, ret, common_window, ms_present = 0;
01519 
01520     common_window = get_bits1(gb);
01521     if (common_window) {
01522         if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
01523             return AVERROR_INVALIDDATA;
01524         i = cpe->ch[1].ics.use_kb_window[0];
01525         cpe->ch[1].ics = cpe->ch[0].ics;
01526         cpe->ch[1].ics.use_kb_window[1] = i;
01527         if (cpe->ch[1].ics.predictor_present && (ac->m4ac.object_type != AOT_AAC_MAIN))
01528             if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
01529                 decode_ltp(ac, &cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
01530         ms_present = get_bits(gb, 2);
01531         if (ms_present == 3) {
01532             av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
01533             return -1;
01534         } else if (ms_present)
01535             decode_mid_side_stereo(cpe, gb, ms_present);
01536     }
01537     if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
01538         return ret;
01539     if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
01540         return ret;
01541 
01542     if (common_window) {
01543         if (ms_present)
01544             apply_mid_side_stereo(ac, cpe);
01545         if (ac->m4ac.object_type == AOT_AAC_MAIN) {
01546             apply_prediction(ac, &cpe->ch[0]);
01547             apply_prediction(ac, &cpe->ch[1]);
01548         }
01549     }
01550 
01551     apply_intensity_stereo(ac, cpe, ms_present);
01552     return 0;
01553 }
01554 
01555 static const float cce_scale[] = {
01556     1.09050773266525765921, //2^(1/8)
01557     1.18920711500272106672, //2^(1/4)
01558     M_SQRT2,
01559     2,
01560 };
01561 
01567 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
01568 {
01569     int num_gain = 0;
01570     int c, g, sfb, ret;
01571     int sign;
01572     float scale;
01573     SingleChannelElement *sce = &che->ch[0];
01574     ChannelCoupling     *coup = &che->coup;
01575 
01576     coup->coupling_point = 2 * get_bits1(gb);
01577     coup->num_coupled = get_bits(gb, 3);
01578     for (c = 0; c <= coup->num_coupled; c++) {
01579         num_gain++;
01580         coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
01581         coup->id_select[c] = get_bits(gb, 4);
01582         if (coup->type[c] == TYPE_CPE) {
01583             coup->ch_select[c] = get_bits(gb, 2);
01584             if (coup->ch_select[c] == 3)
01585                 num_gain++;
01586         } else
01587             coup->ch_select[c] = 2;
01588     }
01589     coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
01590 
01591     sign  = get_bits(gb, 1);
01592     scale = cce_scale[get_bits(gb, 2)];
01593 
01594     if ((ret = decode_ics(ac, sce, gb, 0, 0)))
01595         return ret;
01596 
01597     for (c = 0; c < num_gain; c++) {
01598         int idx  = 0;
01599         int cge  = 1;
01600         int gain = 0;
01601         float gain_cache = 1.;
01602         if (c) {
01603             cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
01604             gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
01605             gain_cache = powf(scale, -gain);
01606         }
01607         if (coup->coupling_point == AFTER_IMDCT) {
01608             coup->gain[c][0] = gain_cache;
01609         } else {
01610             for (g = 0; g < sce->ics.num_window_groups; g++) {
01611                 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
01612                     if (sce->band_type[idx] != ZERO_BT) {
01613                         if (!cge) {
01614                             int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
01615                             if (t) {
01616                                 int s = 1;
01617                                 t = gain += t;
01618                                 if (sign) {
01619                                     s  -= 2 * (t & 0x1);
01620                                     t >>= 1;
01621                                 }
01622                                 gain_cache = powf(scale, -t) * s;
01623                             }
01624                         }
01625                         coup->gain[c][idx] = gain_cache;
01626                     }
01627                 }
01628             }
01629         }
01630     }
01631     return 0;
01632 }
01633 
01639 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
01640                                          GetBitContext *gb)
01641 {
01642     int i;
01643     int num_excl_chan = 0;
01644 
01645     do {
01646         for (i = 0; i < 7; i++)
01647             che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
01648     } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
01649 
01650     return num_excl_chan / 7;
01651 }
01652 
01660 static int decode_dynamic_range(DynamicRangeControl *che_drc,
01661                                 GetBitContext *gb, int cnt)
01662 {
01663     int n             = 1;
01664     int drc_num_bands = 1;
01665     int i;
01666 
01667     /* pce_tag_present? */
01668     if (get_bits1(gb)) {
01669         che_drc->pce_instance_tag  = get_bits(gb, 4);
01670         skip_bits(gb, 4); // tag_reserved_bits
01671         n++;
01672     }
01673 
01674     /* excluded_chns_present? */
01675     if (get_bits1(gb)) {
01676         n += decode_drc_channel_exclusions(che_drc, gb);
01677     }
01678 
01679     /* drc_bands_present? */
01680     if (get_bits1(gb)) {
01681         che_drc->band_incr            = get_bits(gb, 4);
01682         che_drc->interpolation_scheme = get_bits(gb, 4);
01683         n++;
01684         drc_num_bands += che_drc->band_incr;
01685         for (i = 0; i < drc_num_bands; i++) {
01686             che_drc->band_top[i] = get_bits(gb, 8);
01687             n++;
01688         }
01689     }
01690 
01691     /* prog_ref_level_present? */
01692     if (get_bits1(gb)) {
01693         che_drc->prog_ref_level = get_bits(gb, 7);
01694         skip_bits1(gb); // prog_ref_level_reserved_bits
01695         n++;
01696     }
01697 
01698     for (i = 0; i < drc_num_bands; i++) {
01699         che_drc->dyn_rng_sgn[i] = get_bits1(gb);
01700         che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
01701         n++;
01702     }
01703 
01704     return n;
01705 }
01706 
01714 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
01715                                     ChannelElement *che, enum RawDataBlockType elem_type)
01716 {
01717     int crc_flag = 0;
01718     int res = cnt;
01719     switch (get_bits(gb, 4)) { // extension type
01720     case EXT_SBR_DATA_CRC:
01721         crc_flag++;
01722     case EXT_SBR_DATA:
01723         if (!che) {
01724             av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
01725             return res;
01726         } else if (!ac->m4ac.sbr) {
01727             av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
01728             skip_bits_long(gb, 8 * cnt - 4);
01729             return res;
01730         } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
01731             av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
01732             skip_bits_long(gb, 8 * cnt - 4);
01733             return res;
01734         } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
01735             ac->m4ac.sbr = 1;
01736             ac->m4ac.ps = 1;
01737             output_configure(ac, ac->che_pos, ac->che_pos, ac->m4ac.chan_config, ac->output_configured);
01738         } else {
01739             ac->m4ac.sbr = 1;
01740         }
01741         res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
01742         break;
01743     case EXT_DYNAMIC_RANGE:
01744         res = decode_dynamic_range(&ac->che_drc, gb, cnt);
01745         break;
01746     case EXT_FILL:
01747     case EXT_FILL_DATA:
01748     case EXT_DATA_ELEMENT:
01749     default:
01750         skip_bits_long(gb, 8 * cnt - 4);
01751         break;
01752     };
01753     return res;
01754 }
01755 
01762 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
01763                       IndividualChannelStream *ics, int decode)
01764 {
01765     const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
01766     int w, filt, m, i;
01767     int bottom, top, order, start, end, size, inc;
01768     float lpc[TNS_MAX_ORDER];
01769     float tmp[TNS_MAX_ORDER];
01770 
01771     for (w = 0; w < ics->num_windows; w++) {
01772         bottom = ics->num_swb;
01773         for (filt = 0; filt < tns->n_filt[w]; filt++) {
01774             top    = bottom;
01775             bottom = FFMAX(0, top - tns->length[w][filt]);
01776             order  = tns->order[w][filt];
01777             if (order == 0)
01778                 continue;
01779 
01780             // tns_decode_coef
01781             compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
01782 
01783             start = ics->swb_offset[FFMIN(bottom, mmm)];
01784             end   = ics->swb_offset[FFMIN(   top, mmm)];
01785             if ((size = end - start) <= 0)
01786                 continue;
01787             if (tns->direction[w][filt]) {
01788                 inc = -1;
01789                 start = end - 1;
01790             } else {
01791                 inc = 1;
01792             }
01793             start += w * 128;
01794 
01795             if (decode) {
01796                 // ar filter
01797                 for (m = 0; m < size; m++, start += inc)
01798                     for (i = 1; i <= FFMIN(m, order); i++)
01799                         coef[start] -= coef[start - i * inc] * lpc[i - 1];
01800             } else {
01801                 // ma filter
01802                 for (m = 0; m < size; m++, start += inc) {
01803                     tmp[0] = coef[start];
01804                     for (i = 1; i <= FFMIN(m, order); i++)
01805                         coef[start] += tmp[i] * lpc[i - 1];
01806                     for (i = order; i > 0; i--)
01807                         tmp[i] = tmp[i - 1];
01808                 }
01809             }
01810         }
01811     }
01812 }
01813 
01818 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
01819                                    float *in, IndividualChannelStream *ics)
01820 {
01821     const float *lwindow      = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01822     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
01823     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01824     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
01825 
01826     if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
01827         ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);
01828     } else {
01829         memset(in, 0, 448 * sizeof(float));
01830         ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
01831     }
01832     if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
01833         ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
01834     } else {
01835         ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
01836         memset(in + 1024 + 576, 0, 448 * sizeof(float));
01837     }
01838     ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
01839 }
01840 
01844 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
01845 {
01846     const LongTermPrediction *ltp = &sce->ics.ltp;
01847     const uint16_t *offsets = sce->ics.swb_offset;
01848     int i, sfb;
01849 
01850     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
01851         float *predTime = sce->ret;
01852         float *predFreq = ac->buf_mdct;
01853         int16_t num_samples = 2048;
01854 
01855         if (ltp->lag < 1024)
01856             num_samples = ltp->lag + 1024;
01857         for (i = 0; i < num_samples; i++)
01858             predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
01859         memset(&predTime[i], 0, (2048 - i) * sizeof(float));
01860 
01861         windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
01862 
01863         if (sce->tns.present)
01864             apply_tns(predFreq, &sce->tns, &sce->ics, 0);
01865 
01866         for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
01867             if (ltp->used[sfb])
01868                 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
01869                     sce->coeffs[i] += predFreq[i];
01870     }
01871 }
01872 
01876 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
01877 {
01878     IndividualChannelStream *ics = &sce->ics;
01879     float *saved     = sce->saved;
01880     float *saved_ltp = sce->coeffs;
01881     const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01882     const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
01883     int i;
01884 
01885     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01886         memcpy(saved_ltp,       saved, 512 * sizeof(float));
01887         memset(saved_ltp + 576, 0,     448 * sizeof(float));
01888         ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
01889         for (i = 0; i < 64; i++)
01890             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
01891     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
01892         memcpy(saved_ltp,       ac->buf_mdct + 512, 448 * sizeof(float));
01893         memset(saved_ltp + 576, 0,                  448 * sizeof(float));
01894         ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
01895         for (i = 0; i < 64; i++)
01896             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
01897     } else { // LONG_STOP or ONLY_LONG
01898         ac->dsp.vector_fmul_reverse(saved_ltp,       ac->buf_mdct + 512,     &lwindow[512],     512);
01899         for (i = 0; i < 512; i++)
01900             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
01901     }
01902 
01903     memcpy(sce->ltp_state,      sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
01904     memcpy(sce->ltp_state+1024, sce->ret,            1024 * sizeof(*sce->ltp_state));
01905     memcpy(sce->ltp_state+2048, saved_ltp,           1024 * sizeof(*sce->ltp_state));
01906 }
01907 
01911 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
01912 {
01913     IndividualChannelStream *ics = &sce->ics;
01914     float *in    = sce->coeffs;
01915     float *out   = sce->ret;
01916     float *saved = sce->saved;
01917     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
01918     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
01919     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
01920     float *buf  = ac->buf_mdct;
01921     float *temp = ac->temp;
01922     int i;
01923 
01924     // imdct
01925     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01926         for (i = 0; i < 1024; i += 128)
01927             ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
01928     } else
01929         ac->mdct.imdct_half(&ac->mdct, buf, in);
01930 
01931     /* window overlapping
01932      * NOTE: To simplify the overlapping code, all 'meaningless' short to long
01933      * and long to short transitions are considered to be short to short
01934      * transitions. This leaves just two cases (long to long and short to short)
01935      * with a little special sauce for EIGHT_SHORT_SEQUENCE.
01936      */
01937     if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
01938             (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
01939         ac->dsp.vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 512);
01940     } else {
01941         memcpy(                        out,               saved,            448 * sizeof(float));
01942 
01943         if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01944             ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, 64);
01945             ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      64);
01946             ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      64);
01947             ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      64);
01948             ac->dsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      64);
01949             memcpy(                    out + 448 + 4*128, temp, 64 * sizeof(float));
01950         } else {
01951             ac->dsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 64);
01952             memcpy(                    out + 576,         buf + 64,         448 * sizeof(float));
01953         }
01954     }
01955 
01956     // buffer update
01957     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
01958         memcpy(                    saved,       temp + 64,         64 * sizeof(float));
01959         ac->dsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 64);
01960         ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
01961         ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
01962         memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
01963     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
01964         memcpy(                    saved,       buf + 512,        448 * sizeof(float));
01965         memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
01966     } else { // LONG_STOP or ONLY_LONG
01967         memcpy(                    saved,       buf + 512,        512 * sizeof(float));
01968     }
01969 }
01970 
01976 static void apply_dependent_coupling(AACContext *ac,
01977                                      SingleChannelElement *target,
01978                                      ChannelElement *cce, int index)
01979 {
01980     IndividualChannelStream *ics = &cce->ch[0].ics;
01981     const uint16_t *offsets = ics->swb_offset;
01982     float *dest = target->coeffs;
01983     const float *src = cce->ch[0].coeffs;
01984     int g, i, group, k, idx = 0;
01985     if (ac->m4ac.object_type == AOT_AAC_LTP) {
01986         av_log(ac->avctx, AV_LOG_ERROR,
01987                "Dependent coupling is not supported together with LTP\n");
01988         return;
01989     }
01990     for (g = 0; g < ics->num_window_groups; g++) {
01991         for (i = 0; i < ics->max_sfb; i++, idx++) {
01992             if (cce->ch[0].band_type[idx] != ZERO_BT) {
01993                 const float gain = cce->coup.gain[index][idx];
01994                 for (group = 0; group < ics->group_len[g]; group++) {
01995                     for (k = offsets[i]; k < offsets[i + 1]; k++) {
01996                         // XXX dsputil-ize
01997                         dest[group * 128 + k] += gain * src[group * 128 + k];
01998                     }
01999                 }
02000             }
02001         }
02002         dest += ics->group_len[g] * 128;
02003         src  += ics->group_len[g] * 128;
02004     }
02005 }
02006 
02012 static void apply_independent_coupling(AACContext *ac,
02013                                        SingleChannelElement *target,
02014                                        ChannelElement *cce, int index)
02015 {
02016     int i;
02017     const float gain = cce->coup.gain[index][0];
02018     const float *src = cce->ch[0].ret;
02019     float *dest = target->ret;
02020     const int len = 1024 << (ac->m4ac.sbr == 1);
02021 
02022     for (i = 0; i < len; i++)
02023         dest[i] += gain * src[i];
02024 }
02025 
02031 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
02032                                    enum RawDataBlockType type, int elem_id,
02033                                    enum CouplingPoint coupling_point,
02034                                    void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
02035 {
02036     int i, c;
02037 
02038     for (i = 0; i < MAX_ELEM_ID; i++) {
02039         ChannelElement *cce = ac->che[TYPE_CCE][i];
02040         int index = 0;
02041 
02042         if (cce && cce->coup.coupling_point == coupling_point) {
02043             ChannelCoupling *coup = &cce->coup;
02044 
02045             for (c = 0; c <= coup->num_coupled; c++) {
02046                 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
02047                     if (coup->ch_select[c] != 1) {
02048                         apply_coupling_method(ac, &cc->ch[0], cce, index);
02049                         if (coup->ch_select[c] != 0)
02050                             index++;
02051                     }
02052                     if (coup->ch_select[c] != 2)
02053                         apply_coupling_method(ac, &cc->ch[1], cce, index++);
02054                 } else
02055                     index += 1 + (coup->ch_select[c] == 3);
02056             }
02057         }
02058     }
02059 }
02060 
02064 static void spectral_to_sample(AACContext *ac)
02065 {
02066     int i, type;
02067     for (type = 3; type >= 0; type--) {
02068         for (i = 0; i < MAX_ELEM_ID; i++) {
02069             ChannelElement *che = ac->che[type][i];
02070             if (che) {
02071                 if (type <= TYPE_CPE)
02072                     apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
02073                 if (ac->m4ac.object_type == AOT_AAC_LTP) {
02074                     if (che->ch[0].ics.predictor_present) {
02075                         if (che->ch[0].ics.ltp.present)
02076                             apply_ltp(ac, &che->ch[0]);
02077                         if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
02078                             apply_ltp(ac, &che->ch[1]);
02079                     }
02080                 }
02081                 if (che->ch[0].tns.present)
02082                     apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
02083                 if (che->ch[1].tns.present)
02084                     apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
02085                 if (type <= TYPE_CPE)
02086                     apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
02087                 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
02088                     imdct_and_windowing(ac, &che->ch[0]);
02089                     if (ac->m4ac.object_type == AOT_AAC_LTP)
02090                         update_ltp(ac, &che->ch[0]);
02091                     if (type == TYPE_CPE) {
02092                         imdct_and_windowing(ac, &che->ch[1]);
02093                         if (ac->m4ac.object_type == AOT_AAC_LTP)
02094                             update_ltp(ac, &che->ch[1]);
02095                     }
02096                     if (ac->m4ac.sbr > 0) {
02097                         ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
02098                     }
02099                 }
02100                 if (type <= TYPE_CCE)
02101                     apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
02102             }
02103         }
02104     }
02105 }
02106 
02107 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
02108 {
02109     int size;
02110     AACADTSHeaderInfo hdr_info;
02111 
02112     size = avpriv_aac_parse_header(gb, &hdr_info);
02113     if (size > 0) {
02114         if (hdr_info.chan_config) {
02115             enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
02116             memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
02117             ac->m4ac.chan_config = hdr_info.chan_config;
02118             if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
02119                 return -7;
02120             if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config,
02121                                  FFMAX(ac->output_configured, OC_TRIAL_FRAME)))
02122                 return -7;
02123         } else if (ac->output_configured != OC_LOCKED) {
02124             ac->m4ac.chan_config = 0;
02125             ac->output_configured = OC_NONE;
02126         }
02127         if (ac->output_configured != OC_LOCKED) {
02128             ac->m4ac.sbr = -1;
02129             ac->m4ac.ps  = -1;
02130             ac->m4ac.sample_rate     = hdr_info.sample_rate;
02131             ac->m4ac.sampling_index  = hdr_info.sampling_index;
02132             ac->m4ac.object_type     = hdr_info.object_type;
02133         }
02134         if (!ac->avctx->sample_rate)
02135             ac->avctx->sample_rate = hdr_info.sample_rate;
02136         if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
02137             // This is 2 for "VLB " audio in NSV files.
02138             // See samples/nsv/vlb_audio.
02139             av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
02140             ac->warned_num_aac_frames = 1;
02141         }
02142         if (!hdr_info.crc_absent)
02143             skip_bits(gb, 16);
02144     }
02145     return size;
02146 }
02147 
02148 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
02149                                 int *got_frame_ptr, GetBitContext *gb)
02150 {
02151     AACContext *ac = avctx->priv_data;
02152     ChannelElement *che = NULL, *che_prev = NULL;
02153     enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
02154     int err, elem_id;
02155     int samples = 0, multiplier, audio_found = 0;
02156 
02157     if (show_bits(gb, 12) == 0xfff) {
02158         if (parse_adts_frame_header(ac, gb) < 0) {
02159             av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
02160             return -1;
02161         }
02162         if (ac->m4ac.sampling_index > 12) {
02163             av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
02164             return -1;
02165         }
02166     }
02167 
02168     ac->tags_mapped = 0;
02169     // parse
02170     while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
02171         elem_id = get_bits(gb, 4);
02172 
02173         if (elem_type < TYPE_DSE) {
02174             if (!ac->tags_mapped && elem_type == TYPE_CPE && ac->m4ac.chan_config==1) {
02175                 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID]= {0};
02176                 ac->m4ac.chan_config=2;
02177 
02178                 if (set_default_channel_config(ac->avctx, new_che_pos, 2)<0)
02179                     return -1;
02180                 if (output_configure(ac, ac->che_pos, new_che_pos, 2, OC_TRIAL_FRAME)<0)
02181                     return -1;
02182             }
02183             if (!(che=get_che(ac, elem_type, elem_id))) {
02184                 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
02185                        elem_type, elem_id);
02186                 return -1;
02187             }
02188             samples = 1024;
02189         }
02190 
02191         switch (elem_type) {
02192 
02193         case TYPE_SCE:
02194             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
02195             audio_found = 1;
02196             break;
02197 
02198         case TYPE_CPE:
02199             err = decode_cpe(ac, gb, che);
02200             audio_found = 1;
02201             break;
02202 
02203         case TYPE_CCE:
02204             err = decode_cce(ac, gb, che);
02205             break;
02206 
02207         case TYPE_LFE:
02208             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
02209             audio_found = 1;
02210             break;
02211 
02212         case TYPE_DSE:
02213             err = skip_data_stream_element(ac, gb);
02214             break;
02215 
02216         case TYPE_PCE: {
02217             enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
02218             memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
02219             if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
02220                 break;
02221             if (ac->output_configured > OC_TRIAL_PCE)
02222                 av_log(avctx, AV_LOG_INFO,
02223                        "Evaluating a further program_config_element.\n");
02224             err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
02225             if (!err)
02226                 ac->m4ac.chan_config = 0;
02227             break;
02228         }
02229 
02230         case TYPE_FIL:
02231             if (elem_id == 15)
02232                 elem_id += get_bits(gb, 8) - 1;
02233             if (get_bits_left(gb) < 8 * elem_id) {
02234                     av_log(avctx, AV_LOG_ERROR, overread_err);
02235                     return -1;
02236             }
02237             while (elem_id > 0)
02238                 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
02239             err = 0; /* FIXME */
02240             break;
02241 
02242         default:
02243             err = -1; /* should not happen, but keeps compiler happy */
02244             break;
02245         }
02246 
02247         che_prev       = che;
02248         elem_type_prev = elem_type;
02249 
02250         if (err)
02251             return err;
02252 
02253         if (get_bits_left(gb) < 3) {
02254             av_log(avctx, AV_LOG_ERROR, overread_err);
02255             return -1;
02256         }
02257     }
02258 
02259     spectral_to_sample(ac);
02260 
02261     multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
02262     samples <<= multiplier;
02263     if (ac->output_configured < OC_LOCKED) {
02264         avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
02265         avctx->frame_size = samples;
02266     }
02267 
02268     if (samples) {
02269         /* get output buffer */
02270         ac->frame.nb_samples = samples;
02271         if ((err = avctx->get_buffer(avctx, &ac->frame)) < 0) {
02272             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
02273             return err;
02274         }
02275 
02276         if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
02277             ac->fmt_conv.float_interleave((float *)ac->frame.data[0],
02278                                           (const float **)ac->output_data,
02279                                           samples, avctx->channels);
02280         else
02281             ac->fmt_conv.float_to_int16_interleave((int16_t *)ac->frame.data[0],
02282                                                    (const float **)ac->output_data,
02283                                                    samples, avctx->channels);
02284 
02285         *(AVFrame *)data = ac->frame;
02286     }
02287     *got_frame_ptr = !!samples;
02288 
02289     if (ac->output_configured && audio_found)
02290         ac->output_configured = OC_LOCKED;
02291 
02292     return 0;
02293 }
02294 
02295 static int aac_decode_frame(AVCodecContext *avctx, void *data,
02296                             int *got_frame_ptr, AVPacket *avpkt)
02297 {
02298     AACContext *ac = avctx->priv_data;
02299     const uint8_t *buf = avpkt->data;
02300     int buf_size = avpkt->size;
02301     GetBitContext gb;
02302     int buf_consumed;
02303     int buf_offset;
02304     int err;
02305     int new_extradata_size;
02306     const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
02307                                        AV_PKT_DATA_NEW_EXTRADATA,
02308                                        &new_extradata_size);
02309 
02310     if (new_extradata) {
02311         av_free(avctx->extradata);
02312         avctx->extradata = av_mallocz(new_extradata_size +
02313                                       FF_INPUT_BUFFER_PADDING_SIZE);
02314         if (!avctx->extradata)
02315             return AVERROR(ENOMEM);
02316         avctx->extradata_size = new_extradata_size;
02317         memcpy(avctx->extradata, new_extradata, new_extradata_size);
02318         if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
02319                                          avctx->extradata,
02320                                          avctx->extradata_size*8, 1) < 0)
02321             return AVERROR_INVALIDDATA;
02322     }
02323 
02324     init_get_bits(&gb, buf, buf_size * 8);
02325 
02326     if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb)) < 0)
02327         return err;
02328 
02329     buf_consumed = (get_bits_count(&gb) + 7) >> 3;
02330     for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
02331         if (buf[buf_offset])
02332             break;
02333 
02334     return buf_size > buf_offset ? buf_consumed : buf_size;
02335 }
02336 
02337 static av_cold int aac_decode_close(AVCodecContext *avctx)
02338 {
02339     AACContext *ac = avctx->priv_data;
02340     int i, type;
02341 
02342     for (i = 0; i < MAX_ELEM_ID; i++) {
02343         for (type = 0; type < 4; type++) {
02344             if (ac->che[type][i])
02345                 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
02346             av_freep(&ac->che[type][i]);
02347         }
02348     }
02349 
02350     ff_mdct_end(&ac->mdct);
02351     ff_mdct_end(&ac->mdct_small);
02352     ff_mdct_end(&ac->mdct_ltp);
02353     return 0;
02354 }
02355 
02356 
02357 #define LOAS_SYNC_WORD   0x2b7       ///< 11 bits LOAS sync word
02358 
02359 struct LATMContext {
02360     AACContext      aac_ctx;             
02361     int             initialized;         
02362 
02363     // parser data
02364     int             audio_mux_version_A; 
02365     int             frame_length_type;   
02366     int             frame_length;        
02367 };
02368 
02369 static inline uint32_t latm_get_value(GetBitContext *b)
02370 {
02371     int length = get_bits(b, 2);
02372 
02373     return get_bits_long(b, (length+1)*8);
02374 }
02375 
02376 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
02377                                              GetBitContext *gb, int asclen)
02378 {
02379     AACContext *ac        = &latmctx->aac_ctx;
02380     AVCodecContext *avctx = ac->avctx;
02381     MPEG4AudioConfig m4ac = {0};
02382     int config_start_bit  = get_bits_count(gb);
02383     int sync_extension    = 0;
02384     int bits_consumed, esize;
02385 
02386     if (asclen) {
02387         sync_extension = 1;
02388         asclen         = FFMIN(asclen, get_bits_left(gb));
02389     } else
02390         asclen         = get_bits_left(gb);
02391 
02392     if (config_start_bit % 8) {
02393         av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
02394                                "config not byte aligned.\n", 1);
02395         return AVERROR_INVALIDDATA;
02396     }
02397     if (asclen <= 0)
02398         return AVERROR_INVALIDDATA;
02399     bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
02400                                          gb->buffer + (config_start_bit / 8),
02401                                          asclen, sync_extension);
02402 
02403     if (bits_consumed < 0)
02404         return AVERROR_INVALIDDATA;
02405 
02406     if (ac->m4ac.sample_rate != m4ac.sample_rate ||
02407         ac->m4ac.chan_config != m4ac.chan_config) {
02408 
02409         av_log(avctx, AV_LOG_INFO, "audio config changed\n");
02410         latmctx->initialized = 0;
02411 
02412         esize = (bits_consumed+7) / 8;
02413 
02414         if (avctx->extradata_size < esize) {
02415             av_free(avctx->extradata);
02416             avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
02417             if (!avctx->extradata)
02418                 return AVERROR(ENOMEM);
02419         }
02420 
02421         avctx->extradata_size = esize;
02422         memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
02423         memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
02424     }
02425     skip_bits_long(gb, bits_consumed);
02426 
02427     return bits_consumed;
02428 }
02429 
02430 static int read_stream_mux_config(struct LATMContext *latmctx,
02431                                   GetBitContext *gb)
02432 {
02433     int ret, audio_mux_version = get_bits(gb, 1);
02434 
02435     latmctx->audio_mux_version_A = 0;
02436     if (audio_mux_version)
02437         latmctx->audio_mux_version_A = get_bits(gb, 1);
02438 
02439     if (!latmctx->audio_mux_version_A) {
02440 
02441         if (audio_mux_version)
02442             latm_get_value(gb);                 // taraFullness
02443 
02444         skip_bits(gb, 1);                       // allStreamSameTimeFraming
02445         skip_bits(gb, 6);                       // numSubFrames
02446         // numPrograms
02447         if (get_bits(gb, 4)) {                  // numPrograms
02448             av_log_missing_feature(latmctx->aac_ctx.avctx,
02449                                    "multiple programs are not supported\n", 1);
02450             return AVERROR_PATCHWELCOME;
02451         }
02452 
02453         // for each program (which there is only on in DVB)
02454 
02455         // for each layer (which there is only on in DVB)
02456         if (get_bits(gb, 3)) {                   // numLayer
02457             av_log_missing_feature(latmctx->aac_ctx.avctx,
02458                                    "multiple layers are not supported\n", 1);
02459             return AVERROR_PATCHWELCOME;
02460         }
02461 
02462         // for all but first stream: use_same_config = get_bits(gb, 1);
02463         if (!audio_mux_version) {
02464             if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
02465                 return ret;
02466         } else {
02467             int ascLen = latm_get_value(gb);
02468             if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
02469                 return ret;
02470             ascLen -= ret;
02471             skip_bits_long(gb, ascLen);
02472         }
02473 
02474         latmctx->frame_length_type = get_bits(gb, 3);
02475         switch (latmctx->frame_length_type) {
02476         case 0:
02477             skip_bits(gb, 8);       // latmBufferFullness
02478             break;
02479         case 1:
02480             latmctx->frame_length = get_bits(gb, 9);
02481             break;
02482         case 3:
02483         case 4:
02484         case 5:
02485             skip_bits(gb, 6);       // CELP frame length table index
02486             break;
02487         case 6:
02488         case 7:
02489             skip_bits(gb, 1);       // HVXC frame length table index
02490             break;
02491         }
02492 
02493         if (get_bits(gb, 1)) {                  // other data
02494             if (audio_mux_version) {
02495                 latm_get_value(gb);             // other_data_bits
02496             } else {
02497                 int esc;
02498                 do {
02499                     esc = get_bits(gb, 1);
02500                     skip_bits(gb, 8);
02501                 } while (esc);
02502             }
02503         }
02504 
02505         if (get_bits(gb, 1))                     // crc present
02506             skip_bits(gb, 8);                    // config_crc
02507     }
02508 
02509     return 0;
02510 }
02511 
02512 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
02513 {
02514     uint8_t tmp;
02515 
02516     if (ctx->frame_length_type == 0) {
02517         int mux_slot_length = 0;
02518         do {
02519             tmp = get_bits(gb, 8);
02520             mux_slot_length += tmp;
02521         } while (tmp == 255);
02522         return mux_slot_length;
02523     } else if (ctx->frame_length_type == 1) {
02524         return ctx->frame_length;
02525     } else if (ctx->frame_length_type == 3 ||
02526                ctx->frame_length_type == 5 ||
02527                ctx->frame_length_type == 7) {
02528         skip_bits(gb, 2);          // mux_slot_length_coded
02529     }
02530     return 0;
02531 }
02532 
02533 static int read_audio_mux_element(struct LATMContext *latmctx,
02534                                   GetBitContext *gb)
02535 {
02536     int err;
02537     uint8_t use_same_mux = get_bits(gb, 1);
02538     if (!use_same_mux) {
02539         if ((err = read_stream_mux_config(latmctx, gb)) < 0)
02540             return err;
02541     } else if (!latmctx->aac_ctx.avctx->extradata) {
02542         av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
02543                "no decoder config found\n");
02544         return AVERROR(EAGAIN);
02545     }
02546     if (latmctx->audio_mux_version_A == 0) {
02547         int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
02548         if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
02549             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
02550             return AVERROR_INVALIDDATA;
02551         } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
02552             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
02553                    "frame length mismatch %d << %d\n",
02554                    mux_slot_length_bytes * 8, get_bits_left(gb));
02555             return AVERROR_INVALIDDATA;
02556         }
02557     }
02558     return 0;
02559 }
02560 
02561 
02562 static int latm_decode_frame(AVCodecContext *avctx, void *out,
02563                              int *got_frame_ptr, AVPacket *avpkt)
02564 {
02565     struct LATMContext *latmctx = avctx->priv_data;
02566     int                 muxlength, err;
02567     GetBitContext       gb;
02568 
02569     init_get_bits(&gb, avpkt->data, avpkt->size * 8);
02570 
02571     // check for LOAS sync word
02572     if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
02573         return AVERROR_INVALIDDATA;
02574 
02575     muxlength = get_bits(&gb, 13) + 3;
02576     // not enough data, the parser should have sorted this
02577     if (muxlength > avpkt->size)
02578         return AVERROR_INVALIDDATA;
02579 
02580     if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
02581         return err;
02582 
02583     if (!latmctx->initialized) {
02584         if (!avctx->extradata) {
02585             *got_frame_ptr = 0;
02586             return avpkt->size;
02587         } else {
02588             if ((err = decode_audio_specific_config(
02589                     &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.m4ac,
02590                     avctx->extradata, avctx->extradata_size*8, 1)) < 0)
02591                 return err;
02592             latmctx->initialized = 1;
02593         }
02594     }
02595 
02596     if (show_bits(&gb, 12) == 0xfff) {
02597         av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
02598                "ADTS header detected, probably as result of configuration "
02599                "misparsing\n");
02600         return AVERROR_INVALIDDATA;
02601     }
02602 
02603     if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
02604         return err;
02605 
02606     return muxlength;
02607 }
02608 
02609 av_cold static int latm_decode_init(AVCodecContext *avctx)
02610 {
02611     struct LATMContext *latmctx = avctx->priv_data;
02612     int ret = aac_decode_init(avctx);
02613 
02614     if (avctx->extradata_size > 0)
02615         latmctx->initialized = !ret;
02616 
02617     return ret;
02618 }
02619 
02620 
02621 AVCodec ff_aac_decoder = {
02622     .name           = "aac",
02623     .type           = AVMEDIA_TYPE_AUDIO,
02624     .id             = CODEC_ID_AAC,
02625     .priv_data_size = sizeof(AACContext),
02626     .init           = aac_decode_init,
02627     .close          = aac_decode_close,
02628     .decode         = aac_decode_frame,
02629     .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
02630     .sample_fmts = (const enum AVSampleFormat[]) {
02631         AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
02632     },
02633     .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
02634     .channel_layouts = aac_channel_layout,
02635 };
02636 
02637 /*
02638     Note: This decoder filter is intended to decode LATM streams transferred
02639     in MPEG transport streams which only contain one program.
02640     To do a more complex LATM demuxing a separate LATM demuxer should be used.
02641 */
02642 AVCodec ff_aac_latm_decoder = {
02643     .name = "aac_latm",
02644     .type = AVMEDIA_TYPE_AUDIO,
02645     .id   = CODEC_ID_AAC_LATM,
02646     .priv_data_size = sizeof(struct LATMContext),
02647     .init   = latm_decode_init,
02648     .close  = aac_decode_close,
02649     .decode = latm_decode_frame,
02650     .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
02651     .sample_fmts = (const enum AVSampleFormat[]) {
02652         AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
02653     },
02654     .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
02655     .channel_layouts = aac_channel_layout,
02656     .flush = flush,
02657 };