Coverage Report

Created: 2026-12-01 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/proc/self/cwd/external/faac/libfaad/decoder.c
Line
Count
Source
1
/*
2
 * FAAD - Freeware Advanced Audio Decoder
3
 * Copyright (C) 2026 Nils Schimmelmann
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2.1 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 */
15
16
#include "faad_internal.h"
17
18
#ifdef FAAD_STATS
19
#include <stdio.h>
20
#endif
21
22
#include "atomic.h"
23
#include "bits.h"
24
#include "endian.h"
25
26
/* Baselines end at the last field so appended fields remain optional. */
27
22.5k
#define CONFIG_BASELINE_SIZE ((uint32_t)FAAD_CONFIG_BASELINE)
28
0
#define LIBRARY_INFO_BASELINE_SIZE ((uint32_t)FAAD_LIBRARY_INFO_BASELINE)
29
12.4k
#define STREAM_INFO_BASELINE_SIZE ((uint32_t)FAAD_STREAM_INFO_BASELINE)
30
31
/* Append-only fields must not increase the alignment an older caller supplies. */
32
_Static_assert(_Alignof(faad_config) == _Alignof(uint32_t), "config ABI alignment");
33
_Static_assert(_Alignof(faad_stream_info) == _Alignof(uint32_t), "stream ABI alignment");
34
_Static_assert(_Alignof(faad_library_info) == _Alignof(const char *), "library ABI alignment");
35
36
static uint32_t bounded_size(uint32_t caller_size, size_t library_size)
37
12.4k
{
38
12.4k
    return caller_size < library_size ? caller_size : (uint32_t)library_size;
39
12.4k
}
40
41
/* channel_configuration (ISO/IEC 14496-3 Table 1.19); 0 takes its layout from a PCE. */
42
enum channel_config { CFG_PCE, CFG_MONO, CFG_STEREO, CFG_3_0, CFG_4_0, CFG_5_0, CFG_5_1, CFG_7_1,
43
                      CFG_6_1 = 11, CFG_7_1_SIDE_BACK = 12, CFG_COUNT };
44
45
/* Channels a channel_configuration carries (7 is 7.1 wide); 0, a PCE, is
46
 * learnt from the first decoded frame, so start from stereo. */
47
static uint32_t config_channels(uint32_t channel_config)
48
17.0k
{
49
17.0k
    return channel_config == CFG_7_1 || channel_config == CFG_7_1_SIDE_BACK ? 8
50
17.0k
        : channel_config == CFG_6_1 ? 7
51
13.7k
        : (channel_config >= CFG_MONO && channel_config <= CFG_5_1)
52
10.5k
        ? channel_config : (MAX_CHANNELS < 2 ? 1 : 2);
53
17.0k
}
54
55
static uint32_t asc_channels(const AudioSpecificConfig *asc)
56
17.8k
{
57
17.8k
    return asc->pce.channels ? asc->pce.channels : config_channels(asc->num_channels);
58
17.8k
}
59
60
/* WAVE_FORMAT_EXTENSIBLE speakers, by bit position; a layout outputs in this order. */
61
enum speaker_pos { POS_FL, POS_FR, POS_FC, POS_LFE, POS_BL, POS_BR, POS_FLC, POS_FRC, POS_BC, POS_SL, POS_SR,
62
                   POS_COUNT };
63
enum speaker {
64
    SPK_FL = 1 << POS_FL, SPK_FR = 1 << POS_FR, SPK_FC = 1 << POS_FC, SPK_LFE = 1 << POS_LFE,
65
    SPK_BL = 1 << POS_BL, SPK_BR = 1 << POS_BR, SPK_FLC = 1 << POS_FLC, SPK_FRC = 1 << POS_FRC,
66
    SPK_BC = 1 << POS_BC, SPK_SL = 1 << POS_SL, SPK_SR = 1 << POS_SR,
67
    SPK_FRONT = SPK_FL | SPK_FR, SPK_BACK = SPK_BL | SPK_BR, SPK_SIDE = SPK_SL | SPK_SR
68
};
69
70
#if MAX_CHANNELS >= 3
71
#define EL(cat, cpe) (uint8_t)((cat) << 5 | (cpe) << 4)
72
/* Table 1.19: each channel_configuration as the element list a PCE would give.
73
 * Configuration 7 is 7.1 wide: centre, the two front pairs from the centre
74
 * outward, then the surrounds. Apple, FDK and the specification read it so; the
75
 * side/back 7.1 that older encoders also wrote as 7 cannot be told from it. */
76
static const uint8_t config_elements[CFG_COUNT][6] = {
77
    [CFG_MONO] = { EL(ASC_PCE_FRONT, 0), 0xff },
78
    [CFG_STEREO] = { EL(ASC_PCE_FRONT, 1), 0xff },
79
    [CFG_3_0] = { EL(ASC_PCE_FRONT, 0), EL(ASC_PCE_FRONT, 1), 0xff },
80
    [CFG_4_0] = { EL(ASC_PCE_FRONT, 0), EL(ASC_PCE_FRONT, 1), EL(ASC_PCE_BACK, 0), 0xff },
81
    [CFG_5_0] = { EL(ASC_PCE_FRONT, 0), EL(ASC_PCE_FRONT, 1), EL(ASC_PCE_BACK, 1), 0xff },
82
    [CFG_5_1] = { EL(ASC_PCE_FRONT, 0), EL(ASC_PCE_FRONT, 1), EL(ASC_PCE_BACK, 1), EL(ASC_PCE_LFE, 0), 0xff },
83
    [CFG_7_1] = { EL(ASC_PCE_FRONT, 0), EL(ASC_PCE_FRONT, 1), EL(ASC_PCE_FRONT, 1), EL(ASC_PCE_BACK, 1),
84
                  EL(ASC_PCE_LFE, 0) },
85
    /* The 2013 amendment: 6.1 with a back centre, and the side/back 7.1 that
86
     * configuration 7 cannot name. Only a MP4 or raw ASC carries them, as an ADTS
87
     * header has three bits for the configuration. */
88
    [CFG_6_1] = { EL(ASC_PCE_FRONT, 0), EL(ASC_PCE_FRONT, 1), EL(ASC_PCE_BACK, 1), EL(ASC_PCE_BACK, 0),
89
                  EL(ASC_PCE_LFE, 0) },
90
    [CFG_7_1_SIDE_BACK] = { EL(ASC_PCE_FRONT, 0), EL(ASC_PCE_FRONT, 1), EL(ASC_PCE_SIDE, 1), EL(ASC_PCE_BACK, 1),
91
                  EL(ASC_PCE_LFE, 0) },
92
};
93
94
/* A configuration 0 stream whose PCE has not arrived yet comes from a writer
95
 * that signals layouts by PCE, whose 7.1 is front, side, back. */
96
static const uint8_t pce_side_back_7_1[5] = {
97
    EL(ASC_PCE_FRONT, 0), EL(ASC_PCE_FRONT, 1), EL(ASC_PCE_SIDE, 1), EL(ASC_PCE_BACK, 1), EL(ASC_PCE_LFE, 0) };
98
99
/* Gives each element its speakers (a WAVE mask bit per channel) and orders
100
 * the output by position. A layout whose elements cannot be placed, or two of
101
 * which would share a speaker, stays in element order with no mask. Two back
102
 * pairs without a side pair read as side then back, as 7.1 does. */
103
static void layout_build(struct faad_decoder *dec, const uint8_t *el, uint32_t n, bool by_tag)
104
8.44k
{
105
8.44k
    static const uint16_t speakers[4][2] = { { SPK_FC, SPK_FRONT }, { 0, SPK_SIDE }, { SPK_BC, SPK_BACK }, { SPK_LFE, 0 } };
106
8.44k
    struct faad_layout *L = &dec->layout;
107
8.44k
    uint16_t spk[MAX_CHANNELS];
108
8.44k
    uint32_t mask = 0, ch = 0, front_pairs = 0, back_pairs = 0, side = 0, front_total = 0;
109
8.44k
    memset(L, 0, sizeof(*L));
110
8.44k
    L->lfe = 0xff;
111
39.4k
    for (uint32_t i = 0; i < n; i++) {
112
30.9k
        side += el[i] >> 5 == ASC_PCE_SIDE;
113
30.9k
        back_pairs += el[i] >> 4 == (ASC_PCE_BACK << 1 | 1);
114
30.9k
        front_total += el[i] >> 4 == (ASC_PCE_FRONT << 1 | 1);
115
30.9k
    }
116
8.44k
    bool rear_pairs = back_pairs == 2 && !side;
117
32.8k
    for (uint32_t i = 0; i < n; i++) {
118
26.2k
        uint32_t cat = el[i] >> 5, pair = el[i] >> 4 & 1, bits = speakers[cat][pair];
119
26.2k
        if (cat == ASC_PCE_FRONT && pair) {
120
            /* Front pairs are listed from the centre outward: with two, the inner one is FLC/FRC. */
121
6.60k
            if (front_total > 2) bits = 0;
122
6.59k
            else if (front_total == 2 && !front_pairs++) bits = SPK_FLC | SPK_FRC;
123
6.60k
        }
124
26.2k
        if (rear_pairs && cat == ASC_PCE_BACK && pair && !(mask & SPK_SIDE)) bits = SPK_SIDE;
125
26.2k
        if (!bits || (mask & bits) || ch + 1 + pair > MAX_CHANNELS) return;
126
24.6k
        mask |= bits;
127
24.6k
        L->el_key[i] = (uint8_t)((cat == ASC_PCE_LFE ? ID_LFE : pair) << 4 | (el[i] & 0xf));
128
        /* Tags select the elements, so two of one kind cannot share one. */
129
29.5k
        for (uint32_t j = 0; by_tag && j < i; j++)
130
5.14k
            if (L->el_key[j] == L->el_key[i]) return;
131
24.3k
        L->el_slot[i] = (uint8_t)ch;
132
24.3k
        spk[ch] = (uint16_t)(bits & (0u - bits));
133
24.3k
        if (pair) spk[ch + 1] = (uint16_t)(bits & (bits - 1));
134
24.3k
        ch += 1 + pair;
135
24.3k
    }
136
6.58k
    if (!ch) return;
137
37.1k
    for (uint32_t i = 0; i < ch; i++) {
138
30.5k
        uint32_t rank = faac_popcount32(mask & (spk[i] - 1u)); /* speakers before this one */
139
30.5k
        L->map[rank] = (uint8_t)i;
140
30.5k
        if (spk[i] == SPK_LFE) L->lfe = (uint8_t)i;
141
30.5k
    }
142
6.58k
    L->mask = (uint16_t)mask;
143
6.58k
    L->n = (uint8_t)ch;
144
6.58k
    L->n_el = by_tag ? (uint8_t)n : 0;
145
6.58k
}
146
147
void faad_layout_update(struct faad_decoder *dec)
148
9.27k
{
149
9.27k
    struct faad_layout *L = &dec->layout;
150
9.27k
    uint32_t cfg = dec->asc.num_channels;
151
9.27k
    if (cfg) {
152
5.20k
        if (cfg == L->cfg && L->n) return;
153
5.16k
        if (cfg < CFG_COUNT) {
154
5.16k
            uint32_t n = 0;
155
23.1k
            while (n < 5 && config_elements[cfg][n] != 0xff) n++;
156
5.16k
            layout_build(dec, config_elements[cfg], n, false);
157
5.16k
        } else {
158
0
            memset(L, 0, sizeof(*L));
159
0
        }
160
5.16k
    } else {
161
4.06k
        if (L->cfg) memset(L, 0, sizeof(*L)); /* a new layout starts, with no PCM in it yet */
162
4.06k
        if (!L->frozen && dec->asc.pce.n_el)
163
3.27k
            layout_build(dec, dec->asc.pce.el, dec->asc.pce.n_el, true);
164
4.06k
    }
165
9.22k
    L->cfg = (uint8_t)cfg;
166
9.22k
}
167
168
/* A configuration 0 stream may only get its PCE some frames in; the elements
169
 * of its first frame stand for the common configuration they match. */
170
void faad_layout_infer(struct faad_decoder *dec, uint32_t seq)
171
79
{
172
439
    for (uint32_t cfg = CFG_7_1; cfg >= CFG_3_0; cfg--) {
173
372
        uint32_t want = 1, n = 0;
174
1.65k
        for (; n < 5 && config_elements[cfg][n] != 0xff; n++) {
175
1.27k
            uint32_t e = config_elements[cfg][n];
176
1.27k
            want = want << 2 | ((e >> 5) == ASC_PCE_LFE ? ID_LFE : (e >> 4) & 1 ? ID_CPE : ID_SCE);
177
1.27k
        }
178
372
        if (want == seq) {
179
12
            layout_build(dec, cfg == CFG_7_1 ? pce_side_back_7_1 : config_elements[cfg], n, false);
180
12
            return;
181
12
        }
182
372
    }
183
79
}
184
185
/* Tags put the elements of a PCE layout in their slots wherever they sit in the
186
 * stream. A tag the PCE does not list means the writer did not number them as its
187
 * PCE does; if the elements so far are in order, the stream is read in element order. */
188
static uint32_t element_slot(faad_decoder *dec, uint32_t type, uint32_t tag, uint32_t ch_idx, uint32_t occupied)
189
12.1k
{
190
12.1k
    struct faad_layout *L = &dec->layout;
191
12.1k
    if (!L->n_el) return ch_idx;
192
577
    for (uint32_t i = 0; i < L->n_el; i++)
193
484
        if (L->el_key[i] == (type << 4 | tag)) return L->el_slot[i];
194
93
    if (occupied != (1u << ch_idx) - 1) return MAX_CHANNELS; /* an earlier element is out of order */
195
75
    L->n_el = 0;
196
75
    return ch_idx;
197
93
}
198
37.9k
#define SLOTS_BY_TAG(dec) ((dec)->layout.n_el != 0)
199
#else
200
static uint32_t element_slot(faad_decoder *dec, uint32_t type, uint32_t tag, uint32_t ch_idx, uint32_t occupied)
201
{
202
    (void)dec; (void)type; (void)tag; (void)occupied;
203
    return ch_idx;
204
}
205
#define SLOTS_BY_TAG(dec) 0
206
#endif
207
208
static bool downmix_mode_is_valid(enum faad_downmix_mode mode)
209
7.50k
{
210
7.50k
    uint32_t n = faac_popcount32((uint32_t)mode);
211
7.50k
    return mode == FAAD_DOWNMIX_NONE || (!((uint32_t)mode >> POS_COUNT) && n <= 8);
212
7.50k
}
213
214
/* Channels out of a downmix to mode, from channels in. */
215
static uint32_t downmix_out_chs(enum faad_downmix_mode mode, uint32_t channels)
216
17.8k
{
217
17.8k
    uint32_t n = faac_popcount32((uint32_t)mode);
218
17.8k
    return mode != FAAD_DOWNMIX_NONE && channels > n ? n : channels;
219
17.8k
}
220
221
/* Speakers the downmix weighs, in output order; a stream of unknown
222
 * positions is taken to follow the WAV order of its channel count. */
223
static uint32_t downmix_mask(const faad_decoder *dec, uint32_t num_chs)
224
6.42k
{
225
6.42k
    static const uint16_t canon[] = {
226
6.42k
        SPK_FRONT, SPK_FRONT, SPK_FRONT, SPK_FRONT | SPK_FC, SPK_FRONT | SPK_FC | SPK_BC,
227
6.42k
        SPK_FRONT | SPK_FC | SPK_BACK, SPK_FRONT | SPK_FC | SPK_LFE | SPK_BACK,
228
6.42k
        SPK_FRONT | SPK_FC | SPK_LFE | SPK_BC | SPK_SIDE,
229
6.42k
        SPK_FRONT | SPK_FC | SPK_LFE | SPK_BACK | SPK_SIDE };
230
6.42k
    uint32_t mask = faad_layout_mask(dec, num_chs);
231
6.42k
    return mask ? mask : canon[num_chs <= 8 ? num_chs : 0];
232
6.42k
}
233
234
0
#define DM_K 0.70710678f
235
/* A stereo target needs two rows even when the build keeps one channel. */
236
57.7k
#define DM_CH (MAX_CHANNELS < 2 ? 2 : MAX_CHANNELS)
237
/* Weighs input channel in_c into the output that carries speaker spk, if the
238
 * target layout has one. */
239
static void dm_add(float w[][DM_CH], uint32_t tm, uint32_t in_c, uint32_t spk, float v)
240
0
{
241
0
    if (tm & spk) w[faac_popcount32(tm & (spk - 1))][in_c] += v;
242
0
}
243
244
/* Time-domain downmix of channels src[], ordered as the speakers of mask, to
245
 * the speakers of the mode: surround to stereo as Lo = L + 0.707 (C + Ls),
246
 * Ro = R + 0.707 (C + Rs), a lone rear channel at half that, LFE dropped,
247
 * each output scaled so a full-scale input cannot clip; mono as (Lo + Ro) / 2.
248
 * The outputs go to dst[] (one frame_samples run each). Returns the output
249
 * channel count, num_chs itself when there is nothing to mix. */
250
static uint32_t downmix_pcm(enum faad_downmix_mode mode, const float *src[], uint32_t num_chs,
251
                            uint32_t mask, uint32_t frame_samples, float *dst[])
252
6.42k
{
253
6.42k
    bool mono = mode == FAAD_DOWNMIX_MONO;
254
6.42k
    uint32_t tm = mono ? SPK_FRONT : (uint32_t)mode, tn = faac_popcount32(tm);
255
6.42k
    if (mode == FAAD_DOWNMIX_NONE || num_chs < 2 || (!mono && num_chs <= tn))
256
6.42k
        return num_chs;
257
258
0
    float w[DM_CH][DM_CH] = {{0}};
259
0
    for (uint32_t p = 0, in = 0; p < POS_COUNT && in < num_chs; p++) {
260
0
        if (!(mask >> p & 1)) continue;
261
0
        uint32_t c = in++, spk = 1u << p;
262
0
        if (tm & spk) {
263
0
            dm_add(w, tm, c, spk, 1.0f);
264
0
            continue;
265
0
        }
266
0
        switch (p) {
267
0
        case POS_FLC: case POS_FRC:
268
0
            dm_add(w, tm, c, p == POS_FLC ? SPK_FL : SPK_FR, DM_K);
269
0
            dm_add(w, tm, c, SPK_FC, DM_K);
270
0
            break;
271
0
        case POS_FC:
272
0
            dm_add(w, tm, c, SPK_FL, DM_K);
273
0
            dm_add(w, tm, c, SPK_FR, DM_K);
274
0
            break;
275
0
        case POS_BC: {
276
0
            uint32_t pair = (tm & SPK_BACK) == SPK_BACK ? SPK_BACK
277
0
                          : (tm & SPK_SIDE) == SPK_SIDE ? SPK_SIDE : SPK_FRONT;
278
0
            dm_add(w, tm, c, pair & -pair, 0.5f * DM_K);
279
0
            dm_add(w, tm, c, pair & (pair - 1), 0.5f * DM_K);
280
0
            break;
281
0
        }
282
0
        case POS_BL: case POS_BR: case POS_SL: case POS_SR: {
283
0
            bool right = p == POS_BR || p == POS_SR, back = p == POS_BL || p == POS_BR;
284
0
            uint32_t alt = back ? (right ? SPK_SR : SPK_SL) : (right ? SPK_BR : SPK_BL);
285
0
            if (tm & alt) dm_add(w, tm, c, alt, 1.0f);
286
0
            else dm_add(w, tm, c, right ? SPK_FR : SPK_FL, DM_K);
287
0
            break;
288
0
        }
289
0
        default:
290
0
            break;
291
0
        }
292
0
    }
293
294
0
    uint32_t on = mono ? 1 : tn;
295
0
    for (uint32_t o = 0; o < tn; o++) {
296
0
        float sum = 0.0f;
297
0
        for (uint32_t c = 0; c < num_chs; c++) sum += w[o][c];
298
0
        float g = sum > 1.0f ? 1.0f / sum : 1.0f;
299
0
        for (uint32_t c = 0; c < num_chs; c++) w[o][c] *= g;
300
0
    }
301
0
    if (mono)
302
0
        for (uint32_t c = 0; c < num_chs; c++) w[0][c] = 0.5f * (w[0][c] + w[1][c]);
303
304
    /* Channel by channel over a block, in output order; dst may alias src,
305
     * which is only written once the block has been read. */
306
0
    enum { BLOCK = 64 };
307
0
    for (uint32_t b = 0; b < frame_samples; b += BLOCK) {
308
0
        uint32_t n = frame_samples - b < BLOCK ? frame_samples - b : BLOCK;
309
0
        float ob[DM_CH][BLOCK] = {{0}};
310
0
        for (uint32_t o = 0; o < on; o++)
311
0
            for (uint32_t c = 0; c < num_chs; c++)
312
0
                if (w[o][c] != 0.0f)
313
0
                    for (uint32_t i = 0; i < n; i++) ob[o][i] += w[o][c] * src[c][b + i];
314
0
        for (uint32_t o = 0; o < on; o++) memcpy(dst[o] + b, ob[o], n * sizeof(float));
315
0
    }
316
0
    return on;
317
0
}
318
319
static bool spectral_downmix_windows_match(struct faad_decoder *dec, uint32_t num_chs)
320
0
{
321
0
    if (num_chs == 7 && !faad_layout_mask(dec, 7)) return false;
322
0
    const uint8_t *map = faad_layout_map(dec, num_chs);
323
0
    uint32_t mask = downmix_mask(dec, num_chs), first = map ? map[0] : 0, lfe = UINT32_MAX;
324
0
    if (mask & SPK_LFE) {
325
0
        uint32_t out = (mask & SPK_FL ? 1 : 0) + (mask & SPK_FR ? 1 : 0) + (mask & SPK_FC ? 1 : 0);
326
0
        lfe = map ? map[out] : out;
327
0
    }
328
0
    for (uint32_t ch = 0; ch < num_chs; ch++) {
329
0
        if (ch == first || ch == lfe) continue;
330
0
        if (dec->win_seq[ch] != dec->win_seq[first]
331
0
            || dec->win_shape[ch] != dec->win_shape[first]
332
0
            || dec->prev_window_shape[ch] != dec->prev_window_shape[first])
333
0
            return false;
334
0
    }
335
0
    return true;
336
0
}
337
338
/* A spectral downmix keeps only the mixed overlap in the output-channel slots.
339
 * Rebuild source-channel overlaps from the preceding spectra when leaving that
340
 * path; the right-hand IMDCT overlap depends only on that frame's spectrum and
341
 * window, not on the older overlap that contributed to its emitted samples. */
342
static void restore_channel_overlaps(struct faad_decoder *dec, uint32_t channels,
343
                                     uint32_t prior_errors)
344
0
{
345
0
    memset(dec->overlap, 0, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG]));
346
0
    float fade = (prior_errors > 0 && prior_errors <= 5) ? powf(0.8f, (float)prior_errors)
347
0
        : prior_errors > 5 ? 0.0f : 1.0f;
348
0
    if (fade == 0.0f) return;
349
0
    float *prev_frame_spec = dec->pcm + 2 * FRAME_LEN_LONG;
350
0
    float *discard_pcm = dec->pcm + FRAME_LEN_LONG;
351
0
    for (uint32_t ch = 0; ch < channels; ch++) {
352
0
        for (int i = 0; i < FRAME_LEN_LONG; i++)
353
0
            prev_frame_spec[i] = dec->prev_spec[ch][i] * fade;
354
0
        imdct_and_window(dec, ch, dec->prev_window_seq[ch], dec->prev_window_shape[ch],
355
0
                         prev_frame_spec, discard_pcm);
356
0
    }
357
0
}
358
359
/* Combine spectra before IMDCT when every contributing channel has the same
360
 * window state. The two output overlap slots then hold the downmixed history;
361
 * callers restore channel overlaps before a window mismatch or SBR frame. */
362
static bool try_spectral_downmix(struct faad_decoder *dec, uint32_t num_chs,
363
                                 uint32_t *out_num_chs, float *pcm, bool save_history)
364
3.41k
{
365
3.41k
    enum faad_downmix_mode mode = dec->config.downmix_mode;
366
3.41k
    if ((mode != FAAD_DOWNMIX_MONO && mode != FAAD_DOWNMIX_STEREO)
367
0
        || num_chs <= 2 || !spectral_downmix_windows_match(dec, num_chs))
368
3.41k
        return false;
369
370
0
    if (num_chs < 3 || num_chs > 8) return false;
371
0
    const uint8_t *map = faad_layout_map(dec, num_chs);
372
0
    uint32_t mask = downmix_mask(dec, num_chs);
373
0
    uint32_t nl = map ? map[0] : 0, nr = map ? map[1] : 1;
374
0
    if (!dec->spectral_downmix_active) {
375
0
        const float *src[MAX_CHANNELS];
376
0
        float *dst[2] = { pcm, pcm + FRAME_LEN_LONG };
377
0
        for (uint32_t ch = 0; ch < num_chs; ch++)
378
0
            src[ch] = dec->overlap[map ? map[ch] : ch];
379
0
        uint32_t out_channels = downmix_pcm(mode, src, num_chs, mask, FRAME_LEN_LONG, dst);
380
0
        memcpy(dec->overlap[nl], dst[0], FRAME_LEN_LONG * sizeof(float));
381
0
        if (out_channels == 2)
382
0
            memcpy(dec->overlap[nr], dst[1], FRAME_LEN_LONG * sizeof(float));
383
0
    }
384
385
    /* Preserve source spectra for concealment and overlap restoration before
386
     * the in-place mix replaces the left/right channel spectra. */
387
0
    if (save_history)
388
0
        memcpy(dec->prev_spec, dec->spec, sizeof(dec->spec[0]) * num_chs);
389
390
0
    const float *src[MAX_CHANNELS];
391
0
    float *dst[2] = { dec->spec[nl], dec->spec[nr] };
392
0
    for (uint32_t ch = 0; ch < num_chs; ch++)
393
0
        src[ch] = dec->spec[map ? map[ch] : ch];
394
0
    downmix_pcm(mode, src, num_chs, mask, FRAME_LEN_LONG, dst);
395
396
0
    uint8_t seq = dec->win_seq[nl], shape = dec->win_shape[nl];
397
0
    imdct_and_window(dec, nl, seq, shape, dec->spec[nl], pcm);
398
0
    if (mode == FAAD_DOWNMIX_MONO) {
399
0
        *out_num_chs = 1;
400
0
    } else {
401
0
        imdct_and_window(dec, nr, seq, shape, dec->spec[nr], pcm + FRAME_LEN_LONG);
402
0
        *out_num_chs = 2;
403
0
    }
404
0
    for (uint32_t ch = 0; ch < num_chs; ch++) {
405
0
        dec->prev_window_shape[ch] = dec->win_shape[ch];
406
0
        dec->prev_window_seq[ch] = dec->win_seq[ch];
407
0
    }
408
0
    dec->spectral_downmix_active = true;
409
0
    dec->spectral_downmix_channels = num_chs;
410
0
    dec->spectral_downmix_layout = dec->asc.num_channels;
411
0
    return true;
412
0
}
413
414
415
FAADAPI faad_status faad_get_library_info(faad_library_info *out_info)
416
0
{
417
0
    if (!out_info || out_info->struct_size < LIBRARY_INFO_BASELINE_SIZE) {
418
0
        return FAAD_ERR_INVALID_ARGUMENT;
419
0
    }
420
0
    faad_library_info info;
421
0
    memset(&info, 0, sizeof(info));
422
0
    info.struct_size = bounded_size(out_info->struct_size, sizeof(info));
423
0
    info.version = FAAD_VERSION_STRING;
424
0
    info.copyright =
425
0
        "FAAD - Freeware Advanced Audio Decoder (https://freewareadvancedaudio.github.io)\n"
426
0
        " Copyright (C) 2026, Nils Schimmelmann\n";
427
0
    info.max_channels = MAX_CHANNELS;
428
0
#ifndef FAAD_DISABLE_SBR
429
0
    info.flags |= FAAD_LIB_SBR;
430
0
#endif
431
0
#ifndef FAAD_DISABLE_PS
432
0
    info.flags |= FAAD_LIB_PS;
433
0
#endif
434
0
#ifndef FAAD_DISABLE_DAB
435
0
    info.flags |= FAAD_LIB_DAB;
436
0
#endif
437
0
#ifndef FAAD_DISABLE_DRC
438
0
    info.flags |= FAAD_LIB_DRC;
439
0
#endif
440
441
0
    memcpy(out_info, &info, info.struct_size);
442
0
    return FAAD_OK;
443
0
}
444
445
FAADAPI faad_status faad_config_init(faad_config *config, uint32_t caller_size)
446
15.0k
{
447
15.0k
    if (!config || caller_size < CONFIG_BASELINE_SIZE) {
448
0
        return FAAD_ERR_INVALID_ARGUMENT;
449
0
    }
450
15.0k
    faad_config tmp;
451
15.0k
    uint32_t n = caller_size < sizeof(tmp) ? caller_size : (uint32_t)sizeof(tmp);
452
15.0k
    memset(&tmp, 0, sizeof(tmp));
453
15.0k
    tmp.struct_size = n;
454
15.0k
    tmp.stream_format = FAAD_STREAM_ADTS;
455
15.0k
    tmp.output_format = FAAD_OUTPUT_16BIT;
456
15.0k
    tmp.downmix_mode = FAAD_DOWNMIX_NONE;
457
15.0k
    memcpy(config, &tmp, n);
458
15.0k
    return FAAD_OK;
459
15.0k
}
460
461
static uint32_t output_sample_bytes(enum faad_output_format f)
462
20.2k
{
463
20.2k
    return f == FAAD_OUTPUT_16BIT ? 2 : f == FAAD_OUTPUT_24BIT ? 3 : 4;
464
20.2k
}
465
466
static uint32_t output_capacity(const faad_decoder *dec)
467
6.18k
{
468
6.18k
    uint32_t channels = MAX_CHANNELS;
469
6.18k
    if (dec->config.stream_format == FAAD_STREAM_RAW && dec->asc_parsed && (dec->asc.num_channels || dec->asc.pce.channels))
470
5.40k
        channels = asc_channels(&dec->asc);
471
6.18k
#ifndef FAAD_DISABLE_PS
472
6.18k
    if (channels < 2) channels = 2;
473
6.18k
#endif
474
6.18k
    channels = downmix_out_chs(dec->config.downmix_mode, channels);
475
6.18k
    uint32_t samples = FRAME_IS_960(dec) ? 960 : 1024;
476
6.18k
#ifndef FAAD_DISABLE_SBR
477
6.18k
    samples *= 2;
478
6.18k
#endif
479
6.18k
    return samples * channels * output_sample_bytes(dec->config.output_format);
480
6.18k
}
481
482
static uint32_t channel_mask(const faad_decoder *dec, uint32_t channels)
483
18.1k
{
484
18.1k
    if (channels < dec->num_channels) /* mixed: the stream is in the target layout */
485
0
        return (uint32_t)dec->config.downmix_mode;
486
18.1k
    static const uint32_t masks[] = { 0, SPK_FC, SPK_FRONT };
487
18.1k
    return channels <= 2 ? masks[channels] : faad_layout_mask(dec, channels);
488
18.1k
}
489
490
#ifndef FAAD_DISABLE_DRC
491
/* A private cursor makes truncated metadata harmless to the audio parser. */
492
static void read_drc(faad_decoder *dec, BitReader input, uint32_t end)
493
4.13k
{
494
4.13k
    uint8_t top[16], ctl[16], sign[16];
495
4.13k
    bool excluded[MAX_CHANNELS] = { false };
496
4.13k
    unsigned bands = 1, ref = 0;
497
4.13k
    bool has_ref;
498
172k
#define DRC_READ(n) (bits_get_consumed(&input) <= end && (n) <= end - bits_get_consumed(&input) ? bits_get(&input, (n)) : (bad = true, 0u))
499
4.13k
    bool bad = false;
500
4.13k
    if (DRC_READ(1)) { (void)DRC_READ(4); (void)DRC_READ(4); }
501
4.13k
    if (DRC_READ(1)) {
502
3.46k
        unsigned channel = 0;
503
3.46k
        bool more;
504
6.55k
        do {
505
52.4k
            for (unsigned i = 0; i < 7; i++, channel++) {
506
45.8k
                bool omit = DRC_READ(1) != 0;
507
45.8k
                if (channel < MAX_CHANNELS) excluded[channel] = omit;
508
45.8k
            }
509
6.55k
            more = DRC_READ(1) != 0;
510
6.55k
        } while (more && !bad);
511
3.46k
    }
512
4.13k
    bool banded = DRC_READ(1) != 0;
513
4.13k
    if (banded) {
514
2.35k
        bands += DRC_READ(4) & 0xfu;
515
2.35k
        (void)DRC_READ(4);
516
32.6k
        for (unsigned b = 0; b < bands && b < sizeof(top); b++) {
517
30.2k
            top[b] = (uint8_t)DRC_READ(8);
518
30.2k
            if (b && top[b] <= top[b - 1]) bad = true;
519
30.2k
        }
520
2.35k
    } else top[0] = 255;
521
4.13k
    has_ref = DRC_READ(1) != 0;
522
4.13k
    if (has_ref) { ref = DRC_READ(7); (void)DRC_READ(1); }
523
36.2k
    for (unsigned b = 0; b < bands; b++) {
524
32.0k
        sign[b] = (uint8_t)DRC_READ(1);
525
32.0k
        ctl[b] = (uint8_t)DRC_READ(7);
526
32.0k
    }
527
4.13k
#undef DRC_READ
528
4.13k
    if (bad) return;
529
1.78k
    dec->drc.present = true;
530
1.78k
    dec->drc.bands = (uint8_t)bands;
531
1.78k
    memcpy(dec->drc.top, top, bands);
532
1.78k
    memcpy(dec->drc.ctl, ctl, bands);
533
1.78k
    memcpy(dec->drc.sign, sign, bands);
534
1.78k
    memcpy(dec->drc.excluded, excluded, sizeof(excluded));
535
1.78k
    if (has_ref) { dec->drc.ref = (uint8_t)ref; dec->drc.ref_present = true; }
536
1.78k
}
537
538
static void apply_drc(faad_decoder *dec)
539
176
{
540
176
    float gain[16];
541
1.58k
    for (unsigned c = 0; c < MAX_CHANNELS; c++) dec->drc.sbr_gain[c] = 1.0f;
542
465
    for (unsigned b = 0; b < dec->drc.bands; b++) {
543
289
        float scale = dec->drc.sign[b] ? -(float)dec->config.drc_cut : (float)dec->config.drc_boost;
544
        /* One control step is 1/24 octave, the step the encoders that emit
545
         * these gains assume; plain 0.25 dB would drift by 0.3 %. */
546
289
        gain[b] = exp2f(dec->drc.ctl[b] * scale / (127.0f * 24.0f));
547
289
    }
548
909
    for (unsigned c = 0; c < dec->num_channels; c++) {
549
733
        if (dec->drc.excluded[c]) continue;
550
591
        unsigned windows = dec->win_seq[c] == EIGHT_SHORT_SEQUENCE ? 8 : 1;
551
591
        unsigned length = (FRAME_IS_960(dec) ? 960 : 1024) / windows;
552
591
        unsigned start = 0;
553
1.63k
        for (unsigned b = 0; b < dec->drc.bands; b++) {
554
1.03k
            unsigned end = 4u * (dec->drc.top[b] + 1u) / windows;
555
1.03k
            if (end > length) end = length;
556
1.03k
            if (gain[b] != 1.0f && end > start) {
557
741
                dec->drc.applied = true;
558
741
                if (gain[b] > 1.0f) dec->drc.boost = true;
559
3.05k
                for (unsigned w = 0; w < windows; w++)
560
384k
                    for (unsigned i = start; i < end; i++) dec->spec[c][w * length + i] *= gain[b];
561
741
            }
562
1.03k
            start = end;
563
1.03k
        }
564
        /* The HF envelope is absolute energy, independent of core amplitude. */
565
591
        dec->drc.sbr_gain[c] = gain[dec->drc.bands - 1] * gain[dec->drc.bands - 1];
566
591
    }
567
176
}
568
569
/* Keep all PCM arithmetic out of the disabled path. */
570
static bool drc_output(faad_decoder *dec, const float *src[], uint32_t num_chs,
571
                       uint32_t frame_samples, void *out_pcm)
572
6.41k
{
573
6.41k
    float target_gain = dec->config.drc_target_level != 0.0f && dec->drc.ref_present
574
6.41k
        ? exp2f(((float)dec->drc.ref + 4.0f * dec->config.drc_target_level) / 24.0f) : 1.0f;
575
6.41k
    float previous_gain = dec->drc.previous_norm ? dec->drc.previous_norm : 1.0f;
576
6.41k
    if (target_gain != 1.0f || previous_gain != 1.0f || (dec->drc.boost && dec->config.output_format != FAAD_OUTPUT_FLOAT)) {
577
181
        bool floating = dec->config.output_format == FAAD_OUTPUT_FLOAT;
578
181
        bool limit = target_gain > 1.0f || previous_gain > 1.0f || dec->drc.boost;
579
181
        float norm = target_gain / 32768.0f;
580
181
        float ramp = (target_gain - previous_gain) / frame_samples;
581
228k
        for (uint32_t i = 0; i < frame_samples; i++) {
582
228k
            float gain = ramp == 0.0f ? norm : (previous_gain + ramp * (i + 1)) / 32768.0f;
583
1.25M
            for (uint32_t c = 0; c < num_chs; c++) {
584
1.02M
                float sample = src[c][i] * gain;
585
1.02M
                if (floating) ((float *)out_pcm)[i * num_chs + c] = sample;
586
735k
                else {
587
735k
                    float magnitude = fabsf(sample);
588
735k
                    if (limit && magnitude > 0.89f)
589
25.0k
                        sample = copysignf(0.89f + 0.11f * (1.0f - 1.0f / (1.0f + (magnitude - 0.89f) / 0.11f)), sample);
590
735k
                    ((float *)src[c])[i] = sample * 32768.0f;
591
735k
                }
592
1.02M
            }
593
228k
        }
594
181
        if (target_gain != 1.0f || previous_gain != 1.0f) dec->drc.applied = true;
595
181
        if (floating) {
596
42
            dec->drc.previous_norm = target_gain;
597
42
            return true;
598
42
        }
599
181
    }
600
6.37k
    dec->drc.previous_norm = target_gain;
601
6.37k
    return false;
602
6.41k
}
603
604
#endif
605
606
static faad_status resolve_config(const faad_config *cfg, faad_config *resolved)
607
7.50k
{
608
7.50k
    faad_config_init(resolved, sizeof(*resolved));
609
7.50k
    if (!cfg) return FAAD_OK;
610
7.50k
    if (cfg->struct_size < CONFIG_BASELINE_SIZE) return FAAD_ERR_INVALID_ARGUMENT;
611
    /* Absent or partially supplied fields keep defaults.
612
     * Never memcpy a partially supplied scalar or read beyond the caller. */
613
7.50k
#define COPY_CONFIG_FIELD(field) \
614
45.0k
    if (cfg->struct_size >= offsetof(faad_config, field) + sizeof(cfg->field)) \
615
45.0k
        resolved->field = cfg->field
616
7.50k
    COPY_CONFIG_FIELD(stream_format);
617
7.50k
    COPY_CONFIG_FIELD(output_format);
618
7.50k
    COPY_CONFIG_FIELD(downmix_mode);
619
7.50k
#ifndef FAAD_DISABLE_DRC
620
7.50k
    COPY_CONFIG_FIELD(drc_cut);
621
7.50k
    COPY_CONFIG_FIELD(drc_boost);
622
7.50k
    COPY_CONFIG_FIELD(drc_target_level);
623
7.50k
    if (resolved->drc_cut > 127 || resolved->drc_boost > 127
624
7.50k
        || (resolved->drc_target_level != 0.0f
625
7.50k
            && !(resolved->drc_target_level >= -31.75f && resolved->drc_target_level <= -10.0f)))
626
0
        return FAAD_ERR_INVALID_ARGUMENT;
627
7.50k
    resolved->drc_target_level = roundf(4.0f * resolved->drc_target_level) / 4.0f;
628
7.50k
#endif
629
7.50k
#undef COPY_CONFIG_FIELD
630
7.50k
    return (resolved->stream_format == FAAD_STREAM_RAW || resolved->stream_format == FAAD_STREAM_ADTS)
631
7.50k
        && (resolved->output_format == FAAD_OUTPUT_16BIT || resolved->output_format == FAAD_OUTPUT_24BIT
632
3.50k
            || resolved->output_format == FAAD_OUTPUT_24IN32 || resolved->output_format == FAAD_OUTPUT_FLOAT)
633
7.50k
        && downmix_mode_is_valid(resolved->downmix_mode) ? FAAD_OK : FAAD_ERR_INVALID_ARGUMENT;
634
7.50k
}
635
636
static void faad_init_global_tables_impl(void)
637
2
{
638
2
    extern void init_dequant_tables(void);
639
2
    extern void init_huffman_luts(void);
640
2
    extern void init_windows(void);
641
2
#ifndef FAAD_DISABLE_SBR
642
2
    extern void init_qmf_twiddles(void);
643
2
#endif
644
2
    extern void init_is_tables(void);
645
2
#ifndef FAAD_DISABLE_PS
646
2
    extern void init_ps_tables(void);
647
2
#endif
648
649
2
    init_dequant_tables();
650
2
    init_huffman_luts();
651
2
    init_windows();
652
2
#ifndef FAAD_DISABLE_SBR
653
2
    init_qmf_twiddles();
654
2
#endif
655
2
    init_is_tables();
656
2
#ifndef FAAD_DISABLE_PS
657
2
    init_ps_tables();
658
2
#endif
659
2
}
660
661
void faad_init_global_tables(void)
662
7.50k
{
663
7.50k
    static faac_once_t once = FAAC_ONCE_INIT;
664
7.50k
    faac_once_run(&once, faad_init_global_tables_impl);
665
7.50k
}
666
667
static faad_status init_decoder(faad_decoder *dec, const faad_config *resolved,
668
                                const uint8_t *asc_buf, uint32_t asc_len,
669
                                faad_decoder **out_dec)
670
7.50k
{
671
7.50k
    dec->config = *resolved;
672
673
7.50k
    dec->pns_seed = 0x12345678;
674
675
7.50k
    if (asc_buf && asc_len > 0) {
676
6.71k
        BitReader bs;
677
6.71k
        bits_init(&bs, asc_buf, asc_len);
678
6.71k
        faad_status st = asc_decode(&bs, &dec->asc);
679
6.71k
        if (st != FAAD_OK) return st;
680
681
5.52k
        dec->num_channels = asc_channels(&dec->asc);
682
5.52k
        if (dec->num_channels > MAX_CHANNELS) return FAAD_ERR_UNSUPPORTED;
683
5.52k
        dec->core_sample_rate = dec->asc.sample_rate ? dec->asc.sample_rate : 44100;
684
5.52k
        if (get_sr_index(dec->core_sample_rate) < 0) return FAAD_ERR_UNSUPPORTED;
685
5.40k
        dec->sample_rate = dec->asc.is_sbr ? dec->asc.sbr_sample_rate : dec->core_sample_rate;
686
5.40k
        uint32_t core_samples = FRAME_IS_960(dec) ? 960 : 1024;
687
5.40k
        dec->frame_samples = dec->asc.is_sbr ? (core_samples * 2) : core_samples;
688
5.40k
        dec->asc_parsed = true;
689
5.40k
        faad_layout_update(dec);
690
5.40k
        dec->format_known = dec->asc.num_channels != 0 || dec->asc.pce.channels != 0;
691
5.40k
        dec->sbr_seen = dec->asc.is_sbr;
692
5.40k
        dec->ps_seen = dec->asc.is_ps;
693
5.40k
    } else {
694
788
        dec->num_channels = MAX_CHANNELS < 2 ? 1 : 2;
695
788
        dec->sample_rate = 44100;
696
788
        dec->core_sample_rate = 44100;
697
788
        dec->frame_samples = 1024;
698
788
    }
699
6.18k
    dec->core_channels = dec->num_channels;
700
6.18k
    dec->max_output_bytes = output_capacity(dec);
701
702
#ifdef FAAD_STATS
703
    if (g_faadStats.dumpFile) fclose(g_faadStats.dumpFile);
704
    memset(&g_faadStats, 0, sizeof(g_faadStats));
705
#endif
706
6.18k
    *out_dec = dec;
707
6.18k
    return FAAD_OK;
708
7.50k
}
709
710
static void free_split_state(faad_decoder *dec)
711
7.50k
{
712
7.50k
    if (!dec) return;
713
60.0k
#define FREE_PART(field) do { if (dec->field) FreeMemory(dec->field); } while (0)
714
7.50k
#if MAX_CHANNELS >= 3
715
8.66k
    while (dec->coupling) {
716
1.16k
        CouplingChannel *next = dec->coupling->next;
717
1.16k
        if (dec->coupling->overlap) FreeMemory(dec->coupling->overlap);
718
1.16k
        FreeMemory(dec->coupling);
719
1.16k
        dec->coupling = next;
720
1.16k
    }
721
7.50k
#endif
722
7.50k
    FREE_PART(spec);
723
7.50k
    FREE_PART(overlap);
724
7.50k
    FREE_PART(prev_spec);
725
7.50k
#ifndef FAAD_DISABLE_SBR
726
7.50k
    FREE_PART(sbr);
727
7.50k
    FREE_PART(sbr_el);
728
7.50k
    FREE_PART(sbr_scratch.y);
729
7.50k
#endif
730
7.50k
#ifndef FAAD_DISABLE_PS
731
7.50k
    FREE_PART(ps);
732
7.50k
#endif
733
#if defined(FAAD_DISABLE_SBR) || MAX_CHANNELS < 2
734
    FREE_PART(scratch);
735
#endif
736
7.50k
    FREE_PART(pcm);
737
7.50k
    FreeMemory(dec);
738
7.50k
#undef FREE_PART
739
7.50k
}
740
741
#ifndef FAAD_DISABLE_SBR
742
static faad_status alloc_optional(faad_decoder *dec, void **ptr, size_t size)
743
282k
{
744
282k
    if (*ptr) return FAAD_OK;
745
8.02k
    *ptr = AllocMemory(size);
746
8.02k
    if (!*ptr) return FAAD_ERR_NO_MEMORY;
747
8.02k
    memset(*ptr, 0, size);
748
8.02k
    dec->allocated_bytes += size;
749
8.02k
    if (size > dec->largest_allocation) dec->largest_allocation = size;
750
8.02k
    return FAAD_OK;
751
8.02k
}
752
753
faad_status faad_ensure_sbr(faad_decoder *dec)
754
92.2k
{
755
92.2k
    if (alloc_optional(dec, (void **)&dec->sbr, sizeof(SBRChannel[MAX_CHANNELS])) != FAAD_OK
756
92.2k
        || alloc_optional(dec, (void **)&dec->sbr_el, sizeof(SBRElement[MAX_CHANNELS])) != FAAD_OK
757
92.2k
        || alloc_optional(dec, (void **)&dec->sbr_scratch.y,
758
92.2k
                          sizeof(float[SBR_MAX_BANDS][SBR_BUF_SLOTS][2])) != FAAD_OK)
759
0
        return FAAD_ERR_NO_MEMORY;
760
92.2k
    dec->sbr_scratch.x_low = dec->sbr_scratch.y;
761
92.2k
    return FAAD_OK;
762
92.2k
}
763
764
#ifndef FAAD_DISABLE_PS
765
faad_status faad_ensure_ps(faad_decoder *dec)
766
5.84k
{
767
5.84k
    return alloc_optional(dec, (void **)&dec->ps, sizeof(PSState));
768
5.84k
}
769
#endif
770
#endif
771
772
30.0k
#define ALLOC_PART(field, size) do { \
773
30.0k
    dec->field = AllocMemory(size); \
774
30.0k
    if (!dec->field) { free_split_state(dec); return FAAD_ERR_NO_MEMORY; } \
775
30.0k
    memset(dec->field, 0, size); \
776
30.0k
    dec->allocated_bytes += (size); \
777
30.0k
    if ((size) > dec->largest_allocation) dec->largest_allocation = (size); \
778
30.0k
} while (0)
779
780
FAADAPI faad_status faad_decoder_open(const faad_config *config,
781
                                      const uint8_t *asc_buf, uint32_t asc_len,
782
                                      faad_decoder **out)
783
7.50k
{
784
7.50k
    if (!out) return FAAD_ERR_INVALID_ARGUMENT;
785
7.50k
    *out = NULL;
786
7.50k
    faad_config resolved;
787
7.50k
    if (resolve_config(config, &resolved) != FAAD_OK
788
7.50k
        || ((asc_buf == NULL) != (asc_len == 0))
789
7.50k
        || (resolved.stream_format == FAAD_STREAM_RAW && !asc_len))
790
0
        return FAAD_ERR_INVALID_ARGUMENT;
791
7.50k
    faad_init_global_tables();
792
7.50k
    faad_decoder *dec = AllocMemory(sizeof(*dec));
793
7.50k
    if (!dec) return FAAD_ERR_NO_MEMORY;
794
7.50k
    memset(dec, 0, sizeof(*dec));
795
7.50k
    dec->allocated_bytes = sizeof(*dec);
796
7.50k
    dec->largest_allocation = sizeof(*dec);
797
7.50k
    ALLOC_PART(spec, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG]));
798
7.50k
    ALLOC_PART(overlap, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG]));
799
7.50k
    ALLOC_PART(prev_spec, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG]));
800
7.50k
    ALLOC_PART(pcm, sizeof(float[MAX_CHANNELS * FRAME_SAMPLES_MAX]));
801
7.50k
#if !defined(FAAD_DISABLE_SBR) && MAX_CHANNELS >= 2
802
    /* Core PCM is packed into the first half until every IMDCT finishes. */
803
7.50k
    dec->scratch = (FrameScratch *)(dec->pcm + MAX_CHANNELS * FRAME_LEN_LONG);
804
#else
805
    ALLOC_PART(scratch, sizeof(FrameScratch));
806
#endif
807
7.50k
    faad_status st = init_decoder(dec, &resolved, asc_buf, asc_len, out);
808
7.50k
    if (st != FAAD_OK) { free_split_state(dec); return st; }
809
6.18k
#ifndef FAAD_DISABLE_SBR
810
6.18k
    if (dec->asc.is_sbr && faad_ensure_sbr(dec) != FAAD_OK) st = FAAD_ERR_NO_MEMORY;
811
6.18k
#ifndef FAAD_DISABLE_PS
812
6.18k
    if (st == FAAD_OK && dec->asc.is_ps && faad_ensure_ps(dec) != FAAD_OK)
813
0
        st = FAAD_ERR_NO_MEMORY;
814
6.18k
#endif
815
6.18k
#endif
816
6.18k
    if (st != FAAD_OK) { *out = NULL; free_split_state(dec); }
817
6.18k
    return st;
818
7.50k
}
819
#undef ALLOC_PART
820
821
#ifdef FAAD_STATS
822
faadDecStats g_faadStats;
823
824
static void faad_print_stats(void)
825
{
826
    const faadDecStats *s = &g_faadStats;
827
    if (s->totalFrames == 0) return;
828
829
    double tns_pct = s->icsCount > 0 ? 100.0 * s->tnsActiveFrames / s->icsCount : 0.0;
830
    double sbr_pct = s->totalFrames > 0 ? 100.0 * s->sbrActiveFrames / s->totalFrames : 0.0;
831
    double short_pct = s->icsCount > 0 ? 100.0 * s->shortBlockIcsCount / s->icsCount : 0.0;
832
    double pad_avg = s->fillElementCount > 0 ? (double)s->fillElementPadBitsSum / s->fillElementCount : 0.0;
833
    /* Percentages of scalefactor bands, counted per channel slot. */
834
    double ms_pct = s->totalBands > 0 ? 100.0 * s->msBands / s->totalBands : 0.0;
835
    double is_pct = s->totalBands > 0 ? 100.0 * s->isBands / s->totalBands : 0.0;
836
    double pns_pct = s->totalBands > 0 ? 100.0 * s->pnsBands / s->totalBands : 0.0;
837
838
    fprintf(stderr, "\n--- Decoder Diagnostics ---\n");
839
    fprintf(stderr, " Frames              : %u (non-END termination: %u)\n",
840
            s->totalFrames, s->nonEndTermination);
841
    fprintf(stderr, " Elements            : SCE=%u CPE=%u CCE=%u LFE=%u DSE=%u PCE=%u FIL=%u END=%u\n",
842
            s->elementCounts[0], s->elementCounts[1], s->elementCounts[2], s->elementCounts[3],
843
            s->elementCounts[4], s->elementCounts[5], s->elementCounts[6], s->elementCounts[7]);
844
    if (s->minChannels == s->maxChannels) {
845
        fprintf(stderr, " Channels            : %u (constant, 0 changes)\n", s->minChannels);
846
    } else {
847
        fprintf(stderr, " Channels            : varied %u-%u (%u changes)\n",
848
                s->minChannels, s->maxChannels, s->channelCountChanges);
849
    }
850
    fprintf(stderr, " TNS                 : active in %u/%u ics (%.1f%%)\n",
851
            s->tnsActiveFrames, s->icsCount, tns_pct);
852
    fprintf(stderr, " SBR                 : active in %u/%u frames (%.1f%%)\n",
853
            s->sbrActiveFrames, s->totalFrames, sbr_pct);
854
    fprintf(stderr, " SBR payloads        : %u headers, %u envelopes\n",
855
            s->sbrHeaderCount, s->sbrEnvelopeSum);
856
    fprintf(stderr, " Parametric stereo   : active in %u/%u frames\n",
857
            s->psActiveFrames, s->totalFrames);
858
    fprintf(stderr, " Short blocks        : %u/%u ics (%.1f%%)\n",
859
            s->shortBlockIcsCount, s->icsCount, short_pct);
860
    fprintf(stderr, " M/S, IS, PNS bands  : %.1f%% / %.1f%% / %.1f%% of %lu total\n",
861
            ms_pct, is_pct, pns_pct, s->totalBands);
862
863
    fprintf(stderr, " ESCBOOK magnitude   : %u values needed the >=16 escape path\n",
864
            s->escbookMagnitudeEscapes);
865
    fprintf(stderr, " Fill-elt pad-align  : %u elements, avg %.1f bits, max %u bits\n",
866
            s->fillElementCount, pad_avg, s->fillElementMaxPad);
867
    fprintf(stderr, " Error concealment   : %u frames\n", s->errorConcealmentFrames);
868
    fprintf(stderr, "---------------------------\n");
869
}
870
#endif
871
872
FAADAPI faad_status faad_decoder_close(faad_decoder **decoder)
873
6.18k
{
874
6.18k
    if (!decoder) return FAAD_ERR_INVALID_ARGUMENT;
875
6.18k
    faad_decoder *dec = *decoder;
876
6.18k
    if (!dec) return FAAD_OK;
877
6.18k
    *decoder = NULL;
878
#ifdef FAAD_STATS
879
    faad_print_stats();
880
    if (g_faadStats.dumpFile) fclose(g_faadStats.dumpFile);
881
    g_faadStats.dumpFile = NULL;
882
    g_faadStats.dumpOpenTried = false;
883
#endif
884
6.18k
    free_split_state(dec);
885
6.18k
    return FAAD_OK;
886
6.18k
}
887
888
FAADAPI faad_status faad_decoder_get_info(const faad_decoder *decoder, faad_stream_info *out_info)
889
12.4k
{
890
12.4k
    if (!decoder || !out_info || out_info->struct_size < STREAM_INFO_BASELINE_SIZE)
891
0
        return FAAD_ERR_INVALID_ARGUMENT;
892
12.4k
    faad_stream_info info;
893
12.4k
    memset(&info, 0, sizeof(info));
894
12.4k
    info.struct_size = bounded_size(out_info->struct_size, sizeof(info));
895
12.4k
    info.max_output_bytes = decoder->max_output_bytes;
896
12.4k
    if (decoder->format_known) info.flags |= FAAD_STREAM_FORMAT_KNOWN;
897
12.4k
#ifndef FAAD_DISABLE_DRC
898
12.4k
    info.drc_ref_level = -0.25f * (float)decoder->drc.ref;
899
12.4k
    if (decoder->drc.ref_present) info.flags |= FAAD_STREAM_DRC_REF_LEVEL;
900
12.4k
#endif
901
12.4k
    if (!(info.flags & FAAD_STREAM_FORMAT_KNOWN)) {
902
788
        memcpy(out_info, &info, info.struct_size);
903
788
        return FAAD_OK;
904
788
    }
905
12.4k
    bool sbr = decoder->asc.is_sbr || decoder->sbr_seen;
906
11.7k
    info.sample_rate = decoder->core_sample_rate;
907
11.7k
    uint32_t core_samples = FRAME_IS_960(decoder) ? 960 : 1024;
908
11.7k
    info.frame_samples = core_samples;
909
11.7k
#ifndef FAAD_DISABLE_SBR
910
11.7k
    if (sbr) { info.sample_rate *= 2; info.frame_samples = core_samples * 2; }
911
11.7k
#endif
912
11.7k
    info.channels = decoder->num_channels;
913
11.7k
#ifndef FAAD_DISABLE_PS
914
11.7k
    if (decoder->ps_seen && info.channels == 1) info.channels = 2;
915
11.7k
#endif
916
11.7k
    info.channels = downmix_out_chs(decoder->config.downmix_mode, info.channels);
917
11.7k
    info.object_type = (decoder->asc.is_ps || decoder->ps_seen) ? FAAD_OBJ_HE_AAC_V2
918
11.7k
        : sbr ? FAAD_OBJ_HE_AAC_V1 : FAAD_OBJ_LC;
919
11.7k
#ifndef FAAD_DISABLE_SBR
920
11.7k
    info.decoder_delay = sbr ? 2 * FAAD_SBR_CORE_DELAY : 0;
921
11.7k
#endif
922
11.7k
    info.channel_mask = channel_mask(decoder, info.channels);
923
11.7k
    if (decoder->pcm_emitted) {
924
1.59k
        info.sample_rate = decoder->emitted_format.sample_rate;
925
1.59k
        info.channels = decoder->emitted_format.channels;
926
1.59k
        info.frame_samples = decoder->emitted_format.frame_samples;
927
1.59k
        info.channel_mask = decoder->emitted_format.channel_mask;
928
1.59k
        info.decoder_delay = decoder->emitted_format.decoder_delay;
929
1.59k
    }
930
11.7k
    memcpy(out_info, &info, info.struct_size);
931
932
11.7k
    return FAAD_OK;
933
12.4k
}
934
935
FAADAPI faad_status faad_decoder_flush(faad_decoder *decoder)
936
3.50k
{
937
3.50k
    if (!decoder) return FAAD_ERR_INVALID_ARGUMENT;
938
939
3.50k
    memset(decoder->overlap, 0, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG]));
940
3.50k
    memset(decoder->spec, 0, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG]));
941
3.50k
    memset(decoder->prev_spec, 0, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG]));
942
3.50k
    memset(decoder->prev_window_shape, 0, sizeof(decoder->prev_window_shape));
943
3.50k
    memset(decoder->prev_window_seq, 0, sizeof(decoder->prev_window_seq));
944
3.50k
    memset(decoder->win_shape, 0, sizeof(decoder->win_shape));
945
3.50k
    memset(decoder->win_seq, 0, sizeof(decoder->win_seq));
946
3.50k
#ifndef FAAD_DISABLE_SBR
947
3.50k
    memset(decoder->elem_nch, 0, sizeof(decoder->elem_nch));
948
3.50k
#endif
949
3.50k
    memset(decoder->pcm, 0, sizeof(float[MAX_CHANNELS * FRAME_SAMPLES_MAX]));
950
3.50k
    decoder->spectral_downmix_active = false;
951
3.50k
    decoder->spectral_downmix_channels = 0;
952
3.50k
    decoder->spectral_downmix_layout = 0;
953
3.50k
#ifndef FAAD_DISABLE_DRC
954
3.50k
    memset(&decoder->drc, 0, sizeof(decoder->drc));
955
3.50k
#endif
956
3.50k
    decoder->consecutive_errors = 0;
957
3.50k
    decoder->pns_seed = 0x12345678;
958
3.50k
#if MAX_CHANNELS >= 3
959
3.79k
    for (CouplingChannel *cc = decoder->coupling; cc; cc = cc->next) {
960
294
        if (cc->overlap) memset(cc->overlap, 0, sizeof(float[FRAME_LEN_LONG]));
961
294
        cc->prev_shape = 0;
962
294
        cc->present = false;
963
294
    }
964
3.50k
#endif
965
3.50k
#ifndef FAAD_DISABLE_SBR
966
3.50k
    if (decoder->sbr) memset(decoder->sbr, 0, sizeof(SBRChannel[MAX_CHANNELS]));
967
3.50k
    if (decoder->sbr_el) memset(decoder->sbr_el, 0, sizeof(SBRElement[MAX_CHANNELS]));
968
3.50k
#endif
969
3.50k
#ifndef FAAD_DISABLE_PS
970
3.50k
    if (decoder->ps) memset(decoder->ps, 0, sizeof(PSState));
971
3.50k
#endif
972
3.50k
    decoder->sbr_present = false;
973
3.50k
    decoder->ps_present = false;
974
975
3.50k
    return FAAD_OK;
976
3.50k
}
977
978
979
#ifdef FAAD_STATS
980
/* Per-frame record of what the encoder chose, appended to the file named by
981
 * FAAD_DUMP, so streams from different encoders can be diffed decision by
982
 * decision. One line per record, first field the type, second the frame:
983
 *   C frame ch bits win_seq max_sfb groups global_gain | cb:sf:nnz:ms ... / ...
984
 *       one per ICS; bits is the whole element (both channels of a CPE, and
985
 *       the second channel of a CPE carries ms_mask_present there instead)
986
 *   H frame nch amp_res start stop xover freq_scale alter_scale noise_bands
987
 *     limiter_bands limiter_gains interpol smoothing reset kx M n_low n_high n_q e1 e2
988
 *   F frame ch class L_E L_Q freq_res amp_res invf harm_flag n_harm coupling -1 E_dB Q_dB
989
 *   G frame ch class L_E pointer t_E...
990
 *   P frame iid icc num_env
991
 *   PM frame iid_mode icc_mode phase iid_count icc_count phase_count frame_class
992
 *       mode is -1 when disabled; IID modes 0..2 are coarse and 3..5 fine
993
 *   PE frame env border iid... | icc... | ipd... | opd...
994
 *       each vector contains only its enabled parameter count from PM
995
 *   B frame total hdr sect sf spec aux sbr ps fill
996
 *       bits by syntax part; sect/sf/spec/aux (pulse, TNS) sum over the ics,
997
 *       sbr excludes ps, fill is pad after the SBR payload, and the
998
 *       remainder of total is element and ics headers */
999
FILE *faad_dump_file(void)
1000
{
1001
    faadDecStats *st = &g_faadStats;
1002
    if (!st->dumpOpenTried) {
1003
        st->dumpOpenTried = true;
1004
        const char *path = getenv("FAAD_DUMP");
1005
        if (path && *path) st->dumpFile = fopen(path, "a");
1006
    }
1007
    return st->dumpFile;
1008
}
1009
1010
static void core_dump_ics(int ch, const ICSInfo *ics, const float *spec,
1011
                          const uint8_t (*ms)[MAX_SFB], unsigned bits)
1012
{
1013
    FILE *df = faad_dump_file();
1014
    if (!df) return;
1015
    fprintf(df, "C %u %d %u %u %u %u %u |", g_faadStats.totalFrames, ch, bits, ics->window_sequence,
1016
            ics->max_sfb, ics->num_window_groups, ics->global_gain);
1017
    int wo = 0;
1018
    for (int g = 0; g < ics->num_window_groups && g < 8; g++) {
1019
        for (int sfb = 0; sfb < ics->max_sfb && sfb < MAX_SFB; sfb++) {
1020
            int nnz = 0;
1021
            for (int w = 0; w < ics->window_group_length[g]; w++)
1022
                for (int k = ics->sfb_offsets[sfb]; k < ics->sfb_offsets[sfb + 1] && k < 1024; k++)
1023
                    nnz += spec[(wo + w) * 128 + k] != 0.0f;
1024
            fprintf(df, " %u:%d:%d:%d", ics->sfb_cb[g][sfb], ics->scalefactors[g][sfb], nnz,
1025
                    ms ? ms[g][sfb] : 0);
1026
        }
1027
        fprintf(df, " /");
1028
        wo += ics->window_group_length[g];
1029
    }
1030
    fprintf(df, "\n");
1031
}
1032
#endif
1033
1034
/* Clamp and round to nearest: truncating toward zero costs the output half
1035
 * an LSB of error against any rounding decoder, on every sample. */
1036
static inline int16_t pcm_to_s16(float v)
1037
15.0M
{
1038
    /* Clamp, then let the FPU round: adding 1.5*2^23 leaves the rounded
1039
     * integer in the low mantissa bits. Straight-line float ops and one
1040
     * narrowing, so the loops vectorise where copysign + convert did not. */
1041
15.0M
    v = v < 32767.0f ? v : 32767.0f;
1042
15.0M
    v = v > -32768.0f ? v : -32768.0f;
1043
15.0M
    v += 12582912.0f;
1044
    /* A union, not memcpy: with -fno-builtin (ESP-IDF on Xtensa) memcpy becomes a call per sample. */
1045
15.0M
    union { float f; int32_t i; } u;
1046
15.0M
    u.f = v;
1047
15.0M
    return (int16_t)u.i;
1048
15.0M
}
1049
1050
/* Both integer 24-bit containers share scaling, rounding and clipping. */
1051
static inline int32_t pcm_to_s24(float v)
1052
4.36M
{
1053
4.36M
    v *= 256.0f;
1054
4.36M
    v = v < 8388607.0f ? v : 8388607.0f;
1055
4.36M
    v = v > -8388608.0f ? v : -8388608.0f;
1056
4.36M
    return (int32_t)lrintf(v);
1057
4.36M
}
1058
1059
FAADAPI faad_status faad_decode_frame(faad_decoder *decoder,
1060
                                      const uint8_t *in_buf, uint32_t in_bytes,
1061
                                      uint32_t *bytes_consumed,
1062
                                      void *out_pcm, uint32_t out_cap_bytes,
1063
                                      uint32_t *bytes_written,
1064
                                      uint32_t *frame_flags)
1065
7.66k
{
1066
7.66k
    if (bytes_consumed) *bytes_consumed = 0;
1067
7.66k
    if (bytes_written) *bytes_written = 0;
1068
7.66k
    if (frame_flags) *frame_flags = 0;
1069
7.66k
    if (!decoder || !in_buf || !bytes_consumed || !out_pcm || !bytes_written)
1070
0
        return FAAD_ERR_INVALID_ARGUMENT;
1071
    /* RAW lengths enter bit-count arithmetic directly. ADTS lengths are
1072
     * bounded by the 13-bit frame header before payload parsing. */
1073
7.66k
    if (decoder->config.stream_format == FAAD_STREAM_RAW && in_bytes > UINT32_MAX / 8)
1074
0
        return FAAD_ERR_INVALID_ARGUMENT;
1075
7.66k
    uint32_t sample_bytes = output_sample_bytes(decoder->config.output_format);
1076
7.66k
    if (sample_bytes != 3 && ((uintptr_t)out_pcm & (sample_bytes - 1)))
1077
0
        return FAAD_ERR_INVALID_ARGUMENT;
1078
7.66k
    if (out_cap_bytes < decoder->max_output_bytes) return FAAD_ERR_OUTPUT_TOO_SMALL;
1079
7.66k
    if (!in_bytes) return FAAD_ERR_NEED_MORE_DATA;
1080
7.66k
    const uint32_t prior_channels = decoder->num_channels;
1081
7.66k
    const uint32_t prior_errors = decoder->consecutive_errors;
1082
1083
7.66k
    BitReader bs;
1084
7.66k
    bits_init(&bs, in_buf, in_bytes);
1085
7.66k
    uint32_t adts_frame_len = in_bytes;
1086
1087
7.66k
    if (decoder->config.stream_format == FAAD_STREAM_ADTS) {
1088
        /* Validate framing without touching the instance. Preserve a split
1089
         * syncword rather than silently eating its first byte. */
1090
1.14k
        if (in_buf[0] == 0xff && in_bytes == 1) return FAAD_ERR_NEED_MORE_DATA;
1091
1.11k
        if (in_bytes < 2 || in_buf[0] != 0xff || (in_buf[1] & 0xf6) != 0xf0) {
1092
357
            uint32_t skip = 1;
1093
4.93M
            while (skip + 1 < in_bytes && !(in_buf[skip] == 0xff
1094
4.93M
                && (in_buf[skip + 1] & 0xf6) == 0xf0)) skip++;
1095
357
            if (skip + 1 >= in_bytes) skip = in_bytes - (in_buf[in_bytes - 1] == 0xff);
1096
357
            *bytes_consumed = skip;
1097
357
            return FAAD_ERR_SYNC_LOST;
1098
357
        }
1099
760
        uint32_t header_bytes = (in_buf[1] & 1) ? 7 : 9;
1100
760
        if (in_bytes < header_bytes) return FAAD_ERR_NEED_MORE_DATA;
1101
740
        adts_frame_len = ((uint32_t)(in_buf[3] & 3) << 11)
1102
740
            | ((uint32_t)in_buf[4] << 3) | (in_buf[5] >> 5);
1103
740
        if (adts_frame_len < header_bytes) {
1104
10
            *bytes_consumed = 1;
1105
10
            return FAAD_ERR_DECODE_FAILED;
1106
10
        }
1107
730
        if (adts_frame_len > in_bytes) return FAAD_ERR_NEED_MORE_DATA;
1108
530
        AudioSpecificConfig asc;
1109
530
        faad_status st = adts_decode_header(&bs, &asc, &adts_frame_len);
1110
530
        if (st != FAAD_OK || config_channels(asc.num_channels) > MAX_CHANNELS) {
1111
            /* An invalid header is a false sync, so its length field cannot be
1112
             * trusted to skip over real frames behind it. */
1113
54
            *bytes_consumed = st == FAAD_ERR_DECODE_FAILED ? 1 : adts_frame_len;
1114
54
            return st != FAAD_OK ? st : FAAD_ERR_UNSUPPORTED;
1115
54
        }
1116
476
        if (!asc.num_channels) asc.pce = decoder->asc.pce;
1117
476
        decoder->asc = asc;
1118
476
        faad_layout_update(decoder);
1119
        /* Without a configuration or PCE a frame starts from the channel count of
1120
         * the frames before it, not from a stereo guess. */
1121
476
        decoder->core_channels = (!asc.num_channels && !asc.pce.channels && decoder->pcm_emitted)
1122
476
            ? decoder->core_channels : asc_channels(&asc);
1123
476
        decoder->core_sample_rate = asc.sample_rate;
1124
476
        bs.len = adts_frame_len;
1125
476
    }
1126
6.99k
    *bytes_consumed = adts_frame_len;
1127
6.99k
    decoder->num_channels = decoder->core_channels;
1128
6.99k
#ifndef FAAD_DISABLE_DRC
1129
6.99k
    decoder->drc.present = false;
1130
6.99k
#endif
1131
6.99k
    bool decode_success = true;
1132
6.99k
    bool degraded = false;
1133
#ifdef FAAD_STATS
1134
    g_faadStats.totalFrames++;
1135
#endif
1136
6.99k
    uint32_t active_chs = decoder->num_channels;
1137
6.99k
    if (active_chs > MAX_CHANNELS) active_chs = MAX_CHANNELS;
1138
41.5k
    for (uint32_t c = 0; c < active_chs; c++)
1139
34.5k
        memset(decoder->spec[c], 0, sizeof(decoder->spec[c]));
1140
6.99k
    decoder->sbr_present = false;
1141
6.99k
    decoder->ps_present = false;
1142
1143
#ifdef FAAD_STATS
1144
    g_faadStats.frameSectBits = g_faadStats.frameSfBits = g_faadStats.frameSpecBits = 0;
1145
    g_faadStats.frameAuxBits = g_faadStats.frameSbrBits = g_faadStats.framePsBits = 0;
1146
    g_faadStats.frameFillBits = 0;
1147
    unsigned frame_hdr_bits = bits_get_consumed(&bs);
1148
#endif
1149
6.99k
#if MAX_CHANNELS >= 3
1150
6.99k
    CouplingTarget coupling_targets[MAX_CHANNELS];
1151
6.99k
    unsigned coupling_target_count = 0;
1152
7.42k
    for (CouplingChannel *cc = decoder->coupling; cc; cc = cc->next) cc->present = false;
1153
6.99k
#endif
1154
6.99k
    bool have_coupling = false;
1155
6.99k
    uint32_t ch_idx = 0;
1156
6.99k
    uint32_t last_elem_type = ID_SCE;
1157
6.99k
    uint32_t last_elem_ch = 0;
1158
6.99k
    uint32_t occupied = 0;
1159
6.99k
    uint32_t seq = 1; /* element types, two bits each, behind a leading 1 */
1160
6.99k
#ifndef FAAD_DISABLE_SBR
1161
6.99k
    uint8_t elem_nch[MAX_CHANNELS] = {0};
1162
6.99k
#endif
1163
1164
6.99k
    bool saw_end = false;
1165
6.99k
    if (decode_success) {
1166
        /* Fill elements (SBR) follow the last channel element, so the loop
1167
         * runs to END even once every channel slot is taken. */
1168
127k
        while (bits_get_consumed(&bs) + 3 <= bs.len * 8) {
1169
124k
            uint32_t syntax_id = bits_get(&bs, 3);
1170
#ifdef FAAD_STATS
1171
            g_faadStats.elementCounts[syntax_id]++;
1172
#endif
1173
124k
            if (syntax_id == ID_END) {
1174
2.15k
                saw_end = true;
1175
2.15k
                break;
1176
122k
            } else if (syntax_id == ID_SCE || syntax_id == ID_LFE) {
1177
9.57k
                seq = seq << 2 | syntax_id;
1178
9.57k
                uint32_t elem_ch = element_slot(decoder, syntax_id, bits_show(&bs, 4), ch_idx, occupied);
1179
9.57k
                if (elem_ch >= MAX_CHANNELS
1180
9.45k
                    || (SLOTS_BY_TAG(decoder) && (occupied & (1u << elem_ch)))) {
1181
134
                    decode_success = false; break;
1182
134
                }
1183
9.43k
                occupied |= 1u << elem_ch;
1184
9.43k
#ifndef FAAD_DISABLE_SBR
1185
9.43k
                elem_nch[elem_ch] = 1;
1186
9.43k
#endif
1187
9.43k
                last_elem_ch = elem_ch;
1188
9.43k
#if MAX_CHANNELS >= 3
1189
9.43k
                coupling_targets[coupling_target_count++] = (CouplingTarget){
1190
9.43k
                    bs, decoder->pns_seed, (uint8_t)syntax_id, (uint8_t)bits_show(&bs, 4), (uint8_t)elem_ch };
1191
9.43k
#endif
1192
9.43k
                last_elem_type = syntax_id;
1193
#ifdef FAAD_STATS
1194
                unsigned b0 = bits_get_consumed(&bs);
1195
#endif
1196
9.43k
                ICSInfo *ics = &decoder->scratch->cpe.ics[0]; /* cleared by decode_sce */
1197
9.43k
                if (decode_sce(&bs, decoder, ics, elem_ch) != FAAD_OK) {
1198
334
                    decode_success = false; /* the rest of the payload is out of step */
1199
334
                    break;
1200
334
                }
1201
#ifdef FAAD_STATS
1202
                core_dump_ics(elem_ch, ics, decoder->spec[elem_ch], NULL,
1203
                              bits_get_consumed(&bs) - b0);
1204
#endif
1205
9.10k
                decoder->win_seq[elem_ch] = ics->window_sequence;
1206
9.10k
                decoder->win_shape[elem_ch] = ics->window_shape;
1207
9.10k
                apply_pns(ics, decoder->spec[elem_ch], &decoder->pns_seed);
1208
9.10k
                apply_tns(ics, decoder->spec[elem_ch]);
1209
9.10k
                ch_idx += 1;
1210
112k
            } else if (syntax_id == ID_CPE) {
1211
#if MAX_CHANNELS < 2
1212
                decode_success = false; /* a pair cannot fit in the channel ceiling */
1213
                break;
1214
#else
1215
2.56k
                seq = seq << 2 | ID_CPE;
1216
2.56k
                uint32_t elem_ch = element_slot(decoder, syntax_id, bits_show(&bs, 4), ch_idx, occupied);
1217
2.56k
                if (elem_ch + 1 >= MAX_CHANNELS
1218
2.50k
                    || (SLOTS_BY_TAG(decoder) && (occupied & (3u << elem_ch)))) {
1219
62
                    decode_success = false; break;
1220
62
                }
1221
2.50k
                occupied |= 3u << elem_ch;
1222
2.50k
#ifndef FAAD_DISABLE_SBR
1223
2.50k
                elem_nch[elem_ch] = 2;
1224
2.50k
#endif
1225
2.50k
                last_elem_ch = elem_ch;
1226
2.50k
#if MAX_CHANNELS >= 3
1227
2.50k
                coupling_targets[coupling_target_count++] = (CouplingTarget){
1228
2.50k
                    bs, decoder->pns_seed, ID_CPE, (uint8_t)bits_show(&bs, 4), (uint8_t)elem_ch };
1229
2.50k
#endif
1230
2.50k
                last_elem_type = ID_CPE;
1231
2.50k
                CPEInfo *cpe = &decoder->scratch->cpe;
1232
2.50k
                memset(cpe, 0, sizeof(*cpe));
1233
#ifdef FAAD_STATS
1234
                unsigned b0 = bits_get_consumed(&bs);
1235
#endif
1236
2.50k
                if (decode_cpe(&bs, decoder, cpe, elem_ch) != FAAD_OK) {
1237
137
                    decode_success = false;
1238
137
                    break;
1239
137
                }
1240
#ifdef FAAD_STATS
1241
                {
1242
                    unsigned nb = bits_get_consumed(&bs) - b0;
1243
                    /* The all-one mask sends no per-band flags. */
1244
                    if (cpe->ms_mask_present == MS_MASK_ALL)
1245
                        memset(cpe->ms_used, 1, sizeof(cpe->ms_used));
1246
                    const uint8_t (*ms)[MAX_SFB] = cpe->ms_mask_present != MS_MASK_NONE ? (const uint8_t (*)[MAX_SFB])cpe->ms_used : NULL;
1247
                    core_dump_ics(elem_ch, &cpe->ics[0], decoder->spec[elem_ch], ms, nb);
1248
                    core_dump_ics(elem_ch + 1, &cpe->ics[1], decoder->spec[elem_ch + 1], ms, cpe->ms_mask_present);
1249
                }
1250
#endif
1251
7.10k
                for (uint32_t i = 0; i < 2; i++) {
1252
4.73k
                    decoder->win_seq[elem_ch + i] = cpe->ics[i].window_sequence;
1253
4.73k
                    decoder->win_shape[elem_ch + i] = cpe->ics[i].window_shape;
1254
4.73k
                }
1255
1256
2.36k
                apply_pns(&cpe->ics[0], decoder->spec[elem_ch], &decoder->pns_seed);
1257
2.36k
                apply_pns(&cpe->ics[1], decoder->spec[elem_ch + 1], &decoder->pns_seed);
1258
2.36k
                apply_ms_stereo(cpe, decoder->spec[elem_ch], decoder->spec[elem_ch + 1]);
1259
2.36k
                apply_is_stereo(cpe, decoder->spec[elem_ch], decoder->spec[elem_ch + 1]);
1260
2.36k
                apply_tns(&cpe->ics[0], decoder->spec[elem_ch]);
1261
2.36k
                apply_tns(&cpe->ics[1], decoder->spec[elem_ch + 1]);
1262
1263
2.36k
                ch_idx += 2;
1264
2.36k
#endif
1265
110k
            } else if (syntax_id == ID_CCE) {
1266
1.35k
#if MAX_CHANNELS >= 3
1267
1.35k
                faad_status st = decode_cce(&bs, decoder);
1268
1.35k
                if (st == FAAD_ERR_NO_MEMORY) return st;
1269
1.35k
                if (st != FAAD_OK) { decode_success = false; break; }
1270
1.01k
                have_coupling = true;
1271
#else
1272
                return FAAD_ERR_UNSUPPORTED;
1273
#endif
1274
108k
            } else if (syntax_id == ID_DSE) {
1275
44.0k
                decode_dse(&bs);
1276
64.7k
            } else if (syntax_id == ID_PCE) {
1277
13.0k
                if (decode_pce(&bs, decoder) != FAAD_OK) { decode_success = false; break; }
1278
51.6k
            } else if (syntax_id == ID_FIL) {
1279
51.6k
                uint32_t count = bits_get(&bs, 4);
1280
51.6k
                if (count == 15) count += bits_get(&bs, 8) - 1;
1281
51.6k
                if (count > 0) {
1282
51.2k
                    uint32_t fill_end = bits_get_consumed(&bs) + count * 8;
1283
51.2k
                    uint32_t ext_type = bits_get(&bs, 4);
1284
51.2k
                    if (ext_type == SBR_EXTENSION_DATA || ext_type == SBR_EXTENSION_DATA_CRC) {
1285
46.0k
                        uint32_t ch0 = last_elem_ch;
1286
#ifdef FAAD_STATS
1287
                        unsigned sbr_mark = bits_get_consumed(&bs);
1288
                        unsigned ps_mark = g_faadStats.framePsBits;
1289
#endif
1290
                        /* Repack the unaligned fill into a reader whose last bit
1291
                         * is exactly the declared payload boundary. */
1292
46.0k
                        uint8_t payload[269]; /* maximum fill count: 15 + 255 - 1 */
1293
46.0k
                        BitReader source = bs, fill;
1294
46.0k
                        source.byte_pos = (fill_end - count * 8) / 8;
1295
46.0k
                        source.bit_pos = (fill_end - count * 8) % 8;
1296
653k
                        for (uint32_t i = 0; i < count; i++) payload[i] = (uint8_t)bits_get(&source, 8);
1297
46.0k
                        if (source.overread) {
1298
49
                            decode_success = false;
1299
49
                            break;
1300
49
                        }
1301
46.0k
                        bits_init(&fill, payload, count);
1302
46.0k
                        bits_skip(&fill, 4); /* extension type already read */
1303
46.0k
                        faad_status sbr_st = sbr_decode_extension(decoder, &fill, ch0, last_elem_type, ext_type == SBR_EXTENSION_DATA_CRC);
1304
46.0k
                        bits_skip(&bs, bits_get_consumed(&fill) - 4);
1305
46.0k
#ifndef FAAD_DISABLE_SBR
1306
46.0k
                        if (sbr_st == FAAD_ERR_NO_MEMORY) return sbr_st;
1307
46.0k
                        if (sbr_st != FAAD_OK) {
1308
                            /* The core is intact: play it band-limited rather than
1309
                             * conceal it, and keep the half-read payload out of
1310
                             * the envelope history. */
1311
30.0k
                            uint32_t nch = (last_elem_type == ID_CPE) ? 2 : 1;
1312
68.7k
                            for (uint32_t c = ch0; c < ch0 + nch && c < MAX_CHANNELS; c++) decoder->sbr[c].have_frame = false;
1313
30.0k
                            decoder->sbr_present = true;
1314
30.0k
                            degraded = true;
1315
30.0k
                        }
1316
#else
1317
                        (void)sbr_st;
1318
#endif
1319
46.0k
                        uint32_t consumed = bits_get_consumed(&bs);
1320
#ifdef FAAD_STATS
1321
                        g_faadStats.fillElementCount++;
1322
                        g_faadStats.frameSbrBits += consumed - sbr_mark - (g_faadStats.framePsBits - ps_mark);
1323
#endif
1324
46.0k
                        if (consumed < fill_end) {
1325
34.0k
                            uint32_t pad = fill_end - consumed;
1326
34.0k
                            bits_skip(&bs, pad);
1327
#ifdef FAAD_STATS
1328
                            g_faadStats.fillElementPadBitsSum += pad;
1329
                            g_faadStats.frameFillBits += pad;
1330
                            if (pad > g_faadStats.fillElementMaxPad) {
1331
                                g_faadStats.fillElementMaxPad = pad;
1332
                            }
1333
#endif
1334
34.0k
                        }
1335
46.0k
                    } else {
1336
5.20k
#ifndef FAAD_DISABLE_DRC
1337
5.20k
                        if (ext_type == 11) {
1338
4.13k
                            uint32_t end = fill_end;
1339
4.13k
                            if (end > bs.len * 8) end = bs.len * 8;
1340
4.13k
                            read_drc(decoder, bs, end);
1341
4.13k
                        }
1342
5.20k
#endif
1343
5.20k
                        bits_skip(&bs, (count - 1) * 8 + 4);
1344
5.20k
                    }
1345
51.2k
                }
1346
51.6k
            }
1347
124k
        }
1348
#ifdef FAAD_STATS
1349
        if (!saw_end) {
1350
            g_faadStats.nonEndTermination++;
1351
        }
1352
        FILE *df = faad_dump_file();
1353
        if (df) {
1354
            const faadDecStats *s = &g_faadStats;
1355
            fprintf(df, "B %u %u %u %u %u %u %u %u %u %u\n", s->totalFrames, bits_get_consumed(&bs),
1356
                    frame_hdr_bits, s->frameSectBits, s->frameSfBits, s->frameSpecBits, s->frameAuxBits,
1357
                    s->frameSbrBits, s->framePsBits, s->frameFillBits);
1358
        }
1359
#endif
1360
6.99k
    }
1361
1362
6.99k
    if (!saw_end || bs.overread) decode_success = false;
1363
6.99k
#if MAX_CHANNELS >= 3
1364
6.99k
    if (decode_success && have_coupling
1365
355
        && coupling_spectrum(decoder, coupling_targets, coupling_target_count) != FAAD_OK)
1366
90
        decode_success = false;
1367
6.99k
    if (!decode_success)
1368
6.14k
        for (CouplingChannel *cc = decoder->coupling; cc; cc = cc->next) cc->present = false;
1369
6.99k
#endif
1370
6.99k
#if MAX_CHANNELS >= 3
1371
6.99k
    if (SLOTS_BY_TAG(decoder) && occupied != (1u << decoder->layout.n) - 1) decode_success = false;
1372
6.99k
#endif
1373
6.99k
    if (decode_success && !faad_layout_frozen(decoder) && !decoder->asc.num_channels && !decoder->asc.pce.channels)
1374
79
        faad_layout_infer(decoder, seq);
1375
    /* A fixed RAW layout also fixes the lifetime output capacity. */
1376
6.99k
    if (decoder->config.stream_format == FAAD_STREAM_RAW && (decoder->asc.num_channels || decoder->asc.pce.channels)
1377
6.51k
        && ch_idx > asc_channels(&decoder->asc))
1378
570
        return FAAD_ERR_DECODE_FAILED;
1379
1380
6.42k
    if (decode_success && ch_idx > 0) {
1381
1.50k
        decoder->consecutive_errors = 0;
1382
1.50k
        decoder->num_channels = ch_idx;
1383
1.50k
        decoder->core_channels = ch_idx;
1384
1.50k
#ifndef FAAD_DISABLE_SBR
1385
        /* A concealed frame keeps the layout of the frame it repeats. */
1386
1.50k
        memcpy(decoder->elem_nch, elem_nch, sizeof(elem_nch));
1387
1.50k
#endif
1388
#ifdef FAAD_STATS
1389
        if (!g_faadStats.haveLastChannels) {
1390
            g_faadStats.haveLastChannels = true;
1391
            g_faadStats.lastChannels = ch_idx;
1392
            g_faadStats.minChannels = ch_idx;
1393
            g_faadStats.maxChannels = ch_idx;
1394
        } else {
1395
            if (ch_idx != g_faadStats.lastChannels) {
1396
                g_faadStats.channelCountChanges++;
1397
                g_faadStats.lastChannels = ch_idx;
1398
            }
1399
            if (ch_idx < g_faadStats.minChannels) g_faadStats.minChannels = ch_idx;
1400
            if (ch_idx > g_faadStats.maxChannels) g_faadStats.maxChannels = ch_idx;
1401
        }
1402
#endif
1403
4.91k
    } else {
1404
#ifdef FAAD_STATS
1405
        g_faadStats.errorConcealmentFrames++;
1406
#endif
1407
4.91k
        decoder->consecutive_errors++;
1408
4.91k
        float fade = 0.0f;
1409
4.91k
        if (decoder->consecutive_errors <= 5) {
1410
4.91k
            fade = powf(0.8f, (float)decoder->consecutive_errors);
1411
4.91k
        }
1412
29.7k
        for (uint32_t c = 0; c < decoder->num_channels; c++) {
1413
25.4M
            for (int i = 0; i < FRAME_LEN_LONG; i++) {
1414
25.3M
                decoder->spec[c][i] = decoder->prev_spec[c][i] * fade;
1415
25.3M
            }
1416
            /* Repeat the last block's windowing; a start block's spectrum
1417
             * follows its own short-window overlap as a stop block. */
1418
24.7k
            static const uint8_t next_seq[4] = { ONLY_LONG_SEQUENCE, LONG_STOP_SEQUENCE,
1419
24.7k
                                                 EIGHT_SHORT_SEQUENCE, ONLY_LONG_SEQUENCE };
1420
24.7k
            decoder->win_seq[c] = next_seq[decoder->prev_window_seq[c] & 3];
1421
24.7k
            decoder->win_shape[c] = decoder->prev_window_shape[c];
1422
24.7k
        }
1423
4.91k
    }
1424
1425
    /* One buffer, one frame_samples-long run per channel: SBR analyzes a
1426
     * channel's whole core frame before it synthesises that channel, so it
1427
     * works in place over the core output at the start of each run. */
1428
6.42k
    if (decoder->sbr_present) decoder->sbr_seen = true;
1429
6.42k
#ifndef FAAD_DISABLE_PS
1430
6.42k
    if (decoder->ps_present || decoder->asc.is_ps) decoder->ps_seen = true;
1431
6.42k
#endif
1432
6.42k
    bool sbr_frame = decoder->asc.is_sbr || decoder->sbr_present || decoder->sbr_seen;
1433
#ifdef FAAD_DISABLE_SBR
1434
    sbr_frame = false;
1435
#endif
1436
6.42k
    uint32_t core_samples = FRAME_IS_960(decoder) ? 960 : 1024;
1437
6.42k
    decoder->frame_samples = sbr_frame ? (core_samples * 2) : core_samples;
1438
6.42k
#ifndef FAAD_DISABLE_DRC
1439
6.42k
    decoder->drc.applied = decoder->drc.boost = false;
1440
6.42k
    if (decode_success && decoder->drc.present && (decoder->config.drc_cut || decoder->config.drc_boost))
1441
176
        apply_drc(decoder);
1442
6.42k
#endif
1443
6.42k
    float *pcm_final = decoder->pcm;
1444
6.42k
    uint32_t num_chs = decoder->num_channels;
1445
6.42k
    bool spectral_downmixed = false;
1446
6.42k
    if (decoder->spectral_downmix_active
1447
0
        && (sbr_frame || have_coupling || decoder->num_channels <= 2
1448
0
            || decoder->spectral_downmix_channels != decoder->num_channels
1449
0
            || decoder->spectral_downmix_layout != decoder->asc.num_channels
1450
0
            || !spectral_downmix_windows_match(decoder, decoder->num_channels))) {
1451
0
        restore_channel_overlaps(decoder, prior_channels, prior_errors);
1452
0
        decoder->spectral_downmix_active = false;
1453
0
    }
1454
6.42k
    if (!sbr_frame && !have_coupling)
1455
3.41k
        spectral_downmixed = try_spectral_downmix(decoder, decoder->num_channels, &num_chs, pcm_final,
1456
3.41k
                                                     decode_success && ch_idx > 0);
1457
6.42k
    if (!spectral_downmixed) {
1458
6.42k
        uint32_t lfe_channel = faad_downmix_lfe_channel(decoder, decoder->num_channels);
1459
35.3k
        for (uint32_t c = 0; c < decoder->num_channels; c++) {
1460
28.8k
            if (c != lfe_channel)
1461
28.8k
                imdct_and_window(decoder, c, decoder->win_seq[c], decoder->win_shape[c], decoder->spec[c], pcm_final + c * FRAME_LEN_LONG);
1462
28.8k
        }
1463
6.42k
    }
1464
6.42k
    if (!spectral_downmixed && decode_success && ch_idx > 0) {
1465
1.50k
        if (ch_idx == MAX_CHANNELS) {
1466
            /* IMDCT has consumed this spectrum; rotate before SBR reuses spec[0]. */
1467
94
            float (*tmp)[FRAME_LEN_LONG] = decoder->prev_spec;
1468
94
            decoder->prev_spec = decoder->spec;
1469
94
            decoder->spec = tmp;
1470
1.41k
        } else {
1471
            /* A later ADTS header can expand concealment before that channel decodes. */
1472
1.41k
            memcpy(decoder->prev_spec, decoder->spec, sizeof(decoder->spec[0]) * ch_idx);
1473
1.41k
        }
1474
1.50k
    }
1475
6.42k
#if MAX_CHANNELS >= 3
1476
6.42k
    if (decoder->coupling) coupling_pcm(decoder);
1477
6.42k
#endif
1478
6.42k
    if (sbr_frame) {
1479
        /* Move backwards after IMDCT scratch is dead, making room for each
1480
         * channel's doubled output without overwriting another core frame. */
1481
11.1k
        for (uint32_t c = decoder->num_channels; c-- > 1; )
1482
8.49k
            memmove(pcm_final + c * 2048, pcm_final + c * FRAME_LEN_LONG,
1483
8.49k
                    sizeof(float[FRAME_LEN_LONG]));
1484
2.63k
        sbr_apply(decoder, decoder->num_channels, pcm_final);
1485
2.63k
    }
1486
1487
6.42k
    uint32_t frame_samples = decoder->frame_samples;
1488
    /* Channel runs sit at a fixed stride: the IMDCT and SBR buffers are sized
1489
     * for 1024- and 2048-sample frames whatever the core frame length. */
1490
6.42k
    uint32_t pcm_stride = sbr_frame ? 2 * FRAME_LEN_LONG : FRAME_LEN_LONG;
1491
1492
    /* Output in the WAV / SMPTE order (FL FR FC LFE BL BR SL SR), taken
1493
     * from the element order the channel configuration implies. */
1494
6.42k
    const float *src[MAX_CHANNELS < 2 ? 2 : MAX_CHANNELS];
1495
6.42k
    if (!spectral_downmixed) {
1496
6.42k
        num_chs = decoder->num_channels;
1497
6.42k
        const uint8_t *map = faad_layout_map(decoder, num_chs);
1498
35.6k
        for (uint32_t c = 0; c < num_chs; c++)
1499
29.1k
            src[c] = pcm_final + (map ? map[c] : c) * pcm_stride;
1500
6.42k
        float *dst[DM_CH];
1501
57.7k
        for (uint32_t c = 0; c < DM_CH; c++)
1502
51.3k
            dst[c] = pcm_final + c * pcm_stride;
1503
6.42k
        uint32_t mixed = downmix_pcm(decoder->config.downmix_mode, src, num_chs,
1504
6.42k
                                     downmix_mask(decoder, num_chs), frame_samples, dst);
1505
6.42k
        if (mixed != num_chs)
1506
0
            for (num_chs = mixed; mixed--; ) src[mixed] = dst[mixed];
1507
6.42k
    }
1508
6.42k
    if (num_chs <= 2)
1509
5.06k
        for (uint32_t c = 0; c < num_chs; c++) src[c] = pcm_final + c * pcm_stride;
1510
1511
6.42k
    uint32_t required_bytes = frame_samples * num_chs * output_sample_bytes(decoder->config.output_format);
1512
    /* The entry check guarantees capacity before any history advances. A
1513
     * lifetime-bound violation is a rejected frame, never a retryable buffer
1514
     * error after synthesis has already consumed the packet. */
1515
6.42k
    if (required_bytes > decoder->max_output_bytes) return FAAD_ERR_DECODE_FAILED;
1516
1517
6.41k
#ifndef FAAD_DISABLE_DRC
1518
6.41k
    if ((decoder->config.drc_target_level != 0.0f || decoder->drc.boost)
1519
6.41k
        && drc_output(decoder, src, num_chs, frame_samples, out_pcm)) goto output_done;
1520
6.37k
#endif
1521
6.37k
    if (decoder->config.output_format == FAAD_OUTPUT_16BIT) {
1522
2.32k
        int16_t * restrict out_int16 = (int16_t *)out_pcm;
1523
2.32k
        if (num_chs == 2) {
1524
328
            const float * restrict pcm_l = src[0];
1525
328
            const float * restrict pcm_r = src[1];
1526
516k
            for (uint32_t i = 0; i < frame_samples; i++) {
1527
516k
                out_int16[2 * i]     = pcm_to_s16(pcm_l[i]);
1528
516k
                out_int16[2 * i + 1] = pcm_to_s16(pcm_r[i]);
1529
516k
            }
1530
2.00k
        } else if (num_chs == 1) {
1531
301
            const float * restrict pcm_m = src[0];
1532
378k
            for (uint32_t i = 0; i < frame_samples; i++)
1533
378k
                out_int16[i] = pcm_to_s16(pcm_m[i]);
1534
1.70k
        } else {
1535
2.22M
            for (uint32_t i = 0; i < frame_samples; i++)
1536
15.8M
                for (uint32_t c = 0; c < num_chs; c++)
1537
13.6M
                    out_int16[i * num_chs + c] = pcm_to_s16(src[c][i]);
1538
1.70k
        }
1539
4.04k
    } else if (decoder->config.output_format == FAAD_OUTPUT_24BIT) {
1540
        /* Packed in host byte order like the wider formats; byte-wise stores assume no alignment of out_pcm. */
1541
0
        uint8_t * restrict out_u8 = (uint8_t *)out_pcm;
1542
0
        for (uint32_t i = 0; i < frame_samples; i++)
1543
0
            for (uint32_t c = 0; c < num_chs; c++, out_u8 += 3)
1544
0
                write_pcm24(out_u8, pcm_to_s24(src[c][i]), FAAC_BIG_ENDIAN);
1545
4.04k
    } else if (decoder->config.output_format == FAAD_OUTPUT_24IN32) {
1546
884
        int32_t * restrict out_int32 = (int32_t *)out_pcm;
1547
1.32M
        for (uint32_t i = 0; i < frame_samples; i++)
1548
5.68M
            for (uint32_t c = 0; c < num_chs; c++)
1549
4.36M
                out_int32[i * num_chs + c] = pcm_to_s24(src[c][i]);
1550
3.15k
    } else {
1551
        /* The core reconstructs at 16-bit full scale; float output is unity full scale. */
1552
3.15k
        const float norm = 1.0f / 32768.0f;
1553
3.15k
        float * restrict out_f32 = (float *)out_pcm;
1554
3.15k
        if (num_chs == 2) {
1555
617
            const float * restrict pcm_l = src[0];
1556
617
            const float * restrict pcm_r = src[1];
1557
918k
            for (uint32_t i = 0; i < frame_samples; i++) {
1558
917k
                out_f32[2 * i] = pcm_l[i] * norm;
1559
917k
                out_f32[2 * i + 1] = pcm_r[i] * norm;
1560
917k
            }
1561
2.54k
        } else if (num_chs == 1) {
1562
269
            const float * restrict pcm_m = src[0];
1563
430k
            for (uint32_t i = 0; i < frame_samples; i++)
1564
430k
                out_f32[i] = pcm_m[i] * norm;
1565
2.27k
        } else {
1566
3.11M
            for (uint32_t i = 0; i < frame_samples; i++)
1567
21.3M
                for (uint32_t c = 0; c < num_chs; c++)
1568
18.2M
                    out_f32[i * num_chs + c] = src[c][i] * norm;
1569
2.27k
        }
1570
3.15k
    }
1571
1572
6.37k
#ifndef FAAD_DISABLE_DRC
1573
6.41k
output_done:
1574
6.41k
    ;
1575
6.41k
#endif
1576
6.41k
    *bytes_consumed = adts_frame_len;
1577
6.41k
    *bytes_written = required_bytes;
1578
1579
6.41k
    bool sbr_active = sbr_frame;
1580
#ifdef FAAD_STATS
1581
    if (sbr_active) {
1582
        g_faadStats.sbrActiveFrames++;
1583
    }
1584
#endif
1585
1586
6.41k
    decoder->format_known = decoder->format_known || decoder->asc.num_channels != 0
1587
149
        || (decode_success && ch_idx > 0);
1588
6.41k
    decoder->sample_rate = sbr_active ? 2 * decoder->core_sample_rate : decoder->core_sample_rate;
1589
6.41k
    uint32_t mask = channel_mask(decoder, num_chs);
1590
6.41k
    uint32_t delay = sbr_active ? 2 * FAAD_SBR_CORE_DELAY : 0;
1591
6.41k
    uint32_t flags = 0;
1592
6.41k
#ifndef FAAD_DISABLE_DRC
1593
6.41k
    if (decoder->drc.applied) flags |= FAAD_FRAME_DRC;
1594
6.41k
    if (decoder->drc.present) flags |= FAAD_FRAME_DRC_INFO;
1595
6.41k
#endif
1596
6.41k
    if (!decoder->pcm_emitted || decoder->emitted_format.sample_rate != decoder->sample_rate
1597
1.52k
        || decoder->emitted_format.channels != num_chs
1598
1.32k
        || decoder->emitted_format.frame_samples != frame_samples
1599
1.32k
        || decoder->emitted_format.channel_mask != mask
1600
1.32k
        || decoder->emitted_format.decoder_delay != delay)
1601
5.09k
        flags |= FAAD_FRAME_FORMAT_CHANGED;
1602
6.41k
    if (sbr_active) flags |= FAAD_FRAME_SBR;
1603
6.41k
#ifndef FAAD_DISABLE_PS
1604
6.41k
    if (sbr_active && decoder->ps_seen && decoder->core_channels == 1) flags |= FAAD_FRAME_PS;
1605
6.41k
#endif
1606
6.41k
    if (!decode_success || ch_idx == 0) flags |= FAAD_FRAME_CONCEALED;
1607
6.41k
    if (degraded) flags |= FAAD_FRAME_DEGRADED;
1608
6.41k
    if (required_bytes) {
1609
6.41k
        decoder->emitted_format.sample_rate = decoder->sample_rate;
1610
6.41k
        decoder->emitted_format.channels = num_chs;
1611
6.41k
        decoder->emitted_format.frame_samples = frame_samples;
1612
6.41k
        decoder->emitted_format.channel_mask = mask;
1613
6.41k
        decoder->emitted_format.decoder_delay = delay;
1614
6.41k
        decoder->pcm_emitted = true;
1615
6.41k
        faad_layout_freeze(decoder);
1616
6.41k
        decoder->format_known = true;
1617
6.41k
        if (frame_flags) *frame_flags = flags;
1618
6.41k
    }
1619
1620
6.41k
    return FAAD_OK;
1621
6.37k
}
1622
1623
FAADAPI const char *faad_strerror(faad_status status)
1624
0
{
1625
0
    switch (status) {
1626
0
        case FAAD_OK:                   return "Success";
1627
0
        case FAAD_ERR_INVALID_ARGUMENT: return "Invalid argument";
1628
0
        case FAAD_ERR_UNSUPPORTED:      return "Unsupported configuration";
1629
0
        case FAAD_ERR_NO_MEMORY:        return "Insufficient memory allocated";
1630
0
        case FAAD_ERR_OUTPUT_TOO_SMALL: return "Output buffer too small";
1631
0
        case FAAD_ERR_NEED_MORE_DATA:   return "Need more input data";
1632
0
        case FAAD_ERR_DECODE_FAILED:    return "Decoding failed";
1633
0
        case FAAD_ERR_SYNC_LOST:        return "Lost syncword alignment";
1634
0
        default:                        return "Unknown status";
1635
0
    }
1636
0
}