Statistics
| Branch: | Revision:

ffmpeg / libavcodec / aacdec.c @ d36beb3f

History | View | Annotate | Download (82.4 KB)

1
/*
2
 * AAC decoder
3
 * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
4
 * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
5
 *
6
 * AAC LATM decoder
7
 * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
8
 * Copyright (c) 2010      Janne Grunau <janne-ffmpeg@jannau.net>
9
 *
10
 * This file is part of FFmpeg.
11
 *
12
 * FFmpeg is free software; you can redistribute it and/or
13
 * modify it under the terms of the GNU Lesser General Public
14
 * License as published by the Free Software Foundation; either
15
 * version 2.1 of the License, or (at your option) any later version.
16
 *
17
 * FFmpeg is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20
 * Lesser General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Lesser General Public
23
 * License along with FFmpeg; if not, write to the Free Software
24
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25
 */
26

    
27
/**
28
 * @file
29
 * AAC decoder
30
 * @author Oded Shimon  ( ods15 ods15 dyndns org )
31
 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
32
 */
33

    
34
/*
35
 * supported tools
36
 *
37
 * Support?             Name
38
 * N (code in SoC repo) gain control
39
 * Y                    block switching
40
 * Y                    window shapes - standard
41
 * N                    window shapes - Low Delay
42
 * Y                    filterbank - standard
43
 * N (code in SoC repo) filterbank - Scalable Sample Rate
44
 * Y                    Temporal Noise Shaping
45
 * N (code in SoC repo) Long Term Prediction
46
 * Y                    intensity stereo
47
 * Y                    channel coupling
48
 * Y                    frequency domain prediction
49
 * Y                    Perceptual Noise Substitution
50
 * Y                    Mid/Side stereo
51
 * N                    Scalable Inverse AAC Quantization
52
 * N                    Frequency Selective Switch
53
 * N                    upsampling filter
54
 * Y                    quantization & coding - AAC
55
 * N                    quantization & coding - TwinVQ
56
 * N                    quantization & coding - BSAC
57
 * N                    AAC Error Resilience tools
58
 * N                    Error Resilience payload syntax
59
 * N                    Error Protection tool
60
 * N                    CELP
61
 * N                    Silence Compression
62
 * N                    HVXC
63
 * N                    HVXC 4kbits/s VR
64
 * N                    Structured Audio tools
65
 * N                    Structured Audio Sample Bank Format
66
 * N                    MIDI
67
 * N                    Harmonic and Individual Lines plus Noise
68
 * N                    Text-To-Speech Interface
69
 * Y                    Spectral Band Replication
70
 * Y (not in this code) Layer-1
71
 * Y (not in this code) Layer-2
72
 * Y (not in this code) Layer-3
73
 * N                    SinuSoidal Coding (Transient, Sinusoid, Noise)
74
 * Y                    Parametric Stereo
75
 * N                    Direct Stream Transfer
76
 *
77
 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
78
 *       - HE AAC v2 comprises LC AAC with Spectral Band Replication and
79
           Parametric Stereo.
80
 */
81

    
82

    
83
#include "avcodec.h"
84
#include "internal.h"
85
#include "get_bits.h"
86
#include "dsputil.h"
87
#include "fft.h"
88
#include "lpc.h"
89

    
90
#include "aac.h"
91
#include "aactab.h"
92
#include "aacdectab.h"
93
#include "cbrt_tablegen.h"
94
#include "sbr.h"
95
#include "aacsbr.h"
96
#include "mpeg4audio.h"
97
#include "aacadtsdec.h"
98

    
99
#include <assert.h>
100
#include <errno.h>
101
#include <math.h>
102
#include <string.h>
103

    
104
#if ARCH_ARM
105
#   include "arm/aac.h"
106
#endif
107

    
108
union float754 {
109
    float f;
110
    uint32_t i;
111
};
112

    
113
static VLC vlc_scalefactors;
114
static VLC vlc_spectral[11];
115

    
116
static const char overread_err[] = "Input buffer exhausted before END element found\n";
117

    
118
static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
119
{
120
    // For PCE based channel configurations map the channels solely based on tags.
121
    if (!ac->m4ac.chan_config) {
122
        return ac->tag_che_map[type][elem_id];
123
    }
124
    // For indexed channel configurations map the channels solely based on position.
125
    switch (ac->m4ac.chan_config) {
126
    case 7:
127
        if (ac->tags_mapped == 3 && type == TYPE_CPE) {
128
            ac->tags_mapped++;
129
            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
130
        }
131
    case 6:
132
        /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
133
           instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
134
           encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
135
        if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
136
            ac->tags_mapped++;
137
            return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
138
        }
139
    case 5:
140
        if (ac->tags_mapped == 2 && type == TYPE_CPE) {
141
            ac->tags_mapped++;
142
            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
143
        }
144
    case 4:
145
        if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
146
            ac->tags_mapped++;
147
            return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
148
        }
149
    case 3:
150
    case 2:
151
        if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
152
            ac->tags_mapped++;
153
            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
154
        } else if (ac->m4ac.chan_config == 2) {
155
            return NULL;
156
        }
157
    case 1:
158
        if (!ac->tags_mapped && type == TYPE_SCE) {
159
            ac->tags_mapped++;
160
            return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
161
        }
162
    default:
163
        return NULL;
164
    }
165
}
166

    
167
/**
168
 * Check for the channel element in the current channel position configuration.
169
 * If it exists, make sure the appropriate element is allocated and map the
170
 * channel order to match the internal FFmpeg channel layout.
171
 *
172
 * @param   che_pos current channel position configuration
173
 * @param   type channel element type
174
 * @param   id channel element id
175
 * @param   channels count of the number of channels in the configuration
176
 *
177
 * @return  Returns error status. 0 - OK, !0 - error
178
 */
179
static av_cold int che_configure(AACContext *ac,
180
                         enum ChannelPosition che_pos[4][MAX_ELEM_ID],
181
                         int type, int id,
182
                         int *channels)
183
{
184
    if (che_pos[type][id]) {
185
        if (!ac->che[type][id] && !(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
186
            return AVERROR(ENOMEM);
187
        ff_aac_sbr_ctx_init(&ac->che[type][id]->sbr);
188
        if (type != TYPE_CCE) {
189
            ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
190
            if (type == TYPE_CPE ||
191
                (type == TYPE_SCE && ac->m4ac.ps == 1)) {
192
                ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
193
            }
194
        }
195
    } else {
196
        if (ac->che[type][id])
197
            ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
198
        av_freep(&ac->che[type][id]);
199
    }
200
    return 0;
201
}
202

    
203
/**
204
 * Configure output channel order based on the current program configuration element.
205
 *
206
 * @param   che_pos current channel position configuration
207
 * @param   new_che_pos New channel position configuration - we only do something if it differs from the current one.
208
 *
209
 * @return  Returns error status. 0 - OK, !0 - error
210
 */
211
static av_cold int output_configure(AACContext *ac,
212
                            enum ChannelPosition che_pos[4][MAX_ELEM_ID],
213
                            enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
214
                            int channel_config, enum OCStatus oc_type)
215
{
216
    AVCodecContext *avctx = ac->avctx;
217
    int i, type, channels = 0, ret;
218

    
219
    if (new_che_pos != che_pos)
220
    memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
221

    
222
    if (channel_config) {
223
        for (i = 0; i < tags_per_config[channel_config]; i++) {
224
            if ((ret = che_configure(ac, che_pos,
225
                                     aac_channel_layout_map[channel_config - 1][i][0],
226
                                     aac_channel_layout_map[channel_config - 1][i][1],
227
                                     &channels)))
228
                return ret;
229
        }
230

    
231
        memset(ac->tag_che_map, 0,       4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
232

    
233
        avctx->channel_layout = aac_channel_layout[channel_config - 1];
234
    } else {
235
        /* Allocate or free elements depending on if they are in the
236
         * current program configuration.
237
         *
238
         * Set up default 1:1 output mapping.
239
         *
240
         * For a 5.1 stream the output order will be:
241
         *    [ Center ] [ Front Left ] [ Front Right ] [ LFE ] [ Surround Left ] [ Surround Right ]
242
         */
243

    
244
        for (i = 0; i < MAX_ELEM_ID; i++) {
245
            for (type = 0; type < 4; type++) {
246
                if ((ret = che_configure(ac, che_pos, type, i, &channels)))
247
                    return ret;
248
            }
249
        }
250

    
251
        memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
252

    
253
        avctx->channel_layout = 0;
254
    }
255

    
256
    avctx->channels = channels;
257

    
258
    ac->output_configured = oc_type;
259

    
260
    return 0;
261
}
262

    
263
/**
264
 * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
265
 *
266
 * @param cpe_map Stereo (Channel Pair Element) map, NULL if stereo bit is not present.
267
 * @param sce_map mono (Single Channel Element) map
268
 * @param type speaker type/position for these channels
269
 */
270
static void decode_channel_map(enum ChannelPosition *cpe_map,
271
                               enum ChannelPosition *sce_map,
272
                               enum ChannelPosition type,
273
                               GetBitContext *gb, int n)
274
{
275
    while (n--) {
276
        enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
277
        map[get_bits(gb, 4)] = type;
278
    }
279
}
280

    
281
/**
282
 * Decode program configuration element; reference: table 4.2.
283
 *
284
 * @param   new_che_pos New channel position configuration - we only do something if it differs from the current one.
285
 *
286
 * @return  Returns error status. 0 - OK, !0 - error
287
 */
288
static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
289
                      enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
290
                      GetBitContext *gb)
291
{
292
    int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
293
    int comment_len;
294

    
295
    skip_bits(gb, 2);  // object_type
296

    
297
    sampling_index = get_bits(gb, 4);
298
    if (m4ac->sampling_index != sampling_index)
299
        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");
300

    
301
    num_front       = get_bits(gb, 4);
302
    num_side        = get_bits(gb, 4);
303
    num_back        = get_bits(gb, 4);
304
    num_lfe         = get_bits(gb, 2);
305
    num_assoc_data  = get_bits(gb, 3);
306
    num_cc          = get_bits(gb, 4);
307

    
308
    if (get_bits1(gb))
309
        skip_bits(gb, 4); // mono_mixdown_tag
310
    if (get_bits1(gb))
311
        skip_bits(gb, 4); // stereo_mixdown_tag
312

    
313
    if (get_bits1(gb))
314
        skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
315

    
316
    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
317
    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE,  gb, num_side );
318
    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK,  gb, num_back );
319
    decode_channel_map(NULL,                  new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE,   gb, num_lfe  );
320

    
321
    skip_bits_long(gb, 4 * num_assoc_data);
322

    
323
    decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC,    gb, num_cc   );
324

    
325
    align_get_bits(gb);
326

    
327
    /* comment field, first byte is length */
328
    comment_len = get_bits(gb, 8) * 8;
329
    if (get_bits_left(gb) < comment_len) {
330
        av_log(avctx, AV_LOG_ERROR, overread_err);
331
        return -1;
332
    }
333
    skip_bits_long(gb, comment_len);
334
    return 0;
335
}
336

    
337
/**
338
 * Set up channel positions based on a default channel configuration
339
 * as specified in table 1.17.
340
 *
341
 * @param   new_che_pos New channel position configuration - we only do something if it differs from the current one.
342
 *
343
 * @return  Returns error status. 0 - OK, !0 - error
344
 */
345
static av_cold int set_default_channel_config(AVCodecContext *avctx,
346
                                      enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
347
                                      int channel_config)
348
{
349
    if (channel_config < 1 || channel_config > 7) {
350
        av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
351
               channel_config);
352
        return -1;
353
    }
354

    
355
    /* default channel configurations:
356
     *
357
     * 1ch : front center (mono)
358
     * 2ch : L + R (stereo)
359
     * 3ch : front center + L + R
360
     * 4ch : front center + L + R + back center
361
     * 5ch : front center + L + R + back stereo
362
     * 6ch : front center + L + R + back stereo + LFE
363
     * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
364
     */
365

    
366
    if (channel_config != 2)
367
        new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
368
    if (channel_config > 1)
369
        new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
370
    if (channel_config == 4)
371
        new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK;  // back center
372
    if (channel_config > 4)
373
        new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
374
        = AAC_CHANNEL_BACK;  // back stereo
375
    if (channel_config > 5)
376
        new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE;   // LFE
377
    if (channel_config == 7)
378
        new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
379

    
380
    return 0;
381
}
382

    
383
/**
384
 * Decode GA "General Audio" specific configuration; reference: table 4.1.
385
 *
386
 * @param   ac          pointer to AACContext, may be null
387
 * @param   avctx       pointer to AVCCodecContext, used for logging
388
 *
389
 * @return  Returns error status. 0 - OK, !0 - error
390
 */
391
static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
392
                                     GetBitContext *gb,
393
                                     MPEG4AudioConfig *m4ac,
394
                                     int channel_config)
395
{
396
    enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
397
    int extension_flag, ret;
398

    
399
    if (get_bits1(gb)) { // frameLengthFlag
400
        av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
401
        return -1;
402
    }
403

    
404
    if (get_bits1(gb))       // dependsOnCoreCoder
405
        skip_bits(gb, 14);   // coreCoderDelay
406
    extension_flag = get_bits1(gb);
407

    
408
    if (m4ac->object_type == AOT_AAC_SCALABLE ||
409
        m4ac->object_type == AOT_ER_AAC_SCALABLE)
410
        skip_bits(gb, 3);     // layerNr
411

    
412
    memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
413
    if (channel_config == 0) {
414
        skip_bits(gb, 4);  // element_instance_tag
415
        if ((ret = decode_pce(avctx, m4ac, new_che_pos, gb)))
416
            return ret;
417
    } else {
418
        if ((ret = set_default_channel_config(avctx, new_che_pos, channel_config)))
419
            return ret;
420
    }
421
    if (ac && (ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
422
        return ret;
423

    
424
    if (extension_flag) {
425
        switch (m4ac->object_type) {
426
        case AOT_ER_BSAC:
427
            skip_bits(gb, 5);    // numOfSubFrame
428
            skip_bits(gb, 11);   // layer_length
429
            break;
430
        case AOT_ER_AAC_LC:
431
        case AOT_ER_AAC_LTP:
432
        case AOT_ER_AAC_SCALABLE:
433
        case AOT_ER_AAC_LD:
434
            skip_bits(gb, 3);  /* aacSectionDataResilienceFlag
435
                                    * aacScalefactorDataResilienceFlag
436
                                    * aacSpectralDataResilienceFlag
437
                                    */
438
            break;
439
        }
440
        skip_bits1(gb);    // extensionFlag3 (TBD in version 3)
441
    }
442
    return 0;
443
}
444

    
445
/**
446
 * Decode audio specific configuration; reference: table 1.13.
447
 *
448
 * @param   ac          pointer to AACContext, may be null
449
 * @param   avctx       pointer to AVCCodecContext, used for logging
450
 * @param   m4ac        pointer to MPEG4AudioConfig, used for parsing
451
 * @param   data        pointer to AVCodecContext extradata
452
 * @param   data_size   size of AVCCodecContext extradata
453
 *
454
 * @return  Returns error status or number of consumed bits. <0 - error
455
 */
456
static int decode_audio_specific_config(AACContext *ac,
457
                                        AVCodecContext *avctx,
458
                                        MPEG4AudioConfig *m4ac,
459
                                        const uint8_t *data, int data_size)
460
{
461
    GetBitContext gb;
462
    int i;
463

    
464
    init_get_bits(&gb, data, data_size * 8);
465

    
466
    if ((i = ff_mpeg4audio_get_config(m4ac, data, data_size)) < 0)
467
        return -1;
468
    if (m4ac->sampling_index > 12) {
469
        av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
470
        return -1;
471
    }
472
    if (m4ac->sbr == 1 && m4ac->ps == -1)
473
        m4ac->ps = 1;
474

    
475
    skip_bits_long(&gb, i);
476

    
477
    switch (m4ac->object_type) {
478
    case AOT_AAC_MAIN:
479
    case AOT_AAC_LC:
480
        if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
481
            return -1;
482
        break;
483
    default:
484
        av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
485
               m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
486
        return -1;
487
    }
488

    
489
    return get_bits_count(&gb);
490
}
491

    
492
/**
493
 * linear congruential pseudorandom number generator
494
 *
495
 * @param   previous_val    pointer to the current state of the generator
496
 *
497
 * @return  Returns a 32-bit pseudorandom integer
498
 */
499
static av_always_inline int lcg_random(int previous_val)
500
{
501
    return previous_val * 1664525 + 1013904223;
502
}
503

    
504
static av_always_inline void reset_predict_state(PredictorState *ps)
505
{
506
    ps->r0   = 0.0f;
507
    ps->r1   = 0.0f;
508
    ps->cor0 = 0.0f;
509
    ps->cor1 = 0.0f;
510
    ps->var0 = 1.0f;
511
    ps->var1 = 1.0f;
512
}
513

    
514
static void reset_all_predictors(PredictorState *ps)
515
{
516
    int i;
517
    for (i = 0; i < MAX_PREDICTORS; i++)
518
        reset_predict_state(&ps[i]);
519
}
520

    
521
static void reset_predictor_group(PredictorState *ps, int group_num)
522
{
523
    int i;
524
    for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
525
        reset_predict_state(&ps[i]);
526
}
527

    
528
#define AAC_INIT_VLC_STATIC(num, size) \
529
    INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
530
         ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
531
        ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
532
        size);
533

    
534
static av_cold int aac_decode_init(AVCodecContext *avctx)
535
{
536
    AACContext *ac = avctx->priv_data;
537

    
538
    ac->avctx = avctx;
539
    ac->m4ac.sample_rate = avctx->sample_rate;
540

    
541
    if (avctx->extradata_size > 0) {
542
        if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
543
                                         avctx->extradata,
544
                                         avctx->extradata_size) < 0)
545
            return -1;
546
    }
547

    
548
    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
549

    
550
    AAC_INIT_VLC_STATIC( 0, 304);
551
    AAC_INIT_VLC_STATIC( 1, 270);
552
    AAC_INIT_VLC_STATIC( 2, 550);
553
    AAC_INIT_VLC_STATIC( 3, 300);
554
    AAC_INIT_VLC_STATIC( 4, 328);
555
    AAC_INIT_VLC_STATIC( 5, 294);
556
    AAC_INIT_VLC_STATIC( 6, 306);
557
    AAC_INIT_VLC_STATIC( 7, 268);
558
    AAC_INIT_VLC_STATIC( 8, 510);
559
    AAC_INIT_VLC_STATIC( 9, 366);
560
    AAC_INIT_VLC_STATIC(10, 462);
561

    
562
    ff_aac_sbr_init();
563

    
564
    dsputil_init(&ac->dsp, avctx);
565

    
566
    ac->random_state = 0x1f2e3d4c;
567

    
568
    // -1024 - Compensate wrong IMDCT method.
569
    // 32768 - Required to scale values to the correct range for the bias method
570
    //         for float to int16 conversion.
571

    
572
    if (ac->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
573
        ac->add_bias  = 385.0f;
574
        ac->sf_scale  = 1. / (-1024. * 32768.);
575
        ac->sf_offset = 0;
576
    } else {
577
        ac->add_bias  = 0.0f;
578
        ac->sf_scale  = 1. / -1024.;
579
        ac->sf_offset = 60;
580
    }
581

    
582
    ff_aac_tableinit();
583

    
584
    INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
585
                    ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
586
                    ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
587
                    352);
588

    
589
    ff_mdct_init(&ac->mdct, 11, 1, 1.0);
590
    ff_mdct_init(&ac->mdct_small, 8, 1, 1.0);
591
    // window initialization
592
    ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
593
    ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
594
    ff_init_ff_sine_windows(10);
595
    ff_init_ff_sine_windows( 7);
596

    
597
    cbrt_tableinit();
598

    
599
    return 0;
600
}
601

    
602
/**
603
 * Skip data_stream_element; reference: table 4.10.
604
 */
605
static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
606
{
607
    int byte_align = get_bits1(gb);
608
    int count = get_bits(gb, 8);
609
    if (count == 255)
610
        count += get_bits(gb, 8);
611
    if (byte_align)
612
        align_get_bits(gb);
613

    
614
    if (get_bits_left(gb) < 8 * count) {
615
        av_log(ac->avctx, AV_LOG_ERROR, overread_err);
616
        return -1;
617
    }
618
    skip_bits_long(gb, 8 * count);
619
    return 0;
620
}
621

    
622
static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
623
                             GetBitContext *gb)
624
{
625
    int sfb;
626
    if (get_bits1(gb)) {
627
        ics->predictor_reset_group = get_bits(gb, 5);
628
        if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
629
            av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
630
            return -1;
631
        }
632
    }
633
    for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
634
        ics->prediction_used[sfb] = get_bits1(gb);
635
    }
636
    return 0;
637
}
638

    
639
/**
640
 * Decode Individual Channel Stream info; reference: table 4.6.
641
 *
642
 * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
643
 */
644
static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
645
                           GetBitContext *gb, int common_window)
646
{
647
    if (get_bits1(gb)) {
648
        av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
649
        memset(ics, 0, sizeof(IndividualChannelStream));
650
        return -1;
651
    }
652
    ics->window_sequence[1] = ics->window_sequence[0];
653
    ics->window_sequence[0] = get_bits(gb, 2);
654
    ics->use_kb_window[1]   = ics->use_kb_window[0];
655
    ics->use_kb_window[0]   = get_bits1(gb);
656
    ics->num_window_groups  = 1;
657
    ics->group_len[0]       = 1;
658
    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
659
        int i;
660
        ics->max_sfb = get_bits(gb, 4);
661
        for (i = 0; i < 7; i++) {
662
            if (get_bits1(gb)) {
663
                ics->group_len[ics->num_window_groups - 1]++;
664
            } else {
665
                ics->num_window_groups++;
666
                ics->group_len[ics->num_window_groups - 1] = 1;
667
            }
668
        }
669
        ics->num_windows       = 8;
670
        ics->swb_offset        =    ff_swb_offset_128[ac->m4ac.sampling_index];
671
        ics->num_swb           =   ff_aac_num_swb_128[ac->m4ac.sampling_index];
672
        ics->tns_max_bands     = ff_tns_max_bands_128[ac->m4ac.sampling_index];
673
        ics->predictor_present = 0;
674
    } else {
675
        ics->max_sfb               = get_bits(gb, 6);
676
        ics->num_windows           = 1;
677
        ics->swb_offset            =    ff_swb_offset_1024[ac->m4ac.sampling_index];
678
        ics->num_swb               =   ff_aac_num_swb_1024[ac->m4ac.sampling_index];
679
        ics->tns_max_bands         = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
680
        ics->predictor_present     = get_bits1(gb);
681
        ics->predictor_reset_group = 0;
682
        if (ics->predictor_present) {
683
            if (ac->m4ac.object_type == AOT_AAC_MAIN) {
684
                if (decode_prediction(ac, ics, gb)) {
685
                    memset(ics, 0, sizeof(IndividualChannelStream));
686
                    return -1;
687
                }
688
            } else if (ac->m4ac.object_type == AOT_AAC_LC) {
689
                av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
690
                memset(ics, 0, sizeof(IndividualChannelStream));
691
                return -1;
692
            } else {
693
                av_log_missing_feature(ac->avctx, "Predictor bit set but LTP is", 1);
694
                memset(ics, 0, sizeof(IndividualChannelStream));
695
                return -1;
696
            }
697
        }
698
    }
699

    
700
    if (ics->max_sfb > ics->num_swb) {
701
        av_log(ac->avctx, AV_LOG_ERROR,
702
               "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
703
               ics->max_sfb, ics->num_swb);
704
        memset(ics, 0, sizeof(IndividualChannelStream));
705
        return -1;
706
    }
707

    
708
    return 0;
709
}
710

    
711
/**
712
 * Decode band types (section_data payload); reference: table 4.46.
713
 *
714
 * @param   band_type           array of the used band type
715
 * @param   band_type_run_end   array of the last scalefactor band of a band type run
716
 *
717
 * @return  Returns error status. 0 - OK, !0 - error
718
 */
719
static int decode_band_types(AACContext *ac, enum BandType band_type[120],
720
                             int band_type_run_end[120], GetBitContext *gb,
721
                             IndividualChannelStream *ics)
722
{
723
    int g, idx = 0;
724
    const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
725
    for (g = 0; g < ics->num_window_groups; g++) {
726
        int k = 0;
727
        while (k < ics->max_sfb) {
728
            uint8_t sect_end = k;
729
            int sect_len_incr;
730
            int sect_band_type = get_bits(gb, 4);
731
            if (sect_band_type == 12) {
732
                av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
733
                return -1;
734
            }
735
            while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
736
                sect_end += sect_len_incr;
737
            sect_end += sect_len_incr;
738
            if (get_bits_left(gb) < 0) {
739
                av_log(ac->avctx, AV_LOG_ERROR, overread_err);
740
                return -1;
741
            }
742
            if (sect_end > ics->max_sfb) {
743
                av_log(ac->avctx, AV_LOG_ERROR,
744
                       "Number of bands (%d) exceeds limit (%d).\n",
745
                       sect_end, ics->max_sfb);
746
                return -1;
747
            }
748
            for (; k < sect_end; k++) {
749
                band_type        [idx]   = sect_band_type;
750
                band_type_run_end[idx++] = sect_end;
751
            }
752
        }
753
    }
754
    return 0;
755
}
756

    
757
/**
758
 * Decode scalefactors; reference: table 4.47.
759
 *
760
 * @param   global_gain         first scalefactor value as scalefactors are differentially coded
761
 * @param   band_type           array of the used band type
762
 * @param   band_type_run_end   array of the last scalefactor band of a band type run
763
 * @param   sf                  array of scalefactors or intensity stereo positions
764
 *
765
 * @return  Returns error status. 0 - OK, !0 - error
766
 */
767
static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
768
                               unsigned int global_gain,
769
                               IndividualChannelStream *ics,
770
                               enum BandType band_type[120],
771
                               int band_type_run_end[120])
772
{
773
    const int sf_offset = ac->sf_offset + (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE ? 12 : 0);
774
    int g, i, idx = 0;
775
    int offset[3] = { global_gain, global_gain - 90, 100 };
776
    int noise_flag = 1;
777
    static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
778
    for (g = 0; g < ics->num_window_groups; g++) {
779
        for (i = 0; i < ics->max_sfb;) {
780
            int run_end = band_type_run_end[idx];
781
            if (band_type[idx] == ZERO_BT) {
782
                for (; i < run_end; i++, idx++)
783
                    sf[idx] = 0.;
784
            } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
785
                for (; i < run_end; i++, idx++) {
786
                    offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
787
                    if (offset[2] > 255U) {
788
                        av_log(ac->avctx, AV_LOG_ERROR,
789
                               "%s (%d) out of range.\n", sf_str[2], offset[2]);
790
                        return -1;
791
                    }
792
                    sf[idx] = ff_aac_pow2sf_tab[-offset[2] + 300];
793
                }
794
            } else if (band_type[idx] == NOISE_BT) {
795
                for (; i < run_end; i++, idx++) {
796
                    if (noise_flag-- > 0)
797
                        offset[1] += get_bits(gb, 9) - 256;
798
                    else
799
                        offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
800
                    if (offset[1] > 255U) {
801
                        av_log(ac->avctx, AV_LOG_ERROR,
802
                               "%s (%d) out of range.\n", sf_str[1], offset[1]);
803
                        return -1;
804
                    }
805
                    sf[idx] = -ff_aac_pow2sf_tab[offset[1] + sf_offset + 100];
806
                }
807
            } else {
808
                for (; i < run_end; i++, idx++) {
809
                    offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
810
                    if (offset[0] > 255U) {
811
                        av_log(ac->avctx, AV_LOG_ERROR,
812
                               "%s (%d) out of range.\n", sf_str[0], offset[0]);
813
                        return -1;
814
                    }
815
                    sf[idx] = -ff_aac_pow2sf_tab[ offset[0] + sf_offset];
816
                }
817
            }
818
        }
819
    }
820
    return 0;
821
}
822

    
823
/**
824
 * Decode pulse data; reference: table 4.7.
825
 */
826
static int decode_pulses(Pulse *pulse, GetBitContext *gb,
827
                         const uint16_t *swb_offset, int num_swb)
828
{
829
    int i, pulse_swb;
830
    pulse->num_pulse = get_bits(gb, 2) + 1;
831
    pulse_swb        = get_bits(gb, 6);
832
    if (pulse_swb >= num_swb)
833
        return -1;
834
    pulse->pos[0]    = swb_offset[pulse_swb];
835
    pulse->pos[0]   += get_bits(gb, 5);
836
    if (pulse->pos[0] > 1023)
837
        return -1;
838
    pulse->amp[0]    = get_bits(gb, 4);
839
    for (i = 1; i < pulse->num_pulse; i++) {
840
        pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
841
        if (pulse->pos[i] > 1023)
842
            return -1;
843
        pulse->amp[i] = get_bits(gb, 4);
844
    }
845
    return 0;
846
}
847

    
848
/**
849
 * Decode Temporal Noise Shaping data; reference: table 4.48.
850
 *
851
 * @return  Returns error status. 0 - OK, !0 - error
852
 */
853
static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
854
                      GetBitContext *gb, const IndividualChannelStream *ics)
855
{
856
    int w, filt, i, coef_len, coef_res, coef_compress;
857
    const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
858
    const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
859
    for (w = 0; w < ics->num_windows; w++) {
860
        if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
861
            coef_res = get_bits1(gb);
862

    
863
            for (filt = 0; filt < tns->n_filt[w]; filt++) {
864
                int tmp2_idx;
865
                tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
866

    
867
                if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
868
                    av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
869
                           tns->order[w][filt], tns_max_order);
870
                    tns->order[w][filt] = 0;
871
                    return -1;
872
                }
873
                if (tns->order[w][filt]) {
874
                    tns->direction[w][filt] = get_bits1(gb);
875
                    coef_compress = get_bits1(gb);
876
                    coef_len = coef_res + 3 - coef_compress;
877
                    tmp2_idx = 2 * coef_compress + coef_res;
878

    
879
                    for (i = 0; i < tns->order[w][filt]; i++)
880
                        tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
881
                }
882
            }
883
        }
884
    }
885
    return 0;
886
}
887

    
888
/**
889
 * Decode Mid/Side data; reference: table 4.54.
890
 *
891
 * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
892
 *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
893
 *                      [3] reserved for scalable AAC
894
 */
895
static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
896
                                   int ms_present)
897
{
898
    int idx;
899
    if (ms_present == 1) {
900
        for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
901
            cpe->ms_mask[idx] = get_bits1(gb);
902
    } else if (ms_present == 2) {
903
        memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
904
    }
905
}
906

    
907
#ifndef VMUL2
908
static inline float *VMUL2(float *dst, const float *v, unsigned idx,
909
                           const float *scale)
910
{
911
    float s = *scale;
912
    *dst++ = v[idx    & 15] * s;
913
    *dst++ = v[idx>>4 & 15] * s;
914
    return dst;
915
}
916
#endif
917

    
918
#ifndef VMUL4
919
static inline float *VMUL4(float *dst, const float *v, unsigned idx,
920
                           const float *scale)
921
{
922
    float s = *scale;
923
    *dst++ = v[idx    & 3] * s;
924
    *dst++ = v[idx>>2 & 3] * s;
925
    *dst++ = v[idx>>4 & 3] * s;
926
    *dst++ = v[idx>>6 & 3] * s;
927
    return dst;
928
}
929
#endif
930

    
931
#ifndef VMUL2S
932
static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
933
                            unsigned sign, const float *scale)
934
{
935
    union float754 s0, s1;
936

    
937
    s0.f = s1.f = *scale;
938
    s0.i ^= sign >> 1 << 31;
939
    s1.i ^= sign      << 31;
940

    
941
    *dst++ = v[idx    & 15] * s0.f;
942
    *dst++ = v[idx>>4 & 15] * s1.f;
943

    
944
    return dst;
945
}
946
#endif
947

    
948
#ifndef VMUL4S
949
static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
950
                            unsigned sign, const float *scale)
951
{
952
    unsigned nz = idx >> 12;
953
    union float754 s = { .f = *scale };
954
    union float754 t;
955

    
956
    t.i = s.i ^ (sign & 1<<31);
957
    *dst++ = v[idx    & 3] * t.f;
958

    
959
    sign <<= nz & 1; nz >>= 1;
960
    t.i = s.i ^ (sign & 1<<31);
961
    *dst++ = v[idx>>2 & 3] * t.f;
962

    
963
    sign <<= nz & 1; nz >>= 1;
964
    t.i = s.i ^ (sign & 1<<31);
965
    *dst++ = v[idx>>4 & 3] * t.f;
966

    
967
    sign <<= nz & 1; nz >>= 1;
968
    t.i = s.i ^ (sign & 1<<31);
969
    *dst++ = v[idx>>6 & 3] * t.f;
970

    
971
    return dst;
972
}
973
#endif
974

    
975
/**
976
 * Decode spectral data; reference: table 4.50.
977
 * Dequantize and scale spectral data; reference: 4.6.3.3.
978
 *
979
 * @param   coef            array of dequantized, scaled spectral data
980
 * @param   sf              array of scalefactors or intensity stereo positions
981
 * @param   pulse_present   set if pulses are present
982
 * @param   pulse           pointer to pulse data struct
983
 * @param   band_type       array of the used band type
984
 *
985
 * @return  Returns error status. 0 - OK, !0 - error
986
 */
987
static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
988
                                       GetBitContext *gb, const float sf[120],
989
                                       int pulse_present, const Pulse *pulse,
990
                                       const IndividualChannelStream *ics,
991
                                       enum BandType band_type[120])
992
{
993
    int i, k, g, idx = 0;
994
    const int c = 1024 / ics->num_windows;
995
    const uint16_t *offsets = ics->swb_offset;
996
    float *coef_base = coef;
997

    
998
    for (g = 0; g < ics->num_windows; g++)
999
        memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
1000

    
1001
    for (g = 0; g < ics->num_window_groups; g++) {
1002
        unsigned g_len = ics->group_len[g];
1003

    
1004
        for (i = 0; i < ics->max_sfb; i++, idx++) {
1005
            const unsigned cbt_m1 = band_type[idx] - 1;
1006
            float *cfo = coef + offsets[i];
1007
            int off_len = offsets[i + 1] - offsets[i];
1008
            int group;
1009

    
1010
            if (cbt_m1 >= INTENSITY_BT2 - 1) {
1011
                for (group = 0; group < g_len; group++, cfo+=128) {
1012
                    memset(cfo, 0, off_len * sizeof(float));
1013
                }
1014
            } else if (cbt_m1 == NOISE_BT - 1) {
1015
                for (group = 0; group < g_len; group++, cfo+=128) {
1016
                    float scale;
1017
                    float band_energy;
1018

    
1019
                    for (k = 0; k < off_len; k++) {
1020
                        ac->random_state  = lcg_random(ac->random_state);
1021
                        cfo[k] = ac->random_state;
1022
                    }
1023

    
1024
                    band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
1025
                    scale = sf[idx] / sqrtf(band_energy);
1026
                    ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1027
                }
1028
            } else {
1029
                const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1030
                const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1031
                VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1032
                OPEN_READER(re, gb);
1033

    
1034
                switch (cbt_m1 >> 1) {
1035
                case 0:
1036
                    for (group = 0; group < g_len; group++, cfo+=128) {
1037
                        float *cf = cfo;
1038
                        int len = off_len;
1039

    
1040
                        do {
1041
                            int code;
1042
                            unsigned cb_idx;
1043

    
1044
                            UPDATE_CACHE(re, gb);
1045
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1046
                            cb_idx = cb_vector_idx[code];
1047
                            cf = VMUL4(cf, vq, cb_idx, sf + idx);
1048
                        } while (len -= 4);
1049
                    }
1050
                    break;
1051

    
1052
                case 1:
1053
                    for (group = 0; group < g_len; group++, cfo+=128) {
1054
                        float *cf = cfo;
1055
                        int len = off_len;
1056

    
1057
                        do {
1058
                            int code;
1059
                            unsigned nnz;
1060
                            unsigned cb_idx;
1061
                            uint32_t bits;
1062

    
1063
                            UPDATE_CACHE(re, gb);
1064
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1065
                            cb_idx = cb_vector_idx[code];
1066
                            nnz = cb_idx >> 8 & 15;
1067
                            bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1068
                            LAST_SKIP_BITS(re, gb, nnz);
1069
                            cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1070
                        } while (len -= 4);
1071
                    }
1072
                    break;
1073

    
1074
                case 2:
1075
                    for (group = 0; group < g_len; group++, cfo+=128) {
1076
                        float *cf = cfo;
1077
                        int len = off_len;
1078

    
1079
                        do {
1080
                            int code;
1081
                            unsigned cb_idx;
1082

    
1083
                            UPDATE_CACHE(re, gb);
1084
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1085
                            cb_idx = cb_vector_idx[code];
1086
                            cf = VMUL2(cf, vq, cb_idx, sf + idx);
1087
                        } while (len -= 2);
1088
                    }
1089
                    break;
1090

    
1091
                case 3:
1092
                case 4:
1093
                    for (group = 0; group < g_len; group++, cfo+=128) {
1094
                        float *cf = cfo;
1095
                        int len = off_len;
1096

    
1097
                        do {
1098
                            int code;
1099
                            unsigned nnz;
1100
                            unsigned cb_idx;
1101
                            unsigned sign;
1102

    
1103
                            UPDATE_CACHE(re, gb);
1104
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1105
                            cb_idx = cb_vector_idx[code];
1106
                            nnz = cb_idx >> 8 & 15;
1107
                            sign = SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12);
1108
                            LAST_SKIP_BITS(re, gb, nnz);
1109
                            cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1110
                        } while (len -= 2);
1111
                    }
1112
                    break;
1113

    
1114
                default:
1115
                    for (group = 0; group < g_len; group++, cfo+=128) {
1116
                        float *cf = cfo;
1117
                        uint32_t *icf = (uint32_t *) cf;
1118
                        int len = off_len;
1119

    
1120
                        do {
1121
                            int code;
1122
                            unsigned nzt, nnz;
1123
                            unsigned cb_idx;
1124
                            uint32_t bits;
1125
                            int j;
1126

    
1127
                            UPDATE_CACHE(re, gb);
1128
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1129

    
1130
                            if (!code) {
1131
                                *icf++ = 0;
1132
                                *icf++ = 0;
1133
                                continue;
1134
                            }
1135

    
1136
                            cb_idx = cb_vector_idx[code];
1137
                            nnz = cb_idx >> 12;
1138
                            nzt = cb_idx >> 8;
1139
                            bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1140
                            LAST_SKIP_BITS(re, gb, nnz);
1141

    
1142
                            for (j = 0; j < 2; j++) {
1143
                                if (nzt & 1<<j) {
1144
                                    uint32_t b;
1145
                                    int n;
1146
                                    /* The total length of escape_sequence must be < 22 bits according
1147
                                       to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1148
                                    UPDATE_CACHE(re, gb);
1149
                                    b = GET_CACHE(re, gb);
1150
                                    b = 31 - av_log2(~b);
1151

    
1152
                                    if (b > 8) {
1153
                                        av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1154
                                        return -1;
1155
                                    }
1156

    
1157
                                    SKIP_BITS(re, gb, b + 1);
1158
                                    b += 4;
1159
                                    n = (1 << b) + SHOW_UBITS(re, gb, b);
1160
                                    LAST_SKIP_BITS(re, gb, b);
1161
                                    *icf++ = cbrt_tab[n] | (bits & 1<<31);
1162
                                    bits <<= 1;
1163
                                } else {
1164
                                    unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1165
                                    *icf++ = (bits & 1<<31) | v;
1166
                                    bits <<= !!v;
1167
                                }
1168
                                cb_idx >>= 4;
1169
                            }
1170
                        } while (len -= 2);
1171

    
1172
                        ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1173
                    }
1174
                }
1175

    
1176
                CLOSE_READER(re, gb);
1177
            }
1178
        }
1179
        coef += g_len << 7;
1180
    }
1181

    
1182
    if (pulse_present) {
1183
        idx = 0;
1184
        for (i = 0; i < pulse->num_pulse; i++) {
1185
            float co = coef_base[ pulse->pos[i] ];
1186
            while (offsets[idx + 1] <= pulse->pos[i])
1187
                idx++;
1188
            if (band_type[idx] != NOISE_BT && sf[idx]) {
1189
                float ico = -pulse->amp[i];
1190
                if (co) {
1191
                    co /= sf[idx];
1192
                    ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1193
                }
1194
                coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1195
            }
1196
        }
1197
    }
1198
    return 0;
1199
}
1200

    
1201
static av_always_inline float flt16_round(float pf)
1202
{
1203
    union float754 tmp;
1204
    tmp.f = pf;
1205
    tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1206
    return tmp.f;
1207
}
1208

    
1209
static av_always_inline float flt16_even(float pf)
1210
{
1211
    union float754 tmp;
1212
    tmp.f = pf;
1213
    tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1214
    return tmp.f;
1215
}
1216

    
1217
static av_always_inline float flt16_trunc(float pf)
1218
{
1219
    union float754 pun;
1220
    pun.f = pf;
1221
    pun.i &= 0xFFFF0000U;
1222
    return pun.f;
1223
}
1224

    
1225
static av_always_inline void predict(PredictorState *ps, float *coef,
1226
                                     float sf_scale, float inv_sf_scale,
1227
                    int output_enable)
1228
{
1229
    const float a     = 0.953125; // 61.0 / 64
1230
    const float alpha = 0.90625;  // 29.0 / 32
1231
    float e0, e1;
1232
    float pv;
1233
    float k1, k2;
1234
    float   r0 = ps->r0,     r1 = ps->r1;
1235
    float cor0 = ps->cor0, cor1 = ps->cor1;
1236
    float var0 = ps->var0, var1 = ps->var1;
1237

    
1238
    k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1239
    k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1240

    
1241
    pv = flt16_round(k1 * r0 + k2 * r1);
1242
    if (output_enable)
1243
        *coef += pv * sf_scale;
1244

    
1245
    e0 = *coef * inv_sf_scale;
1246
    e1 = e0 - k1 * r0;
1247

    
1248
    ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1249
    ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1250
    ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1251
    ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1252

    
1253
    ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1254
    ps->r0 = flt16_trunc(a * e0);
1255
}
1256

    
1257
/**
1258
 * Apply AAC-Main style frequency domain prediction.
1259
 */
1260
static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1261
{
1262
    int sfb, k;
1263
    float sf_scale = ac->sf_scale, inv_sf_scale = 1 / ac->sf_scale;
1264

    
1265
    if (!sce->ics.predictor_initialized) {
1266
        reset_all_predictors(sce->predictor_state);
1267
        sce->ics.predictor_initialized = 1;
1268
    }
1269

    
1270
    if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1271
        for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
1272
            for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
1273
                predict(&sce->predictor_state[k], &sce->coeffs[k],
1274
                        sf_scale, inv_sf_scale,
1275
                        sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
1276
            }
1277
        }
1278
        if (sce->ics.predictor_reset_group)
1279
            reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
1280
    } else
1281
        reset_all_predictors(sce->predictor_state);
1282
}
1283

    
1284
/**
1285
 * Decode an individual_channel_stream payload; reference: table 4.44.
1286
 *
1287
 * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
1288
 * @param   scale_flag      scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1289
 *
1290
 * @return  Returns error status. 0 - OK, !0 - error
1291
 */
1292
static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1293
                      GetBitContext *gb, int common_window, int scale_flag)
1294
{
1295
    Pulse pulse;
1296
    TemporalNoiseShaping    *tns = &sce->tns;
1297
    IndividualChannelStream *ics = &sce->ics;
1298
    float *out = sce->coeffs;
1299
    int global_gain, pulse_present = 0;
1300

    
1301
    /* This assignment is to silence a GCC warning about the variable being used
1302
     * uninitialized when in fact it always is.
1303
     */
1304
    pulse.num_pulse = 0;
1305

    
1306
    global_gain = get_bits(gb, 8);
1307

    
1308
    if (!common_window && !scale_flag) {
1309
        if (decode_ics_info(ac, ics, gb, 0) < 0)
1310
            return -1;
1311
    }
1312

    
1313
    if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1314
        return -1;
1315
    if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1316
        return -1;
1317

    
1318
    pulse_present = 0;
1319
    if (!scale_flag) {
1320
        if ((pulse_present = get_bits1(gb))) {
1321
            if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1322
                av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
1323
                return -1;
1324
            }
1325
            if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1326
                av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
1327
                return -1;
1328
            }
1329
        }
1330
        if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1331
            return -1;
1332
        if (get_bits1(gb)) {
1333
            av_log_missing_feature(ac->avctx, "SSR", 1);
1334
            return -1;
1335
        }
1336
    }
1337

    
1338
    if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1339
        return -1;
1340

    
1341
    if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
1342
        apply_prediction(ac, sce);
1343

    
1344
    return 0;
1345
}
1346

    
1347
/**
1348
 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1349
 */
1350
static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1351
{
1352
    const IndividualChannelStream *ics = &cpe->ch[0].ics;
1353
    float *ch0 = cpe->ch[0].coeffs;
1354
    float *ch1 = cpe->ch[1].coeffs;
1355
    int g, i, group, idx = 0;
1356
    const uint16_t *offsets = ics->swb_offset;
1357
    for (g = 0; g < ics->num_window_groups; g++) {
1358
        for (i = 0; i < ics->max_sfb; i++, idx++) {
1359
            if (cpe->ms_mask[idx] &&
1360
                    cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
1361
                for (group = 0; group < ics->group_len[g]; group++) {
1362
                    ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
1363
                                              ch1 + group * 128 + offsets[i],
1364
                                              offsets[i+1] - offsets[i]);
1365
                }
1366
            }
1367
        }
1368
        ch0 += ics->group_len[g] * 128;
1369
        ch1 += ics->group_len[g] * 128;
1370
    }
1371
}
1372

    
1373
/**
1374
 * intensity stereo decoding; reference: 4.6.8.2.3
1375
 *
1376
 * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
1377
 *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
1378
 *                      [3] reserved for scalable AAC
1379
 */
1380
static void apply_intensity_stereo(ChannelElement *cpe, int ms_present)
1381
{
1382
    const IndividualChannelStream *ics = &cpe->ch[1].ics;
1383
    SingleChannelElement         *sce1 = &cpe->ch[1];
1384
    float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1385
    const uint16_t *offsets = ics->swb_offset;
1386
    int g, group, i, k, idx = 0;
1387
    int c;
1388
    float scale;
1389
    for (g = 0; g < ics->num_window_groups; g++) {
1390
        for (i = 0; i < ics->max_sfb;) {
1391
            if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1392
                const int bt_run_end = sce1->band_type_run_end[idx];
1393
                for (; i < bt_run_end; i++, idx++) {
1394
                    c = -1 + 2 * (sce1->band_type[idx] - 14);
1395
                    if (ms_present)
1396
                        c *= 1 - 2 * cpe->ms_mask[idx];
1397
                    scale = c * sce1->sf[idx];
1398
                    for (group = 0; group < ics->group_len[g]; group++)
1399
                        for (k = offsets[i]; k < offsets[i + 1]; k++)
1400
                            coef1[group * 128 + k] = scale * coef0[group * 128 + k];
1401
                }
1402
            } else {
1403
                int bt_run_end = sce1->band_type_run_end[idx];
1404
                idx += bt_run_end - i;
1405
                i    = bt_run_end;
1406
            }
1407
        }
1408
        coef0 += ics->group_len[g] * 128;
1409
        coef1 += ics->group_len[g] * 128;
1410
    }
1411
}
1412

    
1413
/**
1414
 * Decode a channel_pair_element; reference: table 4.4.
1415
 *
1416
 * @return  Returns error status. 0 - OK, !0 - error
1417
 */
1418
static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1419
{
1420
    int i, ret, common_window, ms_present = 0;
1421

    
1422
    common_window = get_bits1(gb);
1423
    if (common_window) {
1424
        if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
1425
            return -1;
1426
        i = cpe->ch[1].ics.use_kb_window[0];
1427
        cpe->ch[1].ics = cpe->ch[0].ics;
1428
        cpe->ch[1].ics.use_kb_window[1] = i;
1429
        ms_present = get_bits(gb, 2);
1430
        if (ms_present == 3) {
1431
            av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1432
            return -1;
1433
        } else if (ms_present)
1434
            decode_mid_side_stereo(cpe, gb, ms_present);
1435
    }
1436
    if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1437
        return ret;
1438
    if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1439
        return ret;
1440

    
1441
    if (common_window) {
1442
        if (ms_present)
1443
            apply_mid_side_stereo(ac, cpe);
1444
        if (ac->m4ac.object_type == AOT_AAC_MAIN) {
1445
            apply_prediction(ac, &cpe->ch[0]);
1446
            apply_prediction(ac, &cpe->ch[1]);
1447
        }
1448
    }
1449

    
1450
    apply_intensity_stereo(cpe, ms_present);
1451
    return 0;
1452
}
1453

    
1454
static const float cce_scale[] = {
1455
    1.09050773266525765921, //2^(1/8)
1456
    1.18920711500272106672, //2^(1/4)
1457
    M_SQRT2,
1458
    2,
1459
};
1460

    
1461
/**
1462
 * Decode coupling_channel_element; reference: table 4.8.
1463
 *
1464
 * @return  Returns error status. 0 - OK, !0 - error
1465
 */
1466
static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1467
{
1468
    int num_gain = 0;
1469
    int c, g, sfb, ret;
1470
    int sign;
1471
    float scale;
1472
    SingleChannelElement *sce = &che->ch[0];
1473
    ChannelCoupling     *coup = &che->coup;
1474

    
1475
    coup->coupling_point = 2 * get_bits1(gb);
1476
    coup->num_coupled = get_bits(gb, 3);
1477
    for (c = 0; c <= coup->num_coupled; c++) {
1478
        num_gain++;
1479
        coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1480
        coup->id_select[c] = get_bits(gb, 4);
1481
        if (coup->type[c] == TYPE_CPE) {
1482
            coup->ch_select[c] = get_bits(gb, 2);
1483
            if (coup->ch_select[c] == 3)
1484
                num_gain++;
1485
        } else
1486
            coup->ch_select[c] = 2;
1487
    }
1488
    coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1489

    
1490
    sign  = get_bits(gb, 1);
1491
    scale = cce_scale[get_bits(gb, 2)];
1492

    
1493
    if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1494
        return ret;
1495

    
1496
    for (c = 0; c < num_gain; c++) {
1497
        int idx  = 0;
1498
        int cge  = 1;
1499
        int gain = 0;
1500
        float gain_cache = 1.;
1501
        if (c) {
1502
            cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1503
            gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1504
            gain_cache = powf(scale, -gain);
1505
        }
1506
        if (coup->coupling_point == AFTER_IMDCT) {
1507
            coup->gain[c][0] = gain_cache;
1508
        } else {
1509
            for (g = 0; g < sce->ics.num_window_groups; g++) {
1510
                for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1511
                    if (sce->band_type[idx] != ZERO_BT) {
1512
                        if (!cge) {
1513
                            int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1514
                            if (t) {
1515
                                int s = 1;
1516
                                t = gain += t;
1517
                                if (sign) {
1518
                                    s  -= 2 * (t & 0x1);
1519
                                    t >>= 1;
1520
                                }
1521
                                gain_cache = powf(scale, -t) * s;
1522
                            }
1523
                        }
1524
                        coup->gain[c][idx] = gain_cache;
1525
                    }
1526
                }
1527
            }
1528
        }
1529
    }
1530
    return 0;
1531
}
1532

    
1533
/**
1534
 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1535
 *
1536
 * @return  Returns number of bytes consumed.
1537
 */
1538
static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1539
                                         GetBitContext *gb)
1540
{
1541
    int i;
1542
    int num_excl_chan = 0;
1543

    
1544
    do {
1545
        for (i = 0; i < 7; i++)
1546
            che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1547
    } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1548

    
1549
    return num_excl_chan / 7;
1550
}
1551

    
1552
/**
1553
 * Decode dynamic range information; reference: table 4.52.
1554
 *
1555
 * @param   cnt length of TYPE_FIL syntactic element in bytes
1556
 *
1557
 * @return  Returns number of bytes consumed.
1558
 */
1559
static int decode_dynamic_range(DynamicRangeControl *che_drc,
1560
                                GetBitContext *gb, int cnt)
1561
{
1562
    int n             = 1;
1563
    int drc_num_bands = 1;
1564
    int i;
1565

    
1566
    /* pce_tag_present? */
1567
    if (get_bits1(gb)) {
1568
        che_drc->pce_instance_tag  = get_bits(gb, 4);
1569
        skip_bits(gb, 4); // tag_reserved_bits
1570
        n++;
1571
    }
1572

    
1573
    /* excluded_chns_present? */
1574
    if (get_bits1(gb)) {
1575
        n += decode_drc_channel_exclusions(che_drc, gb);
1576
    }
1577

    
1578
    /* drc_bands_present? */
1579
    if (get_bits1(gb)) {
1580
        che_drc->band_incr            = get_bits(gb, 4);
1581
        che_drc->interpolation_scheme = get_bits(gb, 4);
1582
        n++;
1583
        drc_num_bands += che_drc->band_incr;
1584
        for (i = 0; i < drc_num_bands; i++) {
1585
            che_drc->band_top[i] = get_bits(gb, 8);
1586
            n++;
1587
        }
1588
    }
1589

    
1590
    /* prog_ref_level_present? */
1591
    if (get_bits1(gb)) {
1592
        che_drc->prog_ref_level = get_bits(gb, 7);
1593
        skip_bits1(gb); // prog_ref_level_reserved_bits
1594
        n++;
1595
    }
1596

    
1597
    for (i = 0; i < drc_num_bands; i++) {
1598
        che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1599
        che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1600
        n++;
1601
    }
1602

    
1603
    return n;
1604
}
1605

    
1606
/**
1607
 * Decode extension data (incomplete); reference: table 4.51.
1608
 *
1609
 * @param   cnt length of TYPE_FIL syntactic element in bytes
1610
 *
1611
 * @return Returns number of bytes consumed
1612
 */
1613
static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
1614
                                    ChannelElement *che, enum RawDataBlockType elem_type)
1615
{
1616
    int crc_flag = 0;
1617
    int res = cnt;
1618
    switch (get_bits(gb, 4)) { // extension type
1619
    case EXT_SBR_DATA_CRC:
1620
        crc_flag++;
1621
    case EXT_SBR_DATA:
1622
        if (!che) {
1623
            av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
1624
            return res;
1625
        } else if (!ac->m4ac.sbr) {
1626
            av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
1627
            skip_bits_long(gb, 8 * cnt - 4);
1628
            return res;
1629
        } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
1630
            av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
1631
            skip_bits_long(gb, 8 * cnt - 4);
1632
            return res;
1633
        } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
1634
            ac->m4ac.sbr = 1;
1635
            ac->m4ac.ps = 1;
1636
            output_configure(ac, ac->che_pos, ac->che_pos, ac->m4ac.chan_config, ac->output_configured);
1637
        } else {
1638
            ac->m4ac.sbr = 1;
1639
        }
1640
        res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
1641
        break;
1642
    case EXT_DYNAMIC_RANGE:
1643
        res = decode_dynamic_range(&ac->che_drc, gb, cnt);
1644
        break;
1645
    case EXT_FILL:
1646
    case EXT_FILL_DATA:
1647
    case EXT_DATA_ELEMENT:
1648
    default:
1649
        skip_bits_long(gb, 8 * cnt - 4);
1650
        break;
1651
    };
1652
    return res;
1653
}
1654

    
1655
/**
1656
 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
1657
 *
1658
 * @param   decode  1 if tool is used normally, 0 if tool is used in LTP.
1659
 * @param   coef    spectral coefficients
1660
 */
1661
static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1662
                      IndividualChannelStream *ics, int decode)
1663
{
1664
    const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1665
    int w, filt, m, i;
1666
    int bottom, top, order, start, end, size, inc;
1667
    float lpc[TNS_MAX_ORDER];
1668

    
1669
    for (w = 0; w < ics->num_windows; w++) {
1670
        bottom = ics->num_swb;
1671
        for (filt = 0; filt < tns->n_filt[w]; filt++) {
1672
            top    = bottom;
1673
            bottom = FFMAX(0, top - tns->length[w][filt]);
1674
            order  = tns->order[w][filt];
1675
            if (order == 0)
1676
                continue;
1677

    
1678
            // tns_decode_coef
1679
            compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
1680

    
1681
            start = ics->swb_offset[FFMIN(bottom, mmm)];
1682
            end   = ics->swb_offset[FFMIN(   top, mmm)];
1683
            if ((size = end - start) <= 0)
1684
                continue;
1685
            if (tns->direction[w][filt]) {
1686
                inc = -1;
1687
                start = end - 1;
1688
            } else {
1689
                inc = 1;
1690
            }
1691
            start += w * 128;
1692

    
1693
            // ar filter
1694
            for (m = 0; m < size; m++, start += inc)
1695
                for (i = 1; i <= FFMIN(m, order); i++)
1696
                    coef[start] -= coef[start - i * inc] * lpc[i - 1];
1697
        }
1698
    }
1699
}
1700

    
1701
/**
1702
 * Conduct IMDCT and windowing.
1703
 */
1704
static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce, float bias)
1705
{
1706
    IndividualChannelStream *ics = &sce->ics;
1707
    float *in    = sce->coeffs;
1708
    float *out   = sce->ret;
1709
    float *saved = sce->saved;
1710
    const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1711
    const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1712
    const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1713
    float *buf  = ac->buf_mdct;
1714
    float *temp = ac->temp;
1715
    int i;
1716

    
1717
    // imdct
1718
    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1719
        for (i = 0; i < 1024; i += 128)
1720
            ff_imdct_half(&ac->mdct_small, buf + i, in + i);
1721
    } else
1722
        ff_imdct_half(&ac->mdct, buf, in);
1723

    
1724
    /* window overlapping
1725
     * NOTE: To simplify the overlapping code, all 'meaningless' short to long
1726
     * and long to short transitions are considered to be short to short
1727
     * transitions. This leaves just two cases (long to long and short to short)
1728
     * with a little special sauce for EIGHT_SHORT_SEQUENCE.
1729
     */
1730
    if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
1731
            (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
1732
        ac->dsp.vector_fmul_window(    out,               saved,            buf,         lwindow_prev, bias, 512);
1733
    } else {
1734
        for (i = 0; i < 448; i++)
1735
            out[i] = saved[i] + bias;
1736

    
1737
        if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1738
            ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, bias, 64);
1739
            ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      bias, 64);
1740
            ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      bias, 64);
1741
            ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      bias, 64);
1742
            ac->dsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      bias, 64);
1743
            memcpy(                    out + 448 + 4*128, temp, 64 * sizeof(float));
1744
        } else {
1745
            ac->dsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, bias, 64);
1746
            for (i = 576; i < 1024; i++)
1747
                out[i] = buf[i-512] + bias;
1748
        }
1749
    }
1750

    
1751
    // buffer update
1752
    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1753
        for (i = 0; i < 64; i++)
1754
            saved[i] = temp[64 + i] - bias;
1755
        ac->dsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);
1756
        ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);
1757
        ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);
1758
        memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
1759
    } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1760
        memcpy(                    saved,       buf + 512,        448 * sizeof(float));
1761
        memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
1762
    } else { // LONG_STOP or ONLY_LONG
1763
        memcpy(                    saved,       buf + 512,        512 * sizeof(float));
1764
    }
1765
}
1766

    
1767
/**
1768
 * Apply dependent channel coupling (applied before IMDCT).
1769
 *
1770
 * @param   index   index into coupling gain array
1771
 */
1772
static void apply_dependent_coupling(AACContext *ac,
1773
                                     SingleChannelElement *target,
1774
                                     ChannelElement *cce, int index)
1775
{
1776
    IndividualChannelStream *ics = &cce->ch[0].ics;
1777
    const uint16_t *offsets = ics->swb_offset;
1778
    float *dest = target->coeffs;
1779
    const float *src = cce->ch[0].coeffs;
1780
    int g, i, group, k, idx = 0;
1781
    if (ac->m4ac.object_type == AOT_AAC_LTP) {
1782
        av_log(ac->avctx, AV_LOG_ERROR,
1783
               "Dependent coupling is not supported together with LTP\n");
1784
        return;
1785
    }
1786
    for (g = 0; g < ics->num_window_groups; g++) {
1787
        for (i = 0; i < ics->max_sfb; i++, idx++) {
1788
            if (cce->ch[0].band_type[idx] != ZERO_BT) {
1789
                const float gain = cce->coup.gain[index][idx];
1790
                for (group = 0; group < ics->group_len[g]; group++) {
1791
                    for (k = offsets[i]; k < offsets[i + 1]; k++) {
1792
                        // XXX dsputil-ize
1793
                        dest[group * 128 + k] += gain * src[group * 128 + k];
1794
                    }
1795
                }
1796
            }
1797
        }
1798
        dest += ics->group_len[g] * 128;
1799
        src  += ics->group_len[g] * 128;
1800
    }
1801
}
1802

    
1803
/**
1804
 * Apply independent channel coupling (applied after IMDCT).
1805
 *
1806
 * @param   index   index into coupling gain array
1807
 */
1808
static void apply_independent_coupling(AACContext *ac,
1809
                                       SingleChannelElement *target,
1810
                                       ChannelElement *cce, int index)
1811
{
1812
    int i;
1813
    const float gain = cce->coup.gain[index][0];
1814
    const float bias = ac->add_bias;
1815
    const float *src = cce->ch[0].ret;
1816
    float *dest = target->ret;
1817
    const int len = 1024 << (ac->m4ac.sbr == 1);
1818

    
1819
    for (i = 0; i < len; i++)
1820
        dest[i] += gain * (src[i] - bias);
1821
}
1822

    
1823
/**
1824
 * channel coupling transformation interface
1825
 *
1826
 * @param   apply_coupling_method   pointer to (in)dependent coupling function
1827
 */
1828
static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
1829
                                   enum RawDataBlockType type, int elem_id,
1830
                                   enum CouplingPoint coupling_point,
1831
                                   void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
1832
{
1833
    int i, c;
1834

    
1835
    for (i = 0; i < MAX_ELEM_ID; i++) {
1836
        ChannelElement *cce = ac->che[TYPE_CCE][i];
1837
        int index = 0;
1838

    
1839
        if (cce && cce->coup.coupling_point == coupling_point) {
1840
            ChannelCoupling *coup = &cce->coup;
1841

    
1842
            for (c = 0; c <= coup->num_coupled; c++) {
1843
                if (coup->type[c] == type && coup->id_select[c] == elem_id) {
1844
                    if (coup->ch_select[c] != 1) {
1845
                        apply_coupling_method(ac, &cc->ch[0], cce, index);
1846
                        if (coup->ch_select[c] != 0)
1847
                            index++;
1848
                    }
1849
                    if (coup->ch_select[c] != 2)
1850
                        apply_coupling_method(ac, &cc->ch[1], cce, index++);
1851
                } else
1852
                    index += 1 + (coup->ch_select[c] == 3);
1853
            }
1854
        }
1855
    }
1856
}
1857

    
1858
/**
1859
 * Convert spectral data to float samples, applying all supported tools as appropriate.
1860
 */
1861
static void spectral_to_sample(AACContext *ac)
1862
{
1863
    int i, type;
1864
    float imdct_bias = (ac->m4ac.sbr <= 0) ? ac->add_bias : 0.0f;
1865
    for (type = 3; type >= 0; type--) {
1866
        for (i = 0; i < MAX_ELEM_ID; i++) {
1867
            ChannelElement *che = ac->che[type][i];
1868
            if (che) {
1869
                if (type <= TYPE_CPE)
1870
                    apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
1871
                if (che->ch[0].tns.present)
1872
                    apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
1873
                if (che->ch[1].tns.present)
1874
                    apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
1875
                if (type <= TYPE_CPE)
1876
                    apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
1877
                if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
1878
                    imdct_and_windowing(ac, &che->ch[0], imdct_bias);
1879
                    if (type == TYPE_CPE) {
1880
                        imdct_and_windowing(ac, &che->ch[1], imdct_bias);
1881
                    }
1882
                    if (ac->m4ac.sbr > 0) {
1883
                        ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
1884
                    }
1885
                }
1886
                if (type <= TYPE_CCE)
1887
                    apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
1888
            }
1889
        }
1890
    }
1891
}
1892

    
1893
static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
1894
{
1895
    int size;
1896
    AACADTSHeaderInfo hdr_info;
1897

    
1898
    size = ff_aac_parse_header(gb, &hdr_info);
1899
    if (size > 0) {
1900
        if (ac->output_configured != OC_LOCKED && hdr_info.chan_config) {
1901
            enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
1902
            memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
1903
            ac->m4ac.chan_config = hdr_info.chan_config;
1904
            if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
1905
                return -7;
1906
            if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config, OC_TRIAL_FRAME))
1907
                return -7;
1908
        } else if (ac->output_configured != OC_LOCKED) {
1909
            ac->output_configured = OC_NONE;
1910
        }
1911
        if (ac->output_configured != OC_LOCKED) {
1912
            ac->m4ac.sbr = -1;
1913
            ac->m4ac.ps  = -1;
1914
        }
1915
        ac->m4ac.sample_rate     = hdr_info.sample_rate;
1916
        ac->m4ac.sampling_index  = hdr_info.sampling_index;
1917
        ac->m4ac.object_type     = hdr_info.object_type;
1918
        if (!ac->avctx->sample_rate)
1919
            ac->avctx->sample_rate = hdr_info.sample_rate;
1920
        if (hdr_info.num_aac_frames == 1) {
1921
            if (!hdr_info.crc_absent)
1922
                skip_bits(gb, 16);
1923
        } else {
1924
            av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
1925
            return -1;
1926
        }
1927
    }
1928
    return size;
1929
}
1930

    
1931
static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
1932
                                int *data_size, GetBitContext *gb)
1933
{
1934
    AACContext *ac = avctx->priv_data;
1935
    ChannelElement *che = NULL, *che_prev = NULL;
1936
    enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
1937
    int err, elem_id, data_size_tmp;
1938
    int samples = 0, multiplier;
1939

    
1940
    if (show_bits(gb, 12) == 0xfff) {
1941
        if (parse_adts_frame_header(ac, gb) < 0) {
1942
            av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
1943
            return -1;
1944
        }
1945
        if (ac->m4ac.sampling_index > 12) {
1946
            av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
1947
            return -1;
1948
        }
1949
    }
1950

    
1951
    ac->tags_mapped = 0;
1952
    // parse
1953
    while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
1954
        elem_id = get_bits(gb, 4);
1955

    
1956
        if (elem_type < TYPE_DSE) {
1957
            if (!(che=get_che(ac, elem_type, elem_id))) {
1958
                av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
1959
                       elem_type, elem_id);
1960
                return -1;
1961
            }
1962
            samples = 1024;
1963
        }
1964

    
1965
        switch (elem_type) {
1966

    
1967
        case TYPE_SCE:
1968
            err = decode_ics(ac, &che->ch[0], gb, 0, 0);
1969
            break;
1970

    
1971
        case TYPE_CPE:
1972
            err = decode_cpe(ac, gb, che);
1973
            break;
1974

    
1975
        case TYPE_CCE:
1976
            err = decode_cce(ac, gb, che);
1977
            break;
1978

    
1979
        case TYPE_LFE:
1980
            err = decode_ics(ac, &che->ch[0], gb, 0, 0);
1981
            break;
1982

    
1983
        case TYPE_DSE:
1984
            err = skip_data_stream_element(ac, gb);
1985
            break;
1986

    
1987
        case TYPE_PCE: {
1988
            enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
1989
            memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
1990
            if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
1991
                break;
1992
            if (ac->output_configured > OC_TRIAL_PCE)
1993
                av_log(avctx, AV_LOG_ERROR,
1994
                       "Not evaluating a further program_config_element as this construct is dubious at best.\n");
1995
            else
1996
                err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
1997
            break;
1998
        }
1999

    
2000
        case TYPE_FIL:
2001
            if (elem_id == 15)
2002
                elem_id += get_bits(gb, 8) - 1;
2003
            if (get_bits_left(gb) < 8 * elem_id) {
2004
                    av_log(avctx, AV_LOG_ERROR, overread_err);
2005
                    return -1;
2006
            }
2007
            while (elem_id > 0)
2008
                elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2009
            err = 0; /* FIXME */
2010
            break;
2011

    
2012
        default:
2013
            err = -1; /* should not happen, but keeps compiler happy */
2014
            break;
2015
        }
2016

    
2017
        che_prev       = che;
2018
        elem_type_prev = elem_type;
2019

    
2020
        if (err)
2021
            return err;
2022

    
2023
        if (get_bits_left(gb) < 3) {
2024
            av_log(avctx, AV_LOG_ERROR, overread_err);
2025
            return -1;
2026
        }
2027
    }
2028

    
2029
    spectral_to_sample(ac);
2030

    
2031
    multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
2032
    samples <<= multiplier;
2033
    if (ac->output_configured < OC_LOCKED) {
2034
        avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
2035
        avctx->frame_size = samples;
2036
    }
2037

    
2038
    data_size_tmp = samples * avctx->channels * sizeof(int16_t);
2039
    if (*data_size < data_size_tmp) {
2040
        av_log(avctx, AV_LOG_ERROR,
2041
               "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
2042
               *data_size, data_size_tmp);
2043
        return -1;
2044
    }
2045
    *data_size = data_size_tmp;
2046

    
2047
    if (samples)
2048
        ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, samples, avctx->channels);
2049

    
2050
    if (ac->output_configured)
2051
        ac->output_configured = OC_LOCKED;
2052

    
2053
    return 0;
2054
}
2055

    
2056
static int aac_decode_frame(AVCodecContext *avctx, void *data,
2057
                            int *data_size, AVPacket *avpkt)
2058
{
2059
    const uint8_t *buf = avpkt->data;
2060
    int buf_size = avpkt->size;
2061
    GetBitContext gb;
2062
    int buf_consumed;
2063
    int buf_offset;
2064
    int err;
2065

    
2066
    init_get_bits(&gb, buf, buf_size * 8);
2067

    
2068
    if ((err = aac_decode_frame_int(avctx, data, data_size, &gb)) < 0)
2069
        return err;
2070

    
2071
    buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2072
    for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2073
        if (buf[buf_offset])
2074
            break;
2075

    
2076
    return buf_size > buf_offset ? buf_consumed : buf_size;
2077
}
2078

    
2079
static av_cold int aac_decode_close(AVCodecContext *avctx)
2080
{
2081
    AACContext *ac = avctx->priv_data;
2082
    int i, type;
2083

    
2084
    for (i = 0; i < MAX_ELEM_ID; i++) {
2085
        for (type = 0; type < 4; type++) {
2086
            if (ac->che[type][i])
2087
                ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2088
            av_freep(&ac->che[type][i]);
2089
        }
2090
    }
2091

    
2092
    ff_mdct_end(&ac->mdct);
2093
    ff_mdct_end(&ac->mdct_small);
2094
    return 0;
2095
}
2096

    
2097

    
2098
#define LOAS_SYNC_WORD   0x2b7       ///< 11 bits LOAS sync word
2099

    
2100
struct LATMContext {
2101
    AACContext      aac_ctx;             ///< containing AACContext
2102
    int             initialized;         ///< initilized after a valid extradata was seen
2103

    
2104
    // parser data
2105
    int             audio_mux_version_A; ///< LATM syntax version
2106
    int             frame_length_type;   ///< 0/1 variable/fixed frame length
2107
    int             frame_length;        ///< frame length for fixed frame length
2108
};
2109

    
2110
static inline uint32_t latm_get_value(GetBitContext *b)
2111
{
2112
    int length = get_bits(b, 2);
2113

    
2114
    return get_bits_long(b, (length+1)*8);
2115
}
2116

    
2117
static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2118
                                             GetBitContext *gb)
2119
{
2120
    AVCodecContext *avctx = latmctx->aac_ctx.avctx;
2121
    MPEG4AudioConfig m4ac;
2122
    int  config_start_bit = get_bits_count(gb);
2123
    int     bits_consumed, esize;
2124

    
2125
    if (config_start_bit % 8) {
2126
        av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
2127
                               "config not byte aligned.\n", 1);
2128
        return AVERROR_INVALIDDATA;
2129
    } else {
2130
        bits_consumed =
2131
            decode_audio_specific_config(NULL, avctx, &m4ac,
2132
                                         gb->buffer + (config_start_bit / 8),
2133
                                         get_bits_left(gb) / 8);
2134

    
2135
        if (bits_consumed < 0)
2136
            return AVERROR_INVALIDDATA;
2137

    
2138
        esize = (bits_consumed+7) / 8;
2139

    
2140
        if (avctx->extradata_size <= esize) {
2141
            av_free(avctx->extradata);
2142
            avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2143
            if (!avctx->extradata)
2144
                return AVERROR(ENOMEM);
2145
        }
2146

    
2147
        avctx->extradata_size = esize;
2148
        memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2149
        memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2150

    
2151
        skip_bits_long(gb, bits_consumed);
2152
    }
2153

    
2154
    return bits_consumed;
2155
}
2156

    
2157
static int read_stream_mux_config(struct LATMContext *latmctx,
2158
                                  GetBitContext *gb)
2159
{
2160
    int ret, audio_mux_version = get_bits(gb, 1);
2161

    
2162
    latmctx->audio_mux_version_A = 0;
2163
    if (audio_mux_version)
2164
        latmctx->audio_mux_version_A = get_bits(gb, 1);
2165

    
2166
    if (!latmctx->audio_mux_version_A) {
2167

    
2168
        if (audio_mux_version)
2169
            latm_get_value(gb);                 // taraFullness
2170

    
2171
        skip_bits(gb, 1);                       // allStreamSameTimeFraming
2172
        skip_bits(gb, 6);                       // numSubFrames
2173
        // numPrograms
2174
        if (get_bits(gb, 4)) {                  // numPrograms
2175
            av_log_missing_feature(latmctx->aac_ctx.avctx,
2176
                                   "multiple programs are not supported\n", 1);
2177
            return AVERROR_PATCHWELCOME;
2178
        }
2179

    
2180
        // for each program (which there is only on in DVB)
2181

    
2182
        // for each layer (which there is only on in DVB)
2183
        if (get_bits(gb, 3)) {                   // numLayer
2184
            av_log_missing_feature(latmctx->aac_ctx.avctx,
2185
                                   "multiple layers are not supported\n", 1);
2186
            return AVERROR_PATCHWELCOME;
2187
        }
2188

    
2189
        // for all but first stream: use_same_config = get_bits(gb, 1);
2190
        if (!audio_mux_version) {
2191
            if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
2192
                return ret;
2193
        } else {
2194
            int ascLen = latm_get_value(gb);
2195
            if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
2196
                return ret;
2197
            ascLen -= ret;
2198
            skip_bits_long(gb, ascLen);
2199
        }
2200

    
2201
        latmctx->frame_length_type = get_bits(gb, 3);
2202
        switch (latmctx->frame_length_type) {
2203
        case 0:
2204
            skip_bits(gb, 8);       // latmBufferFullness
2205
            break;
2206
        case 1:
2207
            latmctx->frame_length = get_bits(gb, 9);
2208
            break;
2209
        case 3:
2210
        case 4:
2211
        case 5:
2212
            skip_bits(gb, 6);       // CELP frame length table index
2213
            break;
2214
        case 6:
2215
        case 7:
2216
            skip_bits(gb, 1);       // HVXC frame length table index
2217
            break;
2218
        }
2219

    
2220
        if (get_bits(gb, 1)) {                  // other data
2221
            if (audio_mux_version) {
2222
                latm_get_value(gb);             // other_data_bits
2223
            } else {
2224
                int esc;
2225
                do {
2226
                    esc = get_bits(gb, 1);
2227
                    skip_bits(gb, 8);
2228
                } while (esc);
2229
            }
2230
        }
2231

    
2232
        if (get_bits(gb, 1))                     // crc present
2233
            skip_bits(gb, 8);                    // config_crc
2234
    }
2235

    
2236
    return 0;
2237
}
2238

    
2239
static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2240
{
2241
    uint8_t tmp;
2242

    
2243
    if (ctx->frame_length_type == 0) {
2244
        int mux_slot_length = 0;
2245
        do {
2246
            tmp = get_bits(gb, 8);
2247
            mux_slot_length += tmp;
2248
        } while (tmp == 255);
2249
        return mux_slot_length;
2250
    } else if (ctx->frame_length_type == 1) {
2251
        return ctx->frame_length;
2252
    } else if (ctx->frame_length_type == 3 ||
2253
               ctx->frame_length_type == 5 ||
2254
               ctx->frame_length_type == 7) {
2255
        skip_bits(gb, 2);          // mux_slot_length_coded
2256
    }
2257
    return 0;
2258
}
2259

    
2260
static int read_audio_mux_element(struct LATMContext *latmctx,
2261
                                  GetBitContext *gb)
2262
{
2263
    int err;
2264
    uint8_t use_same_mux = get_bits(gb, 1);
2265
    if (!use_same_mux) {
2266
        if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2267
            return err;
2268
    } else if (!latmctx->aac_ctx.avctx->extradata) {
2269
        av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2270
               "no decoder config found\n");
2271
        return AVERROR(EAGAIN);
2272
    }
2273
    if (latmctx->audio_mux_version_A == 0) {
2274
        int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2275
        if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2276
            av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2277
            return AVERROR_INVALIDDATA;
2278
        } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2279
            av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2280
                   "frame length mismatch %d << %d\n",
2281
                   mux_slot_length_bytes * 8, get_bits_left(gb));
2282
            return AVERROR_INVALIDDATA;
2283
        }
2284
    }
2285
    return 0;
2286
}
2287

    
2288

    
2289
static int latm_decode_frame(AVCodecContext *avctx, void *out, int *out_size,
2290
                             AVPacket *avpkt)
2291
{
2292
    struct LATMContext *latmctx = avctx->priv_data;
2293
    int                 muxlength, err;
2294
    GetBitContext       gb;
2295

    
2296
    if (avpkt->size == 0)
2297
        return 0;
2298

    
2299
    init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2300

    
2301
    // check for LOAS sync word
2302
    if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2303
        return AVERROR_INVALIDDATA;
2304

    
2305
    muxlength = get_bits(&gb, 13) + 3;
2306
    // not enough data, the parser should have sorted this
2307
    if (muxlength > avpkt->size)
2308
        return AVERROR_INVALIDDATA;
2309

    
2310
    if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2311
        return err;
2312

    
2313
    if (!latmctx->initialized) {
2314
        if (!avctx->extradata) {
2315
            *out_size = 0;
2316
            return avpkt->size;
2317
        } else {
2318
            if ((err = aac_decode_init(avctx)) < 0)
2319
                return err;
2320
            latmctx->initialized = 1;
2321
        }
2322
    }
2323

    
2324
    if (show_bits(&gb, 12) == 0xfff) {
2325
        av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2326
               "ADTS header detected, probably as result of configuration "
2327
               "misparsing\n");
2328
        return AVERROR_INVALIDDATA;
2329
    }
2330

    
2331
    if ((err = aac_decode_frame_int(avctx, out, out_size, &gb)) < 0)
2332
        return err;
2333

    
2334
    return muxlength;
2335
}
2336

    
2337
av_cold static int latm_decode_init(AVCodecContext *avctx)
2338
{
2339
    struct LATMContext *latmctx = avctx->priv_data;
2340
    int ret;
2341

    
2342
    ret = aac_decode_init(avctx);
2343

    
2344
    if (avctx->extradata_size > 0) {
2345
        latmctx->initialized = !ret;
2346
    } else {
2347
        latmctx->initialized = 0;
2348
    }
2349

    
2350
    return ret;
2351
}
2352

    
2353

    
2354
AVCodec ff_aac_decoder = {
2355
    "aac",
2356
    AVMEDIA_TYPE_AUDIO,
2357
    CODEC_ID_AAC,
2358
    sizeof(AACContext),
2359
    aac_decode_init,
2360
    NULL,
2361
    aac_decode_close,
2362
    aac_decode_frame,
2363
    .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
2364
    .sample_fmts = (const enum AVSampleFormat[]) {
2365
        AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE
2366
    },
2367
    .channel_layouts = aac_channel_layout,
2368
};
2369

    
2370
/*
2371
    Note: This decoder filter is intended to decode LATM streams transferred
2372
    in MPEG transport streams which only contain one program.
2373
    To do a more complex LATM demuxing a separate LATM demuxer should be used.
2374
*/
2375
AVCodec ff_aac_latm_decoder = {
2376
    .name = "aac_latm",
2377
    .type = CODEC_TYPE_AUDIO,
2378
    .id   = CODEC_ID_AAC_LATM,
2379
    .priv_data_size = sizeof(struct LATMContext),
2380
    .init   = latm_decode_init,
2381
    .close  = aac_decode_close,
2382
    .decode = latm_decode_frame,
2383
    .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
2384
    .sample_fmts = (const enum AVSampleFormat[]) {
2385
        AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE
2386
    },
2387
    .channel_layouts = aac_channel_layout,
2388
};