Statistics
| Branch: | Revision:

ffmpeg / libavcodec / aacdec.c @ b5ec6383

History | View | Annotate | Download (82 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
    // 60    - Required to scale values to the correct range [-32768,32767]
570
    //         for float to int16 conversion. (1 << (60 / 4)) == 32768
571
    ac->sf_scale  = 1. / -1024.;
572
    ac->sf_offset = 60;
573

    
574
    ff_aac_tableinit();
575

    
576
    INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
577
                    ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
578
                    ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
579
                    352);
580

    
581
    ff_mdct_init(&ac->mdct, 11, 1, 1.0);
582
    ff_mdct_init(&ac->mdct_small, 8, 1, 1.0);
583
    // window initialization
584
    ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
585
    ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
586
    ff_init_ff_sine_windows(10);
587
    ff_init_ff_sine_windows( 7);
588

    
589
    cbrt_tableinit();
590

    
591
    return 0;
592
}
593

    
594
/**
595
 * Skip data_stream_element; reference: table 4.10.
596
 */
597
static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
598
{
599
    int byte_align = get_bits1(gb);
600
    int count = get_bits(gb, 8);
601
    if (count == 255)
602
        count += get_bits(gb, 8);
603
    if (byte_align)
604
        align_get_bits(gb);
605

    
606
    if (get_bits_left(gb) < 8 * count) {
607
        av_log(ac->avctx, AV_LOG_ERROR, overread_err);
608
        return -1;
609
    }
610
    skip_bits_long(gb, 8 * count);
611
    return 0;
612
}
613

    
614
static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
615
                             GetBitContext *gb)
616
{
617
    int sfb;
618
    if (get_bits1(gb)) {
619
        ics->predictor_reset_group = get_bits(gb, 5);
620
        if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
621
            av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
622
            return -1;
623
        }
624
    }
625
    for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
626
        ics->prediction_used[sfb] = get_bits1(gb);
627
    }
628
    return 0;
629
}
630

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

    
692
    if (ics->max_sfb > ics->num_swb) {
693
        av_log(ac->avctx, AV_LOG_ERROR,
694
               "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
695
               ics->max_sfb, ics->num_swb);
696
        memset(ics, 0, sizeof(IndividualChannelStream));
697
        return -1;
698
    }
699

    
700
    return 0;
701
}
702

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

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

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

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

    
855
            for (filt = 0; filt < tns->n_filt[w]; filt++) {
856
                int tmp2_idx;
857
                tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
858

    
859
                if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
860
                    av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
861
                           tns->order[w][filt], tns_max_order);
862
                    tns->order[w][filt] = 0;
863
                    return -1;
864
                }
865
                if (tns->order[w][filt]) {
866
                    tns->direction[w][filt] = get_bits1(gb);
867
                    coef_compress = get_bits1(gb);
868
                    coef_len = coef_res + 3 - coef_compress;
869
                    tmp2_idx = 2 * coef_compress + coef_res;
870

    
871
                    for (i = 0; i < tns->order[w][filt]; i++)
872
                        tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
873
                }
874
            }
875
        }
876
    }
877
    return 0;
878
}
879

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

    
899
#ifndef VMUL2
900
static inline float *VMUL2(float *dst, const float *v, unsigned idx,
901
                           const float *scale)
902
{
903
    float s = *scale;
904
    *dst++ = v[idx    & 15] * s;
905
    *dst++ = v[idx>>4 & 15] * s;
906
    return dst;
907
}
908
#endif
909

    
910
#ifndef VMUL4
911
static inline float *VMUL4(float *dst, const float *v, unsigned idx,
912
                           const float *scale)
913
{
914
    float s = *scale;
915
    *dst++ = v[idx    & 3] * s;
916
    *dst++ = v[idx>>2 & 3] * s;
917
    *dst++ = v[idx>>4 & 3] * s;
918
    *dst++ = v[idx>>6 & 3] * s;
919
    return dst;
920
}
921
#endif
922

    
923
#ifndef VMUL2S
924
static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
925
                            unsigned sign, const float *scale)
926
{
927
    union float754 s0, s1;
928

    
929
    s0.f = s1.f = *scale;
930
    s0.i ^= sign >> 1 << 31;
931
    s1.i ^= sign      << 31;
932

    
933
    *dst++ = v[idx    & 15] * s0.f;
934
    *dst++ = v[idx>>4 & 15] * s1.f;
935

    
936
    return dst;
937
}
938
#endif
939

    
940
#ifndef VMUL4S
941
static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
942
                            unsigned sign, const float *scale)
943
{
944
    unsigned nz = idx >> 12;
945
    union float754 s = { .f = *scale };
946
    union float754 t;
947

    
948
    t.i = s.i ^ (sign & 1<<31);
949
    *dst++ = v[idx    & 3] * t.f;
950

    
951
    sign <<= nz & 1; nz >>= 1;
952
    t.i = s.i ^ (sign & 1<<31);
953
    *dst++ = v[idx>>2 & 3] * t.f;
954

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

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

    
963
    return dst;
964
}
965
#endif
966

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

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

    
993
    for (g = 0; g < ics->num_window_groups; g++) {
994
        unsigned g_len = ics->group_len[g];
995

    
996
        for (i = 0; i < ics->max_sfb; i++, idx++) {
997
            const unsigned cbt_m1 = band_type[idx] - 1;
998
            float *cfo = coef + offsets[i];
999
            int off_len = offsets[i + 1] - offsets[i];
1000
            int group;
1001

    
1002
            if (cbt_m1 >= INTENSITY_BT2 - 1) {
1003
                for (group = 0; group < g_len; group++, cfo+=128) {
1004
                    memset(cfo, 0, off_len * sizeof(float));
1005
                }
1006
            } else if (cbt_m1 == NOISE_BT - 1) {
1007
                for (group = 0; group < g_len; group++, cfo+=128) {
1008
                    float scale;
1009
                    float band_energy;
1010

    
1011
                    for (k = 0; k < off_len; k++) {
1012
                        ac->random_state  = lcg_random(ac->random_state);
1013
                        cfo[k] = ac->random_state;
1014
                    }
1015

    
1016
                    band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
1017
                    scale = sf[idx] / sqrtf(band_energy);
1018
                    ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1019
                }
1020
            } else {
1021
                const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1022
                const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1023
                VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1024
                OPEN_READER(re, gb);
1025

    
1026
                switch (cbt_m1 >> 1) {
1027
                case 0:
1028
                    for (group = 0; group < g_len; group++, cfo+=128) {
1029
                        float *cf = cfo;
1030
                        int len = off_len;
1031

    
1032
                        do {
1033
                            int code;
1034
                            unsigned cb_idx;
1035

    
1036
                            UPDATE_CACHE(re, gb);
1037
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1038
                            cb_idx = cb_vector_idx[code];
1039
                            cf = VMUL4(cf, vq, cb_idx, sf + idx);
1040
                        } while (len -= 4);
1041
                    }
1042
                    break;
1043

    
1044
                case 1:
1045
                    for (group = 0; group < g_len; group++, cfo+=128) {
1046
                        float *cf = cfo;
1047
                        int len = off_len;
1048

    
1049
                        do {
1050
                            int code;
1051
                            unsigned nnz;
1052
                            unsigned cb_idx;
1053
                            uint32_t bits;
1054

    
1055
                            UPDATE_CACHE(re, gb);
1056
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1057
                            cb_idx = cb_vector_idx[code];
1058
                            nnz = cb_idx >> 8 & 15;
1059
                            bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1060
                            LAST_SKIP_BITS(re, gb, nnz);
1061
                            cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1062
                        } while (len -= 4);
1063
                    }
1064
                    break;
1065

    
1066
                case 2:
1067
                    for (group = 0; group < g_len; group++, cfo+=128) {
1068
                        float *cf = cfo;
1069
                        int len = off_len;
1070

    
1071
                        do {
1072
                            int code;
1073
                            unsigned cb_idx;
1074

    
1075
                            UPDATE_CACHE(re, gb);
1076
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1077
                            cb_idx = cb_vector_idx[code];
1078
                            cf = VMUL2(cf, vq, cb_idx, sf + idx);
1079
                        } while (len -= 2);
1080
                    }
1081
                    break;
1082

    
1083
                case 3:
1084
                case 4:
1085
                    for (group = 0; group < g_len; group++, cfo+=128) {
1086
                        float *cf = cfo;
1087
                        int len = off_len;
1088

    
1089
                        do {
1090
                            int code;
1091
                            unsigned nnz;
1092
                            unsigned cb_idx;
1093
                            unsigned sign;
1094

    
1095
                            UPDATE_CACHE(re, gb);
1096
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1097
                            cb_idx = cb_vector_idx[code];
1098
                            nnz = cb_idx >> 8 & 15;
1099
                            sign = SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12);
1100
                            LAST_SKIP_BITS(re, gb, nnz);
1101
                            cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1102
                        } while (len -= 2);
1103
                    }
1104
                    break;
1105

    
1106
                default:
1107
                    for (group = 0; group < g_len; group++, cfo+=128) {
1108
                        float *cf = cfo;
1109
                        uint32_t *icf = (uint32_t *) cf;
1110
                        int len = off_len;
1111

    
1112
                        do {
1113
                            int code;
1114
                            unsigned nzt, nnz;
1115
                            unsigned cb_idx;
1116
                            uint32_t bits;
1117
                            int j;
1118

    
1119
                            UPDATE_CACHE(re, gb);
1120
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1121

    
1122
                            if (!code) {
1123
                                *icf++ = 0;
1124
                                *icf++ = 0;
1125
                                continue;
1126
                            }
1127

    
1128
                            cb_idx = cb_vector_idx[code];
1129
                            nnz = cb_idx >> 12;
1130
                            nzt = cb_idx >> 8;
1131
                            bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1132
                            LAST_SKIP_BITS(re, gb, nnz);
1133

    
1134
                            for (j = 0; j < 2; j++) {
1135
                                if (nzt & 1<<j) {
1136
                                    uint32_t b;
1137
                                    int n;
1138
                                    /* The total length of escape_sequence must be < 22 bits according
1139
                                       to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1140
                                    UPDATE_CACHE(re, gb);
1141
                                    b = GET_CACHE(re, gb);
1142
                                    b = 31 - av_log2(~b);
1143

    
1144
                                    if (b > 8) {
1145
                                        av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1146
                                        return -1;
1147
                                    }
1148

    
1149
                                    SKIP_BITS(re, gb, b + 1);
1150
                                    b += 4;
1151
                                    n = (1 << b) + SHOW_UBITS(re, gb, b);
1152
                                    LAST_SKIP_BITS(re, gb, b);
1153
                                    *icf++ = cbrt_tab[n] | (bits & 1<<31);
1154
                                    bits <<= 1;
1155
                                } else {
1156
                                    unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1157
                                    *icf++ = (bits & 1<<31) | v;
1158
                                    bits <<= !!v;
1159
                                }
1160
                                cb_idx >>= 4;
1161
                            }
1162
                        } while (len -= 2);
1163

    
1164
                        ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1165
                    }
1166
                }
1167

    
1168
                CLOSE_READER(re, gb);
1169
            }
1170
        }
1171
        coef += g_len << 7;
1172
    }
1173

    
1174
    if (pulse_present) {
1175
        idx = 0;
1176
        for (i = 0; i < pulse->num_pulse; i++) {
1177
            float co = coef_base[ pulse->pos[i] ];
1178
            while (offsets[idx + 1] <= pulse->pos[i])
1179
                idx++;
1180
            if (band_type[idx] != NOISE_BT && sf[idx]) {
1181
                float ico = -pulse->amp[i];
1182
                if (co) {
1183
                    co /= sf[idx];
1184
                    ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1185
                }
1186
                coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1187
            }
1188
        }
1189
    }
1190
    return 0;
1191
}
1192

    
1193
static av_always_inline float flt16_round(float pf)
1194
{
1195
    union float754 tmp;
1196
    tmp.f = pf;
1197
    tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1198
    return tmp.f;
1199
}
1200

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

    
1209
static av_always_inline float flt16_trunc(float pf)
1210
{
1211
    union float754 pun;
1212
    pun.f = pf;
1213
    pun.i &= 0xFFFF0000U;
1214
    return pun.f;
1215
}
1216

    
1217
static av_always_inline void predict(PredictorState *ps, float *coef,
1218
                                     float sf_scale, float inv_sf_scale,
1219
                    int output_enable)
1220
{
1221
    const float a     = 0.953125; // 61.0 / 64
1222
    const float alpha = 0.90625;  // 29.0 / 32
1223
    float e0, e1;
1224
    float pv;
1225
    float k1, k2;
1226
    float   r0 = ps->r0,     r1 = ps->r1;
1227
    float cor0 = ps->cor0, cor1 = ps->cor1;
1228
    float var0 = ps->var0, var1 = ps->var1;
1229

    
1230
    k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1231
    k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1232

    
1233
    pv = flt16_round(k1 * r0 + k2 * r1);
1234
    if (output_enable)
1235
        *coef += pv * sf_scale;
1236

    
1237
    e0 = *coef * inv_sf_scale;
1238
    e1 = e0 - k1 * r0;
1239

    
1240
    ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1241
    ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1242
    ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1243
    ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1244

    
1245
    ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1246
    ps->r0 = flt16_trunc(a * e0);
1247
}
1248

    
1249
/**
1250
 * Apply AAC-Main style frequency domain prediction.
1251
 */
1252
static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1253
{
1254
    int sfb, k;
1255
    float sf_scale = ac->sf_scale, inv_sf_scale = 1 / ac->sf_scale;
1256

    
1257
    if (!sce->ics.predictor_initialized) {
1258
        reset_all_predictors(sce->predictor_state);
1259
        sce->ics.predictor_initialized = 1;
1260
    }
1261

    
1262
    if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1263
        for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
1264
            for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
1265
                predict(&sce->predictor_state[k], &sce->coeffs[k],
1266
                        sf_scale, inv_sf_scale,
1267
                        sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
1268
            }
1269
        }
1270
        if (sce->ics.predictor_reset_group)
1271
            reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
1272
    } else
1273
        reset_all_predictors(sce->predictor_state);
1274
}
1275

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

    
1293
    /* This assignment is to silence a GCC warning about the variable being used
1294
     * uninitialized when in fact it always is.
1295
     */
1296
    pulse.num_pulse = 0;
1297

    
1298
    global_gain = get_bits(gb, 8);
1299

    
1300
    if (!common_window && !scale_flag) {
1301
        if (decode_ics_info(ac, ics, gb, 0) < 0)
1302
            return -1;
1303
    }
1304

    
1305
    if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1306
        return -1;
1307
    if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1308
        return -1;
1309

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

    
1330
    if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1331
        return -1;
1332

    
1333
    if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
1334
        apply_prediction(ac, sce);
1335

    
1336
    return 0;
1337
}
1338

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

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

    
1405
/**
1406
 * Decode a channel_pair_element; reference: table 4.4.
1407
 *
1408
 * @return  Returns error status. 0 - OK, !0 - error
1409
 */
1410
static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1411
{
1412
    int i, ret, common_window, ms_present = 0;
1413

    
1414
    common_window = get_bits1(gb);
1415
    if (common_window) {
1416
        if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
1417
            return -1;
1418
        i = cpe->ch[1].ics.use_kb_window[0];
1419
        cpe->ch[1].ics = cpe->ch[0].ics;
1420
        cpe->ch[1].ics.use_kb_window[1] = i;
1421
        ms_present = get_bits(gb, 2);
1422
        if (ms_present == 3) {
1423
            av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1424
            return -1;
1425
        } else if (ms_present)
1426
            decode_mid_side_stereo(cpe, gb, ms_present);
1427
    }
1428
    if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1429
        return ret;
1430
    if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1431
        return ret;
1432

    
1433
    if (common_window) {
1434
        if (ms_present)
1435
            apply_mid_side_stereo(ac, cpe);
1436
        if (ac->m4ac.object_type == AOT_AAC_MAIN) {
1437
            apply_prediction(ac, &cpe->ch[0]);
1438
            apply_prediction(ac, &cpe->ch[1]);
1439
        }
1440
    }
1441

    
1442
    apply_intensity_stereo(cpe, ms_present);
1443
    return 0;
1444
}
1445

    
1446
static const float cce_scale[] = {
1447
    1.09050773266525765921, //2^(1/8)
1448
    1.18920711500272106672, //2^(1/4)
1449
    M_SQRT2,
1450
    2,
1451
};
1452

    
1453
/**
1454
 * Decode coupling_channel_element; reference: table 4.8.
1455
 *
1456
 * @return  Returns error status. 0 - OK, !0 - error
1457
 */
1458
static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1459
{
1460
    int num_gain = 0;
1461
    int c, g, sfb, ret;
1462
    int sign;
1463
    float scale;
1464
    SingleChannelElement *sce = &che->ch[0];
1465
    ChannelCoupling     *coup = &che->coup;
1466

    
1467
    coup->coupling_point = 2 * get_bits1(gb);
1468
    coup->num_coupled = get_bits(gb, 3);
1469
    for (c = 0; c <= coup->num_coupled; c++) {
1470
        num_gain++;
1471
        coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1472
        coup->id_select[c] = get_bits(gb, 4);
1473
        if (coup->type[c] == TYPE_CPE) {
1474
            coup->ch_select[c] = get_bits(gb, 2);
1475
            if (coup->ch_select[c] == 3)
1476
                num_gain++;
1477
        } else
1478
            coup->ch_select[c] = 2;
1479
    }
1480
    coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1481

    
1482
    sign  = get_bits(gb, 1);
1483
    scale = cce_scale[get_bits(gb, 2)];
1484

    
1485
    if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1486
        return ret;
1487

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

    
1525
/**
1526
 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1527
 *
1528
 * @return  Returns number of bytes consumed.
1529
 */
1530
static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1531
                                         GetBitContext *gb)
1532
{
1533
    int i;
1534
    int num_excl_chan = 0;
1535

    
1536
    do {
1537
        for (i = 0; i < 7; i++)
1538
            che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1539
    } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1540

    
1541
    return num_excl_chan / 7;
1542
}
1543

    
1544
/**
1545
 * Decode dynamic range information; reference: table 4.52.
1546
 *
1547
 * @param   cnt length of TYPE_FIL syntactic element in bytes
1548
 *
1549
 * @return  Returns number of bytes consumed.
1550
 */
1551
static int decode_dynamic_range(DynamicRangeControl *che_drc,
1552
                                GetBitContext *gb, int cnt)
1553
{
1554
    int n             = 1;
1555
    int drc_num_bands = 1;
1556
    int i;
1557

    
1558
    /* pce_tag_present? */
1559
    if (get_bits1(gb)) {
1560
        che_drc->pce_instance_tag  = get_bits(gb, 4);
1561
        skip_bits(gb, 4); // tag_reserved_bits
1562
        n++;
1563
    }
1564

    
1565
    /* excluded_chns_present? */
1566
    if (get_bits1(gb)) {
1567
        n += decode_drc_channel_exclusions(che_drc, gb);
1568
    }
1569

    
1570
    /* drc_bands_present? */
1571
    if (get_bits1(gb)) {
1572
        che_drc->band_incr            = get_bits(gb, 4);
1573
        che_drc->interpolation_scheme = get_bits(gb, 4);
1574
        n++;
1575
        drc_num_bands += che_drc->band_incr;
1576
        for (i = 0; i < drc_num_bands; i++) {
1577
            che_drc->band_top[i] = get_bits(gb, 8);
1578
            n++;
1579
        }
1580
    }
1581

    
1582
    /* prog_ref_level_present? */
1583
    if (get_bits1(gb)) {
1584
        che_drc->prog_ref_level = get_bits(gb, 7);
1585
        skip_bits1(gb); // prog_ref_level_reserved_bits
1586
        n++;
1587
    }
1588

    
1589
    for (i = 0; i < drc_num_bands; i++) {
1590
        che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1591
        che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1592
        n++;
1593
    }
1594

    
1595
    return n;
1596
}
1597

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

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

    
1661
    for (w = 0; w < ics->num_windows; w++) {
1662
        bottom = ics->num_swb;
1663
        for (filt = 0; filt < tns->n_filt[w]; filt++) {
1664
            top    = bottom;
1665
            bottom = FFMAX(0, top - tns->length[w][filt]);
1666
            order  = tns->order[w][filt];
1667
            if (order == 0)
1668
                continue;
1669

    
1670
            // tns_decode_coef
1671
            compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
1672

    
1673
            start = ics->swb_offset[FFMIN(bottom, mmm)];
1674
            end   = ics->swb_offset[FFMIN(   top, mmm)];
1675
            if ((size = end - start) <= 0)
1676
                continue;
1677
            if (tns->direction[w][filt]) {
1678
                inc = -1;
1679
                start = end - 1;
1680
            } else {
1681
                inc = 1;
1682
            }
1683
            start += w * 128;
1684

    
1685
            // ar filter
1686
            for (m = 0; m < size; m++, start += inc)
1687
                for (i = 1; i <= FFMIN(m, order); i++)
1688
                    coef[start] -= coef[start - i * inc] * lpc[i - 1];
1689
        }
1690
    }
1691
}
1692

    
1693
/**
1694
 * Conduct IMDCT and windowing.
1695
 */
1696
static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
1697
{
1698
    IndividualChannelStream *ics = &sce->ics;
1699
    float *in    = sce->coeffs;
1700
    float *out   = sce->ret;
1701
    float *saved = sce->saved;
1702
    const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1703
    const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1704
    const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1705
    float *buf  = ac->buf_mdct;
1706
    float *temp = ac->temp;
1707
    int i;
1708

    
1709
    // imdct
1710
    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1711
        for (i = 0; i < 1024; i += 128)
1712
            ff_imdct_half(&ac->mdct_small, buf + i, in + i);
1713
    } else
1714
        ff_imdct_half(&ac->mdct, buf, in);
1715

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

    
1729
        if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1730
            ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, 0, 64);
1731
            ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      0, 64);
1732
            ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      0, 64);
1733
            ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      0, 64);
1734
            ac->dsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      0, 64);
1735
            memcpy(                    out + 448 + 4*128, temp, 64 * sizeof(float));
1736
        } else {
1737
            ac->dsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 0, 64);
1738
            for (i = 576; i < 1024; i++)
1739
                out[i] = buf[i-512];
1740
        }
1741
    }
1742

    
1743
    // buffer update
1744
    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1745
        for (i = 0; i < 64; i++)
1746
            saved[i] = temp[64 + i];
1747
        ac->dsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);
1748
        ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);
1749
        ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);
1750
        memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
1751
    } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1752
        memcpy(                    saved,       buf + 512,        448 * sizeof(float));
1753
        memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
1754
    } else { // LONG_STOP or ONLY_LONG
1755
        memcpy(                    saved,       buf + 512,        512 * sizeof(float));
1756
    }
1757
}
1758

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

    
1795
/**
1796
 * Apply independent channel coupling (applied after IMDCT).
1797
 *
1798
 * @param   index   index into coupling gain array
1799
 */
1800
static void apply_independent_coupling(AACContext *ac,
1801
                                       SingleChannelElement *target,
1802
                                       ChannelElement *cce, int index)
1803
{
1804
    int i;
1805
    const float gain = cce->coup.gain[index][0];
1806
    const float *src = cce->ch[0].ret;
1807
    float *dest = target->ret;
1808
    const int len = 1024 << (ac->m4ac.sbr == 1);
1809

    
1810
    for (i = 0; i < len; i++)
1811
        dest[i] += gain * src[i];
1812
}
1813

    
1814
/**
1815
 * channel coupling transformation interface
1816
 *
1817
 * @param   apply_coupling_method   pointer to (in)dependent coupling function
1818
 */
1819
static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
1820
                                   enum RawDataBlockType type, int elem_id,
1821
                                   enum CouplingPoint coupling_point,
1822
                                   void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
1823
{
1824
    int i, c;
1825

    
1826
    for (i = 0; i < MAX_ELEM_ID; i++) {
1827
        ChannelElement *cce = ac->che[TYPE_CCE][i];
1828
        int index = 0;
1829

    
1830
        if (cce && cce->coup.coupling_point == coupling_point) {
1831
            ChannelCoupling *coup = &cce->coup;
1832

    
1833
            for (c = 0; c <= coup->num_coupled; c++) {
1834
                if (coup->type[c] == type && coup->id_select[c] == elem_id) {
1835
                    if (coup->ch_select[c] != 1) {
1836
                        apply_coupling_method(ac, &cc->ch[0], cce, index);
1837
                        if (coup->ch_select[c] != 0)
1838
                            index++;
1839
                    }
1840
                    if (coup->ch_select[c] != 2)
1841
                        apply_coupling_method(ac, &cc->ch[1], cce, index++);
1842
                } else
1843
                    index += 1 + (coup->ch_select[c] == 3);
1844
            }
1845
        }
1846
    }
1847
}
1848

    
1849
/**
1850
 * Convert spectral data to float samples, applying all supported tools as appropriate.
1851
 */
1852
static void spectral_to_sample(AACContext *ac)
1853
{
1854
    int i, type;
1855
    for (type = 3; type >= 0; type--) {
1856
        for (i = 0; i < MAX_ELEM_ID; i++) {
1857
            ChannelElement *che = ac->che[type][i];
1858
            if (che) {
1859
                if (type <= TYPE_CPE)
1860
                    apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
1861
                if (che->ch[0].tns.present)
1862
                    apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
1863
                if (che->ch[1].tns.present)
1864
                    apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
1865
                if (type <= TYPE_CPE)
1866
                    apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
1867
                if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
1868
                    imdct_and_windowing(ac, &che->ch[0]);
1869
                    if (type == TYPE_CPE) {
1870
                        imdct_and_windowing(ac, &che->ch[1]);
1871
                    }
1872
                    if (ac->m4ac.sbr > 0) {
1873
                        ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
1874
                    }
1875
                }
1876
                if (type <= TYPE_CCE)
1877
                    apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
1878
            }
1879
        }
1880
    }
1881
}
1882

    
1883
static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
1884
{
1885
    int size;
1886
    AACADTSHeaderInfo hdr_info;
1887

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

    
1921
static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
1922
                                int *data_size, GetBitContext *gb)
1923
{
1924
    AACContext *ac = avctx->priv_data;
1925
    ChannelElement *che = NULL, *che_prev = NULL;
1926
    enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
1927
    int err, elem_id, data_size_tmp;
1928
    int samples = 0, multiplier;
1929

    
1930
    if (show_bits(gb, 12) == 0xfff) {
1931
        if (parse_adts_frame_header(ac, gb) < 0) {
1932
            av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
1933
            return -1;
1934
        }
1935
        if (ac->m4ac.sampling_index > 12) {
1936
            av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
1937
            return -1;
1938
        }
1939
    }
1940

    
1941
    ac->tags_mapped = 0;
1942
    // parse
1943
    while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
1944
        elem_id = get_bits(gb, 4);
1945

    
1946
        if (elem_type < TYPE_DSE) {
1947
            if (!(che=get_che(ac, elem_type, elem_id))) {
1948
                av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
1949
                       elem_type, elem_id);
1950
                return -1;
1951
            }
1952
            samples = 1024;
1953
        }
1954

    
1955
        switch (elem_type) {
1956

    
1957
        case TYPE_SCE:
1958
            err = decode_ics(ac, &che->ch[0], gb, 0, 0);
1959
            break;
1960

    
1961
        case TYPE_CPE:
1962
            err = decode_cpe(ac, gb, che);
1963
            break;
1964

    
1965
        case TYPE_CCE:
1966
            err = decode_cce(ac, gb, che);
1967
            break;
1968

    
1969
        case TYPE_LFE:
1970
            err = decode_ics(ac, &che->ch[0], gb, 0, 0);
1971
            break;
1972

    
1973
        case TYPE_DSE:
1974
            err = skip_data_stream_element(ac, gb);
1975
            break;
1976

    
1977
        case TYPE_PCE: {
1978
            enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
1979
            memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
1980
            if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
1981
                break;
1982
            if (ac->output_configured > OC_TRIAL_PCE)
1983
                av_log(avctx, AV_LOG_ERROR,
1984
                       "Not evaluating a further program_config_element as this construct is dubious at best.\n");
1985
            else
1986
                err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
1987
            break;
1988
        }
1989

    
1990
        case TYPE_FIL:
1991
            if (elem_id == 15)
1992
                elem_id += get_bits(gb, 8) - 1;
1993
            if (get_bits_left(gb) < 8 * elem_id) {
1994
                    av_log(avctx, AV_LOG_ERROR, overread_err);
1995
                    return -1;
1996
            }
1997
            while (elem_id > 0)
1998
                elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
1999
            err = 0; /* FIXME */
2000
            break;
2001

    
2002
        default:
2003
            err = -1; /* should not happen, but keeps compiler happy */
2004
            break;
2005
        }
2006

    
2007
        che_prev       = che;
2008
        elem_type_prev = elem_type;
2009

    
2010
        if (err)
2011
            return err;
2012

    
2013
        if (get_bits_left(gb) < 3) {
2014
            av_log(avctx, AV_LOG_ERROR, overread_err);
2015
            return -1;
2016
        }
2017
    }
2018

    
2019
    spectral_to_sample(ac);
2020

    
2021
    multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
2022
    samples <<= multiplier;
2023
    if (ac->output_configured < OC_LOCKED) {
2024
        avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
2025
        avctx->frame_size = samples;
2026
    }
2027

    
2028
    data_size_tmp = samples * avctx->channels * sizeof(int16_t);
2029
    if (*data_size < data_size_tmp) {
2030
        av_log(avctx, AV_LOG_ERROR,
2031
               "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
2032
               *data_size, data_size_tmp);
2033
        return -1;
2034
    }
2035
    *data_size = data_size_tmp;
2036

    
2037
    if (samples)
2038
        ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, samples, avctx->channels);
2039

    
2040
    if (ac->output_configured)
2041
        ac->output_configured = OC_LOCKED;
2042

    
2043
    return 0;
2044
}
2045

    
2046
static int aac_decode_frame(AVCodecContext *avctx, void *data,
2047
                            int *data_size, AVPacket *avpkt)
2048
{
2049
    const uint8_t *buf = avpkt->data;
2050
    int buf_size = avpkt->size;
2051
    GetBitContext gb;
2052
    int buf_consumed;
2053
    int buf_offset;
2054
    int err;
2055

    
2056
    init_get_bits(&gb, buf, buf_size * 8);
2057

    
2058
    if ((err = aac_decode_frame_int(avctx, data, data_size, &gb)) < 0)
2059
        return err;
2060

    
2061
    buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2062
    for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2063
        if (buf[buf_offset])
2064
            break;
2065

    
2066
    return buf_size > buf_offset ? buf_consumed : buf_size;
2067
}
2068

    
2069
static av_cold int aac_decode_close(AVCodecContext *avctx)
2070
{
2071
    AACContext *ac = avctx->priv_data;
2072
    int i, type;
2073

    
2074
    for (i = 0; i < MAX_ELEM_ID; i++) {
2075
        for (type = 0; type < 4; type++) {
2076
            if (ac->che[type][i])
2077
                ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2078
            av_freep(&ac->che[type][i]);
2079
        }
2080
    }
2081

    
2082
    ff_mdct_end(&ac->mdct);
2083
    ff_mdct_end(&ac->mdct_small);
2084
    return 0;
2085
}
2086

    
2087

    
2088
#define LOAS_SYNC_WORD   0x2b7       ///< 11 bits LOAS sync word
2089

    
2090
struct LATMContext {
2091
    AACContext      aac_ctx;             ///< containing AACContext
2092
    int             initialized;         ///< initilized after a valid extradata was seen
2093

    
2094
    // parser data
2095
    int             audio_mux_version_A; ///< LATM syntax version
2096
    int             frame_length_type;   ///< 0/1 variable/fixed frame length
2097
    int             frame_length;        ///< frame length for fixed frame length
2098
};
2099

    
2100
static inline uint32_t latm_get_value(GetBitContext *b)
2101
{
2102
    int length = get_bits(b, 2);
2103

    
2104
    return get_bits_long(b, (length+1)*8);
2105
}
2106

    
2107
static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2108
                                             GetBitContext *gb)
2109
{
2110
    AVCodecContext *avctx = latmctx->aac_ctx.avctx;
2111
    MPEG4AudioConfig m4ac;
2112
    int  config_start_bit = get_bits_count(gb);
2113
    int     bits_consumed, esize;
2114

    
2115
    if (config_start_bit % 8) {
2116
        av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
2117
                               "config not byte aligned.\n", 1);
2118
        return AVERROR_INVALIDDATA;
2119
    } else {
2120
        bits_consumed =
2121
            decode_audio_specific_config(NULL, avctx, &m4ac,
2122
                                         gb->buffer + (config_start_bit / 8),
2123
                                         get_bits_left(gb) / 8);
2124

    
2125
        if (bits_consumed < 0)
2126
            return AVERROR_INVALIDDATA;
2127

    
2128
        esize = (bits_consumed+7) / 8;
2129

    
2130
        if (avctx->extradata_size <= esize) {
2131
            av_free(avctx->extradata);
2132
            avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2133
            if (!avctx->extradata)
2134
                return AVERROR(ENOMEM);
2135
        }
2136

    
2137
        avctx->extradata_size = esize;
2138
        memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2139
        memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2140

    
2141
        skip_bits_long(gb, bits_consumed);
2142
    }
2143

    
2144
    return bits_consumed;
2145
}
2146

    
2147
static int read_stream_mux_config(struct LATMContext *latmctx,
2148
                                  GetBitContext *gb)
2149
{
2150
    int ret, audio_mux_version = get_bits(gb, 1);
2151

    
2152
    latmctx->audio_mux_version_A = 0;
2153
    if (audio_mux_version)
2154
        latmctx->audio_mux_version_A = get_bits(gb, 1);
2155

    
2156
    if (!latmctx->audio_mux_version_A) {
2157

    
2158
        if (audio_mux_version)
2159
            latm_get_value(gb);                 // taraFullness
2160

    
2161
        skip_bits(gb, 1);                       // allStreamSameTimeFraming
2162
        skip_bits(gb, 6);                       // numSubFrames
2163
        // numPrograms
2164
        if (get_bits(gb, 4)) {                  // numPrograms
2165
            av_log_missing_feature(latmctx->aac_ctx.avctx,
2166
                                   "multiple programs are not supported\n", 1);
2167
            return AVERROR_PATCHWELCOME;
2168
        }
2169

    
2170
        // for each program (which there is only on in DVB)
2171

    
2172
        // for each layer (which there is only on in DVB)
2173
        if (get_bits(gb, 3)) {                   // numLayer
2174
            av_log_missing_feature(latmctx->aac_ctx.avctx,
2175
                                   "multiple layers are not supported\n", 1);
2176
            return AVERROR_PATCHWELCOME;
2177
        }
2178

    
2179
        // for all but first stream: use_same_config = get_bits(gb, 1);
2180
        if (!audio_mux_version) {
2181
            if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
2182
                return ret;
2183
        } else {
2184
            int ascLen = latm_get_value(gb);
2185
            if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
2186
                return ret;
2187
            ascLen -= ret;
2188
            skip_bits_long(gb, ascLen);
2189
        }
2190

    
2191
        latmctx->frame_length_type = get_bits(gb, 3);
2192
        switch (latmctx->frame_length_type) {
2193
        case 0:
2194
            skip_bits(gb, 8);       // latmBufferFullness
2195
            break;
2196
        case 1:
2197
            latmctx->frame_length = get_bits(gb, 9);
2198
            break;
2199
        case 3:
2200
        case 4:
2201
        case 5:
2202
            skip_bits(gb, 6);       // CELP frame length table index
2203
            break;
2204
        case 6:
2205
        case 7:
2206
            skip_bits(gb, 1);       // HVXC frame length table index
2207
            break;
2208
        }
2209

    
2210
        if (get_bits(gb, 1)) {                  // other data
2211
            if (audio_mux_version) {
2212
                latm_get_value(gb);             // other_data_bits
2213
            } else {
2214
                int esc;
2215
                do {
2216
                    esc = get_bits(gb, 1);
2217
                    skip_bits(gb, 8);
2218
                } while (esc);
2219
            }
2220
        }
2221

    
2222
        if (get_bits(gb, 1))                     // crc present
2223
            skip_bits(gb, 8);                    // config_crc
2224
    }
2225

    
2226
    return 0;
2227
}
2228

    
2229
static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2230
{
2231
    uint8_t tmp;
2232

    
2233
    if (ctx->frame_length_type == 0) {
2234
        int mux_slot_length = 0;
2235
        do {
2236
            tmp = get_bits(gb, 8);
2237
            mux_slot_length += tmp;
2238
        } while (tmp == 255);
2239
        return mux_slot_length;
2240
    } else if (ctx->frame_length_type == 1) {
2241
        return ctx->frame_length;
2242
    } else if (ctx->frame_length_type == 3 ||
2243
               ctx->frame_length_type == 5 ||
2244
               ctx->frame_length_type == 7) {
2245
        skip_bits(gb, 2);          // mux_slot_length_coded
2246
    }
2247
    return 0;
2248
}
2249

    
2250
static int read_audio_mux_element(struct LATMContext *latmctx,
2251
                                  GetBitContext *gb)
2252
{
2253
    int err;
2254
    uint8_t use_same_mux = get_bits(gb, 1);
2255
    if (!use_same_mux) {
2256
        if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2257
            return err;
2258
    } else if (!latmctx->aac_ctx.avctx->extradata) {
2259
        av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2260
               "no decoder config found\n");
2261
        return AVERROR(EAGAIN);
2262
    }
2263
    if (latmctx->audio_mux_version_A == 0) {
2264
        int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2265
        if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2266
            av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2267
            return AVERROR_INVALIDDATA;
2268
        } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2269
            av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2270
                   "frame length mismatch %d << %d\n",
2271
                   mux_slot_length_bytes * 8, get_bits_left(gb));
2272
            return AVERROR_INVALIDDATA;
2273
        }
2274
    }
2275
    return 0;
2276
}
2277

    
2278

    
2279
static int latm_decode_frame(AVCodecContext *avctx, void *out, int *out_size,
2280
                             AVPacket *avpkt)
2281
{
2282
    struct LATMContext *latmctx = avctx->priv_data;
2283
    int                 muxlength, err;
2284
    GetBitContext       gb;
2285

    
2286
    if (avpkt->size == 0)
2287
        return 0;
2288

    
2289
    init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2290

    
2291
    // check for LOAS sync word
2292
    if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2293
        return AVERROR_INVALIDDATA;
2294

    
2295
    muxlength = get_bits(&gb, 13) + 3;
2296
    // not enough data, the parser should have sorted this
2297
    if (muxlength > avpkt->size)
2298
        return AVERROR_INVALIDDATA;
2299

    
2300
    if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2301
        return err;
2302

    
2303
    if (!latmctx->initialized) {
2304
        if (!avctx->extradata) {
2305
            *out_size = 0;
2306
            return avpkt->size;
2307
        } else {
2308
            if ((err = aac_decode_init(avctx)) < 0)
2309
                return err;
2310
            latmctx->initialized = 1;
2311
        }
2312
    }
2313

    
2314
    if (show_bits(&gb, 12) == 0xfff) {
2315
        av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2316
               "ADTS header detected, probably as result of configuration "
2317
               "misparsing\n");
2318
        return AVERROR_INVALIDDATA;
2319
    }
2320

    
2321
    if ((err = aac_decode_frame_int(avctx, out, out_size, &gb)) < 0)
2322
        return err;
2323

    
2324
    return muxlength;
2325
}
2326

    
2327
av_cold static int latm_decode_init(AVCodecContext *avctx)
2328
{
2329
    struct LATMContext *latmctx = avctx->priv_data;
2330
    int ret;
2331

    
2332
    ret = aac_decode_init(avctx);
2333

    
2334
    if (avctx->extradata_size > 0) {
2335
        latmctx->initialized = !ret;
2336
    } else {
2337
        latmctx->initialized = 0;
2338
    }
2339

    
2340
    return ret;
2341
}
2342

    
2343

    
2344
AVCodec ff_aac_decoder = {
2345
    "aac",
2346
    AVMEDIA_TYPE_AUDIO,
2347
    CODEC_ID_AAC,
2348
    sizeof(AACContext),
2349
    aac_decode_init,
2350
    NULL,
2351
    aac_decode_close,
2352
    aac_decode_frame,
2353
    .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
2354
    .sample_fmts = (const enum AVSampleFormat[]) {
2355
        AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE
2356
    },
2357
    .channel_layouts = aac_channel_layout,
2358
};
2359

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