GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/aacdec_template.c Lines: 1473 1881 78.3 %
Date: 2021-01-26 11:44:58 Branches: 931 1314 70.9 %

Line Branch Exec Source
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
 * Copyright (c) 2008-2013 Alex Converse <alex.converse@gmail.com>
6
 *
7
 * AAC LATM decoder
8
 * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
9
 * Copyright (c) 2010      Janne Grunau <janne-libav@jannau.net>
10
 *
11
 * AAC decoder fixed-point implementation
12
 * Copyright (c) 2013
13
 *      MIPS Technologies, Inc., California.
14
 *
15
 * This file is part of FFmpeg.
16
 *
17
 * FFmpeg is free software; you can redistribute it and/or
18
 * modify it under the terms of the GNU Lesser General Public
19
 * License as published by the Free Software Foundation; either
20
 * version 2.1 of the License, or (at your option) any later version.
21
 *
22
 * FFmpeg is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25
 * Lesser General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU Lesser General Public
28
 * License along with FFmpeg; if not, write to the Free Software
29
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30
 */
31
32
/**
33
 * @file
34
 * AAC decoder
35
 * @author Oded Shimon  ( ods15 ods15 dyndns org )
36
 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
37
 *
38
 * AAC decoder fixed-point implementation
39
 * @author Stanislav Ocovaj ( stanislav.ocovaj imgtec com )
40
 * @author Nedeljko Babic ( nedeljko.babic imgtec com )
41
 */
42
43
/*
44
 * supported tools
45
 *
46
 * Support?                     Name
47
 * N (code in SoC repo)         gain control
48
 * Y                            block switching
49
 * Y                            window shapes - standard
50
 * N                            window shapes - Low Delay
51
 * Y                            filterbank - standard
52
 * N (code in SoC repo)         filterbank - Scalable Sample Rate
53
 * Y                            Temporal Noise Shaping
54
 * Y                            Long Term Prediction
55
 * Y                            intensity stereo
56
 * Y                            channel coupling
57
 * Y                            frequency domain prediction
58
 * Y                            Perceptual Noise Substitution
59
 * Y                            Mid/Side stereo
60
 * N                            Scalable Inverse AAC Quantization
61
 * N                            Frequency Selective Switch
62
 * N                            upsampling filter
63
 * Y                            quantization & coding - AAC
64
 * N                            quantization & coding - TwinVQ
65
 * N                            quantization & coding - BSAC
66
 * N                            AAC Error Resilience tools
67
 * N                            Error Resilience payload syntax
68
 * N                            Error Protection tool
69
 * N                            CELP
70
 * N                            Silence Compression
71
 * N                            HVXC
72
 * N                            HVXC 4kbits/s VR
73
 * N                            Structured Audio tools
74
 * N                            Structured Audio Sample Bank Format
75
 * N                            MIDI
76
 * N                            Harmonic and Individual Lines plus Noise
77
 * N                            Text-To-Speech Interface
78
 * Y                            Spectral Band Replication
79
 * Y (not in this code)         Layer-1
80
 * Y (not in this code)         Layer-2
81
 * Y (not in this code)         Layer-3
82
 * N                            SinuSoidal Coding (Transient, Sinusoid, Noise)
83
 * Y                            Parametric Stereo
84
 * N                            Direct Stream Transfer
85
 * Y  (not in fixed point code) Enhanced AAC Low Delay (ER AAC ELD)
86
 *
87
 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
88
 *       - HE AAC v2 comprises LC AAC with Spectral Band Replication and
89
           Parametric Stereo.
90
 */
91
92
#include "libavutil/thread.h"
93
94
static VLC vlc_scalefactors;
95
static VLC vlc_spectral[11];
96
97
static int output_configure(AACContext *ac,
98
                            uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
99
                            enum OCStatus oc_type, int get_new_frame);
100
101
#define overread_err "Input buffer exhausted before END element found\n"
102
103
528
static int count_channels(uint8_t (*layout)[3], int tags)
104
{
105
528
    int i, sum = 0;
106
1618
    for (i = 0; i < tags; i++) {
107
1090
        int syn_ele = layout[i][0];
108
1090
        int pos     = layout[i][2];
109
2180
        sum += (1 + (syn_ele == TYPE_CPE)) *
110

1090
               (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
111
    }
112
528
    return sum;
113
}
114
115
/**
116
 * Check for the channel element in the current channel position configuration.
117
 * If it exists, make sure the appropriate element is allocated and map the
118
 * channel order to match the internal FFmpeg channel layout.
119
 *
120
 * @param   che_pos current channel position configuration
121
 * @param   type channel element type
122
 * @param   id channel element id
123
 * @param   channels count of the number of channels in the configuration
124
 *
125
 * @return  Returns error status. 0 - OK, !0 - error
126
 */
127
4582
static av_cold int che_configure(AACContext *ac,
128
                                 enum ChannelPosition che_pos,
129
                                 int type, int id, int *channels)
130
{
131
4582
    if (*channels >= MAX_CHANNELS)
132
        return AVERROR_INVALIDDATA;
133
4582
    if (che_pos) {
134
4582
        if (!ac->che[type][id]) {
135
347
            if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
136
                return AVERROR(ENOMEM);
137
347
            AAC_RENAME(ff_aac_sbr_ctx_init)(ac, &ac->che[type][id]->sbr, type);
138
        }
139
4582
        if (type != TYPE_CCE) {
140


4574
            if (*channels >= MAX_CHANNELS - (type == TYPE_CPE || (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1))) {
141
                av_log(ac->avctx, AV_LOG_ERROR, "Too many channels\n");
142
                return AVERROR_INVALIDDATA;
143
            }
144
4574
            ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
145

4574
            if (type == TYPE_CPE ||
146
773
                (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
147
4100
                ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
148
            }
149
        }
150
    } else {
151
        if (ac->che[type][id])
152
            AAC_RENAME(ff_aac_sbr_ctx_close)(&ac->che[type][id]->sbr);
153
        av_freep(&ac->che[type][id]);
154
    }
155
4582
    return 0;
156
}
157
158
49857
static int frame_configure_elements(AVCodecContext *avctx)
159
{
160
49857
    AACContext *ac = avctx->priv_data;
161
    int type, id, ch, ret;
162
163
    /* set channel pointers to internal buffers by default */
164
249285
    for (type = 0; type < 4; type++) {
165
3390276
        for (id = 0; id < MAX_ELEM_ID; id++) {
166
3190848
            ChannelElement *che = ac->che[type][id];
167
3190848
            if (che) {
168
63237
                che->ch[0].ret = che->ch[0].ret_buf;
169
63237
                che->ch[1].ret = che->ch[1].ret_buf;
170
            }
171
        }
172
    }
173
174
    /* get output buffer */
175
49857
    av_frame_unref(ac->frame);
176
49857
    if (!avctx->channels)
177
        return 1;
178
179
49857
    ac->frame->nb_samples = 2048;
180
49857
    if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0)
181
        return ret;
182
183
    /* map output channel pointers to AVFrame data */
184
144264
    for (ch = 0; ch < avctx->channels; ch++) {
185
94407
        if (ac->output_element[ch])
186
94407
            ac->output_element[ch]->ret = (INTFLOAT *)ac->frame->extended_data[ch];
187
    }
188
189
49857
    return 0;
190
}
191
192
struct elem_to_channel {
193
    uint64_t av_position;
194
    uint8_t syn_ele;
195
    uint8_t elem_id;
196
    uint8_t aac_position;
197
};
198
199
3738
static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
200
                       uint8_t (*layout_map)[3], int offset, uint64_t left,
201
                       uint64_t right, int pos, uint64_t *layout)
202
{
203
3738
    if (layout_map[offset][0] == TYPE_CPE) {
204
3734
        e2c_vec[offset] = (struct elem_to_channel) {
205
3734
            .av_position  = left | right,
206
            .syn_ele      = TYPE_CPE,
207
3734
            .elem_id      = layout_map[offset][1],
208
            .aac_position = pos
209
        };
210
3734
        if (e2c_vec[offset].av_position != UINT64_MAX)
211
3734
            *layout |= e2c_vec[offset].av_position;
212
213
3734
        return 1;
214
    } else {
215
4
        e2c_vec[offset] = (struct elem_to_channel) {
216
            .av_position  = left,
217
            .syn_ele      = TYPE_SCE,
218
4
            .elem_id      = layout_map[offset][1],
219
            .aac_position = pos
220
        };
221
4
        e2c_vec[offset + 1] = (struct elem_to_channel) {
222
            .av_position  = right,
223
            .syn_ele      = TYPE_SCE,
224
4
            .elem_id      = layout_map[offset + 1][1],
225
            .aac_position = pos
226
        };
227
4
        if (left != UINT64_MAX)
228
4
            *layout |= left;
229
230
4
        if (right != UINT64_MAX)
231
4
            *layout |= right;
232
233
4
        return 2;
234
    }
235
}
236
237
13095
static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
238
                                 int *current)
239
{
240
13095
    int num_pos_channels = 0;
241
13095
    int first_cpe        = 0;
242
13095
    int sce_parity       = 0;
243
    int i;
244
17602
    for (i = *current; i < tags; i++) {
245
4708
        if (layout_map[i][2] != pos)
246
201
            break;
247
4507
        if (layout_map[i][0] == TYPE_CPE) {
248
3734
            if (sce_parity) {
249

71
                if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
250
71
                    sce_parity = 0;
251
                } else {
252
                    return -1;
253
                }
254
            }
255
3734
            num_pos_channels += 2;
256
3734
            first_cpe         = 1;
257
        } else {
258
773
            num_pos_channels++;
259
773
            sce_parity ^= 1;
260
        }
261
    }
262

13095
    if (sce_parity &&
263

694
        ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
264
        return -1;
265
13095
    *current = i;
266
13095
    return num_pos_channels;
267
}
268
269
#define PREFIX_FOR_22POINT2 (AV_CH_LAYOUT_7POINT1_WIDE_BACK|AV_CH_BACK_CENTER|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT|AV_CH_LOW_FREQUENCY_2)
270
4365
static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
271
{
272
    int i, n, total_non_cc_elements;
273
4365
    struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
274
    int num_front_channels, num_side_channels, num_back_channels;
275
4365
    uint64_t layout = 0;
276
277
4365
    if (FF_ARRAY_ELEMS(e2c_vec) < tags)
278
        return 0;
279
280
4365
    i = 0;
281
    num_front_channels =
282
4365
        count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
283
4365
    if (num_front_channels < 0)
284
        return 0;
285
    num_side_channels =
286
4365
        count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
287
4365
    if (num_side_channels < 0)
288
        return 0;
289
    num_back_channels =
290
4365
        count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
291
4365
    if (num_back_channels < 0)
292
        return 0;
293
294

4365
    if (num_side_channels == 0 && num_back_channels >= 4) {
295
        num_side_channels = 2;
296
        num_back_channels -= 2;
297
    }
298
299
4365
    i = 0;
300
4365
    if (num_front_channels & 1) {
301
765
        e2c_vec[i] = (struct elem_to_channel) {
302
            .av_position  = AV_CH_FRONT_CENTER,
303
            .syn_ele      = TYPE_SCE,
304
765
            .elem_id      = layout_map[i][1],
305
            .aac_position = AAC_CHANNEL_FRONT
306
        };
307
765
        layout |= e2c_vec[i].av_position;
308
765
        i++;
309
765
        num_front_channels--;
310
    }
311
4365
    if (num_front_channels >= 4) {
312
8
        i += assign_pair(e2c_vec, layout_map, i,
313
                         AV_CH_FRONT_LEFT_OF_CENTER,
314
                         AV_CH_FRONT_RIGHT_OF_CENTER,
315
                         AAC_CHANNEL_FRONT, &layout);
316
8
        num_front_channels -= 2;
317
    }
318
4365
    if (num_front_channels >= 2) {
319
3671
        i += assign_pair(e2c_vec, layout_map, i,
320
                         AV_CH_FRONT_LEFT,
321
                         AV_CH_FRONT_RIGHT,
322
                         AAC_CHANNEL_FRONT, &layout);
323
3671
        num_front_channels -= 2;
324
    }
325
4365
    while (num_front_channels >= 2) {
326
        i += assign_pair(e2c_vec, layout_map, i,
327
                         UINT64_MAX,
328
                         UINT64_MAX,
329
                         AAC_CHANNEL_FRONT, &layout);
330
        num_front_channels -= 2;
331
    }
332
333
4365
    if (num_side_channels >= 2) {
334
        i += assign_pair(e2c_vec, layout_map, i,
335
                         AV_CH_SIDE_LEFT,
336
                         AV_CH_SIDE_RIGHT,
337
                         AAC_CHANNEL_FRONT, &layout);
338
        num_side_channels -= 2;
339
    }
340
4365
    while (num_side_channels >= 2) {
341
        i += assign_pair(e2c_vec, layout_map, i,
342
                         UINT64_MAX,
343
                         UINT64_MAX,
344
                         AAC_CHANNEL_SIDE, &layout);
345
        num_side_channels -= 2;
346
    }
347
348
4365
    while (num_back_channels >= 4) {
349
        i += assign_pair(e2c_vec, layout_map, i,
350
                         UINT64_MAX,
351
                         UINT64_MAX,
352
                         AAC_CHANNEL_BACK, &layout);
353
        num_back_channels -= 2;
354
    }
355
4365
    if (num_back_channels >= 2) {
356
59
        i += assign_pair(e2c_vec, layout_map, i,
357
                         AV_CH_BACK_LEFT,
358
                         AV_CH_BACK_RIGHT,
359
                         AAC_CHANNEL_BACK, &layout);
360
59
        num_back_channels -= 2;
361
    }
362
4365
    if (num_back_channels) {
363
        e2c_vec[i] = (struct elem_to_channel) {
364
            .av_position  = AV_CH_BACK_CENTER,
365
            .syn_ele      = TYPE_SCE,
366
            .elem_id      = layout_map[i][1],
367
            .aac_position = AAC_CHANNEL_BACK
368
        };
369
        layout |= e2c_vec[i].av_position;
370
        i++;
371
        num_back_channels--;
372
    }
373
374

4365
    if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
375
67
        e2c_vec[i] = (struct elem_to_channel) {
376
            .av_position  = AV_CH_LOW_FREQUENCY,
377
            .syn_ele      = TYPE_LFE,
378
67
            .elem_id      = layout_map[i][1],
379
            .aac_position = AAC_CHANNEL_LFE
380
        };
381
67
        layout |= e2c_vec[i].av_position;
382
67
        i++;
383
    }
384

4365
    if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
385
        e2c_vec[i] = (struct elem_to_channel) {
386
            .av_position  = AV_CH_LOW_FREQUENCY_2,
387
            .syn_ele      = TYPE_LFE,
388
            .elem_id      = layout_map[i][1],
389
            .aac_position = AAC_CHANNEL_LFE
390
        };
391
        layout |= e2c_vec[i].av_position;
392
        i++;
393
    }
394

4365
    while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
395
        e2c_vec[i] = (struct elem_to_channel) {
396
            .av_position  = UINT64_MAX,
397
            .syn_ele      = TYPE_LFE,
398
            .elem_id      = layout_map[i][1],
399
            .aac_position = AAC_CHANNEL_LFE
400
        };
401
        i++;
402
    }
403
404
    // The previous checks would end up at 8 at this point for 22.2
405

4365
    if (layout == PREFIX_FOR_22POINT2 && tags == 16 && i == 8) {
406
        const uint8_t (*reference_layout_map)[3] = aac_channel_layout_map[12];
407
        for (int j = 0; j < tags; j++) {
408
            if (layout_map[j][0] != reference_layout_map[j][0] ||
409
                layout_map[j][2] != reference_layout_map[j][2])
410
                goto end_of_layout_definition;
411
        }
412
413
        e2c_vec[i] = (struct elem_to_channel) {
414
            .av_position  = AV_CH_TOP_FRONT_CENTER,
415
            .syn_ele      = layout_map[i][0],
416
            .elem_id      = layout_map[i][1],
417
            .aac_position = layout_map[i][2]
418
        }; layout |= e2c_vec[i].av_position; i++;
419
        i += assign_pair(e2c_vec, layout_map, i,
420
                         AV_CH_TOP_FRONT_LEFT,
421
                         AV_CH_TOP_FRONT_RIGHT,
422
                         AAC_CHANNEL_FRONT,
423
                         &layout);
424
        i += assign_pair(e2c_vec, layout_map, i,
425
                         AV_CH_TOP_SIDE_LEFT,
426
                         AV_CH_TOP_SIDE_RIGHT,
427
                         AAC_CHANNEL_SIDE,
428
                         &layout);
429
        e2c_vec[i] = (struct elem_to_channel) {
430
            .av_position  = AV_CH_TOP_CENTER,
431
            .syn_ele      = layout_map[i][0],
432
            .elem_id      = layout_map[i][1],
433
            .aac_position = layout_map[i][2]
434
        }; layout |= e2c_vec[i].av_position; i++;
435
        i += assign_pair(e2c_vec, layout_map, i,
436
                         AV_CH_TOP_BACK_LEFT,
437
                         AV_CH_TOP_BACK_RIGHT,
438
                         AAC_CHANNEL_BACK,
439
                         &layout);
440
        e2c_vec[i] = (struct elem_to_channel) {
441
            .av_position  = AV_CH_TOP_BACK_CENTER,
442
            .syn_ele      = layout_map[i][0],
443
            .elem_id      = layout_map[i][1],
444
            .aac_position = layout_map[i][2]
445
        }; layout |= e2c_vec[i].av_position; i++;
446
        e2c_vec[i] = (struct elem_to_channel) {
447
            .av_position  = AV_CH_BOTTOM_FRONT_CENTER,
448
            .syn_ele      = layout_map[i][0],
449
            .elem_id      = layout_map[i][1],
450
            .aac_position = layout_map[i][2]
451
        }; layout |= e2c_vec[i].av_position; i++;
452
        i += assign_pair(e2c_vec, layout_map, i,
453
                         AV_CH_BOTTOM_FRONT_LEFT,
454
                         AV_CH_BOTTOM_FRONT_RIGHT,
455
                         AAC_CHANNEL_FRONT,
456
                         &layout);
457
    }
458
459
4365
end_of_layout_definition:
460
461
4365
    total_non_cc_elements = n = i;
462
463
4365
    if (layout == AV_CH_LAYOUT_22POINT2) {
464
        // For 22.2 reorder the result as needed
465
        FFSWAP(struct elem_to_channel, e2c_vec[2], e2c_vec[0]);   // FL & FR first (final), FC third
466
        FFSWAP(struct elem_to_channel, e2c_vec[2], e2c_vec[1]);   // FC second (final), FLc & FRc third
467
        FFSWAP(struct elem_to_channel, e2c_vec[6], e2c_vec[2]);   // LFE1 third (final), FLc & FRc seventh
468
        FFSWAP(struct elem_to_channel, e2c_vec[4], e2c_vec[3]);   // BL & BR fourth (final), SiL & SiR fifth
469
        FFSWAP(struct elem_to_channel, e2c_vec[6], e2c_vec[4]);   // FLc & FRc fifth (final), SiL & SiR seventh
470
        FFSWAP(struct elem_to_channel, e2c_vec[7], e2c_vec[6]);   // LFE2 seventh (final), SiL & SiR eight (final)
471
        FFSWAP(struct elem_to_channel, e2c_vec[9], e2c_vec[8]);   // TpFL & TpFR ninth (final), TFC tenth (final)
472
        FFSWAP(struct elem_to_channel, e2c_vec[11], e2c_vec[10]); // TC eleventh (final), TpSiL & TpSiR twelth
473
        FFSWAP(struct elem_to_channel, e2c_vec[12], e2c_vec[11]); // TpBL & TpBR twelth (final), TpSiL & TpSiR thirteenth (final)
474
    } else {
475
        // For everything else, utilize the AV channel position define as a
476
        // stable sort.
477
        do {
478
4444
            int next_n = 0;
479
4787
            for (i = 1; i < n; i++)
480
343
                if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
481
146
                    FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
482
146
                    next_n = i;
483
                }
484
4444
            n = next_n;
485
4444
        } while (n > 0);
486
487
    }
488
489
8939
    for (i = 0; i < total_non_cc_elements; i++) {
490
4574
        layout_map[i][0] = e2c_vec[i].syn_ele;
491
4574
        layout_map[i][1] = e2c_vec[i].elem_id;
492
4574
        layout_map[i][2] = e2c_vec[i].aac_position;
493
    }
494
495
4365
    return layout;
496
}
497
498
/**
499
 * Save current output configuration if and only if it has been locked.
500
 */
501
4118
static int push_output_configuration(AACContext *ac) {
502
4118
    int pushed = 0;
503
504

4118
    if (ac->oc[1].status == OC_LOCKED || ac->oc[0].status == OC_NONE) {
505
4118
        ac->oc[0] = ac->oc[1];
506
4118
        pushed = 1;
507
    }
508
4118
    ac->oc[1].status = OC_NONE;
509
4118
    return pushed;
510
}
511
512
/**
513
 * Restore the previous output configuration if and only if the current
514
 * configuration is unlocked.
515
 */
516
static void pop_output_configuration(AACContext *ac) {
517
    if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
518
        ac->oc[1] = ac->oc[0];
519
        ac->avctx->channels = ac->oc[1].channels;
520
        ac->avctx->channel_layout = ac->oc[1].channel_layout;
521
        output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
522
                         ac->oc[1].status, 0);
523
    }
524
}
525
526
/**
527
 * Configure output channel order based on the current program
528
 * configuration element.
529
 *
530
 * @return  Returns error status. 0 - OK, !0 - error
531
 */
532
4365
static int output_configure(AACContext *ac,
533
                            uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
534
                            enum OCStatus oc_type, int get_new_frame)
535
{
536
4365
    AVCodecContext *avctx = ac->avctx;
537
4365
    int i, channels = 0, ret;
538
4365
    uint64_t layout = 0;
539
4365
    uint8_t id_map[TYPE_END][MAX_ELEM_ID] = {{ 0 }};
540
4365
    uint8_t type_counts[TYPE_END] = { 0 };
541
542
4365
    if (ac->oc[1].layout_map != layout_map) {
543
4353
        memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
544
4353
        ac->oc[1].layout_map_tags = tags;
545
    }
546
8947
    for (i = 0; i < tags; i++) {
547
4582
        int type =         layout_map[i][0];
548
4582
        int id =           layout_map[i][1];
549
4582
        id_map[type][id] = type_counts[type]++;
550
4582
        if (id_map[type][id] >= MAX_ELEM_ID) {
551
            avpriv_request_sample(ac->avctx, "Too large remapped id");
552
            return AVERROR_PATCHWELCOME;
553
        }
554
    }
555
    // Try to sniff a reasonable channel order, otherwise output the
556
    // channels in the order the PCE declared them.
557
4365
    if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
558
4365
        layout = sniff_channel_order(layout_map, tags);
559
8947
    for (i = 0; i < tags; i++) {
560
4582
        int type =     layout_map[i][0];
561
4582
        int id =       layout_map[i][1];
562
4582
        int iid =      id_map[type][id];
563
4582
        int position = layout_map[i][2];
564
        // Allocate or free elements depending on if they are in the
565
        // current program configuration.
566
4582
        ret = che_configure(ac, position, type, iid, &channels);
567
4582
        if (ret < 0)
568
            return ret;
569
4582
        ac->tag_che_map[type][id] = ac->che[type][iid];
570
    }
571

4365
    if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
572
366
        if (layout == AV_CH_FRONT_CENTER) {
573
366
            layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
574
        } else {
575
            layout = 0;
576
        }
577
    }
578
579
4365
    if (layout) avctx->channel_layout = layout;
580
4365
                            ac->oc[1].channel_layout = layout;
581
4365
    avctx->channels       = ac->oc[1].channels       = channels;
582
4365
    ac->oc[1].status = oc_type;
583
584
4365
    if (get_new_frame) {
585
12
        if ((ret = frame_configure_elements(ac->avctx)) < 0)
586
            return ret;
587
    }
588
589
4365
    return 0;
590
}
591
592
static void flush(AVCodecContext *avctx)
593
{
594
    AACContext *ac= avctx->priv_data;
595
    int type, i, j;
596
597
    for (type = 3; type >= 0; type--) {
598
        for (i = 0; i < MAX_ELEM_ID; i++) {
599
            ChannelElement *che = ac->che[type][i];
600
            if (che) {
601
                for (j = 0; j <= 1; j++) {
602
                    memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
603
                }
604
            }
605
        }
606
    }
607
}
608
609
/**
610
 * Set up channel positions based on a default channel configuration
611
 * as specified in table 1.17.
612
 *
613
 * @return  Returns error status. 0 - OK, !0 - error
614
 */
615
4631
static int set_default_channel_config(AACContext *ac, AVCodecContext *avctx,
616
                                      uint8_t (*layout_map)[3],
617
                                      int *tags,
618
                                      int channel_config)
619
{
620


4631
    if (channel_config < 1 || (channel_config > 7 && channel_config < 11) ||
621
        channel_config > 13) {
622
        av_log(avctx, AV_LOG_ERROR,
623
               "invalid default channel configuration (%d)\n",
624
               channel_config);
625
        return AVERROR_INVALIDDATA;
626
    }
627
4631
    *tags = tags_per_config[channel_config];
628
4631
    memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
629
4631
           *tags * sizeof(*layout_map));
630
631
    /*
632
     * AAC specification has 7.1(wide) as a default layout for 8-channel streams.
633
     * However, at least Nero AAC encoder encodes 7.1 streams using the default
634
     * channel config 7, mapping the side channels of the original audio stream
635
     * to the second AAC_CHANNEL_FRONT pair in the AAC stream. Similarly, e.g. FAAD
636
     * decodes the second AAC_CHANNEL_FRONT pair as side channels, therefore decoding
637
     * the incorrect streams as if they were correct (and as the encoder intended).
638
     *
639
     * As actual intended 7.1(wide) streams are very rare, default to assuming a
640
     * 7.1 layout was intended.
641
     */
642


4631
    if (channel_config == 7 && avctx->strict_std_compliance < FF_COMPLIANCE_STRICT && (!ac || !ac->warned_71_wide++)) {
643
        av_log(avctx, AV_LOG_INFO, "Assuming an incorrectly encoded 7.1 channel layout"
644
               " instead of a spec-compliant 7.1(wide) layout, use -strict %d to decode"
645
               " according to the specification instead.\n", FF_COMPLIANCE_STRICT);
646
        layout_map[2][2] = AAC_CHANNEL_SIDE;
647
    }
648
649
4631
    return 0;
650
}
651
652
62891
static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
653
{
654
    /* For PCE based channel configurations map the channels solely based
655
     * on tags. */
656
62891
    if (!ac->oc[1].m4ac.chan_config) {
657
24124
        return ac->tag_che_map[type][elem_id];
658
    }
659
    // Allow single CPE stereo files to be signalled with mono configuration.
660

38767
    if (!ac->tags_mapped && type == TYPE_CPE &&
661
20533
        ac->oc[1].m4ac.chan_config == 1) {
662
        uint8_t layout_map[MAX_ELEM_ID*4][3];
663
        int layout_map_tags;
664
        push_output_configuration(ac);
665
666
        av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
667
668
        if (set_default_channel_config(ac, ac->avctx, layout_map,
669
                                       &layout_map_tags, 2) < 0)
670
            return NULL;
671
        if (output_configure(ac, layout_map, layout_map_tags,
672
                             OC_TRIAL_FRAME, 1) < 0)
673
            return NULL;
674
675
        ac->oc[1].m4ac.chan_config = 2;
676
        ac->oc[1].m4ac.ps = 0;
677
    }
678
    // And vice-versa
679

38767
    if (!ac->tags_mapped && type == TYPE_SCE &&
680
15774
        ac->oc[1].m4ac.chan_config == 2) {
681
        uint8_t layout_map[MAX_ELEM_ID * 4][3];
682
        int layout_map_tags;
683
        push_output_configuration(ac);
684
685
        av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
686
687
        if (set_default_channel_config(ac, ac->avctx, layout_map,
688
                                       &layout_map_tags, 1) < 0)
689
            return NULL;
690
        if (output_configure(ac, layout_map, layout_map_tags,
691
                             OC_TRIAL_FRAME, 1) < 0)
692
            return NULL;
693
694
        ac->oc[1].m4ac.chan_config = 1;
695
        if (ac->oc[1].m4ac.sbr)
696
            ac->oc[1].m4ac.ps = -1;
697
    }
698
    /* For indexed channel configurations map the channels solely based
699
     * on position. */
700


38767
    switch (ac->oc[1].m4ac.chan_config) {
701
    case 13:
702
        if (ac->tags_mapped > 3 && ((type == TYPE_CPE && elem_id < 8) ||
703
                                    (type == TYPE_SCE && elem_id < 6) ||
704
                                    (type == TYPE_LFE && elem_id < 2))) {
705
            ac->tags_mapped++;
706
            return ac->tag_che_map[type][elem_id] = ac->che[type][elem_id];
707
        }
708
    case 12:
709
    case 7:
710
        if (ac->tags_mapped == 3 && type == TYPE_CPE) {
711
            ac->tags_mapped++;
712
            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
713
        }
714
    case 11:
715
        if (ac->tags_mapped == 2 &&
716
            ac->oc[1].m4ac.chan_config == 11 &&
717
            type == TYPE_SCE) {
718
            ac->tags_mapped++;
719
            return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
720
        }
721
    case 6:
722
        /* Some streams incorrectly code 5.1 audio as
723
         * SCE[0] CPE[0] CPE[1] SCE[1]
724
         * instead of
725
         * SCE[0] CPE[0] CPE[1] LFE[0].
726
         * If we seem to have encountered such a stream, transfer
727
         * the LFE[0] element to the SCE[1]'s mapping */
728

3280
        if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
729

820
            if (!ac->warned_remapping_once && (type != TYPE_LFE || elem_id != 0)) {
730
                av_log(ac->avctx, AV_LOG_WARNING,
731
                   "This stream seems to incorrectly report its last channel as %s[%d], mapping to LFE[0]\n",
732
                   type == TYPE_SCE ? "SCE" : "LFE", elem_id);
733
                ac->warned_remapping_once++;
734
            }
735
820
            ac->tags_mapped++;
736
820
            return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
737
        }
738
    case 5:
739

2460
        if (ac->tags_mapped == 2 && type == TYPE_CPE) {
740
820
            ac->tags_mapped++;
741
820
            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
742
        }
743
    case 4:
744
        /* Some streams incorrectly code 4.0 audio as
745
         * SCE[0] CPE[0] LFE[0]
746
         * instead of
747
         * SCE[0] CPE[0] SCE[1].
748
         * If we seem to have encountered such a stream, transfer
749
         * the SCE[1] element to the LFE[0]'s mapping */
750

1640
        if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
751
            if (!ac->warned_remapping_once && (type != TYPE_SCE || elem_id != 1)) {
752
                av_log(ac->avctx, AV_LOG_WARNING,
753
                   "This stream seems to incorrectly report its last channel as %s[%d], mapping to SCE[1]\n",
754
                   type == TYPE_SCE ? "SCE" : "LFE", elem_id);
755
                ac->warned_remapping_once++;
756
            }
757
            ac->tags_mapped++;
758
            return ac->tag_che_map[type][elem_id] = ac->che[TYPE_SCE][1];
759
        }
760
1640
        if (ac->tags_mapped == 2 &&
761
            ac->oc[1].m4ac.chan_config == 4 &&
762
            type == TYPE_SCE) {
763
            ac->tags_mapped++;
764
            return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
765
        }
766
    case 3:
767
    case 2:
768

22173
        if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
769
            type == TYPE_CPE) {
770
21353
            ac->tags_mapped++;
771
21353
            return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
772
820
        } else if (ac->oc[1].m4ac.chan_config == 2) {
773
            return NULL;
774
        }
775
    case 1:
776

15774
        if (!ac->tags_mapped && type == TYPE_SCE) {
777
15774
            ac->tags_mapped++;
778
15774
            return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
779
        }
780
    default:
781
        return NULL;
782
    }
783
}
784
785
/**
786
 * Decode an array of 4 bit element IDs, optionally interleaved with a
787
 * stereo/mono switching bit.
788
 *
789
 * @param type speaker type/position for these channels
790
 */
791
215
static void decode_channel_map(uint8_t layout_map[][3],
792
                               enum ChannelPosition type,
793
                               GetBitContext *gb, int n)
794
{
795
310
    while (n--) {
796
        enum RawDataBlockType syn_ele;
797

95
        switch (type) {
798
75
        case AAC_CHANNEL_FRONT:
799
        case AAC_CHANNEL_BACK:
800
        case AAC_CHANNEL_SIDE:
801
75
            syn_ele = get_bits1(gb);
802
75
            break;
803
8
        case AAC_CHANNEL_CC:
804
8
            skip_bits1(gb);
805
8
            syn_ele = TYPE_CCE;
806
8
            break;
807
12
        case AAC_CHANNEL_LFE:
808
12
            syn_ele = TYPE_LFE;
809
12
            break;
810
        default:
811
            // AAC_CHANNEL_OFF has no channel map
812
            av_assert0(0);
813
        }
814
95
        layout_map[0][0] = syn_ele;
815
95
        layout_map[0][1] = get_bits(gb, 4);
816
95
        layout_map[0][2] = type;
817
95
        layout_map++;
818
    }
819
215
}
820
821
43
static inline void relative_align_get_bits(GetBitContext *gb,
822
                                           int reference_position) {
823
43
    int n = (reference_position - get_bits_count(gb) & 7);
824
43
    if (n)
825
39
        skip_bits(gb, n);
826
43
}
827
828
/**
829
 * Decode program configuration element; reference: table 4.2.
830
 *
831
 * @return  Returns error status. 0 - OK, !0 - error
832
 */
833
43
static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
834
                      uint8_t (*layout_map)[3],
835
                      GetBitContext *gb, int byte_align_ref)
836
{
837
    int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
838
    int sampling_index;
839
    int comment_len;
840
    int tags;
841
842
43
    skip_bits(gb, 2);  // object_type
843
844
43
    sampling_index = get_bits(gb, 4);
845
43
    if (m4ac->sampling_index != sampling_index)
846
        av_log(avctx, AV_LOG_WARNING,
847
               "Sample rate index in program config element does not "
848
               "match the sample rate index configured by the container.\n");
849
850
43
    num_front       = get_bits(gb, 4);
851
43
    num_side        = get_bits(gb, 4);
852
43
    num_back        = get_bits(gb, 4);
853
43
    num_lfe         = get_bits(gb, 2);
854
43
    num_assoc_data  = get_bits(gb, 3);
855
43
    num_cc          = get_bits(gb, 4);
856
857
43
    if (get_bits1(gb))
858
        skip_bits(gb, 4); // mono_mixdown_tag
859
43
    if (get_bits1(gb))
860
        skip_bits(gb, 4); // stereo_mixdown_tag
861
862
43
    if (get_bits1(gb))
863
        skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
864
865
43
    if (get_bits_left(gb) < 5 * (num_front + num_side + num_back + num_cc) + 4 *(num_lfe + num_assoc_data + num_cc)) {
866
        av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
867
        return -1;
868
    }
869
43
    decode_channel_map(layout_map       , AAC_CHANNEL_FRONT, gb, num_front);
870
43
    tags = num_front;
871
43
    decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE,  gb, num_side);
872
43
    tags += num_side;
873
43
    decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK,  gb, num_back);
874
43
    tags += num_back;
875
43
    decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE,   gb, num_lfe);
876
43
    tags += num_lfe;
877
878
43
    skip_bits_long(gb, 4 * num_assoc_data);
879
880
43
    decode_channel_map(layout_map + tags, AAC_CHANNEL_CC,    gb, num_cc);
881
43
    tags += num_cc;
882
883
43
    relative_align_get_bits(gb, byte_align_ref);
884
885
    /* comment field, first byte is length */
886
43
    comment_len = get_bits(gb, 8) * 8;
887
43
    if (get_bits_left(gb) < comment_len) {
888
        av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
889
        return AVERROR_INVALIDDATA;
890
    }
891
43
    skip_bits_long(gb, comment_len);
892
43
    return tags;
893
}
894
895
/**
896
 * Decode GA "General Audio" specific configuration; reference: table 4.1.
897
 *
898
 * @param   ac          pointer to AACContext, may be null
899
 * @param   avctx       pointer to AVCCodecContext, used for logging
900
 *
901
 * @return  Returns error status. 0 - OK, !0 - error
902
 */
903
528
static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
904
                                     GetBitContext *gb,
905
                                     int get_bit_alignment,
906
                                     MPEG4AudioConfig *m4ac,
907
                                     int channel_config)
908
{
909
    int extension_flag, ret, ep_config, res_flags;
910
    uint8_t layout_map[MAX_ELEM_ID*4][3];
911
528
    int tags = 0;
912
913
#if USE_FIXED
914
17
    if (get_bits1(gb)) { // frameLengthFlag
915
        avpriv_report_missing_feature(avctx, "Fixed point 960/120 MDCT window");
916
        return AVERROR_PATCHWELCOME;
917
    }
918
17
    m4ac->frame_length_short = 0;
919
#else
920
511
    m4ac->frame_length_short = get_bits1(gb);
921

511
    if (m4ac->frame_length_short && m4ac->sbr == 1) {
922
      avpriv_report_missing_feature(avctx, "SBR with 960 frame length");
923
      if (ac) ac->warned_960_sbr = 1;
924
      m4ac->sbr = 0;
925
      m4ac->ps = 0;
926
    }
927
#endif
928
929
528
    if (get_bits1(gb))       // dependsOnCoreCoder
930
        skip_bits(gb, 14);   // coreCoderDelay
931
528
    extension_flag = get_bits1(gb);
932
933
528
    if (m4ac->object_type == AOT_AAC_SCALABLE ||
934
528
        m4ac->object_type == AOT_ER_AAC_SCALABLE)
935
        skip_bits(gb, 3);     // layerNr
936
937
528
    if (channel_config == 0) {
938
43
        skip_bits(gb, 4);  // element_instance_tag
939
43
        tags = decode_pce(avctx, m4ac, layout_map, gb, get_bit_alignment);
940
43
        if (tags < 0)
941
            return tags;
942
    } else {
943
485
        if ((ret = set_default_channel_config(ac, avctx, layout_map,
944
                                              &tags, channel_config)))
945
            return ret;
946
    }
947
948
528
    if (count_channels(layout_map, tags) > 1) {
949
438
        m4ac->ps = 0;
950

90
    } else if (m4ac->sbr == 1 && m4ac->ps == -1)
951
18
        m4ac->ps = 1;
952
953

528
    if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
954
        return ret;
955
956
528
    if (extension_flag) {
957
4
        switch (m4ac->object_type) {
958
        case AOT_ER_BSAC:
959
            skip_bits(gb, 5);    // numOfSubFrame
960
            skip_bits(gb, 11);   // layer_length
961
            break;
962
4
        case AOT_ER_AAC_LC:
963
        case AOT_ER_AAC_LTP:
964
        case AOT_ER_AAC_SCALABLE:
965
        case AOT_ER_AAC_LD:
966
4
            res_flags = get_bits(gb, 3);
967
4
            if (res_flags) {
968
                avpriv_report_missing_feature(avctx,
969
                                              "AAC data resilience (flags %x)",
970
                                              res_flags);
971
                return AVERROR_PATCHWELCOME;
972
            }
973
4
            break;
974
        }
975
4
        skip_bits1(gb);    // extensionFlag3 (TBD in version 3)
976
    }
977
528
    switch (m4ac->object_type) {
978
4
    case AOT_ER_AAC_LC:
979
    case AOT_ER_AAC_LTP:
980
    case AOT_ER_AAC_SCALABLE:
981
    case AOT_ER_AAC_LD:
982
4
        ep_config = get_bits(gb, 2);
983
4
        if (ep_config) {
984
            avpriv_report_missing_feature(avctx,
985
                                          "epConfig %d", ep_config);
986
            return AVERROR_PATCHWELCOME;
987
        }
988
    }
989
528
    return 0;
990
}
991
992
10
static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
993
                                     GetBitContext *gb,
994
                                     MPEG4AudioConfig *m4ac,
995
                                     int channel_config)
996
{
997
    int ret, ep_config, res_flags;
998
    uint8_t layout_map[MAX_ELEM_ID*4][3];
999
10
    int tags = 0;
1000
10
    const int ELDEXT_TERM = 0;
1001
1002
10
    m4ac->ps  = 0;
1003
10
    m4ac->sbr = 0;
1004
#if USE_FIXED
1005
2
    if (get_bits1(gb)) { // frameLengthFlag
1006
        avpriv_request_sample(avctx, "960/120 MDCT window");
1007
        return AVERROR_PATCHWELCOME;
1008
    }
1009
#else
1010
8
    m4ac->frame_length_short = get_bits1(gb);
1011
#endif
1012
10
    res_flags = get_bits(gb, 3);
1013
10
    if (res_flags) {
1014
        avpriv_report_missing_feature(avctx,
1015
                                      "AAC data resilience (flags %x)",
1016
                                      res_flags);
1017
        return AVERROR_PATCHWELCOME;
1018
    }
1019
1020
10
    if (get_bits1(gb)) { // ldSbrPresentFlag
1021
        avpriv_report_missing_feature(avctx,
1022
                                      "Low Delay SBR");
1023
        return AVERROR_PATCHWELCOME;
1024
    }
1025
1026
10
    while (get_bits(gb, 4) != ELDEXT_TERM) {
1027
        int len = get_bits(gb, 4);
1028
        if (len == 15)
1029
            len += get_bits(gb, 8);
1030
        if (len == 15 + 255)
1031
            len += get_bits(gb, 16);
1032
        if (get_bits_left(gb) < len * 8 + 4) {
1033
            av_log(avctx, AV_LOG_ERROR, overread_err);
1034
            return AVERROR_INVALIDDATA;
1035
        }
1036
        skip_bits_long(gb, 8 * len);
1037
    }
1038
1039
10
    if ((ret = set_default_channel_config(ac, avctx, layout_map,
1040
                                          &tags, channel_config)))
1041
        return ret;
1042
1043

10
    if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
1044
        return ret;
1045
1046
10
    ep_config = get_bits(gb, 2);
1047
10
    if (ep_config) {
1048
        avpriv_report_missing_feature(avctx,
1049
                                      "epConfig %d", ep_config);
1050
        return AVERROR_PATCHWELCOME;
1051
    }
1052
10
    return 0;
1053
}
1054
1055
/**
1056
 * Decode audio specific configuration; reference: table 1.13.
1057
 *
1058
 * @param   ac          pointer to AACContext, may be null
1059
 * @param   avctx       pointer to AVCCodecContext, used for logging
1060
 * @param   m4ac        pointer to MPEG4AudioConfig, used for parsing
1061
 * @param   gb          buffer holding an audio specific config
1062
 * @param   get_bit_alignment relative alignment for byte align operations
1063
 * @param   sync_extension look for an appended sync extension
1064
 *
1065
 * @return  Returns error status or number of consumed bits. <0 - error
1066
 */
1067
538
static int decode_audio_specific_config_gb(AACContext *ac,
1068
                                           AVCodecContext *avctx,
1069
                                           MPEG4AudioConfig *m4ac,
1070
                                           GetBitContext *gb,
1071
                                           int get_bit_alignment,
1072
                                           int sync_extension)
1073
{
1074
    int i, ret;
1075
538
    GetBitContext gbc = *gb;
1076
1077
538
    if ((i = ff_mpeg4audio_get_config_gb(m4ac, &gbc, sync_extension, avctx)) < 0)
1078
        return AVERROR_INVALIDDATA;
1079
1080
538
    if (m4ac->sampling_index > 12) {
1081
        av_log(avctx, AV_LOG_ERROR,
1082
               "invalid sampling rate index %d\n",
1083
               m4ac->sampling_index);
1084
        return AVERROR_INVALIDDATA;
1085
    }
1086
538
    if (m4ac->object_type == AOT_ER_AAC_LD &&
1087

4
        (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
1088
        av_log(avctx, AV_LOG_ERROR,
1089
               "invalid low delay sampling rate index %d\n",
1090
               m4ac->sampling_index);
1091
        return AVERROR_INVALIDDATA;
1092
    }
1093
1094
538
    skip_bits_long(gb, i);
1095
1096
538
    switch (m4ac->object_type) {
1097
528
    case AOT_AAC_MAIN:
1098
    case AOT_AAC_LC:
1099
    case AOT_AAC_SSR:
1100
    case AOT_AAC_LTP:
1101
    case AOT_ER_AAC_LC:
1102
    case AOT_ER_AAC_LD:
1103
528
        if ((ret = decode_ga_specific_config(ac, avctx, gb, get_bit_alignment,
1104
                                            m4ac, m4ac->chan_config)) < 0)
1105
            return ret;
1106
528
        break;
1107
10
    case AOT_ER_AAC_ELD:
1108
10
        if ((ret = decode_eld_specific_config(ac, avctx, gb,
1109
                                              m4ac, m4ac->chan_config)) < 0)
1110
            return ret;
1111
10
        break;
1112
    default:
1113
        avpriv_report_missing_feature(avctx,
1114
                                      "Audio object type %s%d",
1115
                                      m4ac->sbr == 1 ? "SBR+" : "",
1116
                                      m4ac->object_type);
1117
        return AVERROR(ENOSYS);
1118
    }
1119
1120
    ff_dlog(avctx,
1121
            "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
1122
            m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
1123
            m4ac->sample_rate, m4ac->sbr,
1124
            m4ac->ps);
1125
1126
538
    return get_bits_count(gb);
1127
}
1128
1129
217
static int decode_audio_specific_config(AACContext *ac,
1130
                                        AVCodecContext *avctx,
1131
                                        MPEG4AudioConfig *m4ac,
1132
                                        const uint8_t *data, int64_t bit_size,
1133
                                        int sync_extension)
1134
{
1135
    int i, ret;
1136
    GetBitContext gb;
1137
1138

217
    if (bit_size < 0 || bit_size > INT_MAX) {
1139
        av_log(avctx, AV_LOG_ERROR, "Audio specific config size is invalid\n");
1140
        return AVERROR_INVALIDDATA;
1141
    }
1142
1143
    ff_dlog(avctx, "audio specific config size %d\n", (int)bit_size >> 3);
1144
1556
    for (i = 0; i < bit_size >> 3; i++)
1145
        ff_dlog(avctx, "%02x ", data[i]);
1146
    ff_dlog(avctx, "\n");
1147
1148
217
    if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
1149
        return ret;
1150
1151
217
    return decode_audio_specific_config_gb(ac, avctx, m4ac, &gb, 0,
1152
                                           sync_extension);
1153
}
1154
1155
/**
1156
 * linear congruential pseudorandom number generator
1157
 *
1158
 * @param   previous_val    pointer to the current state of the generator
1159
 *
1160
 * @return  Returns a 32-bit pseudorandom integer
1161
 */
1162
5948804
static av_always_inline int lcg_random(unsigned previous_val)
1163
{
1164
5948804
    union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
1165
5948804
    return v.s;
1166
}
1167
1168
40
static void reset_all_predictors(PredictorState *ps)
1169
{
1170
    int i;
1171
26920
    for (i = 0; i < MAX_PREDICTORS; i++)
1172
26880
        reset_predict_state(&ps[i]);
1173
40
}
1174
1175
59
static int sample_rate_idx (int rate)
1176
{
1177
59
         if (92017 <= rate) return 0;
1178
59
    else if (75132 <= rate) return 1;
1179
59
    else if (55426 <= rate) return 2;
1180
59
    else if (46009 <= rate) return 3;
1181
58
    else if (37566 <= rate) return 4;
1182
42
    else if (27713 <= rate) return 5;
1183
39
    else if (23004 <= rate) return 6;
1184
39
    else if (18783 <= rate) return 7;
1185
39
    else if (13856 <= rate) return 8;
1186
35
    else if (11502 <= rate) return 9;
1187
35
    else if (9391  <= rate) return 10;
1188
35
    else                    return 11;
1189
}
1190
1191
518
static void reset_predictor_group(PredictorState *ps, int group_num)
1192
{
1193
    int i;
1194
12180
    for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1195
11662
        reset_predict_state(&ps[i]);
1196
518
}
1197
1198
static void aacdec_init(AACContext *ac);
1199
1200
164
static av_cold void aac_static_table_init(void)
1201
{
1202
    static VLC_TYPE vlc_buf[304 + 270 + 550 + 300 + 328 +
1203
                            294 + 306 + 268 + 510 + 366 + 462][2];
1204
1968
    for (unsigned i = 0, offset = 0; i < 11; i++) {
1205
1804
        vlc_spectral[i].table           = &vlc_buf[offset];
1206
1804
        vlc_spectral[i].table_allocated = FF_ARRAY_ELEMS(vlc_buf) - offset;
1207
1804
        ff_init_vlc_sparse(&vlc_spectral[i], 8, ff_aac_spectral_sizes[i],
1208
1804
                           ff_aac_spectral_bits[i],       sizeof(ff_aac_spectral_bits[i][0]),
1209
                                                          sizeof(ff_aac_spectral_bits[i][0]),
1210
1804
                           ff_aac_spectral_codes[i],      sizeof(ff_aac_spectral_codes[i][0]),
1211
                                                          sizeof(ff_aac_spectral_codes[i][0]),
1212
1804
                           ff_aac_codebook_vector_idx[i], sizeof(ff_aac_codebook_vector_idx[i][0]),
1213
                                                          sizeof(ff_aac_codebook_vector_idx[i][0]),
1214
                 INIT_VLC_STATIC_OVERLONG);
1215
1804
        offset += vlc_spectral[i].table_size;
1216
    }
1217
1218
164
    AAC_RENAME(ff_aac_sbr_init)();
1219
1220
164
    ff_aac_tableinit();
1221
1222
164
    INIT_VLC_STATIC(&vlc_scalefactors, 7,
1223
                    FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1224
                    ff_aac_scalefactor_bits,
1225
                    sizeof(ff_aac_scalefactor_bits[0]),
1226
                    sizeof(ff_aac_scalefactor_bits[0]),
1227
                    ff_aac_scalefactor_code,
1228
                    sizeof(ff_aac_scalefactor_code[0]),
1229
                    sizeof(ff_aac_scalefactor_code[0]),
1230
                    352);
1231
1232
    // window initialization
1233
#if !USE_FIXED
1234
148
    AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(aac_kbd_long_960), 4.0, 960);
1235
148
    AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(aac_kbd_short_120), 6.0, 120);
1236
148
    AAC_RENAME(ff_sine_window_init)(AAC_RENAME(sine_960), 960);
1237
148
    AAC_RENAME(ff_sine_window_init)(AAC_RENAME(sine_120), 120);
1238
148
    ff_aac_float_common_init();
1239
#else
1240
16
    AAC_RENAME(ff_kbd_window_init)(AAC_KBD_RENAME(kbd_long_1024), 4.0, 1024);
1241
16
    AAC_RENAME(ff_kbd_window_init)(AAC_KBD_RENAME(kbd_short_128), 6.0, 128);
1242
16
    AAC_RENAME(ff_init_ff_sine_windows)(10);
1243
16
    AAC_RENAME(ff_init_ff_sine_windows)( 7);
1244
#endif
1245
164
    AAC_RENAME(ff_init_ff_sine_windows)( 9);
1246
1247
164
    AAC_RENAME(ff_cbrt_tableinit)();
1248
164
}
1249
1250
static AVOnce aac_table_init = AV_ONCE_INIT;
1251
1252
269
static av_cold int aac_decode_init(AVCodecContext *avctx)
1253
{
1254
269
    AACContext *ac = avctx->priv_data;
1255
    int ret;
1256
1257
269
    if (avctx->sample_rate > 96000)
1258
        return AVERROR_INVALIDDATA;
1259
1260
269
    ret = ff_thread_once(&aac_table_init, &aac_static_table_init);
1261
269
    if (ret != 0)
1262
        return AVERROR_UNKNOWN;
1263
1264
269
    ac->avctx = avctx;
1265
269
    ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1266
1267
269
    aacdec_init(ac);
1268
#if USE_FIXED
1269
19
    avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
1270
#else
1271
250
    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1272
#endif /* USE_FIXED */
1273
1274
269
    if (avctx->extradata_size > 0) {
1275
210
        if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1276
210
                                                avctx->extradata,
1277
210
                                                avctx->extradata_size * 8LL,
1278
                                                1)) < 0)
1279
            return ret;
1280
    } else {
1281
        int sr, i;
1282
        uint8_t layout_map[MAX_ELEM_ID*4][3];
1283
        int layout_map_tags;
1284
1285
59
        sr = sample_rate_idx(avctx->sample_rate);
1286
59
        ac->oc[1].m4ac.sampling_index = sr;
1287
59
        ac->oc[1].m4ac.channels = avctx->channels;
1288
59
        ac->oc[1].m4ac.sbr = -1;
1289
59
        ac->oc[1].m4ac.ps = -1;
1290
1291
107
        for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1292
107
            if (ff_mpeg4audio_channels[i] == avctx->channels)
1293
59
                break;
1294
59
        if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1295
            i = 0;
1296
        }
1297
59
        ac->oc[1].m4ac.chan_config = i;
1298
1299
59
        if (ac->oc[1].m4ac.chan_config) {
1300
24
            int ret = set_default_channel_config(ac, avctx, layout_map,
1301
                &layout_map_tags, ac->oc[1].m4ac.chan_config);
1302
24
            if (!ret)
1303
24
                output_configure(ac, layout_map, layout_map_tags,
1304
                                 OC_GLOBAL_HDR, 0);
1305
            else if (avctx->err_recognition & AV_EF_EXPLODE)
1306
                return AVERROR_INVALIDDATA;
1307
        }
1308
    }
1309
1310
269
    if (avctx->channels > MAX_CHANNELS) {
1311
        av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1312
        return AVERROR_INVALIDDATA;
1313
    }
1314
1315
#if USE_FIXED
1316
19
    ac->fdsp = avpriv_alloc_fixed_dsp(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1317
#else
1318
250
    ac->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1319
#endif /* USE_FIXED */
1320
269
    if (!ac->fdsp) {
1321
        return AVERROR(ENOMEM);
1322
    }
1323
1324
269
    ac->random_state = 0x1f2e3d4c;
1325
1326
269
    AAC_RENAME_32(ff_mdct_init)(&ac->mdct,       11, 1, 1.0 / RANGE15(1024.0));
1327
269
    AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ld,    10, 1, 1.0 / RANGE15(512.0));
1328
269
    AAC_RENAME_32(ff_mdct_init)(&ac->mdct_small,  8, 1, 1.0 / RANGE15(128.0));
1329
269
    AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ltp,   11, 0, RANGE15(-2.0));
1330
#if !USE_FIXED
1331
250
    ret = ff_mdct15_init(&ac->mdct120, 1, 3, 1.0f/(16*1024*120*2));
1332
250
    if (ret < 0)
1333
        return ret;
1334
250
    ret = ff_mdct15_init(&ac->mdct480, 1, 5, 1.0f/(16*1024*960));
1335
250
    if (ret < 0)
1336
        return ret;
1337
250
    ret = ff_mdct15_init(&ac->mdct960, 1, 6, 1.0f/(16*1024*960*2));
1338
250
    if (ret < 0)
1339
        return ret;
1340
#endif
1341
1342
269
    return 0;
1343
}
1344
1345
/**
1346
 * Skip data_stream_element; reference: table 4.10.
1347
 */
1348
2821
static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1349
{
1350
2821
    int byte_align = get_bits1(gb);
1351
2821
    int count = get_bits(gb, 8);
1352
2821
    if (count == 255)
1353
        count += get_bits(gb, 8);
1354
2821
    if (byte_align)
1355
2454
        align_get_bits(gb);
1356
1357
2821
    if (get_bits_left(gb) < 8 * count) {
1358
        av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1359
        return AVERROR_INVALIDDATA;
1360
    }
1361
2821
    skip_bits_long(gb, 8 * count);
1362
2821
    return 0;
1363
}
1364
1365
1426
static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1366
                             GetBitContext *gb)
1367
{
1368
    int sfb;
1369
1426
    if (get_bits1(gb)) {
1370
359
        ics->predictor_reset_group = get_bits(gb, 5);
1371
359
        if (ics->predictor_reset_group == 0 ||
1372
359
            ics->predictor_reset_group > 30) {
1373
            av_log(ac->avctx, AV_LOG_ERROR,
1374
                   "Invalid Predictor Reset Group.\n");
1375
            return AVERROR_INVALIDDATA;
1376
        }
1377
    }
1378
47801
    for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1379
46375
        ics->prediction_used[sfb] = get_bits1(gb);
1380
    }
1381
1426
    return 0;
1382
}
1383
1384
/**
1385
 * Decode Long Term Prediction data; reference: table 4.xx.
1386
 */
1387
786
static void decode_ltp(LongTermPrediction *ltp,
1388
                       GetBitContext *gb, uint8_t max_sfb)
1389
{
1390
    int sfb;
1391
1392
786
    ltp->lag  = get_bits(gb, 11);
1393
786
    ltp->coef = ltp_coef[get_bits(gb, 3)];
1394
32226
    for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1395
31440
        ltp->used[sfb] = get_bits1(gb);
1396
786
}
1397
1398
/**
1399
 * Decode Individual Channel Stream info; reference: table 4.6.
1400
 */
1401
63113
static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1402
                           GetBitContext *gb)
1403
{
1404
63113
    const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
1405
63113
    const int aot = m4ac->object_type;
1406
63113
    const int sampling_index = m4ac->sampling_index;
1407
63113
    int ret_fail = AVERROR_INVALIDDATA;
1408
1409
63113
    if (aot != AOT_ER_AAC_ELD) {
1410
46748
        if (get_bits1(gb)) {
1411
            av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1412
            if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
1413
                return AVERROR_INVALIDDATA;
1414
        }
1415
46748
        ics->window_sequence[1] = ics->window_sequence[0];
1416
46748
        ics->window_sequence[0] = get_bits(gb, 2);
1417
46748
        if (aot == AOT_ER_AAC_LD &&
1418
2424
            ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1419
            av_log(ac->avctx, AV_LOG_ERROR,
1420
                   "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1421
                   "window sequence %d found.\n", ics->window_sequence[0]);
1422
            ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1423
            return AVERROR_INVALIDDATA;
1424
        }
1425
46748
        ics->use_kb_window[1]   = ics->use_kb_window[0];
1426
46748
        ics->use_kb_window[0]   = get_bits1(gb);
1427
    }
1428
63113
    ics->num_window_groups  = 1;
1429
63113
    ics->group_len[0]       = 1;
1430
63113
    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1431
        int i;
1432
1328
        ics->max_sfb = get_bits(gb, 4);
1433
10624
        for (i = 0; i < 7; i++) {
1434
9296
            if (get_bits1(gb)) {
1435
5868
                ics->group_len[ics->num_window_groups - 1]++;
1436
            } else {
1437
3428
                ics->num_window_groups++;
1438
3428
                ics->group_len[ics->num_window_groups - 1] = 1;
1439
            }
1440
        }
1441
1328
        ics->num_windows       = 8;
1442
1328
        if (m4ac->frame_length_short) {
1443
1
            ics->swb_offset    =  ff_swb_offset_120[sampling_index];
1444
1
            ics->num_swb       = ff_aac_num_swb_120[sampling_index];
1445
        } else {
1446
1327
            ics->swb_offset    =  ff_swb_offset_128[sampling_index];
1447
1327
            ics->num_swb       = ff_aac_num_swb_128[sampling_index];
1448
        }
1449
1328
        ics->tns_max_bands     = ff_tns_max_bands_128[sampling_index];
1450
1328
        ics->predictor_present = 0;
1451
    } else {
1452
61785
        ics->max_sfb           = get_bits(gb, 6);
1453
61785
        ics->num_windows       = 1;
1454

61785
        if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1455
18789
            if (m4ac->frame_length_short) {
1456
3559
                ics->swb_offset    =     ff_swb_offset_480[sampling_index];
1457
3559
                ics->num_swb       =    ff_aac_num_swb_480[sampling_index];
1458
3559
                ics->tns_max_bands =  ff_tns_max_bands_480[sampling_index];
1459
            } else {
1460
15230
                ics->swb_offset    =     ff_swb_offset_512[sampling_index];
1461
15230
                ics->num_swb       =    ff_aac_num_swb_512[sampling_index];
1462
15230
                ics->tns_max_bands =  ff_tns_max_bands_512[sampling_index];
1463
            }
1464

18789
            if (!ics->num_swb || !ics->swb_offset) {
1465
                ret_fail = AVERROR_BUG;
1466
                goto fail;
1467
            }
1468
        } else {
1469
42996
            if (m4ac->frame_length_short) {
1470
386
                ics->num_swb    = ff_aac_num_swb_960[sampling_index];
1471
386
                ics->swb_offset = ff_swb_offset_960[sampling_index];
1472
            } else {
1473
42610
                ics->num_swb    = ff_aac_num_swb_1024[sampling_index];
1474
42610
                ics->swb_offset = ff_swb_offset_1024[sampling_index];
1475
            }
1476
42996
            ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
1477
        }
1478
61785
        if (aot != AOT_ER_AAC_ELD) {
1479
45420
            ics->predictor_present     = get_bits1(gb);
1480
45420
            ics->predictor_reset_group = 0;
1481
        }
1482
61785
        if (ics->predictor_present) {
1483
1964
            if (aot == AOT_AAC_MAIN) {
1484
1426
                if (decode_prediction(ac, ics, gb)) {
1485
                    goto fail;
1486
                }
1487

538
            } else if (aot == AOT_AAC_LC ||
1488
                       aot == AOT_ER_AAC_LC) {
1489
                av_log(ac->avctx, AV_LOG_ERROR,
1490
                       "Prediction is not allowed in AAC-LC.\n");
1491
                goto fail;
1492
            } else {
1493
538
                if (aot == AOT_ER_AAC_LD) {
1494
                    av_log(ac->avctx, AV_LOG_ERROR,
1495
                           "LTP in ER AAC LD not yet implemented.\n");
1496
                    ret_fail = AVERROR_PATCHWELCOME;
1497
                    goto fail;
1498
                }
1499
538
                if ((ics->ltp.present = get_bits(gb, 1)))
1500
382
                    decode_ltp(&ics->ltp, gb, ics->max_sfb);
1501
            }
1502
        }
1503
    }
1504
1505
63113
    if (ics->max_sfb > ics->num_swb) {
1506
        av_log(ac->avctx, AV_LOG_ERROR,
1507
               "Number of scalefactor bands in group (%d) "
1508
               "exceeds limit (%d).\n",
1509
               ics->max_sfb, ics->num_swb);
1510
        goto fail;
1511
    }
1512
1513
63113
    return 0;
1514
fail:
1515
    ics->max_sfb = 0;
1516
    return ret_fail;
1517
}
1518
1519
/**
1520
 * Decode band types (section_data payload); reference: table 4.46.
1521
 *
1522
 * @param   band_type           array of the used band type
1523
 * @param   band_type_run_end   array of the last scalefactor band of a band type run
1524
 *
1525
 * @return  Returns error status. 0 - OK, !0 - error
1526
 */
1527
93570
static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1528
                             int band_type_run_end[120], GetBitContext *gb,
1529
                             IndividualChannelStream *ics)
1530
{
1531
93570
    int g, idx = 0;
1532
93570
    const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1533
192378
    for (g = 0; g < ics->num_window_groups; g++) {
1534
98808
        int k = 0;
1535
561011
        while (k < ics->max_sfb) {
1536
462203
            uint8_t sect_end = k;
1537
            int sect_len_incr;
1538
462203
            int sect_band_type = get_bits(gb, 4);
1539
462203
            if (sect_band_type == 12) {
1540
                av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1541
                return AVERROR_INVALIDDATA;
1542
            }
1543
            do {
1544
480902
                sect_len_incr = get_bits(gb, bits);
1545
480902
                sect_end += sect_len_incr;
1546
480902
                if (get_bits_left(gb) < 0) {
1547
                    av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1548
                    return AVERROR_INVALIDDATA;
1549
                }
1550
480902
                if (sect_end > ics->max_sfb) {
1551
                    av_log(ac->avctx, AV_LOG_ERROR,
1552
                           "Number of bands (%d) exceeds limit (%d).\n",
1553
                           sect_end, ics->max_sfb);
1554
                    return AVERROR_INVALIDDATA;
1555
                }
1556
480902
            } while (sect_len_incr == (1 << bits) - 1);
1557
3925845
            for (; k < sect_end; k++) {
1558
3463642
                band_type        [idx]   = sect_band_type;
1559
3463642
                band_type_run_end[idx++] = sect_end;
1560
            }
1561
        }
1562
    }
1563
93570
    return 0;
1564
}
1565
1566
/**
1567
 * Decode scalefactors; reference: table 4.47.
1568
 *
1569
 * @param   global_gain         first scalefactor value as scalefactors are differentially coded
1570
 * @param   band_type           array of the used band type
1571
 * @param   band_type_run_end   array of the last scalefactor band of a band type run
1572
 * @param   sf                  array of scalefactors or intensity stereo positions
1573
 *
1574
 * @return  Returns error status. 0 - OK, !0 - error
1575
 */
1576
93570
static int decode_scalefactors(AACContext *ac, INTFLOAT sf[120], GetBitContext *gb,
1577
                               unsigned int global_gain,
1578
                               IndividualChannelStream *ics,
1579
                               enum BandType band_type[120],
1580
                               int band_type_run_end[120])
1581
{
1582
93570
    int g, i, idx = 0;
1583
93570
    int offset[3] = { global_gain, global_gain - NOISE_OFFSET, 0 };
1584
    int clipped_offset;
1585
93570
    int noise_flag = 1;
1586
192378
    for (g = 0; g < ics->num_window_groups; g++) {
1587
561011
        for (i = 0; i < ics->max_sfb;) {
1588
462203
            int run_end = band_type_run_end[idx];
1589
462203
            if (band_type[idx] == ZERO_BT) {
1590
597906
                for (; i < run_end; i++, idx++)
1591
534874
                    sf[idx] = FIXR(0.);
1592
399171
            } else if ((band_type[idx] == INTENSITY_BT) ||
1593
389791
                       (band_type[idx] == INTENSITY_BT2)) {
1594
75328
                for (; i < run_end; i++, idx++) {
1595
65837
                    offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1596
65837
                    clipped_offset = av_clip(offset[2], -155, 100);
1597
65837
                    if (offset[2] != clipped_offset) {
1598
                        avpriv_request_sample(ac->avctx,
1599
                                              "If you heard an audible artifact, there may be a bug in the decoder. "
1600
                                              "Clipped intensity stereo position (%d -> %d)",
1601
                                              offset[2], clipped_offset);
1602
                    }
1603
#if USE_FIXED
1604
17856
                    sf[idx] = 100 - clipped_offset;
1605
#else
1606
47981
                    sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1607
#endif /* USE_FIXED */
1608
                }
1609
389680
            } else if (band_type[idx] == NOISE_BT) {
1610
289566
                for (; i < run_end; i++, idx++) {
1611
281905
                    if (noise_flag-- > 0)
1612
6716
                        offset[1] += get_bits(gb, NOISE_PRE_BITS) - NOISE_PRE;
1613
                    else
1614
275189
                        offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1615
281905
                    clipped_offset = av_clip(offset[1], -100, 155);
1616
281905
                    if (offset[1] != clipped_offset) {
1617
                        avpriv_request_sample(ac->avctx,
1618
                                              "If you heard an audible artifact, there may be a bug in the decoder. "
1619
                                              "Clipped noise gain (%d -> %d)",
1620
                                              offset[1], clipped_offset);
1621
                    }
1622
#if USE_FIXED
1623
137931
                    sf[idx] = -(100 + clipped_offset);
1624
#else
1625
143974
                    sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1626
#endif /* USE_FIXED */
1627
                }
1628
            } else {
1629
2963045
                for (; i < run_end; i++, idx++) {
1630
2581026
                    offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1631
2581026
                    if (offset[0] > 255U) {
1632
                        av_log(ac->avctx, AV_LOG_ERROR,
1633
                               "Scalefactor (%d) out of range.\n", offset[0]);
1634
                        return AVERROR_INVALIDDATA;
1635
                    }
1636
#if USE_FIXED
1637
772587
                    sf[idx] = -offset[0];
1638
#else
1639
1808439
                    sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1640
#endif /* USE_FIXED */
1641
                }
1642
            }
1643
        }
1644
    }
1645
93570
    return 0;
1646
}
1647
1648
/**
1649
 * Decode pulse data; reference: table 4.7.
1650
 */
1651
1098
static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1652
                         const uint16_t *swb_offset, int num_swb)
1653
{
1654
    int i, pulse_swb;
1655
1098
    pulse->num_pulse = get_bits(gb, 2) + 1;
1656
1098
    pulse_swb        = get_bits(gb, 6);
1657
1098
    if (pulse_swb >= num_swb)
1658
        return -1;
1659
1098
    pulse->pos[0]    = swb_offset[pulse_swb];
1660
1098
    pulse->pos[0]   += get_bits(gb, 5);
1661
1098
    if (pulse->pos[0] >= swb_offset[num_swb])
1662
        return -1;
1663
1098
    pulse->amp[0]    = get_bits(gb, 4);
1664
2744
    for (i = 1; i < pulse->num_pulse; i++) {
1665
1646
        pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1666
1646
        if (pulse->pos[i] >= swb_offset[num_swb])
1667
            return -1;
1668
1646
        pulse->amp[i] = get_bits(gb, 4);
1669
    }
1670
1098
    return 0;
1671
}
1672
1673
/**
1674
 * Decode Temporal Noise Shaping data; reference: table 4.48.
1675
 *
1676
 * @return  Returns error status. 0 - OK, !0 - error
1677
 */
1678
6927
static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1679
                      GetBitContext *gb, const IndividualChannelStream *ics)
1680
{
1681
    int w, filt, i, coef_len, coef_res, coef_compress;
1682
6927
    const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1683

6927
    const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1684
18467
    for (w = 0; w < ics->num_windows; w++) {
1685
11540
        if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1686
7918
            coef_res = get_bits1(gb);
1687
1688
17297
            for (filt = 0; filt < tns->n_filt[w]; filt++) {
1689
                int tmp2_idx;
1690
9379
                tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1691
1692
9379
                if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1693
                    av_log(ac->avctx, AV_LOG_ERROR,
1694
                           "TNS filter order %d is greater than maximum %d.\n",
1695
                           tns->order[w][filt], tns_max_order);
1696
                    tns->order[w][filt] = 0;
1697
                    return AVERROR_INVALIDDATA;
1698
                }
1699
9379
                if (tns->order[w][filt]) {
1700
8859
                    tns->direction[w][filt] = get_bits1(gb);
1701
8859
                    coef_compress = get_bits1(gb);
1702
8859
                    coef_len = coef_res + 3 - coef_compress;
1703
8859
                    tmp2_idx = 2 * coef_compress + coef_res;
1704
1705
67167
                    for (i = 0; i < tns->order[w][filt]; i++)
1706
58308
                        tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1707
                }
1708
            }
1709
        }
1710
    }
1711
6927
    return 0;
1712
}
1713
1714
/**
1715
 * Decode Mid/Side data; reference: table 4.54.
1716
 *
1717
 * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
1718
 *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
1719
 *                      [3] reserved for scalable AAC
1720
 */
1721
26972
static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1722
                                   int ms_present)
1723
{
1724
    int idx;
1725
26972
    int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1726
26972
    if (ms_present == 1) {
1727
510319
        for (idx = 0; idx < max_idx; idx++)
1728
497635
            cpe->ms_mask[idx] = get_bits1(gb);
1729
14288
    } else if (ms_present == 2) {
1730
14288
        memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
1731
    }
1732
26972
}
1733
1734
/**
1735
 * Decode spectral data; reference: table 4.50.
1736
 * Dequantize and scale spectral data; reference: 4.6.3.3.
1737
 *
1738
 * @param   coef            array of dequantized, scaled spectral data
1739
 * @param   sf              array of scalefactors or intensity stereo positions
1740
 * @param   pulse_present   set if pulses are present
1741
 * @param   pulse           pointer to pulse data struct
1742
 * @param   band_type       array of the used band type
1743
 *
1744
 * @return  Returns error status. 0 - OK, !0 - error
1745
 */
1746
93570
static int decode_spectrum_and_dequant(AACContext *ac, INTFLOAT coef[1024],
1747
                                       GetBitContext *gb, const INTFLOAT sf[120],
1748
                                       int pulse_present, const Pulse *pulse,
1749
                                       const IndividualChannelStream *ics,
1750
                                       enum BandType band_type[120])
1751
{
1752
93570
    int i, k, g, idx = 0;
1753
93570
    const int c = 1024 / ics->num_windows;
1754
93570
    const uint16_t *offsets = ics->swb_offset;
1755
93570
    INTFLOAT *coef_base = coef;
1756
1757
201742
    for (g = 0; g < ics->num_windows; g++)
1758
108172
        memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1759
108172
               sizeof(INTFLOAT) * (c - offsets[ics->max_sfb]));
1760
1761
192378
    for (g = 0; g < ics->num_window_groups; g++) {
1762
98808
        unsigned g_len = ics->group_len[g];
1763
1764
3562450
        for (i = 0; i < ics->max_sfb; i++, idx++) {
1765
3463642
            const unsigned cbt_m1 = band_type[idx] - 1;
1766
3463642
            INTFLOAT *cfo = coef + offsets[i];
1767
3463642
            int off_len = offsets[i + 1] - offsets[i];
1768
            int group;
1769
1770
3463642
            if (cbt_m1 >= INTENSITY_BT2 - 1) {
1771
1239511
                for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1772
638800
                    memset(cfo, 0, off_len * sizeof(*cfo));
1773
                }
1774
2862931
            } else if (cbt_m1 == NOISE_BT - 1) {
1775
563829
                for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1776
                    INTFLOAT band_energy;
1777
#if USE_FIXED
1778
3021407
                    for (k = 0; k < off_len; k++) {
1779
2883476
                        ac->random_state  = lcg_random(ac->random_state);
1780
2883476
                        cfo[k] = ac->random_state >> 3;
1781
                    }
1782
1783
137931
                    band_energy = ac->fdsp->scalarproduct_fixed(cfo, cfo, off_len);
1784
137931
                    band_energy = fixed_sqrt(band_energy, 31);
1785
137931
                    noise_scale(cfo, sf[idx], band_energy, off_len);
1786
#else
1787
                    float scale;
1788
1789
3209321
                    for (k = 0; k < off_len; k++) {
1790
3065328
                        ac->random_state  = lcg_random(ac->random_state);
1791
3065328
                        cfo[k] = ac->random_state;
1792
                    }
1793
1794
143993
                    band_energy = ac->fdsp->scalarproduct_float(cfo, cfo, off_len);
1795
143993
                    scale = sf[idx] / sqrtf(band_energy);
1796
143993
                    ac->fdsp->vector_fmul_scalar(cfo, cfo, scale, off_len);
1797
#endif /* USE_FIXED */
1798
                }
1799
            } else {
1800
#if !USE_FIXED
1801
1808439
                const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1802
#endif /* !USE_FIXED */
1803
2581026
                VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1804
2581026
                OPEN_READER(re, gb);
1805
1806

2581026
                switch (cbt_m1 >> 1) {
1807
623853
                case 0:
1808
1275041
                    for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1809
651188
                        INTFLOAT *cf = cfo;
1810
651188
                        int len = off_len;
1811
1812
                        do {
1813
                            int code;
1814
                            unsigned cb_idx;
1815
1816
3240209
                            UPDATE_CACHE(re, gb);
1817
3240209
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1818
3240209
                            cb_idx = code;
1819
#if USE_FIXED
1820
978157
                            cf = DEC_SQUAD(cf, cb_idx);
1821
#else
1822
2262052
                            cf = VMUL4(cf, vq, cb_idx, sf + idx);
1823
#endif /* USE_FIXED */
1824
3240209
                        } while (len -= 4);
1825
                    }
1826
623853
                    break;
1827
1828
576068
                case 1:
1829
1164595
                    for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1830
588527
                        INTFLOAT *cf = cfo;
1831
588527
                        int len = off_len;
1832
1833
                        do {
1834
                            int code;
1835
                            unsigned nnz;
1836
                            unsigned cb_idx;
1837
                            uint32_t bits;
1838
1839
2627045
                            UPDATE_CACHE(re, gb);
1840
2627045
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1841
2627045
                            cb_idx = code;
1842
2627045
                            nnz = cb_idx >> 8 & 15;
1843
2627045
                            bits = nnz ? GET_CACHE(re, gb) : 0;
1844
2627045
                            LAST_SKIP_BITS(re, gb, nnz);
1845
#if USE_FIXED
1846
816691
                            cf = DEC_UQUAD(cf, cb_idx, bits);
1847
#else
1848
1810354
                            cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1849
#endif /* USE_FIXED */
1850
2627045
                        } while (len -= 4);
1851
                    }
1852
576068
                    break;
1853
1854
401104
                case 2:
1855
814898
                    for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1856
413794
                        INTFLOAT *cf = cfo;
1857
413794
                        int len = off_len;
1858
1859
                        do {
1860
                            int code;
1861
                            unsigned cb_idx;
1862
1863
2511382
                            UPDATE_CACHE(re, gb);
1864
2511382
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1865
2511382
                            cb_idx = code;
1866
#if USE_FIXED
1867
672272
                            cf = DEC_SPAIR(cf, cb_idx);
1868
#else
1869
1839110
                            cf = VMUL2(cf, vq, cb_idx, sf + idx);
1870
#endif /* USE_FIXED */
1871
2511382
                        } while (len -= 2);
1872
                    }
1873
401104
                    break;
1874
1875
542564
                case 3:
1876
                case 4:
1877
1103581
                    for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1878
561017
                        INTFLOAT *cf = cfo;
1879
561017
                        int len = off_len;
1880
1881
                        do {
1882
                            int code;
1883
                            unsigned nnz;
1884
                            unsigned cb_idx;
1885
                            unsigned sign;
1886
1887
2968794
                            UPDATE_CACHE(re, gb);
1888
2968794
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1889
2968794
                            cb_idx = code;
1890
2968794
                            nnz = cb_idx >> 8 & 15;
1891
2968794
                            sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1892
2968794
                            LAST_SKIP_BITS(re, gb, nnz);
1893
#if USE_FIXED
1894
703742
                            cf = DEC_UPAIR(cf, cb_idx, sign);
1895
#else
1896
2265052
                            cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1897
#endif /* USE_FIXED */
1898
2968794
                        } while (len -= 2);
1899
                    }
1900
542564
                    break;
1901
1902
437437
                default:
1903
884717
                    for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1904
#if USE_FIXED
1905
119275
                        int *icf = cfo;
1906
                        int v;
1907
#else
1908
328005
                        float *cf = cfo;
1909
328005
                        uint32_t *icf = (uint32_t *) cf;
1910
#endif /* USE_FIXED */
1911
447280
                        int len = off_len;
1912
1913
                        do {
1914
                            int code;
1915
                            unsigned nzt, nnz;
1916
                            unsigned cb_idx;
1917
                            uint32_t bits;
1918
                            int j;
1919
1920
1476974
                            UPDATE_CACHE(re, gb);
1921
1476974
                            GET_VLC(code, re, gb, vlc_tab, 8, 2);
1922
1476974
                            cb_idx = code;
1923
1924
1476974
                            if (cb_idx == 0x0000) {
1925
68942
                                *icf++ = 0;
1926
68942
                                *icf++ = 0;
1927
68942
                                continue;
1928
                            }
1929
1930
1408032
                            nnz = cb_idx >> 12;
1931
1408032
                            nzt = cb_idx >> 8;
1932
1408032
                            bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1933
1408032
                            LAST_SKIP_BITS(re, gb, nnz);
1934
1935
4224096
                            for (j = 0; j < 2; j++) {
1936
2816064
                                if (nzt & 1<<j) {
1937
                                    uint32_t b;
1938
                                    int n;
1939
                                    /* The total length of escape_sequence must be < 22 bits according
1940
                                       to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1941
367172
                                    UPDATE_CACHE(re, gb);
1942
367172
                                    b = GET_CACHE(re, gb);
1943
367172
                                    b = 31 - av_log2(~b);
1944
1945
367172
                                    if (b > 8) {
1946
                                        av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1947
                                        return AVERROR_INVALIDDATA;
1948
                                    }
1949
1950
367172
                                    SKIP_BITS(re, gb, b + 1);
1951
367172
                                    b += 4;
1952
367172
                                    n = (1 << b) + SHOW_UBITS(re, gb, b);
1953
367172
                                    LAST_SKIP_BITS(re, gb, b);
1954
#if USE_FIXED
1955
64951
                                    v = n;
1956
64951
                                    if (bits & 1U<<31)
1957
32336
                                        v = -v;
1958
64951
                                    *icf++ = v;
1959
#else
1960
302221
                                    *icf++ = ff_cbrt_tab[n] | (bits & 1U<<31);
1961
#endif /* USE_FIXED */
1962
367172
                                    bits <<= 1;
1963
                                } else {
1964
#if USE_FIXED
1965
539259
                                    v = cb_idx & 15;
1966
539259
                                    if (bits & 1U<<31)
1967
256298
                                        v = -v;
1968
539259
                                    *icf++ = v;
1969
#else
1970
1909633
                                    unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1971
1909633
                                    *icf++ = (bits & 1U<<31) | v;
1972
#endif /* USE_FIXED */
1973
2448892
                                    bits <<= !!v;
1974
                                }
1975
2816064
                                cb_idx >>= 4;
1976
                            }
1977
1476974
                        } while (len -= 2);
1978
#if !USE_FIXED
1979
328005
                        ac->fdsp->vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1980
#endif /* !USE_FIXED */
1981
                    }
1982
                }
1983
1984
2581026
                CLOSE_READER(re, gb);
1985
            }
1986
        }
1987
98808
        coef += g_len << 7;
1988
    }
1989
1990
93570
    if (pulse_present) {
1991
1098
        idx = 0;
1992
3842
        for (i = 0; i < pulse->num_pulse; i++) {
1993
2744
            INTFLOAT co = coef_base[ pulse->pos[i] ];
1994
6840
            while (offsets[idx + 1] <= pulse->pos[i])
1995
4096
                idx++;
1996

2744
            if (band_type[idx] != NOISE_BT && sf[idx]) {
1997
2668
                INTFLOAT ico = -pulse->amp[i];
1998
#if USE_FIXED
1999
864
                if (co) {
2000
730
                    ico = co + (co > 0 ? -ico : ico);
2001
                }
2002
864
                coef_base[ pulse->pos[i] ] = ico;
2003
#else
2004
1804
                if (co) {
2005
1564
                    co /= sf[idx];
2006
1564
                    ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
2007
                }
2008
1804
                coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
2009
#endif /* USE_FIXED */
2010
            }
2011
        }
2012
    }
2013
#if USE_FIXED
2014
28710
    coef = coef_base;
2015
28710
    idx = 0;
2016
59752
    for (g = 0; g < ics->num_window_groups; g++) {
2017
31042
        unsigned g_len = ics->group_len[g];
2018
2019
1071091
        for (i = 0; i < ics->max_sfb; i++, idx++) {
2020
1040049
            const unsigned cbt_m1 = band_type[idx] - 1;
2021
1040049
            int *cfo = coef + offsets[i];
2022
1040049
            int off_len = offsets[i + 1] - offsets[i];
2023
            int group;
2024
2025
1040049
            if (cbt_m1 < NOISE_BT - 1) {
2026
1560445
                for (group = 0; group < (int)g_len; group++, cfo+=128) {
2027
787858
                    ac->vector_pow43(cfo, off_len);
2028
787858
                    ac->subband_scale(cfo, cfo, sf[idx], 34, off_len, ac->avctx);
2029
                }
2030
            }
2031
        }
2032
31042
        coef += g_len << 7;
2033
    }
2034
#endif /* USE_FIXED */
2035
93570
    return 0;
2036
}
2037
2038
/**
2039
 * Apply AAC-Main style frequency domain prediction.
2040
 */
2041
7388
static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
2042
{
2043
    int sfb, k;
2044
2045
7388
    if (!sce->ics.predictor_initialized) {
2046
20
        reset_all_predictors(sce->predictor_state);
2047
20
        sce->ics.predictor_initialized = 1;
2048
    }
2049
2050
7388
    if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2051
7368
        for (sfb = 0;
2052
262566
             sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
2053
255198
             sfb++) {
2054
255198
            for (k = sce->ics.swb_offset[sfb];
2055
4303134
                 k < sce->ics.swb_offset[sfb + 1];
2056
4047936
                 k++) {
2057
4047936
                predict(&sce->predictor_state[k], &sce->coeffs[k],
2058
4047936
                        sce->ics.predictor_present &&
2059
892992
                        sce->ics.prediction_used[sfb]);
2060
            }
2061
        }
2062
7368
        if (sce->ics.predictor_reset_group)
2063
518
            reset_predictor_group(sce->predictor_state,
2064
                                  sce->ics.predictor_reset_group);
2065
    } else
2066
20
        reset_all_predictors(sce->predictor_state);
2067
7388
}
2068
2069
static void decode_gain_control(SingleChannelElement * sce, GetBitContext * gb)
2070
{
2071
    // wd_num, wd_test, aloc_size
2072
    static const uint8_t gain_mode[4][3] = {
2073
        {1, 0, 5},  // ONLY_LONG_SEQUENCE = 0,
2074
        {2, 1, 2},  // LONG_START_SEQUENCE,
2075
        {8, 0, 2},  // EIGHT_SHORT_SEQUENCE,
2076
        {2, 1, 5},  // LONG_STOP_SEQUENCE
2077
    };
2078
2079
    const int mode = sce->ics.window_sequence[0];
2080
    uint8_t bd, wd, ad;
2081
2082
    // FIXME: Store the gain control data on |sce| and do something with it.
2083
    uint8_t max_band = get_bits(gb, 2);
2084
    for (bd = 0; bd < max_band; bd++) {
2085
        for (wd = 0; wd < gain_mode[mode][0]; wd++) {
2086
            uint8_t adjust_num = get_bits(gb, 3);
2087
            for (ad = 0; ad < adjust_num; ad++) {
2088
                skip_bits(gb, 4 + ((wd == 0 && gain_mode[mode][1])
2089
                                     ? 4
2090
                                     : gain_mode[mode][2]));
2091
            }
2092
        }
2093
    }
2094
}
2095
2096
/**
2097
 * Decode an individual_channel_stream payload; reference: table 4.44.
2098
 *
2099
 * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
2100
 * @param   scale_flag      scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
2101
 *
2102
 * @return  Returns error status. 0 - OK, !0 - error
2103
 */
2104
93570
static int decode_ics(AACContext *ac, SingleChannelElement *sce,
2105
                      GetBitContext *gb, int common_window, int scale_flag)
2106
{
2107
    Pulse pulse;
2108
93570
    TemporalNoiseShaping    *tns = &sce->tns;
2109
93570
    IndividualChannelStream *ics = &sce->ics;
2110
93570
    INTFLOAT *out = sce->coeffs;
2111
93570
    int global_gain, eld_syntax, er_syntax, pulse_present = 0;
2112
    int ret;
2113
2114
93570
    eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2115
280710
    er_syntax  = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
2116
93570
                 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
2117

277074
                 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
2118
89934
                 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2119
2120
    /* This assignment is to silence a GCC warning about the variable being used
2121
     * uninitialized when in fact it always is.
2122
     */
2123
93570
    pulse.num_pulse = 0;
2124
2125
93570
    global_gain = get_bits(gb, 8);
2126
2127

93570
    if (!common_window && !scale_flag) {
2128
32656
        ret = decode_ics_info(ac, ics, gb);
2129
32656
        if (ret < 0)
2130
            goto fail;
2131
    }
2132
2133
93570
    if ((ret = decode_band_types(ac, sce->band_type,
2134
93570
                                 sce->band_type_run_end, gb, ics)) < 0)
2135
        goto fail;
2136
93570
    if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
2137
93570
                                  sce->band_type, sce->band_type_run_end)) < 0)
2138
        goto fail;
2139
2140
93570
    pulse_present = 0;
2141
93570
    if (!scale_flag) {
2142

93570
        if (!eld_syntax && (pulse_present = get_bits1(gb))) {
2143
1098
            if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2144
                av_log(ac->avctx, AV_LOG_ERROR,
2145
                       "Pulse tool not allowed in eight short sequence.\n");
2146
                ret = AVERROR_INVALIDDATA;
2147
                goto fail;
2148
            }
2149
1098
            if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
2150
                av_log(ac->avctx, AV_LOG_ERROR,
2151
                       "Pulse data corrupt or invalid.\n");
2152
                ret = AVERROR_INVALIDDATA;
2153
                goto fail;
2154
            }
2155
        }
2156
93570
        tns->present = get_bits1(gb);
2157

93570
        if (tns->present && !er_syntax) {
2158
5663
            ret = decode_tns(ac, tns, gb, ics);
2159
5663
            if (ret < 0)
2160
                goto fail;
2161
        }
2162

93570
        if (!eld_syntax && get_bits1(gb)) {
2163
            decode_gain_control(sce, gb);
2164
            if (!ac->warned_gain_control) {
2165
                avpriv_report_missing_feature(ac->avctx, "Gain control");
2166
                ac->warned_gain_control = 1;
2167
            }
2168
        }
2169
        // I see no textual basis in the spec for this occurring after SSR gain
2170
        // control, but this is what both reference and real implmentations do
2171

93570
        if (tns->present && er_syntax) {
2172
1264
            ret = decode_tns(ac, tns, gb, ics);
2173
1264
            if (ret < 0)
2174
                goto fail;
2175
        }
2176
    }
2177
2178
93570
    ret = decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
2179
93570
                                    &pulse, ics, sce->band_type);
2180
93570
    if (ret < 0)
2181
        goto fail;
2182
2183

93570
    if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
2184
6094
        apply_prediction(ac, sce);
2185
2186
93570
    return 0;
2187
fail:
2188
    tns->present = 0;
2189
    return ret;
2190
}
2191
2192
/**
2193
 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
2194
 */
2195
26972
static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
2196
{
2197
26972
    const IndividualChannelStream *ics = &cpe->ch[0].ics;
2198
26972
    INTFLOAT *ch0 = cpe->ch[0].coeffs;
2199
26972
    INTFLOAT *ch1 = cpe->ch[1].coeffs;
2200
26972
    int g, i, group, idx = 0;
2201
26972
    const uint16_t *offsets = ics->swb_offset;
2202
55649
    for (g = 0; g < ics->num_window_groups; g++) {
2203
1041551
        for (i = 0; i < ics->max_sfb; i++, idx++) {
2204
1012874
            if (cpe->ms_mask[idx] &&
2205
794177
                cpe->ch[0].band_type[idx] < NOISE_BT &&
2206
794177
                cpe->ch[1].band_type[idx] < NOISE_BT) {
2207
#if USE_FIXED
2208
500617
                for (group = 0; group < ics->group_len[g]; group++) {
2209
253158
                    ac->fdsp->butterflies_fixed(ch0 + group * 128 + offsets[i],
2210
253158
                                                ch1 + group * 128 + offsets[i],
2211
253158
                                                offsets[i+1] - offsets[i]);
2212
#else
2213
1113172
                for (group = 0; group < ics->group_len[g]; group++) {
2214
568830
                    ac->fdsp->butterflies_float(ch0 + group * 128 + offsets[i],
2215
568830
                                               ch1 + group * 128 + offsets[i],
2216
568830
                                               offsets[i+1] - offsets[i]);
2217
#endif /* USE_FIXED */
2218
                }
2219
            }
2220
        }
2221
28677
        ch0 += ics->group_len[g] * 128;
2222
28677
        ch1 += ics->group_len[g] * 128;
2223
    }
2224
26972
}
2225
2226
/**
2227
 * intensity stereo decoding; reference: 4.6.8.2.3
2228
 *
2229
 * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
2230
 *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
2231
 *                      [3] reserved for scalable AAC
2232
 */
2233
30679
static void apply_intensity_stereo(AACContext *ac,
2234
                                   ChannelElement *cpe, int ms_present)
2235
{
2236
30679
    const IndividualChannelStream *ics = &cpe->ch[1].ics;
2237
30679
    SingleChannelElement         *sce1 = &cpe->ch[1];
2238
30679
    INTFLOAT *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
2239
30679
    const uint16_t *offsets = ics->swb_offset;
2240
30679
    int g, group, i, idx = 0;
2241
    int c;
2242
    INTFLOAT scale;
2243
63286
    for (g = 0; g < ics->num_window_groups; g++) {
2244
193297
        for (i = 0; i < ics->max_sfb;) {
2245
160690
            if (sce1->band_type[idx] == INTENSITY_BT ||
2246
160801
                sce1->band_type[idx] == INTENSITY_BT2) {
2247
9491
                const int bt_run_end = sce1->band_type_run_end[idx];
2248
75328
                for (; i < bt_run_end; i++, idx++) {
2249
65837
                    c = -1 + 2 * (sce1->band_type[idx] - 14);
2250
65837
                    if (ms_present)
2251
60954
                        c *= 1 - 2 * cpe->ms_mask[idx];
2252
65837
                    scale = c * sce1->sf[idx];
2253
131995
                    for (group = 0; group < ics->group_len[g]; group++)
2254
#if USE_FIXED
2255
17955
                        ac->subband_scale(coef1 + group * 128 + offsets[i],
2256
17955
                                      coef0 + group * 128 + offsets[i],
2257
                                      scale,
2258
                                      23,
2259
17955
                                      offsets[i + 1] - offsets[i] ,ac->avctx);
2260
#else
2261
48203
                        ac->fdsp->vector_fmul_scalar(coef1 + group * 128 + offsets[i],
2262
48203
                                                    coef0 + group * 128 + offsets[i],
2263
                                                    scale,
2264
48203
                                                    offsets[i + 1] - offsets[i]);
2265
#endif /* USE_FIXED */
2266
                }
2267
            } else {
2268
151199
                int bt_run_end = sce1->band_type_run_end[idx];
2269
151199
                idx += bt_run_end - i;
2270
151199
                i    = bt_run_end;
2271
            }
2272
        }
2273
32607
        coef0 += ics->group_len[g] * 128;
2274
32607
        coef1 += ics->group_len[g] * 128;
2275
    }
2276
30679
}
2277
2278
/**
2279
 * Decode a channel_pair_element; reference: table 4.4.
2280
 *
2281
 * @return  Returns error status. 0 - OK, !0 - error
2282
 */
2283
30679
static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2284
{
2285
30679
    int i, ret, common_window, ms_present = 0;
2286
30679
    int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2287
2288

30679
    common_window = eld_syntax || get_bits1(gb);
2289
30679
    if (common_window) {
2290
30457
        if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2291
            return AVERROR_INVALIDDATA;
2292
30457
        i = cpe->ch[1].ics.use_kb_window[0];
2293
30457
        cpe->ch[1].ics = cpe->ch[0].ics;
2294
30457
        cpe->ch[1].ics.use_kb_window[1] = i;
2295
30457
        if (cpe->ch[1].ics.predictor_present &&
2296
723
            (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2297
538
            if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2298
404
                decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2299
30457
        ms_present = get_bits(gb, 2);
2300
30457
        if (ms_present == 3) {
2301
            av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2302
            return AVERROR_INVALIDDATA;
2303
30457
        } else if (ms_present)
2304
26972
            decode_mid_side_stereo(cpe, gb, ms_present);
2305
    }
2306
30679
    if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2307
        return ret;
2308
30679
    if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2309
        return ret;
2310
2311
30679
    if (common_window) {
2312
30457
        if (ms_present)
2313
26972
            apply_mid_side_stereo(ac, cpe);
2314
30457
        if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2315
647
            apply_prediction(ac, &cpe->ch[0]);
2316
647
            apply_prediction(ac, &cpe->ch[1]);
2317
        }
2318
    }
2319
2320
30679
    apply_intensity_stereo(ac, cpe, ms_present);
2321
30679
    return 0;
2322
}
2323
2324
static const float cce_scale[] = {
2325
    1.09050773266525765921, //2^(1/8)
2326
    1.18920711500272106672, //2^(1/4)
2327
    M_SQRT2,
2328
    2,
2329
};
2330
2331
/**
2332
 * Decode coupling_channel_element; reference: table 4.8.
2333
 *
2334
 * @return  Returns error status. 0 - OK, !0 - error
2335
 */
2336
1174
static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2337
{
2338
1174
    int num_gain = 0;
2339
    int c, g, sfb, ret;
2340
    int sign;
2341
    INTFLOAT scale;
2342
1174
    SingleChannelElement *sce = &che->ch[0];
2343
1174
    ChannelCoupling     *coup = &che->coup;
2344
2345
1174
    coup->coupling_point = 2 * get_bits1(gb);
2346
1174
    coup->num_coupled = get_bits(gb, 3);
2347
3915
    for (c = 0; c <= coup->num_coupled; c++) {
2348
2741
        num_gain++;
2349
2741
        coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2350
2741
        coup->id_select[c] = get_bits(gb, 4);
2351
2741
        if (coup->type[c] == TYPE_CPE) {
2352
2348
            coup->ch_select[c] = get_bits(gb, 2);
2353
2348
            if (coup->ch_select[c] == 3)
2354
1967
                num_gain++;
2355
        } else
2356
393
            coup->ch_select[c] = 2;
2357
    }
2358

1174
    coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2359
2360
1174
    sign  = get_bits(gb, 1);
2361
#if USE_FIXED
2362
130
    scale = get_bits(gb, 2);
2363
#else
2364
1044
    scale = cce_scale[get_bits(gb, 2)];
2365
#endif
2366
2367
1174
    if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2368
        return ret;
2369
2370
5882
    for (c = 0; c < num_gain; c++) {
2371
4708
        int idx  = 0;
2372
4708
        int cge  = 1;
2373
4708
        int gain = 0;
2374
4708
        INTFLOAT gain_cache = FIXR10(1.);
2375
4708
        if (c) {
2376
3534
            cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2377
3534
            gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2378
3534
            gain_cache = GET_GAIN(scale, gain);
2379
#if USE_FIXED
2380
520
            if ((abs(gain_cache)-1024) >> 3 > 30)
2381
                return AVERROR(ERANGE);
2382
#endif
2383
        }
2384
4708
        if (coup->coupling_point == AFTER_IMDCT) {
2385
1965
            coup->gain[c][0] = gain_cache;
2386
        } else {
2387
5486
            for (g = 0; g < sce->ics.num_window_groups; g++) {
2388
112463
                for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2389
109720
                    if (sce->band_type[idx] != ZERO_BT) {
2390
5196
                        if (!cge) {
2391
2879
                            int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2392
2879
                            if (t) {
2393
2724
                                int s = 1;
2394
2724
                                t = gain += t;
2395
2724
                                if (sign) {
2396
1666
                                    s  -= 2 * (t & 0x1);
2397
1666
                                    t >>= 1;
2398
                                }
2399
2724
                                gain_cache = GET_GAIN(scale, t) * s;
2400
#if USE_FIXED
2401
                                if ((abs(gain_cache)-1024) >> 3 > 30)
2402
                                    return AVERROR(ERANGE);
2403
#endif
2404
                            }
2405
                        }
2406
5196
                        coup->gain[c][idx] = gain_cache;
2407
                    }
2408
                }
2409
            }
2410
        }
2411
    }
2412
1174
    return 0;
2413
}
2414
2415
/**
2416
 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2417
 *
2418
 * @return  Returns number of bytes consumed.
2419
 */
2420
4
static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2421
                                         GetBitContext *gb)
2422
{
2423
    int i;
2424
4
    int num_excl_chan = 0;
2425
2426
    do {
2427
32
        for (i = 0; i < 7; i++)
2428
28
            che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2429

4
    } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2430
2431
4
    return num_excl_chan / 7;
2432
}
2433
2434
/**
2435
 * Decode dynamic range information; reference: table 4.52.
2436
 *
2437
 * @return  Returns number of bytes consumed.
2438
 */
2439
880
static int decode_dynamic_range(DynamicRangeControl *che_drc,
2440
                                GetBitContext *gb)
2441
{
2442
880
    int n             = 1;
2443
880
    int drc_num_bands = 1;
2444
    int i;
2445
2446
    /* pce_tag_present? */
2447
880
    if (get_bits1(gb)) {
2448
        che_drc->pce_instance_tag  = get_bits(gb, 4);
2449
        skip_bits(gb, 4); // tag_reserved_bits
2450
        n++;
2451
    }
2452
2453
    /* excluded_chns_present? */
2454
880
    if (get_bits1(gb)) {
2455
4
        n += decode_drc_channel_exclusions(che_drc, gb);
2456
    }
2457
2458
    /* drc_bands_present? */
2459
880
    if (get_bits1(gb)) {
2460
35
        che_drc->band_incr            = get_bits(gb, 4);
2461
35
        che_drc->interpolation_scheme = get_bits(gb, 4);
2462
35
        n++;
2463
35
        drc_num_bands += che_drc->band_incr;
2464
140
        for (i = 0; i < drc_num_bands; i++) {
2465
105
            che_drc->band_top[i] = get_bits(gb, 8);
2466
105
            n++;
2467
        }
2468
    }
2469
2470
    /* prog_ref_level_present? */
2471
880
    if (get_bits1(gb)) {
2472
878
        che_drc->prog_ref_level = get_bits(gb, 7);
2473
878
        skip_bits1(gb); // prog_ref_level_reserved_bits
2474
878
        n++;
2475
    }
2476
2477
1830
    for (i = 0; i < drc_num_bands; i++) {
2478
950
        che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2479
950
        che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2480
950
        n++;
2481
    }
2482
2483
880
    return n;
2484
}
2485
2486
8949
static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2487
    uint8_t buf[256];
2488
    int i, major, minor;
2489
2490
8949
    if (len < 13+7*8)
2491
380
        goto unknown;
2492
2493
8569
    get_bits(gb, 13); len -= 13;
2494
2495

1136714
    for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2496
1128145
        buf[i] = get_bits(gb, 8);
2497
2498
8569
    buf[i] = 0;
2499
8569
    if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2500
        av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2501
2502
8569
    if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2503
19
        ac->avctx->internal->skip_samples = 1024;
2504
    }
2505
2506
8550
unknown:
2507
8949
    skip_bits_long(gb, len);
2508
2509
8949
    return 0;
2510
}
2511
2512
/**
2513
 * Decode extension data (incomplete); reference: table 4.51.
2514
 *
2515
 * @param   cnt length of TYPE_FIL syntactic element in bytes
2516
 *
2517
 * @return Returns number of bytes consumed
2518
 */
2519
23680
static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2520
                                    ChannelElement *che, enum RawDataBlockType elem_type)
2521
{
2522
23680
    int crc_flag = 0;
2523
23680
    int res = cnt;
2524
23680
    int type = get_bits(gb, 4);
2525
2526
23680
    if (ac->avctx->debug & FF_DEBUG_STARTCODE)
2527
        av_log(ac->avctx, AV_LOG_DEBUG, "extension type: %d len:%d\n", type, cnt);
2528
2529

23680
    switch (type) { // extension type
2530
    case EXT_SBR_DATA_CRC:
2531
        crc_flag++;
2532
10901
    case EXT_SBR_DATA:
2533
10901
        if (!che) {
2534
            av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2535
            return res;
2536
10901
        } else if (ac->oc[1].m4ac.frame_length_short) {
2537
            if (!ac->warned_960_sbr)
2538
              avpriv_report_missing_feature(ac->avctx,
2539
                                            "SBR with 960 frame length");
2540
            ac->warned_960_sbr = 1;
2541
            skip_bits_long(gb, 8 * cnt - 4);
2542
            return res;
2543
10901
        } else if (!ac->oc[1].m4ac.sbr) {
2544
            av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2545
            skip_bits_long(gb, 8 * cnt - 4);
2546
            return res;
2547

10901
        } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2548
            av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2549
            skip_bits_long(gb, 8 * cnt - 4);
2550
            return res;
2551

10901
        } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2552
12
            ac->oc[1].m4ac.sbr = 1;
2553
12
            ac->oc[1].m4ac.ps = 1;
2554
12
            ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2555
12
            output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2556
                             ac->oc[1].status, 1);
2557
        } else {
2558
10889
            ac->oc[1].m4ac.sbr = 1;
2559
10889
            ac->avctx->profile = FF_PROFILE_AAC_HE;
2560
        }
2561
10901
        res = AAC_RENAME(ff_decode_sbr_extension)(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2562
10901
        break;
2563
880
    case EXT_DYNAMIC_RANGE:
2564
880
        res = decode_dynamic_range(&ac->che_drc, gb);
2565
880
        break;
2566
8949
    case EXT_FILL:
2567
8949
        decode_fill(ac, gb, 8 * cnt - 4);
2568
8949
        break;
2569
2950
    case EXT_FILL_DATA:
2570
    case EXT_DATA_ELEMENT:
2571
    default:
2572
2950
        skip_bits_long(gb, 8 * cnt - 4);
2573
2950
        break;
2574
    };
2575
23680
    return res;
2576
}
2577
2578
/**
2579
 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2580
 *
2581
 * @param   decode  1 if tool is used normally, 0 if tool is used in LTP.
2582
 * @param   coef    spectral coefficients
2583
 */
2584
6933
static void apply_tns(INTFLOAT coef_param[1024], TemporalNoiseShaping *tns,
2585
                      IndividualChannelStream *ics, int decode)
2586
{
2587
6933
    const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2588
    int w, filt, m, i;
2589
    int bottom, top, order, start, end, size, inc;
2590
    INTFLOAT lpc[TNS_MAX_ORDER];
2591
    INTFLOAT tmp[TNS_MAX_ORDER+1];
2592
6933
    UINTFLOAT *coef = coef_param;
2593
2594
6933
    if(!mmm)
2595
6
        return;
2596
2597
18467
    for (w = 0; w < ics->num_windows; w++) {
2598
11540
        bottom = ics->num_swb;
2599
20919
        for (filt = 0; filt < tns->n_filt[w]; filt++) {
2600
9379
            top    = bottom;
2601
9379
            bottom = FFMAX(0, top - tns->length[w][filt]);
2602
9379
            order  = tns->order[w][filt];
2603
9379
            if (order == 0)
2604
520
                continue;
2605
2606
            // tns_decode_coef
2607
8859
            AAC_RENAME(compute_lpc_coefs)(tns->coef[w][filt], order, lpc, 0, 0, 0);
2608
2609
8859
            start = ics->swb_offset[FFMIN(bottom, mmm)];
2610
8859
            end   = ics->swb_offset[FFMIN(   top, mmm)];
2611
8859
            if ((size = end - start) <= 0)
2612
8
                continue;
2613
8851
            if (tns->direction[w][filt]) {
2614
3586
                inc = -1;
2615
3586
                start = end - 1;
2616
            } else {
2617
5265
                inc = 1;
2618
            }
2619
8851
            start += w * 128;
2620
2621
8851
            if (decode) {
2622
                // ar filter
2623
2738921
                for (m = 0; m < size; m++, start += inc)
2624
23883725
                    for (i = 1; i <= FFMIN(m, order); i++)
2625
21153649
                        coef[start] -= AAC_MUL26((INTFLOAT)coef[start - i * inc], lpc[i - 1]);
2626
            } else {
2627
                // ma filter
2628
3702
                for (m = 0; m < size; m++, start += inc) {
2629
3696
                    tmp[0] = coef[start];
2630
39112
                    for (i = 1; i <= FFMIN(m, order); i++)
2631
35416
                        coef[start] += AAC_MUL26(tmp[i], lpc[i - 1]);
2632
39424
                    for (i = order; i > 0; i--)
2633
35728
                        tmp[i] = tmp[i - 1];
2634
                }
2635
            }
2636
        }
2637
    }
2638
}
2639
2640
/**
2641
 *  Apply windowing and MDCT to obtain the spectral
2642
 *  coefficient from the predicted sample by LTP.
2643
 */
2644
786
static void windowing_and_mdct_ltp(AACContext *ac, INTFLOAT *out,
2645
                                   INTFLOAT *in, IndividualChannelStream *ics)
2646
{
2647
786
    const INTFLOAT *lwindow      = ics->use_kb_window[0] ? AAC_KBD_RENAME(kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2648
786
    const INTFLOAT *swindow      = ics->use_kb_window[0] ? AAC_KBD_RENAME(kbd_short_128) : AAC_RENAME(ff_sine_128);
2649
786
    const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_KBD_RENAME(kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2650
786
    const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_KBD_RENAME(kbd_short_128) : AAC_RENAME(ff_sine_128);
2651
2652
786
    if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2653
784
        ac->fdsp->vector_fmul(in, in, lwindow_prev, 1024);
2654
    } else {
2655
2
        memset(in, 0, 448 * sizeof(*in));
2656
2
        ac->fdsp->vector_fmul(in + 448, in + 448, swindow_prev, 128);
2657
    }
2658
786
    if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2659
786
        ac->fdsp->vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2660
    } else {
2661
        ac->fdsp->vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2662
        memset(in + 1024 + 576, 0, 448 * sizeof(*in));
2663
    }
2664
786
    ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2665
786
}
2666
2667
/**
2668
 * Apply the long term prediction
2669
 */
2670
786
static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2671
{
2672
786
    const LongTermPrediction *ltp = &sce->ics.ltp;
2673
786
    const uint16_t *offsets = sce->ics.swb_offset;
2674
    int i, sfb;
2675
2676
786
    if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2677
786
        INTFLOAT *predTime = sce->ret;
2678
786
        INTFLOAT *predFreq = ac->buf_mdct;
2679
786
        int16_t num_samples = 2048;
2680
2681
786
        if (ltp->lag < 1024)
2682
            num_samples = ltp->lag + 1024;
2683
1610514
        for (i = 0; i < num_samples; i++)
2684
1609728
            predTime[i] = AAC_MUL30(sce->ltp_state[i + 2048 - ltp->lag], ltp->coef);
2685
786
        memset(&predTime[i], 0, (2048 - i) * sizeof(*predTime));
2686
2687
786
        ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2688
2689
786
        if (sce->tns.present)
2690
6
            ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2691
2692
32226
        for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2693
31440
            if (ltp->used[sfb])
2694
370412
                for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2695
347544
                    sce->coeffs[i] += (UINTFLOAT)predFreq[i];
2696
    }
2697
786
}
2698
2699
/**
2700
 * Update the LTP buffer for next frame
2701
 */
2702
3568
static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2703
{
2704
3568
    IndividualChannelStream *ics = &sce->ics;
2705
3568
    INTFLOAT *saved     = sce->saved;
2706
3568
    INTFLOAT *saved_ltp = sce->coeffs;
2707
3568
    const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_KBD_RENAME(kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2708
3568
    const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_KBD_RENAME(kbd_short_128) : AAC_RENAME(ff_sine_128);
2709
    int i;
2710
2711
3568
    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2712
4
        memcpy(saved_ltp,       saved, 512 * sizeof(*saved_ltp));
2713
4
        memset(saved_ltp + 576, 0,     448 * sizeof(*saved_ltp));
2714
4
        ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2715
2716
260
        for (i = 0; i < 64; i++)
2717
256
            saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2718
3564
    } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2719
4
        memcpy(saved_ltp,       ac->buf_mdct + 512, 448 * sizeof(*saved_ltp));
2720
4
        memset(saved_ltp + 576, 0,                  448 * sizeof(*saved_ltp));
2721
4
        ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2722
2723
260
        for (i = 0; i < 64; i++)
2724
256
            saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2725
    } else { // LONG_STOP or ONLY_LONG
2726
3560
        ac->fdsp->vector_fmul_reverse(saved_ltp,       ac->buf_mdct + 512,     &lwindow[512],     512);
2727
2728
1826280
        for (i = 0; i < 512; i++)
2729
1822720
            saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], lwindow[511 - i]);
2730
    }
2731
2732
3568
    memcpy(sce->ltp_state,      sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2733
3568
    memcpy(sce->ltp_state+1024, sce->ret,            1024 * sizeof(*sce->ltp_state));
2734
3568
    memcpy(sce->ltp_state+2048, saved_ltp,           1024 * sizeof(*sce->ltp_state));
2735
3568
}
2736
2737
/**
2738
 * Conduct IMDCT and windowing.
2739
 */
2740
62168
static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2741
{
2742
62168
    IndividualChannelStream *ics = &sce->ics;
2743
62168
    INTFLOAT *in    = sce->coeffs;
2744
62168
    INTFLOAT *out   = sce->ret;
2745
62168
    INTFLOAT *saved = sce->saved;
2746
62168
    const INTFLOAT *swindow      = ics->use_kb_window[0] ? AAC_KBD_RENAME(kbd_short_128) : AAC_RENAME(ff_sine_128);
2747
62168
    const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_KBD_RENAME(kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2748
62168
    const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_KBD_RENAME(kbd_short_128) : AAC_RENAME(ff_sine_128);
2749
62168
    INTFLOAT *buf  = ac->buf_mdct;
2750
62168
    INTFLOAT *temp = ac->temp;
2751
    int i;
2752
2753
    // imdct
2754
62168
    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2755
18765
        for (i = 0; i < 1024; i += 128)
2756
16680
            ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2757
    } else {
2758
60083
        ac->mdct.imdct_half(&ac->mdct, buf, in);
2759
#if USE_FIXED
2760
16815125
        for (i=0; i<1024; i++)
2761
16798720
          buf[i] = (buf[i] + 4LL) >> 3;
2762
#endif /* USE_FIXED */
2763
    }
2764
2765
    /* window overlapping
2766
     * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2767
     * and long to short transitions are considered to be short to short
2768
     * transitions. This leaves just two cases (long to long and short to short)
2769
     * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2770
     */
2771

62168
    if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2772

59004
            (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2773
59002
        ac->fdsp->vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 512);
2774
    } else {
2775
3166
        memcpy(                         out,               saved,            448 * sizeof(*out));
2776
2777
3166
        if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2778
2085
            ac->fdsp->vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, 64);
2779
2085
            ac->fdsp->vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      64);
2780
2085
            ac->fdsp->vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      64);
2781
2085
            ac->fdsp->vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      64);
2782
2085
            ac->fdsp->vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      64);
2783
2085
            memcpy(                     out + 448 + 4*128, temp, 64 * sizeof(*out));
2784
        } else {
2785
1081
            ac->fdsp->vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 64);
2786
1081
            memcpy(                     out + 576,         buf + 64,         448 * sizeof(*out));
2787
        }
2788
    }
2789
2790
    // buffer update
2791
62168
    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2792
2085
        memcpy(                     saved,       temp + 64,         64 * sizeof(*saved));
2793
2085
        ac->fdsp->vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 64);
2794
2085
        ac->fdsp->vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2795
2085
        ac->fdsp->vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2796
2085
        memcpy(                     saved + 448, buf + 7*128 + 64,  64 * sizeof(*saved));
2797
60083
    } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2798
1204
        memcpy(                     saved,       buf + 512,        448 * sizeof(*saved));
2799
1204
        memcpy(                     saved + 448, buf + 7*128 + 64,  64 * sizeof(*saved));
2800
    } else { // LONG_STOP or ONLY_LONG
2801
58879
        memcpy(                     saved,       buf + 512,        512 * sizeof(*saved));
2802
    }
2803
62168
}
2804
2805
/**
2806
 * Conduct IMDCT and windowing.
2807
 */
2808
387
static void imdct_and_windowing_960(AACContext *ac, SingleChannelElement *sce)
2809
{
2810
#if !USE_FIXED
2811
387
    IndividualChannelStream *ics = &sce->ics;
2812
387
    INTFLOAT *in    = sce->coeffs;
2813
387
    INTFLOAT *out   = sce->ret;
2814
387
    INTFLOAT *saved = sce->saved;
2815
387
    const INTFLOAT *swindow      = ics->use_kb_window[0] ? AAC_RENAME(aac_kbd_short_120) : AAC_RENAME(sine_120);
2816
387
    const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(aac_kbd_long_960) : AAC_RENAME(sine_960);
2817
387
    const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(aac_kbd_short_120) : AAC_RENAME(sine_120);
2818
387
    INTFLOAT *buf  = ac->buf_mdct;
2819
387
    INTFLOAT *temp = ac->temp;
2820
    int i;
2821
2822
    // imdct
2823
387
    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2824
9
        for (i = 0; i < 8; i++)
2825
8
            ac->mdct120->imdct_half(ac->mdct120, buf + i * 120, in + i * 128, 1);
2826
    } else {
2827
386
        ac->mdct960->imdct_half(ac->mdct960, buf, in, 1);
2828
    }
2829
2830
    /* window overlapping
2831
     * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2832
     * and long to short transitions are considered to be short to short
2833
     * transitions. This leaves just two cases (long to long and short to short)
2834
     * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2835
     */
2836
2837

387
    if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2838

385
        (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2839
385
        ac->fdsp->vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 480);
2840
    } else {
2841
2
        memcpy(                          out,               saved,            420 * sizeof(*out));
2842
2843
2
        if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2844
1
            ac->fdsp->vector_fmul_window(out + 420 + 0*120, saved + 420,      buf + 0*120, swindow_prev, 60);
2845
1
            ac->fdsp->vector_fmul_window(out + 420 + 1*120, buf + 0*120 + 60, buf + 1*120, swindow,      60);
2846
1
            ac->fdsp->vector_fmul_window(out + 420 + 2*120, buf + 1*120 + 60, buf + 2*120, swindow,      60);
2847
1
            ac->fdsp->vector_fmul_window(out + 420 + 3*120, buf + 2*120 + 60, buf + 3*120, swindow,      60);
2848
1
            ac->fdsp->vector_fmul_window(temp,              buf + 3*120 + 60, buf + 4*120, swindow,      60);
2849
1
            memcpy(                      out + 420 + 4*120, temp, 60 * sizeof(*out));
2850
        } else {
2851
1
            ac->fdsp->vector_fmul_window(out + 420,         saved + 420,      buf,         swindow_prev, 60);
2852
1
            memcpy(                      out + 540,         buf + 60,         420 * sizeof(*out));
2853
        }
2854
    }
2855
2856
    // buffer update
2857
387
    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2858
1
        memcpy(                      saved,       temp + 60,         60 * sizeof(*saved));
2859
1
        ac->fdsp->vector_fmul_window(saved + 60,  buf + 4*120 + 60, buf + 5*120, swindow, 60);
2860
1
        ac->fdsp->vector_fmul_window(saved + 180, buf + 5*120 + 60, buf + 6*120, swindow, 60);
2861
1
        ac->fdsp->vector_fmul_window(saved + 300, buf + 6*120 + 60, buf + 7*120, swindow, 60);
2862
1
        memcpy(                      saved + 420, buf + 7*120 + 60,  60 * sizeof(*saved));
2863
386
    } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2864
2
        memcpy(                      saved,       buf + 480,        420 * sizeof(*saved));
2865
2
        memcpy(                      saved + 420, buf + 7*120 + 60,  60 * sizeof(*saved));
2866
    } else { // LONG_STOP or ONLY_LONG
2867
384
        memcpy(                      saved,       buf + 480,        480 * sizeof(*saved));
2868
    }
2869
#endif
2870
387
}
2871
3636
static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2872
{
2873
3636
    IndividualChannelStream *ics = &sce->ics;
2874
3636
    INTFLOAT *in    = sce->coeffs;
2875
3636
    INTFLOAT *out   = sce->ret;
2876
3636
    INTFLOAT *saved = sce->saved;
2877
3636
    INTFLOAT *buf  = ac->buf_mdct;
2878
#if USE_FIXED
2879
    int i;
2880
#endif /* USE_FIXED */
2881
2882
    // imdct
2883
3636
    ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2884
2885
#if USE_FIXED
2886
1857300
    for (i = 0; i < 1024; i++)
2887
1855488
        buf[i] = (buf[i] + 2) >> 2;
2888
#endif /* USE_FIXED */
2889
2890
    // window overlapping
2891
3636
    if (ics->use_kb_window[1]) {
2892
        // AAC LD uses a low overlap sine window instead of a KBD window
2893
62
        memcpy(out, saved, 192 * sizeof(*out));
2894
62
        ac->fdsp->vector_fmul_window(out + 192, saved + 192, buf, AAC_RENAME(ff_sine_128), 64);
2895
62
        memcpy(                     out + 320, buf + 64, 192 * sizeof(*out));
2896
    } else {
2897
3574
        ac->fdsp->vector_fmul_window(out, saved, buf, AAC_RENAME(ff_sine_512), 256);
2898
    }
2899
2900
    // buffer update
2901
3636
    memcpy(saved, buf + 256, 256 * sizeof(*saved));
2902
3636
}
2903
2904
26598
static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2905
{
2906
26598
    INTFLOAT *in    = sce->coeffs;
2907
26598
    INTFLOAT *out   = sce->ret;
2908
26598
    INTFLOAT *saved = sce->saved;
2909
26598
    INTFLOAT *buf  = ac->buf_mdct;
2910
    int i;
2911
26598
    const int n  = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
2912
26598
    const int n2 = n >> 1;
2913
26598
    const int n4 = n >> 2;
2914
26598
    const INTFLOAT *const window = n == 480 ? AAC_RENAME(ff_aac_eld_window_480) :
2915
                                           AAC_RENAME(ff_aac_eld_window_512);
2916
2917
    // Inverse transform, mapped to the conventional IMDCT by
2918
    // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2919
    // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2920
    // International Conference on Audio, Language and Image Processing, ICALIP 2008.
2921
    // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2922
3374198
    for (i = 0; i < n2; i+=2) {
2923
        INTFLOAT temp;
2924
3347600
        temp =  in[i    ]; in[i    ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2925
3347600
        temp = -in[i + 1]; in[i + 1] =  in[n - 2 - i]; in[n - 2 - i] = temp;
2926
    }
2927
#if !USE_FIXED
2928
16861
    if (n == 480)
2929
7118
        ac->mdct480->imdct_half(ac->mdct480, buf, in, 1);
2930
    else
2931
#endif
2932
19480
        ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2933
2934
#if USE_FIXED
2935
9980425
    for (i = 0; i < 1024; i++)
2936
9970688
      buf[i] = (buf[i] + 1) >> 1;
2937
#endif /* USE_FIXED */
2938
2939
6721798
    for (i = 0; i < n; i+=2) {
2940
6695200
        buf[i] = -buf[i];
2941
    }
2942
    // Like with the regular IMDCT at this point we still have the middle half
2943
    // of a transform but with even symmetry on the left and odd symmetry on
2944
    // the right
2945
2946
    // window overlapping
2947
    // The spec says to use samples [0..511] but the reference decoder uses
2948
    // samples [128..639].
2949
3374198
    for (i = n4; i < n2; i ++) {
2950
3347600
        out[i - n4] = AAC_MUL31(   buf[    n2 - 1 - i] , window[i       - n4]) +
2951
3347600
                      AAC_MUL31( saved[        i + n2] , window[i +   n - n4]) +
2952
3347600
                      AAC_MUL31(-saved[n + n2 - 1 - i] , window[i + 2*n - n4]) +
2953
3347600
                      AAC_MUL31(-saved[  2*n + n2 + i] , window[i + 3*n - n4]);
2954
    }
2955
6721798
    for (i = 0; i < n2; i ++) {
2956
6695200
        out[n4 + i] = AAC_MUL31(   buf[              i] , window[i + n2       - n4]) +
2957
6695200
                      AAC_MUL31(-saved[      n - 1 - i] , window[i + n2 +   n - n4]) +
2958
6695200
                      AAC_MUL31(-saved[          n + i] , window[i + n2 + 2*n - n4]) +
2959
6695200
                      AAC_MUL31( saved[2*n + n - 1 - i] , window[i + n2 + 3*n - n4]);
2960
    }
2961
3374198
    for (i = 0; i < n4; i ++) {
2962
3347600
        out[n2 + n4 + i] = AAC_MUL31(   buf[    i + n2] , window[i +   n - n4]) +
2963
3347600
                           AAC_MUL31(-saved[n2 - 1 - i] , window[i + 2*n - n4]) +
2964
3347600
                           AAC_MUL31(-saved[n + n2 + i] , window[i + 3*n - n4]);
2965
    }
2966
2967
    // buffer update
2968
26598
    memmove(saved + n, saved, 2 * n * sizeof(*saved));
2969
26598
    memcpy( saved,       buf,     n * sizeof(*saved));
2970
26598
}
2971
2972
/**
2973
 * channel coupling transformation interface
2974
 *
2975
 * @param   apply_coupling_method   pointer to (in)dependent coupling function
2976
 */
2977
175813
static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2978
                                   enum RawDataBlockType type, int elem_id,
2979
                                   enum CouplingPoint coupling_point,
2980
                                   void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2981
{
2982
    int i, c;
2983
2984
2988821
    for (i = 0; i < MAX_ELEM_ID; i++) {
2985
2813008
        ChannelElement *cce = ac->che[TYPE_CCE][i];
2986
2813008
        int index = 0;
2987
2988

2813008
        if (cce && cce->coup.coupling_point == coupling_point) {
2989
3915
            ChannelCoupling *coup = &cce->coup;
2990
2991
13317
            for (c = 0; c <= coup->num_coupled; c++) {
2992

9402
                if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2993
2741
                    if (coup->ch_select[c] != 1) {
2994
2561
                        apply_coupling_method(ac, &cc->ch[0], cce, index);
2995
2561
                        if (coup->ch_select[c] != 0)
2996
2561
                            index++;
2997
                    }
2998
2741
                    if (coup->ch_select[c] != 2)
2999
2147
                        apply_coupling_method(ac, &cc->ch[1], cce, index++);
3000
                } else
3001
6661
                    index += 1 + (coup->ch_select[c] == 3);
3002
            }
3003
        }
3004
    }
3005
175813
}
3006
3007
/**
3008
 * Convert spectral data to samples, applying all supported tools as appropriate.
3009
 */
3010
49845
static void spectral_to_sample(AACContext *ac, int samples)
3011
{
3012
    int i, type;
3013
    void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
3014
49845
    switch (ac->oc[1].m4ac.object_type) {
3015
606
    case AOT_ER_AAC_LD:
3016
606
        imdct_and_window = imdct_and_windowing_ld;
3017
606
        break;
3018
16365
    case AOT_ER_AAC_ELD:
3019
16365
        imdct_and_window = imdct_and_windowing_eld;
3020
16365
        break;
3021
32874
    default:
3022
32874
        if (ac->oc[1].m4ac.frame_length_short)
3023
387
            imdct_and_window = imdct_and_windowing_960;
3024
        else
3025
32487
            imdct_and_window = ac->imdct_and_windowing;
3026
    }
3027
249225
    for (type = 3; type >= 0; type--) {
3028
3389460
        for (i = 0; i < MAX_ELEM_ID; i++) {
3029
3190080
            ChannelElement *che = ac->che[type][i];
3030

3190080
            if (che && che->present) {
3031
62891
                if (type <= TYPE_CPE)
3032
58213
                    apply_channel_coupling(ac, che, type, i, BEFORE_TNS, AAC_RENAME(apply_dependent_coupling));
3033
62891
                if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
3034
1784
                    if (che->ch[0].ics.predictor_present) {
3035
538
                        if (che->ch[0].ics.ltp.present)
3036
382
                            ac->apply_ltp(ac, &che->ch[0]);
3037

538
                        if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
3038
404
                            ac->apply_ltp(ac, &che->ch[1]);
3039
                    }
3040
                }
3041
62891
                if (che->ch[0].tns.present)
3042
4633
                    ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
3043
62891
                if (che->ch[1].tns.present)
3044
2294
                    ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
3045
62891
                if (type <= TYPE_CPE)
3046
58213
                    apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, AAC_RENAME(apply_dependent_coupling));
3047

62891
                if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
3048
62110
                    imdct_and_window(ac, &che->ch[0]);
3049
62110
                    if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
3050
1784
                        ac->update_ltp(ac, &che->ch[0]);
3051
62110
                    if (type == TYPE_CPE) {
3052
30679
                        imdct_and_window(ac, &che->ch[1]);
3053
30679
                        if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
3054
1784
                            ac->update_ltp(ac, &che->ch[1]);
3055
                    }
3056
62110
                    if (ac->oc[1].m4ac.sbr > 0) {
3057
12411
                        AAC_RENAME(ff_sbr_apply)(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
3058
                    }
3059
                }
3060
62891
                if (type <= TYPE_CCE)
3061
59387
                    apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, AAC_RENAME(apply_independent_coupling));
3062
3063
#if USE_FIXED
3064
                {
3065
                    int j;
3066
                    /* preparation for resampler */
3067
19746147
                    for(j = 0; j<samples; j++){
3068
19726848
                        che->ch[0].ret[j] = (int32_t)av_clip64((int64_t)che->ch[0].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
3069
19726848
                        if(type == TYPE_CPE)
3070
9935872
                            che->ch[1].ret[j] = (int32_t)av_clip64((int64_t)che->ch[1].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
3071
                    }
3072
                }
3073
#endif /* USE_FIXED */
3074
62891
                che->present = 0;
3075
3127189
            } else if (che) {
3076
329
                av_log(ac->avctx, AV_LOG_VERBOSE, "ChannelElement %d.%d missing \n", type, i);
3077
            }
3078
        }
3079
    }
3080
49845
}
3081
3082
4112
static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
3083
{
3084
    int size;
3085
    AACADTSHeaderInfo hdr_info;
3086
    uint8_t layout_map[MAX_ELEM_ID*4][3];
3087
    int layout_map_tags, ret;
3088
3089
4112
    size = ff_adts_header_parse(gb, &hdr_info);
3090
4112
    if (size > 0) {
3091

4112
        if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
3092
            // This is 2 for "VLB " audio in NSV files.
3093
            // See samples/nsv/vlb_audio.
3094
            avpriv_report_missing_feature(ac->avctx,
3095
                                          "More than one AAC RDB per ADTS frame");
3096
            ac->warned_num_aac_frames = 1;
3097
        }
3098
4112
        push_output_configuration(ac);
3099
4112
        if (hdr_info.chan_config) {
3100
4112
            ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
3101
4112
            if ((ret = set_default_channel_config(ac, ac->avctx,
3102
                                                  layout_map,
3103
                                                  &layout_map_tags,
3104
4112
                                                  hdr_info.chan_config)) < 0)
3105
                return ret;
3106
4112
            if ((ret = output_configure(ac, layout_map, layout_map_tags,
3107
4112
                                        FFMAX(ac->oc[1].status,
3108
                                              OC_TRIAL_FRAME), 0)) < 0)
3109
                return ret;
3110
        } else {
3111
            ac->oc[1].m4ac.chan_config = 0;
3112
            /**
3113
             * dual mono frames in Japanese DTV can have chan_config 0
3114
             * WITHOUT specifying PCE.
3115
             *  thus, set dual mono as default.
3116
             */
3117
            if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
3118
                layout_map_tags = 2;
3119
                layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
3120
                layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
3121
                layout_map[0][1] = 0;
3122
                layout_map[1][1] = 1;
3123
                if (output_configure(ac, layout_map, layout_map_tags,
3124
                                     OC_TRIAL_FRAME, 0))
3125
                    return -7;
3126
            }
3127
        }
3128
4112
        ac->oc[1].m4ac.sample_rate     = hdr_info.sample_rate;
3129
4112
        ac->oc[1].m4ac.sampling_index  = hdr_info.sampling_index;
3130
4112
        ac->oc[1].m4ac.object_type     = hdr_info.object_type;
3131
4112
        ac->oc[1].m4ac.frame_length_short = 0;
3132
4112
        if (ac->oc[0].status != OC_LOCKED ||
3133
4058
            ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
3134
4058
            ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
3135
54
            ac->oc[1].m4ac.sbr = -1;
3136
54
            ac->oc[1].m4ac.ps  = -1;
3137
        }
3138
4112
        if (!hdr_info.crc_absent)
3139
1
            skip_bits(gb, 16);
3140
    }
3141
4112
    return size;
3142
}
3143
3144
16971
static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
3145
                               int *got_frame_ptr, GetBitContext *gb)
3146
{
3147
16971
    AACContext *ac = avctx->priv_data;
3148
16971
    const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
3149
    ChannelElement *che;
3150
    int err, i;
3151
16971
    int samples = m4ac->frame_length_short ? 960 : 1024;
3152
16971
    int chan_config = m4ac->chan_config;
3153
16971
    int aot = m4ac->object_type;
3154
3155

16971
    if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
3156
16971
        samples >>= 1;
3157
3158
16971
    ac->frame = data;
3159
3160
16971
    if ((err = frame_configure_elements(avctx)) < 0)
3161
        return err;
3162
3163
    // The FF_PROFILE_AAC_* defines are all object_type - 1
3164
    // This may lead to an undefined profile being signaled
3165
16971
    ac->avctx->profile = aot - 1;
3166
3167
16971
    ac->tags_mapped = 0;
3168
3169


16971
    if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
3170
        avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
3171
                              chan_config);
3172
        return AVERROR_INVALIDDATA;
3173
    }
3174
35760
    for (i = 0; i < tags_per_config[chan_config]; i++) {
3175
18789
        const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
3176
18789
        const int elem_id   = aac_channel_layout_map[chan_config-1][i][1];
3177
18789
        if (!(che=get_che(ac, elem_type, elem_id))) {
3178
            av_log(ac->avctx, AV_LOG_ERROR,
3179
                   "channel element %d.%d is not allocated\n",
3180
                   elem_type, elem_id);
3181
            return AVERROR_INVALIDDATA;
3182
        }
3183
18789
        che->present = 1;
3184
18789
        if (aot != AOT_ER_AAC_ELD)
3185
2424
            skip_bits(gb, 4);
3186

18789
        switch (elem_type) {
3187
6738
        case TYPE_SCE:
3188
6738
            err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3189
6738
            break;
3190
11445
        case TYPE_CPE:
3191
11445
            err = decode_cpe(ac, gb, che);
3192
11445
            break;
3193
606
        case TYPE_LFE:
3194
606
            err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3195
606
            break;
3196
        }
3197
18789
        if (err < 0)
3198
            return err;
3199
    }
3200
3201
16971
    spectral_to_sample(ac, samples);
3202
3203

16971
    if (!ac->frame->data[0] && samples) {
3204
        av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
3205
        return AVERROR_INVALIDDATA;
3206
    }
3207
3208
16971
    ac->frame->nb_samples = samples;
3209
16971
    ac->frame->sample_rate = avctx->sample_rate;
3210
16971
    *got_frame_ptr = 1;
3211
3212
16971
    skip_bits_long(gb, get_bits_left(gb));
3213
16971
    return 0;
3214
}
3215
3216
32874
static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
3217
                                int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
3218
{
3219
32874
    AACContext *ac = avctx->priv_data;
3220
32874
    ChannelElement *che = NULL, *che_prev = NULL;
3221
32874
    enum RawDataBlockType elem_type, che_prev_type = TYPE_END;
3222
    int err, elem_id;
3223
32874
    int samples = 0, multiplier, audio_found = 0, pce_found = 0;
3224
32874
    int is_dmono, sce_count = 0;
3225
    int payload_alignment;
3226
32874
    uint8_t che_presence[4][MAX_ELEM_ID] = {{0}};
3227
3228
32874
    ac->frame = data;
3229
3230
32874
    if (show_bits(gb, 12) == 0xfff) {
3231
4112
        if ((err = parse_adts_frame_header(ac, gb)) < 0) {
3232
            av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
3233
            goto fail;
3234
        }
3235
4112
        if (ac->oc[1].m4ac.sampling_index > 12) {
3236
            av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
3237
            err = AVERROR_INVALIDDATA;
3238
            goto fail;
3239
        }
3240
    }
3241
3242
32874
    if ((err = frame_configure_elements(avctx)) < 0)
3243
        goto fail;
3244
3245
    // The FF_PROFILE_AAC_* defines are all object_type - 1
3246
    // This may lead to an undefined profile being signaled
3247
32874
    ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
3248
3249
32874
    payload_alignment = get_bits_count(gb);
3250
32874
    ac->tags_mapped = 0;
3251
    // parse
3252
104998
    while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
3253
72124
        elem_id = get_bits(gb, 4);
3254
3255
72124
        if (avctx->debug & FF_DEBUG_STARTCODE)
3256
            av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
3257
3258

72124
        if (!avctx->channels && elem_type != TYPE_PCE) {
3259
            err = AVERROR_INVALIDDATA;
3260
            goto fail;
3261
        }
3262
3263
72124
        if (elem_type < TYPE_DSE) {
3264
44102
            if (che_presence[elem_type][elem_id]) {
3265
                int error = che_presence[elem_type][elem_id] > 1;
3266
                av_log(ac->avctx, error ? AV_LOG_ERROR : AV_LOG_DEBUG, "channel element %d.%d duplicate\n",
3267
                       elem_type, elem_id);
3268
                if (error) {
3269
                    err = AVERROR_INVALIDDATA;
3270
                    goto fail;
3271
                }
3272
            }
3273
44102
            che_presence[elem_type][elem_id]++;
3274
3275
44102
            if (!(che=get_che(ac, elem_type, elem_id))) {
3276
                av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
3277
                       elem_type, elem_id);
3278
                err = AVERROR_INVALIDDATA;
3279
                goto fail;
3280
            }
3281
44102
            samples = ac->oc[1].m4ac.frame_length_short ? 960 : 1024;
3282
44102
            che->present = 1;
3283
        }
3284
3285


72124
        switch (elem_type) {
3286
3287
20796
        case TYPE_SCE:
3288
20796
            err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3289
20796
            audio_found = 1;
3290
20796
            sce_count++;
3291
20796
            break;
3292
3293
19234
        case TYPE_CPE:
3294
19234
            err = decode_cpe(ac, gb, che);
3295
19234
            audio_found = 1;
3296
19234
            break;
3297
3298
1174
        case TYPE_CCE:
3299
1174
            err = decode_cce(ac, gb, che);
3300
1174
            break;
3301
3302
2898
        case TYPE_LFE:
3303
2898
            err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3304
2898
            audio_found = 1;
3305
2898
            break;
3306
3307
2821
        case TYPE_DSE:
3308
2821
            err = skip_data_stream_element(ac, gb);
3309
2821
            break;
3310
3311
        case TYPE_PCE: {
3312
            uint8_t layout_map[MAX_ELEM_ID*4][3] = {{0}};
3313
            int tags;
3314
3315
            int pushed = push_output_configuration(ac);
3316
            if (pce_found && !pushed) {
3317
                err = AVERROR_INVALIDDATA;
3318
                goto fail;
3319
            }
3320
3321
            tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb,
3322
                              payload_alignment);
3323
            if (tags < 0) {
3324
                err = tags;
3325
                break;
3326
            }
3327
            if (pce_found) {
3328
                av_log(avctx, AV_LOG_ERROR,
3329
                       "Not evaluating a further program_config_element as this construct is dubious at best.\n");
3330
                pop_output_configuration(ac);
3331
            } else {
3332
                err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
3333
                if (!err)
3334
                    ac->oc[1].m4ac.chan_config = 0;
3335
                pce_found = 1;
3336
            }
3337
            break;
3338
        }
3339
3340
25201
        case TYPE_FIL:
3341
25201
            if (elem_id == 15)
3342
16437
                elem_id += get_bits(gb, 8) - 1;
3343
25201
            if (get_bits_left(gb) < 8 * elem_id) {
3344
                    av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
3345
                    err = AVERROR_INVALIDDATA;
3346
                    goto fail;
3347
            }
3348
25201
            err = 0;
3349
48881
            while (elem_id > 0) {
3350
23680
                int ret = decode_extension_payload(ac, gb, elem_id, che_prev, che_prev_type);
3351
23680
                if (ret < 0) {
3352
                    err = ret;
3353
                    break;
3354
                }
3355
23680
                elem_id -= ret;
3356
            }
3357
25201
            break;
3358
3359
        default:
3360
            err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
3361
            break;
3362
        }
3363
3364
72124
        if (elem_type < TYPE_DSE) {
3365
44102
            che_prev      = che;
3366
44102
            che_prev_type = elem_type;
3367
        }
3368
3369
72124
        if (err)
3370
            goto fail;