/src/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 "faac_endian.h" |
25 | | |
26 | | /* Baselines end at the last field so appended fields remain optional. */ |
27 | 9.79k | #define CONFIG_BASELINE_SIZE ((uint32_t)FAAD_CONFIG_BASELINE) |
28 | 0 | #define LIBRARY_INFO_BASELINE_SIZE ((uint32_t)FAAD_LIBRARY_INFO_BASELINE) |
29 | 3.18k | #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 | 3.18k | { |
38 | 3.18k | return caller_size < library_size ? caller_size : (uint32_t)library_size; |
39 | 3.18k | } |
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 | 242k | { |
49 | 242k | return channel_config == CFG_7_1 || channel_config == CFG_7_1_SIDE_BACK ? 8 |
50 | 242k | : channel_config == CFG_6_1 ? 7 |
51 | 242k | : (channel_config >= CFG_MONO && channel_config <= CFG_5_1) |
52 | 242k | ? channel_config : (MAX_CHANNELS < 2 ? 1 : 2); |
53 | 242k | } |
54 | | |
55 | | static uint32_t asc_channels(const AudioSpecificConfig *asc) |
56 | 247k | { |
57 | 247k | return asc->pce.channels ? asc->pce.channels : config_channels(asc->num_channels); |
58 | 247k | } |
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 | 3.22k | { |
105 | 3.22k | static const uint16_t speakers[4][2] = { { SPK_FC, SPK_FRONT }, { 0, SPK_SIDE }, { SPK_BC, SPK_BACK }, { SPK_LFE, 0 } }; |
106 | 3.22k | struct faad_layout *L = &dec->layout; |
107 | 3.22k | uint16_t spk[MAX_CHANNELS]; |
108 | 3.22k | uint32_t mask = 0, ch = 0, front_pairs = 0, back_pairs = 0, side = 0, front_total = 0; |
109 | 3.22k | memset(L, 0, sizeof(*L)); |
110 | 3.22k | L->lfe = 0xff; |
111 | 7.13k | for (uint32_t i = 0; i < n; i++) { |
112 | 3.91k | side += el[i] >> 5 == ASC_PCE_SIDE; |
113 | 3.91k | back_pairs += el[i] >> 4 == (ASC_PCE_BACK << 1 | 1); |
114 | 3.91k | front_total += el[i] >> 4 == (ASC_PCE_FRONT << 1 | 1); |
115 | 3.91k | } |
116 | 3.22k | bool rear_pairs = back_pairs == 2 && !side; |
117 | 6.98k | for (uint32_t i = 0; i < n; i++) { |
118 | 3.85k | uint32_t cat = el[i] >> 5, pair = el[i] >> 4 & 1, bits = speakers[cat][pair]; |
119 | 3.85k | if (cat == ASC_PCE_FRONT && pair) { |
120 | | /* Front pairs are listed from the centre outward: with two, the inner one is FLC/FRC. */ |
121 | 3.06k | if (front_total > 2) bits = 0; |
122 | 3.06k | else if (front_total == 2 && !front_pairs++) bits = SPK_FLC | SPK_FRC; |
123 | 3.06k | } |
124 | 3.85k | if (rear_pairs && cat == ASC_PCE_BACK && pair && !(mask & SPK_SIDE)) bits = SPK_SIDE; |
125 | 3.85k | if (!bits || (mask & bits) || ch + 1 + pair > MAX_CHANNELS) return; |
126 | 3.76k | mask |= bits; |
127 | 3.76k | 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 | 3.96k | for (uint32_t j = 0; by_tag && j < i; j++) |
130 | 204 | if (L->el_key[j] == L->el_key[i]) return; |
131 | 3.76k | L->el_slot[i] = (uint8_t)ch; |
132 | 3.76k | spk[ch] = (uint16_t)(bits & (0u - bits)); |
133 | 3.76k | if (pair) spk[ch + 1] = (uint16_t)(bits & (bits - 1)); |
134 | 3.76k | ch += 1 + pair; |
135 | 3.76k | } |
136 | 3.13k | if (!ch) return; |
137 | 9.85k | for (uint32_t i = 0; i < ch; i++) { |
138 | 6.72k | uint32_t rank = faac_popcount32(mask & (spk[i] - 1u)); /* speakers before this one */ |
139 | 6.72k | L->map[rank] = (uint8_t)i; |
140 | 6.72k | if (spk[i] == SPK_LFE) L->lfe = (uint8_t)i; |
141 | 6.72k | } |
142 | 3.13k | L->mask = (uint16_t)mask; |
143 | 3.13k | L->n = (uint8_t)ch; |
144 | 3.13k | L->n_el = by_tag ? (uint8_t)n : 0; |
145 | 3.13k | } |
146 | | |
147 | | void faad_layout_update(struct faad_decoder *dec) |
148 | 3.29k | { |
149 | 3.29k | struct faad_layout *L = &dec->layout; |
150 | 3.29k | uint32_t cfg = dec->asc.num_channels; |
151 | 3.29k | if (cfg) { |
152 | 3.07k | if (cfg == L->cfg && L->n) return; |
153 | 3.07k | if (cfg < CFG_COUNT) { |
154 | 3.07k | uint32_t n = 0; |
155 | 6.56k | while (n < 5 && config_elements[cfg][n] != 0xff) n++; |
156 | 3.07k | layout_build(dec, config_elements[cfg], n, false); |
157 | 3.07k | } else { |
158 | 0 | memset(L, 0, sizeof(*L)); |
159 | 0 | } |
160 | 3.07k | } else { |
161 | 224 | if (L->cfg) memset(L, 0, sizeof(*L)); /* a new layout starts, with no PCM in it yet */ |
162 | 224 | if (!L->frozen && dec->asc.pce.n_el) |
163 | 154 | layout_build(dec, dec->asc.pce.el, dec->asc.pce.n_el, true); |
164 | 224 | } |
165 | 3.29k | L->cfg = (uint8_t)cfg; |
166 | 3.29k | } |
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 | 0 | { |
172 | 0 | for (uint32_t cfg = CFG_7_1; cfg >= CFG_3_0; cfg--) { |
173 | 0 | uint32_t want = 1, n = 0; |
174 | 0 | for (; n < 5 && config_elements[cfg][n] != 0xff; n++) { |
175 | 0 | uint32_t e = config_elements[cfg][n]; |
176 | 0 | want = want << 2 | ((e >> 5) == ASC_PCE_LFE ? ID_LFE : (e >> 4) & 1 ? ID_CPE : ID_SCE); |
177 | 0 | } |
178 | 0 | if (want == seq) { |
179 | 0 | layout_build(dec, cfg == CFG_7_1 ? pce_side_back_7_1 : config_elements[cfg], n, false); |
180 | 0 | return; |
181 | 0 | } |
182 | 0 | } |
183 | 0 | } |
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 | 422k | { |
190 | 422k | struct faad_layout *L = &dec->layout; |
191 | 422k | if (!L->n_el) return ch_idx; |
192 | 953 | for (uint32_t i = 0; i < L->n_el; i++) |
193 | 844 | if (L->el_key[i] == (type << 4 | tag)) return L->el_slot[i]; |
194 | 109 | if (occupied != (1u << ch_idx) - 1) return MAX_CHANNELS; /* an earlier element is out of order */ |
195 | 28 | L->n_el = 0; |
196 | 28 | return ch_idx; |
197 | 109 | } |
198 | 1.31M | #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 | 3.26k | { |
210 | 3.26k | uint32_t n = faac_popcount32((uint32_t)mode); |
211 | 3.26k | return mode == FAAD_DOWNMIX_NONE || (!((uint32_t)mode >> POS_COUNT) && n <= 8); |
212 | 3.26k | } |
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 | 6.37k | { |
217 | 6.37k | uint32_t n = faac_popcount32((uint32_t)mode); |
218 | 6.37k | return mode != FAAD_DOWNMIX_NONE && channels > n ? n : channels; |
219 | 6.37k | } |
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 | 187k | { |
225 | 187k | static const uint16_t canon[] = { |
226 | 187k | SPK_FRONT, SPK_FRONT, SPK_FRONT, SPK_FRONT | SPK_FC, SPK_FRONT | SPK_FC | SPK_BC, |
227 | 187k | SPK_FRONT | SPK_FC | SPK_BACK, SPK_FRONT | SPK_FC | SPK_LFE | SPK_BACK, |
228 | 187k | SPK_FRONT | SPK_FC | SPK_LFE | SPK_BC | SPK_SIDE, |
229 | 187k | SPK_FRONT | SPK_FC | SPK_LFE | SPK_BACK | SPK_SIDE }; |
230 | 187k | uint32_t mask = faad_layout_mask(dec, num_chs); |
231 | 187k | return mask ? mask : canon[num_chs <= 8 ? num_chs : 0]; |
232 | 187k | } |
233 | | |
234 | 0 | #define DM_K 0.70710678f |
235 | | /* A stereo target needs two rows even when the build keeps one channel. */ |
236 | 1.68M | #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 | 187k | { |
253 | 187k | bool mono = mode == FAAD_DOWNMIX_MONO; |
254 | 187k | uint32_t tm = mono ? SPK_FRONT : (uint32_t)mode, tn = faac_popcount32(tm); |
255 | 187k | if (mode == FAAD_DOWNMIX_NONE || num_chs < 2 || (!mono && num_chs <= tn)) |
256 | 187k | 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 | 105k | { |
365 | 105k | enum faad_downmix_mode mode = dec->config.downmix_mode; |
366 | 105k | if ((mode != FAAD_DOWNMIX_MONO && mode != FAAD_DOWNMIX_STEREO) |
367 | 0 | || num_chs <= 2 || !spectral_downmix_windows_match(dec, num_chs)) |
368 | 105k | 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 | 6.53k | { |
447 | 6.53k | if (!config || caller_size < CONFIG_BASELINE_SIZE) { |
448 | 0 | return FAAD_ERR_INVALID_ARGUMENT; |
449 | 0 | } |
450 | 6.53k | faad_config tmp; |
451 | 6.53k | uint32_t n = caller_size < sizeof(tmp) ? caller_size : (uint32_t)sizeof(tmp); |
452 | 6.53k | memset(&tmp, 0, sizeof(tmp)); |
453 | 6.53k | tmp.struct_size = n; |
454 | 6.53k | tmp.stream_format = FAAD_STREAM_ADTS; |
455 | 6.53k | tmp.output_format = FAAD_OUTPUT_16BIT; |
456 | 6.53k | tmp.downmix_mode = FAAD_DOWNMIX_NONE; |
457 | 6.53k | memcpy(config, &tmp, n); |
458 | 6.53k | return FAAD_OK; |
459 | 6.53k | } |
460 | | |
461 | | static uint32_t output_sample_bytes(enum faad_output_format f) |
462 | 432k | { |
463 | 432k | return f == FAAD_OUTPUT_16BIT ? 2 : f == FAAD_OUTPUT_24BIT ? 3 : 4; |
464 | 432k | } |
465 | | |
466 | | static uint32_t output_capacity(const faad_decoder *dec) |
467 | 3.18k | { |
468 | 3.18k | uint32_t channels = MAX_CHANNELS; |
469 | 3.18k | if (dec->config.stream_format == FAAD_STREAM_RAW && dec->asc_parsed && (dec->asc.num_channels || dec->asc.pce.channels)) |
470 | 3.18k | channels = asc_channels(&dec->asc); |
471 | 3.18k | #ifndef FAAD_DISABLE_PS |
472 | 3.18k | if (channels < 2) channels = 2; |
473 | 3.18k | #endif |
474 | 3.18k | channels = downmix_out_chs(dec->config.downmix_mode, channels); |
475 | 3.18k | uint32_t samples = FRAME_IS_960(dec) ? 960 : 1024; |
476 | 3.18k | #ifndef FAAD_DISABLE_SBR |
477 | 3.18k | samples *= 2; |
478 | 3.18k | #endif |
479 | 3.18k | return samples * channels * output_sample_bytes(dec->config.output_format); |
480 | 3.18k | } |
481 | | |
482 | | static uint32_t channel_mask(const faad_decoder *dec, uint32_t channels) |
483 | 190k | { |
484 | 190k | if (channels < dec->num_channels) /* mixed: the stream is in the target layout */ |
485 | 0 | return (uint32_t)dec->config.downmix_mode; |
486 | 190k | static const uint32_t masks[] = { 0, SPK_FC, SPK_FRONT }; |
487 | 190k | return channels <= 2 ? masks[channels] : faad_layout_mask(dec, channels); |
488 | 190k | } |
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 | 828 | { |
494 | 828 | uint8_t top[16], ctl[16], sign[16]; |
495 | 828 | bool excluded[MAX_CHANNELS] = { false }; |
496 | 828 | unsigned bands = 1, ref = 0; |
497 | 828 | bool has_ref; |
498 | 22.9k | #define DRC_READ(n) (bits_get_consumed(&input) <= end && (n) <= end - bits_get_consumed(&input) ? bits_get(&input, (n)) : (bad = true, 0u)) |
499 | 828 | bool bad = false; |
500 | 828 | if (DRC_READ(1)) { (void)DRC_READ(4); (void)DRC_READ(4); } |
501 | 828 | if (DRC_READ(1)) { |
502 | 354 | unsigned channel = 0; |
503 | 354 | bool more; |
504 | 1.22k | do { |
505 | 9.78k | for (unsigned i = 0; i < 7; i++, channel++) { |
506 | 8.56k | bool omit = DRC_READ(1) != 0; |
507 | 8.56k | if (channel < MAX_CHANNELS) excluded[channel] = omit; |
508 | 8.56k | } |
509 | 1.22k | more = DRC_READ(1) != 0; |
510 | 1.22k | } while (more && !bad); |
511 | 354 | } |
512 | 828 | bool banded = DRC_READ(1) != 0; |
513 | 828 | if (banded) { |
514 | 347 | bands += DRC_READ(4) & 0xfu; |
515 | 347 | (void)DRC_READ(4); |
516 | 2.55k | for (unsigned b = 0; b < bands && b < sizeof(top); b++) { |
517 | 2.20k | top[b] = (uint8_t)DRC_READ(8); |
518 | 2.20k | if (b && top[b] <= top[b - 1]) bad = true; |
519 | 2.20k | } |
520 | 481 | } else top[0] = 255; |
521 | 828 | has_ref = DRC_READ(1) != 0; |
522 | 828 | if (has_ref) { ref = DRC_READ(7); (void)DRC_READ(1); } |
523 | 3.51k | for (unsigned b = 0; b < bands; b++) { |
524 | 2.68k | sign[b] = (uint8_t)DRC_READ(1); |
525 | 2.68k | ctl[b] = (uint8_t)DRC_READ(7); |
526 | 2.68k | } |
527 | 828 | #undef DRC_READ |
528 | 828 | if (bad) return; |
529 | 506 | dec->drc.present = true; |
530 | 506 | dec->drc.bands = (uint8_t)bands; |
531 | 506 | memcpy(dec->drc.top, top, bands); |
532 | 506 | memcpy(dec->drc.ctl, ctl, bands); |
533 | 506 | memcpy(dec->drc.sign, sign, bands); |
534 | 506 | memcpy(dec->drc.excluded, excluded, sizeof(excluded)); |
535 | 506 | if (has_ref) { dec->drc.ref = (uint8_t)ref; dec->drc.ref_present = true; } |
536 | 506 | } |
537 | | |
538 | | static void apply_drc(faad_decoder *dec) |
539 | 0 | { |
540 | 0 | float gain[16]; |
541 | 0 | for (unsigned c = 0; c < MAX_CHANNELS; c++) dec->drc.sbr_gain[c] = 1.0f; |
542 | 0 | for (unsigned b = 0; b < dec->drc.bands; b++) { |
543 | 0 | 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 | 0 | gain[b] = exp2f(dec->drc.ctl[b] * scale / (127.0f * 24.0f)); |
547 | 0 | } |
548 | 0 | for (unsigned c = 0; c < dec->num_channels; c++) { |
549 | 0 | if (dec->drc.excluded[c]) continue; |
550 | 0 | unsigned windows = dec->win_seq[c] == EIGHT_SHORT_SEQUENCE ? 8 : 1; |
551 | 0 | unsigned length = (FRAME_IS_960(dec) ? 960 : 1024) / windows; |
552 | 0 | unsigned start = 0; |
553 | 0 | for (unsigned b = 0; b < dec->drc.bands; b++) { |
554 | 0 | unsigned end = 4u * (dec->drc.top[b] + 1u) / windows; |
555 | 0 | if (end > length) end = length; |
556 | 0 | if (gain[b] != 1.0f && end > start) { |
557 | 0 | dec->drc.applied = true; |
558 | 0 | if (gain[b] > 1.0f) dec->drc.boost = true; |
559 | 0 | for (unsigned w = 0; w < windows; w++) |
560 | 0 | for (unsigned i = start; i < end; i++) dec->spec[c][w * length + i] *= gain[b]; |
561 | 0 | } |
562 | 0 | start = end; |
563 | 0 | } |
564 | | /* The HF envelope is absolute energy, independent of core amplitude. */ |
565 | 0 | dec->drc.sbr_gain[c] = gain[dec->drc.bands - 1] * gain[dec->drc.bands - 1]; |
566 | 0 | } |
567 | 0 | } |
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 | 0 | { |
573 | 0 | float target_gain = dec->config.drc_target_level != 0.0f && dec->drc.ref_present |
574 | 0 | ? exp2f(((float)dec->drc.ref + 4.0f * dec->config.drc_target_level) / 24.0f) : 1.0f; |
575 | 0 | float previous_gain = dec->drc.previous_norm ? dec->drc.previous_norm : 1.0f; |
576 | 0 | if (target_gain != 1.0f || previous_gain != 1.0f || (dec->drc.boost && dec->config.output_format != FAAD_OUTPUT_FLOAT)) { |
577 | 0 | bool floating = dec->config.output_format == FAAD_OUTPUT_FLOAT; |
578 | 0 | bool limit = target_gain > 1.0f || previous_gain > 1.0f || dec->drc.boost; |
579 | 0 | float norm = target_gain / 32768.0f; |
580 | 0 | float ramp = (target_gain - previous_gain) / frame_samples; |
581 | 0 | for (uint32_t i = 0; i < frame_samples; i++) { |
582 | 0 | float gain = ramp == 0.0f ? norm : (previous_gain + ramp * (i + 1)) / 32768.0f; |
583 | 0 | for (uint32_t c = 0; c < num_chs; c++) { |
584 | 0 | float sample = src[c][i] * gain; |
585 | 0 | if (floating) ((float *)out_pcm)[i * num_chs + c] = sample; |
586 | 0 | else { |
587 | 0 | float magnitude = fabsf(sample); |
588 | 0 | if (limit && magnitude > 0.89f) |
589 | 0 | sample = copysignf(0.89f + 0.11f * (1.0f - 1.0f / (1.0f + (magnitude - 0.89f) / 0.11f)), sample); |
590 | 0 | ((float *)src[c])[i] = sample * 32768.0f; |
591 | 0 | } |
592 | 0 | } |
593 | 0 | } |
594 | 0 | if (target_gain != 1.0f || previous_gain != 1.0f) dec->drc.applied = true; |
595 | 0 | if (floating) { |
596 | 0 | dec->drc.previous_norm = target_gain; |
597 | 0 | return true; |
598 | 0 | } |
599 | 0 | } |
600 | 0 | dec->drc.previous_norm = target_gain; |
601 | 0 | return false; |
602 | 0 | } |
603 | | |
604 | | #endif |
605 | | |
606 | | static faad_status resolve_config(const faad_config *cfg, faad_config *resolved) |
607 | 3.26k | { |
608 | 3.26k | faad_config_init(resolved, sizeof(*resolved)); |
609 | 3.26k | if (!cfg) return FAAD_OK; |
610 | 3.26k | 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 | 3.26k | #define COPY_CONFIG_FIELD(field) \ |
614 | 19.5k | if (cfg->struct_size >= offsetof(faad_config, field) + sizeof(cfg->field)) \ |
615 | 19.5k | resolved->field = cfg->field |
616 | 3.26k | COPY_CONFIG_FIELD(stream_format); |
617 | 3.26k | COPY_CONFIG_FIELD(output_format); |
618 | 3.26k | COPY_CONFIG_FIELD(downmix_mode); |
619 | 3.26k | #ifndef FAAD_DISABLE_DRC |
620 | 3.26k | COPY_CONFIG_FIELD(drc_cut); |
621 | 3.26k | COPY_CONFIG_FIELD(drc_boost); |
622 | 3.26k | COPY_CONFIG_FIELD(drc_target_level); |
623 | 3.26k | if (resolved->drc_cut > 127 || resolved->drc_boost > 127 |
624 | 3.26k | || (resolved->drc_target_level != 0.0f |
625 | 0 | && !(resolved->drc_target_level >= -31.75f && resolved->drc_target_level <= -10.0f))) |
626 | 0 | return FAAD_ERR_INVALID_ARGUMENT; |
627 | 3.26k | resolved->drc_target_level = roundf(4.0f * resolved->drc_target_level) / 4.0f; |
628 | 3.26k | #endif |
629 | 3.26k | #undef COPY_CONFIG_FIELD |
630 | 3.26k | return (resolved->stream_format == FAAD_STREAM_RAW || resolved->stream_format == FAAD_STREAM_ADTS) |
631 | 3.26k | && (resolved->output_format == FAAD_OUTPUT_16BIT || resolved->output_format == FAAD_OUTPUT_24BIT |
632 | 0 | || resolved->output_format == FAAD_OUTPUT_24IN32 || resolved->output_format == FAAD_OUTPUT_FLOAT) |
633 | 3.26k | && downmix_mode_is_valid(resolved->downmix_mode) ? FAAD_OK : FAAD_ERR_INVALID_ARGUMENT; |
634 | 3.26k | } |
635 | | |
636 | | static void faad_init_global_tables_impl(void) |
637 | 1 | { |
638 | 1 | extern void init_dequant_tables(void); |
639 | 1 | extern void init_huffman_luts(void); |
640 | 1 | extern void init_windows(void); |
641 | 1 | #ifndef FAAD_DISABLE_SBR |
642 | 1 | extern void init_qmf_twiddles(void); |
643 | 1 | #endif |
644 | 1 | extern void init_is_tables(void); |
645 | 1 | #ifndef FAAD_DISABLE_PS |
646 | 1 | extern void init_ps_tables(void); |
647 | 1 | #endif |
648 | | |
649 | 1 | init_dequant_tables(); |
650 | 1 | init_huffman_luts(); |
651 | 1 | init_windows(); |
652 | 1 | #ifndef FAAD_DISABLE_SBR |
653 | 1 | init_qmf_twiddles(); |
654 | 1 | #endif |
655 | 1 | init_is_tables(); |
656 | 1 | #ifndef FAAD_DISABLE_PS |
657 | 1 | init_ps_tables(); |
658 | 1 | #endif |
659 | 1 | } |
660 | | |
661 | | void faad_init_global_tables(void) |
662 | 3.26k | { |
663 | 3.26k | static faac_once_t once = FAAC_ONCE_INIT; |
664 | 3.26k | faac_once_run(&once, faad_init_global_tables_impl); |
665 | 3.26k | } |
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 | 3.26k | { |
671 | 3.26k | dec->config = *resolved; |
672 | | |
673 | 3.26k | dec->pns_seed = 0x12345678; |
674 | | |
675 | 3.26k | if (asc_buf && asc_len > 0) { |
676 | 3.26k | BitReader bs; |
677 | 3.26k | bits_init(&bs, asc_buf, asc_len); |
678 | 3.26k | faad_status st = asc_decode(&bs, &dec->asc); |
679 | 3.26k | if (st != FAAD_OK) return st; |
680 | | |
681 | 3.18k | dec->num_channels = asc_channels(&dec->asc); |
682 | 3.18k | if (dec->num_channels > MAX_CHANNELS) return FAAD_ERR_UNSUPPORTED; |
683 | 3.18k | dec->core_sample_rate = dec->asc.sample_rate ? dec->asc.sample_rate : 44100; |
684 | 3.18k | if (get_sr_index(dec->core_sample_rate) < 0) return FAAD_ERR_UNSUPPORTED; |
685 | 3.18k | dec->sample_rate = dec->asc.is_sbr ? dec->asc.sbr_sample_rate : dec->core_sample_rate; |
686 | 3.18k | uint32_t core_samples = FRAME_IS_960(dec) ? 960 : 1024; |
687 | 3.18k | dec->frame_samples = dec->asc.is_sbr ? (core_samples * 2) : core_samples; |
688 | 3.18k | dec->asc_parsed = true; |
689 | 3.18k | faad_layout_update(dec); |
690 | 3.18k | dec->format_known = dec->asc.num_channels != 0 || dec->asc.pce.channels != 0; |
691 | 3.18k | dec->sbr_seen = dec->asc.is_sbr; |
692 | 3.18k | dec->ps_seen = dec->asc.is_ps; |
693 | 3.18k | } else { |
694 | 0 | dec->num_channels = MAX_CHANNELS < 2 ? 1 : 2; |
695 | 0 | dec->sample_rate = 44100; |
696 | 0 | dec->core_sample_rate = 44100; |
697 | 0 | dec->frame_samples = 1024; |
698 | 0 | } |
699 | 3.18k | dec->core_channels = dec->num_channels; |
700 | 3.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 | 3.18k | *out_dec = dec; |
707 | 3.18k | return FAAD_OK; |
708 | 3.26k | } |
709 | | |
710 | | static void free_split_state(faad_decoder *dec) |
711 | 3.26k | { |
712 | 3.26k | if (!dec) return; |
713 | 26.1k | #define FREE_PART(field) do { if (dec->field) FreeMemory(dec->field); } while (0) |
714 | 3.26k | #if MAX_CHANNELS >= 3 |
715 | 11.0k | while (dec->coupling) { |
716 | 7.77k | CouplingChannel *next = dec->coupling->next; |
717 | 7.77k | if (dec->coupling->overlap) FreeMemory(dec->coupling->overlap); |
718 | 7.77k | FreeMemory(dec->coupling); |
719 | 7.77k | dec->coupling = next; |
720 | 7.77k | } |
721 | 3.26k | #endif |
722 | 3.26k | FREE_PART(spec); |
723 | 3.26k | FREE_PART(overlap); |
724 | 3.26k | FREE_PART(prev_spec); |
725 | 3.26k | #ifndef FAAD_DISABLE_SBR |
726 | 3.26k | FREE_PART(sbr); |
727 | 3.26k | FREE_PART(sbr_el); |
728 | 3.26k | FREE_PART(sbr_scratch.y); |
729 | 3.26k | #endif |
730 | 3.26k | #ifndef FAAD_DISABLE_PS |
731 | 3.26k | FREE_PART(ps); |
732 | 3.26k | #endif |
733 | | #if defined(FAAD_DISABLE_SBR) || MAX_CHANNELS < 2 |
734 | | FREE_PART(scratch); |
735 | | #endif |
736 | 3.26k | FREE_PART(pcm); |
737 | 3.26k | FreeMemory(dec); |
738 | 3.26k | #undef FREE_PART |
739 | 3.26k | } |
740 | | |
741 | | #ifndef FAAD_DISABLE_SBR |
742 | | static faad_status alloc_optional(faad_decoder *dec, void **ptr, size_t size) |
743 | 140k | { |
744 | 140k | if (*ptr) return FAAD_OK; |
745 | 6.39k | *ptr = AllocMemory(size); |
746 | 6.39k | if (!*ptr) return FAAD_ERR_NO_MEMORY; |
747 | 6.39k | memset(*ptr, 0, size); |
748 | 6.39k | dec->allocated_bytes += size; |
749 | 6.39k | if (size > dec->largest_allocation) dec->largest_allocation = size; |
750 | 6.39k | return FAAD_OK; |
751 | 6.39k | } |
752 | | |
753 | | faad_status faad_ensure_sbr(faad_decoder *dec) |
754 | 46.2k | { |
755 | 46.2k | if (alloc_optional(dec, (void **)&dec->sbr, sizeof(SBRChannel[MAX_CHANNELS])) != FAAD_OK |
756 | 46.2k | || alloc_optional(dec, (void **)&dec->sbr_el, sizeof(SBRElement[MAX_CHANNELS])) != FAAD_OK |
757 | 46.2k | || alloc_optional(dec, (void **)&dec->sbr_scratch.y, |
758 | 46.2k | sizeof(float[SBR_MAX_BANDS][SBR_BUF_SLOTS][2])) != FAAD_OK) |
759 | 0 | return FAAD_ERR_NO_MEMORY; |
760 | 46.2k | dec->sbr_scratch.x_low = dec->sbr_scratch.y; |
761 | 46.2k | return FAAD_OK; |
762 | 46.2k | } |
763 | | |
764 | | #ifndef FAAD_DISABLE_PS |
765 | | faad_status faad_ensure_ps(faad_decoder *dec) |
766 | 1.68k | { |
767 | 1.68k | return alloc_optional(dec, (void **)&dec->ps, sizeof(PSState)); |
768 | 1.68k | } |
769 | | #endif |
770 | | #endif |
771 | | |
772 | 13.0k | #define ALLOC_PART(field, size) do { \ |
773 | 13.0k | dec->field = AllocMemory(size); \ |
774 | 13.0k | if (!dec->field) { free_split_state(dec); return FAAD_ERR_NO_MEMORY; } \ |
775 | 13.0k | memset(dec->field, 0, size); \ |
776 | 13.0k | dec->allocated_bytes += (size); \ |
777 | 13.0k | if ((size) > dec->largest_allocation) dec->largest_allocation = (size); \ |
778 | 13.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 | 3.26k | { |
784 | 3.26k | if (!out) return FAAD_ERR_INVALID_ARGUMENT; |
785 | 3.26k | *out = NULL; |
786 | 3.26k | faad_config resolved; |
787 | 3.26k | if (resolve_config(config, &resolved) != FAAD_OK |
788 | 3.26k | || ((asc_buf == NULL) != (asc_len == 0)) |
789 | 3.26k | || (resolved.stream_format == FAAD_STREAM_RAW && !asc_len)) |
790 | 0 | return FAAD_ERR_INVALID_ARGUMENT; |
791 | 3.26k | faad_init_global_tables(); |
792 | 3.26k | faad_decoder *dec = AllocMemory(sizeof(*dec)); |
793 | 3.26k | if (!dec) return FAAD_ERR_NO_MEMORY; |
794 | 3.26k | memset(dec, 0, sizeof(*dec)); |
795 | 3.26k | dec->allocated_bytes = sizeof(*dec); |
796 | 3.26k | dec->largest_allocation = sizeof(*dec); |
797 | 3.26k | ALLOC_PART(spec, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG])); |
798 | 3.26k | ALLOC_PART(overlap, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG])); |
799 | 3.26k | ALLOC_PART(prev_spec, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG])); |
800 | 3.26k | ALLOC_PART(pcm, sizeof(float[MAX_CHANNELS * FRAME_SAMPLES_MAX])); |
801 | 3.26k | #if !defined(FAAD_DISABLE_SBR) && MAX_CHANNELS >= 2 |
802 | | /* Core PCM is packed into the first half until every IMDCT finishes. */ |
803 | 3.26k | dec->scratch = (FrameScratch *)(dec->pcm + MAX_CHANNELS * FRAME_LEN_LONG); |
804 | | #else |
805 | | ALLOC_PART(scratch, sizeof(FrameScratch)); |
806 | | #endif |
807 | 3.26k | faad_status st = init_decoder(dec, &resolved, asc_buf, asc_len, out); |
808 | 3.26k | if (st != FAAD_OK) { free_split_state(dec); return st; } |
809 | 3.18k | #ifndef FAAD_DISABLE_SBR |
810 | 3.18k | if (dec->asc.is_sbr && faad_ensure_sbr(dec) != FAAD_OK) st = FAAD_ERR_NO_MEMORY; |
811 | 3.18k | #ifndef FAAD_DISABLE_PS |
812 | 3.18k | if (st == FAAD_OK && dec->asc.is_ps && faad_ensure_ps(dec) != FAAD_OK) |
813 | 0 | st = FAAD_ERR_NO_MEMORY; |
814 | 3.18k | #endif |
815 | 3.18k | #endif |
816 | 3.18k | if (st != FAAD_OK) { *out = NULL; free_split_state(dec); } |
817 | 3.18k | return st; |
818 | 3.26k | } |
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 | 3.18k | { |
874 | 3.18k | if (!decoder) return FAAD_ERR_INVALID_ARGUMENT; |
875 | 3.18k | faad_decoder *dec = *decoder; |
876 | 3.18k | if (!dec) return FAAD_OK; |
877 | 3.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 | 3.18k | free_split_state(dec); |
885 | 3.18k | return FAAD_OK; |
886 | 3.18k | } |
887 | | |
888 | | FAADAPI faad_status faad_decoder_get_info(const faad_decoder *decoder, faad_stream_info *out_info) |
889 | 3.18k | { |
890 | 3.18k | if (!decoder || !out_info || out_info->struct_size < STREAM_INFO_BASELINE_SIZE) |
891 | 0 | return FAAD_ERR_INVALID_ARGUMENT; |
892 | 3.18k | faad_stream_info info; |
893 | 3.18k | memset(&info, 0, sizeof(info)); |
894 | 3.18k | info.struct_size = bounded_size(out_info->struct_size, sizeof(info)); |
895 | 3.18k | info.max_output_bytes = decoder->max_output_bytes; |
896 | 3.18k | if (decoder->format_known) info.flags |= FAAD_STREAM_FORMAT_KNOWN; |
897 | 3.18k | #ifndef FAAD_DISABLE_DRC |
898 | 3.18k | info.drc_ref_level = -0.25f * (float)decoder->drc.ref; |
899 | 3.18k | if (decoder->drc.ref_present) info.flags |= FAAD_STREAM_DRC_REF_LEVEL; |
900 | 3.18k | #endif |
901 | 3.18k | if (!(info.flags & FAAD_STREAM_FORMAT_KNOWN)) { |
902 | 0 | memcpy(out_info, &info, info.struct_size); |
903 | 0 | return FAAD_OK; |
904 | 0 | } |
905 | 3.18k | bool sbr = decoder->asc.is_sbr || decoder->sbr_seen; |
906 | 3.18k | info.sample_rate = decoder->core_sample_rate; |
907 | 3.18k | uint32_t core_samples = FRAME_IS_960(decoder) ? 960 : 1024; |
908 | 3.18k | info.frame_samples = core_samples; |
909 | 3.18k | #ifndef FAAD_DISABLE_SBR |
910 | 3.18k | if (sbr) { info.sample_rate *= 2; info.frame_samples = core_samples * 2; } |
911 | 3.18k | #endif |
912 | 3.18k | info.channels = decoder->num_channels; |
913 | 3.18k | #ifndef FAAD_DISABLE_PS |
914 | 3.18k | if (decoder->ps_seen && info.channels == 1) info.channels = 2; |
915 | 3.18k | #endif |
916 | 3.18k | info.channels = downmix_out_chs(decoder->config.downmix_mode, info.channels); |
917 | 3.18k | info.object_type = (decoder->asc.is_ps || decoder->ps_seen) ? FAAD_OBJ_HE_AAC_V2 |
918 | 3.18k | : sbr ? FAAD_OBJ_HE_AAC_V1 : FAAD_OBJ_LC; |
919 | 3.18k | #ifndef FAAD_DISABLE_SBR |
920 | 3.18k | info.decoder_delay = sbr ? 2 * FAAD_SBR_CORE_DELAY : 0; |
921 | 3.18k | #endif |
922 | 3.18k | info.channel_mask = channel_mask(decoder, info.channels); |
923 | 3.18k | if (decoder->pcm_emitted) { |
924 | 0 | info.sample_rate = decoder->emitted_format.sample_rate; |
925 | 0 | info.channels = decoder->emitted_format.channels; |
926 | 0 | info.frame_samples = decoder->emitted_format.frame_samples; |
927 | 0 | info.channel_mask = decoder->emitted_format.channel_mask; |
928 | 0 | info.decoder_delay = decoder->emitted_format.decoder_delay; |
929 | 0 | } |
930 | 3.18k | memcpy(out_info, &info, info.struct_size); |
931 | | |
932 | 3.18k | return FAAD_OK; |
933 | 3.18k | } |
934 | | |
935 | | FAADAPI faad_status faad_decoder_flush(faad_decoder *decoder) |
936 | 0 | { |
937 | 0 | if (!decoder) return FAAD_ERR_INVALID_ARGUMENT; |
938 | | |
939 | 0 | memset(decoder->overlap, 0, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG])); |
940 | 0 | memset(decoder->spec, 0, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG])); |
941 | 0 | memset(decoder->prev_spec, 0, sizeof(float[MAX_CHANNELS][FRAME_LEN_LONG])); |
942 | 0 | memset(decoder->prev_window_shape, 0, sizeof(decoder->prev_window_shape)); |
943 | 0 | memset(decoder->prev_window_seq, 0, sizeof(decoder->prev_window_seq)); |
944 | 0 | memset(decoder->win_shape, 0, sizeof(decoder->win_shape)); |
945 | 0 | memset(decoder->win_seq, 0, sizeof(decoder->win_seq)); |
946 | 0 | #ifndef FAAD_DISABLE_SBR |
947 | 0 | memset(decoder->elem_nch, 0, sizeof(decoder->elem_nch)); |
948 | 0 | #endif |
949 | 0 | memset(decoder->pcm, 0, sizeof(float[MAX_CHANNELS * FRAME_SAMPLES_MAX])); |
950 | 0 | decoder->spectral_downmix_active = false; |
951 | 0 | decoder->spectral_downmix_channels = 0; |
952 | 0 | decoder->spectral_downmix_layout = 0; |
953 | 0 | #ifndef FAAD_DISABLE_DRC |
954 | 0 | memset(&decoder->drc, 0, sizeof(decoder->drc)); |
955 | 0 | #endif |
956 | 0 | decoder->consecutive_errors = 0; |
957 | 0 | decoder->pns_seed = 0x12345678; |
958 | 0 | #if MAX_CHANNELS >= 3 |
959 | 0 | for (CouplingChannel *cc = decoder->coupling; cc; cc = cc->next) { |
960 | 0 | if (cc->overlap) memset(cc->overlap, 0, sizeof(float[FRAME_LEN_LONG])); |
961 | 0 | cc->prev_shape = 0; |
962 | 0 | cc->present = false; |
963 | 0 | } |
964 | 0 | #endif |
965 | 0 | #ifndef FAAD_DISABLE_SBR |
966 | 0 | if (decoder->sbr) memset(decoder->sbr, 0, sizeof(SBRChannel[MAX_CHANNELS])); |
967 | 0 | if (decoder->sbr_el) memset(decoder->sbr_el, 0, sizeof(SBRElement[MAX_CHANNELS])); |
968 | 0 | #endif |
969 | 0 | #ifndef FAAD_DISABLE_PS |
970 | 0 | if (decoder->ps) memset(decoder->ps, 0, sizeof(PSState)); |
971 | 0 | #endif |
972 | 0 | decoder->sbr_present = false; |
973 | 0 | decoder->ps_present = false; |
974 | |
|
975 | 0 | return FAAD_OK; |
976 | 0 | } |
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 | 467M | { |
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 | 467M | v = v < 32767.0f ? v : 32767.0f; |
1042 | 467M | v = v > -32768.0f ? v : -32768.0f; |
1043 | 467M | v += 12582912.0f; |
1044 | | /* A union, not memcpy: with -fno-builtin (ESP-IDF on Xtensa) memcpy becomes a call per sample. */ |
1045 | 467M | union { float f; int32_t i; } u; |
1046 | 467M | u.f = v; |
1047 | 467M | return (int16_t)u.i; |
1048 | 467M | } |
1049 | | |
1050 | | /* Both integer 24-bit containers share scaling, rounding and clipping. */ |
1051 | | static inline int32_t pcm_to_s24(float v) |
1052 | 0 | { |
1053 | 0 | v *= 256.0f; |
1054 | 0 | v = v < 8388607.0f ? v : 8388607.0f; |
1055 | 0 | v = v > -8388608.0f ? v : -8388608.0f; |
1056 | 0 | return (int32_t)lrintf(v); |
1057 | 0 | } |
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 | 241k | { |
1066 | 241k | if (bytes_consumed) *bytes_consumed = 0; |
1067 | 241k | if (bytes_written) *bytes_written = 0; |
1068 | 241k | if (frame_flags) *frame_flags = 0; |
1069 | 241k | 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 | 241k | if (decoder->config.stream_format == FAAD_STREAM_RAW && in_bytes > UINT32_MAX / 8) |
1074 | 0 | return FAAD_ERR_INVALID_ARGUMENT; |
1075 | 241k | uint32_t sample_bytes = output_sample_bytes(decoder->config.output_format); |
1076 | 241k | if (sample_bytes != 3 && ((uintptr_t)out_pcm & (sample_bytes - 1))) |
1077 | 0 | return FAAD_ERR_INVALID_ARGUMENT; |
1078 | 241k | if (out_cap_bytes < decoder->max_output_bytes) return FAAD_ERR_OUTPUT_TOO_SMALL; |
1079 | 241k | if (!in_bytes) return FAAD_ERR_NEED_MORE_DATA; |
1080 | 241k | const uint32_t prior_channels = decoder->num_channels; |
1081 | 241k | const uint32_t prior_errors = decoder->consecutive_errors; |
1082 | | |
1083 | 241k | BitReader bs; |
1084 | 241k | bits_init(&bs, in_buf, in_bytes); |
1085 | 241k | uint32_t adts_frame_len = in_bytes; |
1086 | | |
1087 | 241k | 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 | 0 | if (in_buf[0] == 0xff && in_bytes == 1) return FAAD_ERR_NEED_MORE_DATA; |
1091 | 0 | if (in_bytes < 2 || in_buf[0] != 0xff || (in_buf[1] & 0xf6) != 0xf0) { |
1092 | 0 | uint32_t skip = 1; |
1093 | 0 | while (skip + 1 < in_bytes && !(in_buf[skip] == 0xff |
1094 | 0 | && (in_buf[skip + 1] & 0xf6) == 0xf0)) skip++; |
1095 | 0 | if (skip + 1 >= in_bytes) skip = in_bytes - (in_buf[in_bytes - 1] == 0xff); |
1096 | 0 | *bytes_consumed = skip; |
1097 | 0 | return FAAD_ERR_SYNC_LOST; |
1098 | 0 | } |
1099 | 0 | uint32_t header_bytes = (in_buf[1] & 1) ? 7 : 9; |
1100 | 0 | if (in_bytes < header_bytes) return FAAD_ERR_NEED_MORE_DATA; |
1101 | 0 | adts_frame_len = ((uint32_t)(in_buf[3] & 3) << 11) |
1102 | 0 | | ((uint32_t)in_buf[4] << 3) | (in_buf[5] >> 5); |
1103 | 0 | if (adts_frame_len < header_bytes) { |
1104 | 0 | *bytes_consumed = 1; |
1105 | 0 | return FAAD_ERR_DECODE_FAILED; |
1106 | 0 | } |
1107 | 0 | if (adts_frame_len > in_bytes) return FAAD_ERR_NEED_MORE_DATA; |
1108 | 0 | AudioSpecificConfig asc; |
1109 | 0 | faad_status st = adts_decode_header(&bs, &asc, &adts_frame_len); |
1110 | 0 | 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 | 0 | *bytes_consumed = st == FAAD_ERR_DECODE_FAILED ? 1 : adts_frame_len; |
1114 | 0 | return st != FAAD_OK ? st : FAAD_ERR_UNSUPPORTED; |
1115 | 0 | } |
1116 | 0 | if (!asc.num_channels) asc.pce = decoder->asc.pce; |
1117 | 0 | decoder->asc = asc; |
1118 | 0 | 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 | 0 | decoder->core_channels = (!asc.num_channels && !asc.pce.channels && decoder->pcm_emitted) |
1122 | 0 | ? decoder->core_channels : asc_channels(&asc); |
1123 | 0 | decoder->core_sample_rate = asc.sample_rate; |
1124 | 0 | bs.len = adts_frame_len; |
1125 | 0 | } |
1126 | 241k | *bytes_consumed = adts_frame_len; |
1127 | 241k | decoder->num_channels = decoder->core_channels; |
1128 | 241k | #ifndef FAAD_DISABLE_DRC |
1129 | 241k | decoder->drc.present = false; |
1130 | 241k | #endif |
1131 | 241k | bool decode_success = true; |
1132 | 241k | bool degraded = false; |
1133 | | #ifdef FAAD_STATS |
1134 | | g_faadStats.totalFrames++; |
1135 | | #endif |
1136 | 241k | uint32_t active_chs = decoder->num_channels; |
1137 | 241k | if (active_chs > MAX_CHANNELS) active_chs = MAX_CHANNELS; |
1138 | 653k | for (uint32_t c = 0; c < active_chs; c++) |
1139 | 412k | memset(decoder->spec[c], 0, sizeof(decoder->spec[c])); |
1140 | 241k | decoder->sbr_present = false; |
1141 | 241k | 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 | 241k | #if MAX_CHANNELS >= 3 |
1150 | 241k | CouplingTarget coupling_targets[MAX_CHANNELS]; |
1151 | 241k | unsigned coupling_target_count = 0; |
1152 | 794k | for (CouplingChannel *cc = decoder->coupling; cc; cc = cc->next) cc->present = false; |
1153 | 241k | #endif |
1154 | 241k | bool have_coupling = false; |
1155 | 241k | uint32_t ch_idx = 0; |
1156 | 241k | uint32_t last_elem_type = ID_SCE; |
1157 | 241k | uint32_t last_elem_ch = 0; |
1158 | 241k | uint32_t occupied = 0; |
1159 | 241k | uint32_t seq = 1; /* element types, two bits each, behind a leading 1 */ |
1160 | 241k | #ifndef FAAD_DISABLE_SBR |
1161 | 241k | uint8_t elem_nch[MAX_CHANNELS] = {0}; |
1162 | 241k | #endif |
1163 | | |
1164 | 241k | bool saw_end = false; |
1165 | 241k | 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 | 669k | while (bits_get_consumed(&bs) + 3 <= bs.len * 8) { |
1169 | 539k | uint32_t syntax_id = bits_get(&bs, 3); |
1170 | | #ifdef FAAD_STATS |
1171 | | g_faadStats.elementCounts[syntax_id]++; |
1172 | | #endif |
1173 | 539k | if (syntax_id == ID_END) { |
1174 | 35.6k | saw_end = true; |
1175 | 35.6k | break; |
1176 | 504k | } else if (syntax_id == ID_SCE || syntax_id == ID_LFE) { |
1177 | 391k | seq = seq << 2 | syntax_id; |
1178 | 391k | uint32_t elem_ch = element_slot(decoder, syntax_id, bits_show(&bs, 4), ch_idx, occupied); |
1179 | 391k | if (elem_ch >= MAX_CHANNELS |
1180 | 387k | || (SLOTS_BY_TAG(decoder) && (occupied & (1u << elem_ch)))) { |
1181 | 4.30k | decode_success = false; break; |
1182 | 4.30k | } |
1183 | 386k | occupied |= 1u << elem_ch; |
1184 | 386k | #ifndef FAAD_DISABLE_SBR |
1185 | 386k | elem_nch[elem_ch] = 1; |
1186 | 386k | #endif |
1187 | 386k | last_elem_ch = elem_ch; |
1188 | 386k | #if MAX_CHANNELS >= 3 |
1189 | 386k | coupling_targets[coupling_target_count++] = (CouplingTarget){ |
1190 | 386k | bs, decoder->pns_seed, (uint8_t)syntax_id, (uint8_t)bits_show(&bs, 4), (uint8_t)elem_ch }; |
1191 | 386k | #endif |
1192 | 386k | last_elem_type = syntax_id; |
1193 | | #ifdef FAAD_STATS |
1194 | | unsigned b0 = bits_get_consumed(&bs); |
1195 | | #endif |
1196 | 386k | ICSInfo *ics = &decoder->scratch->cpe.ics[0]; /* cleared by decode_sce */ |
1197 | 386k | if (decode_sce(&bs, decoder, ics, elem_ch) != FAAD_OK) { |
1198 | 42.1k | decode_success = false; /* the rest of the payload is out of step */ |
1199 | 42.1k | break; |
1200 | 42.1k | } |
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 | 344k | decoder->win_seq[elem_ch] = ics->window_sequence; |
1206 | 344k | decoder->win_shape[elem_ch] = ics->window_shape; |
1207 | 344k | apply_pns(ics, decoder->spec[elem_ch], &decoder->pns_seed); |
1208 | 344k | apply_tns(ics, decoder->spec[elem_ch]); |
1209 | 344k | ch_idx += 1; |
1210 | 344k | } 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 | 31.4k | seq = seq << 2 | ID_CPE; |
1216 | 31.4k | uint32_t elem_ch = element_slot(decoder, syntax_id, bits_show(&bs, 4), ch_idx, occupied); |
1217 | 31.4k | if (elem_ch + 1 >= MAX_CHANNELS |
1218 | 31.2k | || (SLOTS_BY_TAG(decoder) && (occupied & (3u << elem_ch)))) { |
1219 | 245 | decode_success = false; break; |
1220 | 245 | } |
1221 | 31.2k | occupied |= 3u << elem_ch; |
1222 | 31.2k | #ifndef FAAD_DISABLE_SBR |
1223 | 31.2k | elem_nch[elem_ch] = 2; |
1224 | 31.2k | #endif |
1225 | 31.2k | last_elem_ch = elem_ch; |
1226 | 31.2k | #if MAX_CHANNELS >= 3 |
1227 | 31.2k | coupling_targets[coupling_target_count++] = (CouplingTarget){ |
1228 | 31.2k | bs, decoder->pns_seed, ID_CPE, (uint8_t)bits_show(&bs, 4), (uint8_t)elem_ch }; |
1229 | 31.2k | #endif |
1230 | 31.2k | last_elem_type = ID_CPE; |
1231 | 31.2k | CPEInfo *cpe = &decoder->scratch->cpe; |
1232 | 31.2k | memset(cpe, 0, sizeof(*cpe)); |
1233 | | #ifdef FAAD_STATS |
1234 | | unsigned b0 = bits_get_consumed(&bs); |
1235 | | #endif |
1236 | 31.2k | if (decode_cpe(&bs, decoder, cpe, elem_ch) != FAAD_OK) { |
1237 | 7.36k | decode_success = false; |
1238 | 7.36k | break; |
1239 | 7.36k | } |
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 | 71.5k | for (uint32_t i = 0; i < 2; i++) { |
1252 | 47.7k | decoder->win_seq[elem_ch + i] = cpe->ics[i].window_sequence; |
1253 | 47.7k | decoder->win_shape[elem_ch + i] = cpe->ics[i].window_shape; |
1254 | 47.7k | } |
1255 | | |
1256 | 23.8k | apply_pns(&cpe->ics[0], decoder->spec[elem_ch], &decoder->pns_seed); |
1257 | 23.8k | apply_pns(&cpe->ics[1], decoder->spec[elem_ch + 1], &decoder->pns_seed); |
1258 | 23.8k | apply_ms_stereo(cpe, decoder->spec[elem_ch], decoder->spec[elem_ch + 1]); |
1259 | 23.8k | apply_is_stereo(cpe, decoder->spec[elem_ch], decoder->spec[elem_ch + 1]); |
1260 | 23.8k | apply_tns(&cpe->ics[0], decoder->spec[elem_ch]); |
1261 | 23.8k | apply_tns(&cpe->ics[1], decoder->spec[elem_ch + 1]); |
1262 | | |
1263 | 23.8k | ch_idx += 2; |
1264 | 23.8k | #endif |
1265 | 81.5k | } else if (syntax_id == ID_CCE) { |
1266 | 19.1k | #if MAX_CHANNELS >= 3 |
1267 | 19.1k | faad_status st = decode_cce(&bs, decoder); |
1268 | 19.1k | if (st == FAAD_ERR_NO_MEMORY) return st; |
1269 | 19.1k | if (st != FAAD_OK) { decode_success = false; break; } |
1270 | 7.74k | have_coupling = true; |
1271 | | #else |
1272 | | return FAAD_ERR_UNSUPPORTED; |
1273 | | #endif |
1274 | 62.3k | } else if (syntax_id == ID_DSE) { |
1275 | 15.8k | decode_dse(&bs); |
1276 | 46.5k | } else if (syntax_id == ID_PCE) { |
1277 | 10.0k | if (decode_pce(&bs, decoder) != FAAD_OK) { decode_success = false; break; } |
1278 | 36.4k | } else if (syntax_id == ID_FIL) { |
1279 | 36.4k | uint32_t count = bits_get(&bs, 4); |
1280 | 36.4k | if (count == 15) count += bits_get(&bs, 8) - 1; |
1281 | 36.4k | if (count > 0) { |
1282 | 28.8k | uint32_t fill_end = bits_get_consumed(&bs) + count * 8; |
1283 | 28.8k | uint32_t ext_type = bits_get(&bs, 4); |
1284 | 28.8k | if (ext_type == SBR_EXTENSION_DATA || ext_type == SBR_EXTENSION_DATA_CRC) { |
1285 | 23.8k | 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 | 23.8k | uint8_t payload[269]; /* maximum fill count: 15 + 255 - 1 */ |
1293 | 23.8k | BitReader source = bs, fill; |
1294 | 23.8k | source.byte_pos = (fill_end - count * 8) / 8; |
1295 | 23.8k | source.bit_pos = (fill_end - count * 8) % 8; |
1296 | 258k | for (uint32_t i = 0; i < count; i++) payload[i] = (uint8_t)bits_get(&source, 8); |
1297 | 23.8k | if (source.overread) { |
1298 | 714 | decode_success = false; |
1299 | 714 | break; |
1300 | 714 | } |
1301 | 23.1k | bits_init(&fill, payload, count); |
1302 | 23.1k | bits_skip(&fill, 4); /* extension type already read */ |
1303 | 23.1k | faad_status sbr_st = sbr_decode_extension(decoder, &fill, ch0, last_elem_type, ext_type == SBR_EXTENSION_DATA_CRC); |
1304 | 23.1k | bits_skip(&bs, bits_get_consumed(&fill) - 4); |
1305 | 23.1k | #ifndef FAAD_DISABLE_SBR |
1306 | 23.1k | if (sbr_st == FAAD_ERR_NO_MEMORY) return sbr_st; |
1307 | 23.1k | 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 | 19.1k | uint32_t nch = (last_elem_type == ID_CPE) ? 2 : 1; |
1312 | 38.4k | for (uint32_t c = ch0; c < ch0 + nch && c < MAX_CHANNELS; c++) decoder->sbr[c].have_frame = false; |
1313 | 19.1k | decoder->sbr_present = true; |
1314 | 19.1k | degraded = true; |
1315 | 19.1k | } |
1316 | | #else |
1317 | | (void)sbr_st; |
1318 | | #endif |
1319 | 23.1k | 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 | 23.1k | if (consumed < fill_end) { |
1325 | 17.9k | uint32_t pad = fill_end - consumed; |
1326 | 17.9k | 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 | 17.9k | } |
1335 | 23.1k | } else { |
1336 | 5.05k | #ifndef FAAD_DISABLE_DRC |
1337 | 5.05k | if (ext_type == 11) { |
1338 | 828 | uint32_t end = fill_end; |
1339 | 828 | if (end > bs.len * 8) end = bs.len * 8; |
1340 | 828 | read_drc(decoder, bs, end); |
1341 | 828 | } |
1342 | 5.05k | #endif |
1343 | 5.05k | bits_skip(&bs, (count - 1) * 8 + 4); |
1344 | 5.05k | } |
1345 | 28.8k | } |
1346 | 36.4k | } |
1347 | 539k | } |
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 | 241k | } |
1361 | | |
1362 | 241k | if (!saw_end || bs.overread) decode_success = false; |
1363 | 241k | #if MAX_CHANNELS >= 3 |
1364 | 241k | if (decode_success && have_coupling |
1365 | 1.29k | && coupling_spectrum(decoder, coupling_targets, coupling_target_count) != FAAD_OK) |
1366 | 1.04k | decode_success = false; |
1367 | 241k | if (!decode_success) |
1368 | 681k | for (CouplingChannel *cc = decoder->coupling; cc; cc = cc->next) cc->present = false; |
1369 | 241k | #endif |
1370 | 241k | #if MAX_CHANNELS >= 3 |
1371 | 241k | if (SLOTS_BY_TAG(decoder) && occupied != (1u << decoder->layout.n) - 1) decode_success = false; |
1372 | 241k | #endif |
1373 | 241k | if (decode_success && !faad_layout_frozen(decoder) && !decoder->asc.num_channels && !decoder->asc.pce.channels) |
1374 | 0 | faad_layout_infer(decoder, seq); |
1375 | | /* A fixed RAW layout also fixes the lifetime output capacity. */ |
1376 | 241k | if (decoder->config.stream_format == FAAD_STREAM_RAW && (decoder->asc.num_channels || decoder->asc.pce.channels) |
1377 | 241k | && ch_idx > asc_channels(&decoder->asc)) |
1378 | 53.3k | return FAAD_ERR_DECODE_FAILED; |
1379 | | |
1380 | 187k | if (decode_success && ch_idx > 0) { |
1381 | 10.2k | decoder->consecutive_errors = 0; |
1382 | 10.2k | decoder->num_channels = ch_idx; |
1383 | 10.2k | decoder->core_channels = ch_idx; |
1384 | 10.2k | #ifndef FAAD_DISABLE_SBR |
1385 | | /* A concealed frame keeps the layout of the frame it repeats. */ |
1386 | 10.2k | memcpy(decoder->elem_nch, elem_nch, sizeof(elem_nch)); |
1387 | 10.2k | #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 | 177k | } else { |
1404 | | #ifdef FAAD_STATS |
1405 | | g_faadStats.errorConcealmentFrames++; |
1406 | | #endif |
1407 | 177k | decoder->consecutive_errors++; |
1408 | 177k | float fade = 0.0f; |
1409 | 177k | if (decoder->consecutive_errors <= 5) { |
1410 | 28.0k | fade = powf(0.8f, (float)decoder->consecutive_errors); |
1411 | 28.0k | } |
1412 | 481k | for (uint32_t c = 0; c < decoder->num_channels; c++) { |
1413 | 311M | for (int i = 0; i < FRAME_LEN_LONG; i++) { |
1414 | 311M | decoder->spec[c][i] = decoder->prev_spec[c][i] * fade; |
1415 | 311M | } |
1416 | | /* Repeat the last block's windowing; a start block's spectrum |
1417 | | * follows its own short-window overlap as a stop block. */ |
1418 | 304k | static const uint8_t next_seq[4] = { ONLY_LONG_SEQUENCE, LONG_STOP_SEQUENCE, |
1419 | 304k | EIGHT_SHORT_SEQUENCE, ONLY_LONG_SEQUENCE }; |
1420 | 304k | decoder->win_seq[c] = next_seq[decoder->prev_window_seq[c] & 3]; |
1421 | 304k | decoder->win_shape[c] = decoder->prev_window_shape[c]; |
1422 | 304k | } |
1423 | 177k | } |
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 | 187k | if (decoder->sbr_present) decoder->sbr_seen = true; |
1429 | 187k | #ifndef FAAD_DISABLE_PS |
1430 | 187k | if (decoder->ps_present || decoder->asc.is_ps) decoder->ps_seen = true; |
1431 | 187k | #endif |
1432 | 187k | 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 | 187k | uint32_t core_samples = FRAME_IS_960(decoder) ? 960 : 1024; |
1437 | 187k | decoder->frame_samples = sbr_frame ? (core_samples * 2) : core_samples; |
1438 | 187k | #ifndef FAAD_DISABLE_DRC |
1439 | 187k | decoder->drc.applied = decoder->drc.boost = false; |
1440 | 187k | if (decode_success && decoder->drc.present && (decoder->config.drc_cut || decoder->config.drc_boost)) |
1441 | 0 | apply_drc(decoder); |
1442 | 187k | #endif |
1443 | 187k | float *pcm_final = decoder->pcm; |
1444 | 187k | uint32_t num_chs = decoder->num_channels; |
1445 | 187k | bool spectral_downmixed = false; |
1446 | 187k | 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 | 187k | if (!sbr_frame && !have_coupling) |
1455 | 105k | spectral_downmixed = try_spectral_downmix(decoder, decoder->num_channels, &num_chs, pcm_final, |
1456 | 105k | decode_success && ch_idx > 0); |
1457 | 187k | if (!spectral_downmixed) { |
1458 | 187k | uint32_t lfe_channel = faad_downmix_lfe_channel(decoder, decoder->num_channels); |
1459 | 510k | for (uint32_t c = 0; c < decoder->num_channels; c++) { |
1460 | 322k | if (c != lfe_channel) |
1461 | 322k | imdct_and_window(decoder, c, decoder->win_seq[c], decoder->win_shape[c], decoder->spec[c], pcm_final + c * FRAME_LEN_LONG); |
1462 | 322k | } |
1463 | 187k | } |
1464 | 187k | if (!spectral_downmixed && decode_success && ch_idx > 0) { |
1465 | 10.2k | if (ch_idx == MAX_CHANNELS) { |
1466 | | /* IMDCT has consumed this spectrum; rotate before SBR reuses spec[0]. */ |
1467 | 14 | float (*tmp)[FRAME_LEN_LONG] = decoder->prev_spec; |
1468 | 14 | decoder->prev_spec = decoder->spec; |
1469 | 14 | decoder->spec = tmp; |
1470 | 10.2k | } else { |
1471 | | /* A later ADTS header can expand concealment before that channel decodes. */ |
1472 | 10.2k | memcpy(decoder->prev_spec, decoder->spec, sizeof(decoder->spec[0]) * ch_idx); |
1473 | 10.2k | } |
1474 | 10.2k | } |
1475 | 187k | #if MAX_CHANNELS >= 3 |
1476 | 187k | if (decoder->coupling) coupling_pcm(decoder); |
1477 | 187k | #endif |
1478 | 187k | 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 | 124k | for (uint32_t c = decoder->num_channels; c-- > 1; ) |
1482 | 44.3k | memmove(pcm_final + c * 2048, pcm_final + c * FRAME_LEN_LONG, |
1483 | 44.3k | sizeof(float[FRAME_LEN_LONG])); |
1484 | 80.1k | sbr_apply(decoder, decoder->num_channels, pcm_final); |
1485 | 80.1k | } |
1486 | | |
1487 | 187k | 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 | 187k | 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 | 187k | const float *src[MAX_CHANNELS < 2 ? 2 : MAX_CHANNELS]; |
1495 | 187k | if (!spectral_downmixed) { |
1496 | 187k | num_chs = decoder->num_channels; |
1497 | 187k | const uint8_t *map = faad_layout_map(decoder, num_chs); |
1498 | 523k | for (uint32_t c = 0; c < num_chs; c++) |
1499 | 335k | src[c] = pcm_final + (map ? map[c] : c) * pcm_stride; |
1500 | 187k | float *dst[DM_CH]; |
1501 | 1.68M | for (uint32_t c = 0; c < DM_CH; c++) |
1502 | 1.50M | dst[c] = pcm_final + c * pcm_stride; |
1503 | 187k | uint32_t mixed = downmix_pcm(decoder->config.downmix_mode, src, num_chs, |
1504 | 187k | downmix_mask(decoder, num_chs), frame_samples, dst); |
1505 | 187k | if (mixed != num_chs) |
1506 | 0 | for (num_chs = mixed; mixed--; ) src[mixed] = dst[mixed]; |
1507 | 187k | } |
1508 | 187k | if (num_chs <= 2) |
1509 | 477k | for (uint32_t c = 0; c < num_chs; c++) src[c] = pcm_final + c * pcm_stride; |
1510 | | |
1511 | 187k | 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 | 187k | if (required_bytes > decoder->max_output_bytes) return FAAD_ERR_DECODE_FAILED; |
1516 | | |
1517 | 186k | #ifndef FAAD_DISABLE_DRC |
1518 | 186k | if ((decoder->config.drc_target_level != 0.0f || decoder->drc.boost) |
1519 | 0 | && drc_output(decoder, src, num_chs, frame_samples, out_pcm)) goto output_done; |
1520 | 186k | #endif |
1521 | 186k | if (decoder->config.output_format == FAAD_OUTPUT_16BIT) { |
1522 | 186k | int16_t * restrict out_int16 = (int16_t *)out_pcm; |
1523 | 186k | if (num_chs == 2) { |
1524 | 120k | const float * restrict pcm_l = src[0]; |
1525 | 120k | const float * restrict pcm_r = src[1]; |
1526 | 170M | for (uint32_t i = 0; i < frame_samples; i++) { |
1527 | 170M | out_int16[2 * i] = pcm_to_s16(pcm_l[i]); |
1528 | 170M | out_int16[2 * i + 1] = pcm_to_s16(pcm_r[i]); |
1529 | 170M | } |
1530 | 120k | } else if (num_chs == 1) { |
1531 | 57.8k | const float * restrict pcm_m = src[0]; |
1532 | 87.4M | for (uint32_t i = 0; i < frame_samples; i++) |
1533 | 87.4M | out_int16[i] = pcm_to_s16(pcm_m[i]); |
1534 | 57.8k | } else { |
1535 | 10.5M | for (uint32_t i = 0; i < frame_samples; i++) |
1536 | 50.0M | for (uint32_t c = 0; c < num_chs; c++) |
1537 | 39.5M | out_int16[i * num_chs + c] = pcm_to_s16(src[c][i]); |
1538 | 8.45k | } |
1539 | 186k | } 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 | 0 | } else if (decoder->config.output_format == FAAD_OUTPUT_24IN32) { |
1546 | 0 | int32_t * restrict out_int32 = (int32_t *)out_pcm; |
1547 | 0 | for (uint32_t i = 0; i < frame_samples; i++) |
1548 | 0 | for (uint32_t c = 0; c < num_chs; c++) |
1549 | 0 | out_int32[i * num_chs + c] = pcm_to_s24(src[c][i]); |
1550 | 0 | } else { |
1551 | | /* The core reconstructs at 16-bit full scale; float output is unity full scale. */ |
1552 | 0 | const float norm = 1.0f / 32768.0f; |
1553 | 0 | float * restrict out_f32 = (float *)out_pcm; |
1554 | 0 | if (num_chs == 2) { |
1555 | 0 | const float * restrict pcm_l = src[0]; |
1556 | 0 | const float * restrict pcm_r = src[1]; |
1557 | 0 | for (uint32_t i = 0; i < frame_samples; i++) { |
1558 | 0 | out_f32[2 * i] = pcm_l[i] * norm; |
1559 | 0 | out_f32[2 * i + 1] = pcm_r[i] * norm; |
1560 | 0 | } |
1561 | 0 | } else if (num_chs == 1) { |
1562 | 0 | const float * restrict pcm_m = src[0]; |
1563 | 0 | for (uint32_t i = 0; i < frame_samples; i++) |
1564 | 0 | out_f32[i] = pcm_m[i] * norm; |
1565 | 0 | } else { |
1566 | 0 | for (uint32_t i = 0; i < frame_samples; i++) |
1567 | 0 | for (uint32_t c = 0; c < num_chs; c++) |
1568 | 0 | out_f32[i * num_chs + c] = src[c][i] * norm; |
1569 | 0 | } |
1570 | 0 | } |
1571 | | |
1572 | 186k | #ifndef FAAD_DISABLE_DRC |
1573 | 186k | output_done: |
1574 | 186k | ; |
1575 | 186k | #endif |
1576 | 186k | *bytes_consumed = adts_frame_len; |
1577 | 186k | *bytes_written = required_bytes; |
1578 | | |
1579 | 186k | bool sbr_active = sbr_frame; |
1580 | | #ifdef FAAD_STATS |
1581 | | if (sbr_active) { |
1582 | | g_faadStats.sbrActiveFrames++; |
1583 | | } |
1584 | | #endif |
1585 | | |
1586 | 186k | decoder->format_known = decoder->format_known || decoder->asc.num_channels != 0 |
1587 | 0 | || (decode_success && ch_idx > 0); |
1588 | 186k | decoder->sample_rate = sbr_active ? 2 * decoder->core_sample_rate : decoder->core_sample_rate; |
1589 | 186k | uint32_t mask = channel_mask(decoder, num_chs); |
1590 | 186k | uint32_t delay = sbr_active ? 2 * FAAD_SBR_CORE_DELAY : 0; |
1591 | 186k | uint32_t flags = 0; |
1592 | 186k | #ifndef FAAD_DISABLE_DRC |
1593 | 186k | if (decoder->drc.applied) flags |= FAAD_FRAME_DRC; |
1594 | 186k | if (decoder->drc.present) flags |= FAAD_FRAME_DRC_INFO; |
1595 | 186k | #endif |
1596 | 186k | if (!decoder->pcm_emitted || decoder->emitted_format.sample_rate != decoder->sample_rate |
1597 | 182k | || decoder->emitted_format.channels != num_chs |
1598 | 180k | || decoder->emitted_format.frame_samples != frame_samples |
1599 | 180k | || decoder->emitted_format.channel_mask != mask |
1600 | 180k | || decoder->emitted_format.decoder_delay != delay) |
1601 | 6.67k | flags |= FAAD_FRAME_FORMAT_CHANGED; |
1602 | 186k | if (sbr_active) flags |= FAAD_FRAME_SBR; |
1603 | 186k | #ifndef FAAD_DISABLE_PS |
1604 | 186k | if (sbr_active && decoder->ps_seen && decoder->core_channels == 1) flags |= FAAD_FRAME_PS; |
1605 | 186k | #endif |
1606 | 186k | if (!decode_success || ch_idx == 0) flags |= FAAD_FRAME_CONCEALED; |
1607 | 186k | if (degraded) flags |= FAAD_FRAME_DEGRADED; |
1608 | 186k | if (required_bytes) { |
1609 | 186k | decoder->emitted_format.sample_rate = decoder->sample_rate; |
1610 | 186k | decoder->emitted_format.channels = num_chs; |
1611 | 186k | decoder->emitted_format.frame_samples = frame_samples; |
1612 | 186k | decoder->emitted_format.channel_mask = mask; |
1613 | 186k | decoder->emitted_format.decoder_delay = delay; |
1614 | 186k | decoder->pcm_emitted = true; |
1615 | 186k | faad_layout_freeze(decoder); |
1616 | 186k | decoder->format_known = true; |
1617 | 186k | if (frame_flags) *frame_flags = flags; |
1618 | 186k | } |
1619 | | |
1620 | 186k | return FAAD_OK; |
1621 | 186k | } |
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 | } |