/src/faac/libfaac/channels.c
Line | Count | Source |
1 | | /* |
2 | | * FAAC - Freeware Advanced Audio Coder |
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 "channels.h" |
17 | | #include "huff2.h" |
18 | | #include "frame.h" |
19 | | #include "sbr.h" |
20 | | #include <string.h> |
21 | | #include <stdio.h> |
22 | | |
23 | | _Static_assert(TNS_MAX_FILTERS <= (1 << LEN_TNS_NFILTL) - 1, |
24 | | "TnsWindowData.tnsFilter[] holds more filters than numFilters can encode in LEN_TNS_NFILTL bits"); |
25 | | _Static_assert(TNS_MAX_ORDER <= (1 << LEN_TNS_ORDERL) - 1, |
26 | | "TnsFilterData order exceeds what LEN_TNS_ORDERL bits can encode"); |
27 | | |
28 | | /** |
29 | | * Maps input channels to AAC elements (SCE, CPE, LFE), per ISO/IEC 14496-3's |
30 | | * channel configuration table: one SCE up front unless exactly 2 channels |
31 | | * remain, then as many CPEs as fit two at a time, then a trailing odd |
32 | | * channel becomes an LFE (if enabled) or a final SCE. |
33 | | */ |
34 | | int InitElements(AACElement * __restrict elements, int *numElements, int numChannels, bool useLfe) |
35 | 2.94k | { |
36 | | #if MAX_CHANNELS < 6 |
37 | | (void)useLfe; |
38 | | #endif |
39 | 2.94k | uint8_t sceTag = 0; |
40 | 2.94k | uint8_t cpeTag = 0; |
41 | 2.94k | #if MAX_CHANNELS >= 6 |
42 | 2.94k | uint8_t lfeTag = 0; |
43 | 2.94k | #endif |
44 | | |
45 | 2.94k | int currentElem = 0; |
46 | 2.94k | int currentCh = 0; |
47 | 2.94k | int channelsRemaining = numChannels; |
48 | | |
49 | 2.94k | memset(elements, 0, sizeof(AACElement) * MAX_CHANNELS); |
50 | | |
51 | | // Initial SCE for Config 1, 3, 4, 5, 6, 7 |
52 | 2.94k | if (channelsRemaining != 2 && channelsRemaining > 0) { |
53 | 2.79k | elements[currentElem].type = ID_SCE; |
54 | 2.79k | elements[currentElem].tag = sceTag++; |
55 | 2.79k | elements[currentElem].channels[0] = currentCh++; |
56 | 2.79k | elements[currentElem].channels[1] = -1; |
57 | | |
58 | 2.79k | currentElem++; |
59 | 2.79k | channelsRemaining--; |
60 | 2.79k | } |
61 | | |
62 | | // CPE groups |
63 | 8.63k | while (channelsRemaining > 1) { |
64 | 5.69k | elements[currentElem].type = ID_CPE; |
65 | 5.69k | elements[currentElem].tag = cpeTag++; |
66 | 5.69k | elements[currentElem].channels[0] = currentCh++; |
67 | 5.69k | elements[currentElem].channels[1] = currentCh++; |
68 | | |
69 | 5.69k | currentElem++; |
70 | 5.69k | channelsRemaining -= 2; |
71 | 5.69k | } |
72 | | |
73 | | // Residual SCE or LFE |
74 | 2.94k | if (channelsRemaining == 1) { |
75 | 1.95k | #if MAX_CHANNELS >= 6 |
76 | 1.95k | if (useLfe) { |
77 | 1.85k | elements[currentElem].type = ID_LFE; |
78 | 1.85k | elements[currentElem].tag = lfeTag++; |
79 | 1.85k | } else { |
80 | 98 | #endif |
81 | 98 | elements[currentElem].type = ID_SCE; |
82 | 98 | elements[currentElem].tag = sceTag++; |
83 | 98 | #if MAX_CHANNELS >= 6 |
84 | 98 | } |
85 | 1.95k | #endif |
86 | 1.95k | elements[currentElem].channels[0] = currentCh++; |
87 | 1.95k | elements[currentElem].channels[1] = -1; |
88 | | |
89 | 1.95k | currentElem++; |
90 | 1.95k | } |
91 | | |
92 | 2.94k | *numElements = currentElem; |
93 | 2.94k | return 0; |
94 | 2.94k | } |
95 | | |
96 | | static int WriteICSInfo(BitStream *bs, CoderInfo *coder) |
97 | 150k | { |
98 | 150k | PutBit(bs, 0, LEN_ICS_RESERV); |
99 | 150k | PutBit(bs, coder->block_type, LEN_WIN_SEQ); |
100 | 150k | PutBit(bs, coder->window_shape, LEN_WIN_SH); |
101 | 150k | int bits = LEN_ICS_RESERV + LEN_WIN_SEQ + LEN_WIN_SH; |
102 | | |
103 | 150k | if (coder->block_type == ONLY_SHORT_WINDOW) { |
104 | 55.2k | PutBit(bs, coder->sfbn, LEN_MAX_SFBS); |
105 | | |
106 | 55.2k | int grouping_bits = 0; |
107 | | /* Construct the 7 scale factor window grouping bits directly from group lengths. |
108 | | * A bit is 1 if adjacent sub-windows belong to the same group, 0 if a new group starts. */ |
109 | 213k | for (int i = 0; i < coder->groups.n; i++) { |
110 | 158k | int len = coder->groups.len[i]; |
111 | 158k | if (len > 1) { |
112 | 97.6k | grouping_bits = (grouping_bits << (len - 1)) | ((1 << (len - 1)) - 1); |
113 | 97.6k | } |
114 | 158k | if (i < coder->groups.n - 1) { |
115 | 102k | grouping_bits <<= 1; |
116 | 102k | } |
117 | 158k | } |
118 | 55.2k | PutBit(bs, grouping_bits, MAX_SHORT_WINDOWS - 1); |
119 | 55.2k | bits += LEN_MAX_SFBS + (MAX_SHORT_WINDOWS - 1); |
120 | 94.8k | } else { |
121 | 94.8k | PutBit(bs, coder->sfbn, LEN_MAX_SFBL); |
122 | 94.8k | PutBit(bs, 0, LEN_PRED_PRES); |
123 | 94.8k | bits += LEN_MAX_SFBL + LEN_PRED_PRES; |
124 | 94.8k | } |
125 | | |
126 | 150k | return bits; |
127 | 150k | } |
128 | | |
129 | | static int WriteICS(BitStream *bs, CoderInfo *coder, bool commonWindow) |
130 | 187k | { |
131 | 187k | PutBit(bs, coder->global_gain, LEN_GLOB_GAIN); |
132 | 187k | int bits = LEN_GLOB_GAIN; |
133 | | |
134 | 187k | if (!commonWindow) bits += WriteICSInfo(bs, coder); |
135 | | |
136 | 187k | bits += writebooks(coder, bs); |
137 | 187k | bits += writesf(coder, bs); |
138 | | |
139 | 187k | PutBit(bs, 0, LEN_PULSE_PRES); |
140 | 187k | bits += LEN_PULSE_PRES; |
141 | | |
142 | 187k | TnsInfo *tns = &coder->tnsInfo; |
143 | 187k | PutBit(bs, tns->tnsDataPresent, LEN_TNS_PRES); |
144 | 187k | bits += LEN_TNS_PRES; |
145 | | |
146 | | /* TNS is long-only (see tns.c): tnsDataPresent is never set for |
147 | | * ONLY_SHORT_WINDOW, so there's exactly one window's worth of TNS data |
148 | | * to write, always at the long-window field widths. */ |
149 | 187k | if (tns->tnsDataPresent) { |
150 | 9.99k | TnsWindowData *win = &tns->windowData; |
151 | | |
152 | 9.99k | PutBit(bs, win->numFilters, LEN_TNS_NFILTL); |
153 | 9.99k | bits += LEN_TNS_NFILTL; |
154 | | |
155 | 9.99k | if (win->numFilters > 0) { |
156 | 9.99k | PutBit(bs, win->coefResolution - DEF_TNS_RES_OFFSET, LEN_TNS_COEFF_RES); |
157 | 9.99k | bits += LEN_TNS_COEFF_RES; |
158 | | |
159 | 19.9k | for (int f = 0; f < win->numFilters; f++) { |
160 | 9.99k | TnsFilterData *flt = &win->tnsFilter[f]; |
161 | 9.99k | PutBit(bs, flt->length, LEN_TNS_LENGTHL); |
162 | 9.99k | PutBit(bs, flt->order, LEN_TNS_ORDERL); |
163 | 9.99k | bits += LEN_TNS_LENGTHL + LEN_TNS_ORDERL; |
164 | | |
165 | 9.99k | if (flt->order > 0) { |
166 | 9.99k | PutBit(bs, flt->direction, LEN_TNS_DIRECTION); |
167 | 9.99k | PutBit(bs, flt->coefCompress, LEN_TNS_COMPRESS); |
168 | 9.99k | bits += LEN_TNS_DIRECTION + LEN_TNS_COMPRESS; |
169 | | |
170 | 9.99k | int res = win->coefResolution - flt->coefCompress; |
171 | 69.8k | for (int i = 1; i <= flt->order; i++) { |
172 | 59.8k | PutBit(bs, flt->index[i] & ((1 << res) - 1), res); |
173 | 59.8k | bits += res; |
174 | 59.8k | } |
175 | 9.99k | } |
176 | 9.99k | } |
177 | 9.99k | } |
178 | 9.99k | } |
179 | | |
180 | 187k | PutBit(bs, 0, LEN_GAIN_PRES); |
181 | 187k | bits += LEN_GAIN_PRES; |
182 | | |
183 | 187k | BitAccumulator acc = {0}; |
184 | 187k | AccumBegin(&acc, bs); |
185 | 15.8M | for (int i = 0; i < coder->datacnt; i++) { |
186 | 15.6M | int len = coder->s[i] >> 24; |
187 | 15.6M | if (len > 0) { |
188 | 15.6M | AccumPutBits(&acc, coder->s[i] & 0xffffff, len); |
189 | 15.6M | bits += len; |
190 | 15.6M | } |
191 | 15.6M | } |
192 | 187k | AccumEnd(&acc); |
193 | | |
194 | 187k | return bits; |
195 | 187k | } |
196 | | |
197 | | int WriteElement(BitStream *bs, AACElement *elem, CoderInfo *coder) |
198 | 122k | { |
199 | 122k | PutBit(bs, elem->type, LEN_SE_ID); |
200 | 122k | PutBit(bs, elem->tag, LEN_TAG); |
201 | 122k | int bits = LEN_SE_ID + LEN_TAG; |
202 | | |
203 | 122k | switch (elem->type) { |
204 | 36.0k | case ID_SCE: |
205 | 36.0k | #if MAX_CHANNELS >= 6 |
206 | 56.8k | case ID_LFE: |
207 | 56.8k | #endif |
208 | 56.8k | bits += WriteICS(bs, &coder[elem->channels[0]], false); |
209 | 56.8k | break; |
210 | | |
211 | 65.2k | case ID_CPE: |
212 | 65.2k | PutBit(bs, elem->common_window, LEN_COM_WIN); |
213 | 65.2k | bits += LEN_COM_WIN; |
214 | | |
215 | 65.2k | if (elem->common_window) { |
216 | 37.3k | bits += WriteICSInfo(bs, &coder[elem->channels[0]]); |
217 | | /* The quantizer can revert M/S bands (e.g. to PNS) after the |
218 | | * stereo decision, so signal the mask only if a band still uses it. */ |
219 | 37.3k | int n = coder[elem->channels[0]].groups.n * coder[elem->channels[0]].sfbn; |
220 | 37.3k | int first = 0; |
221 | 758k | while (first < n && !elem->msInfo.ms_used[first]) first++; |
222 | 37.3k | bool msPresent = first < n; |
223 | 37.3k | PutBit(bs, msPresent, LEN_MASK_PRES); |
224 | 37.3k | bits += LEN_MASK_PRES; |
225 | 37.3k | if (msPresent) { |
226 | 835k | for (int i = 0; i < n; i++) PutBit(bs, elem->msInfo.ms_used[i], LEN_MASK); |
227 | 17.4k | bits += n * LEN_MASK; |
228 | 17.4k | } |
229 | 37.3k | } |
230 | 65.2k | bits += WriteICS(bs, &coder[elem->channels[0]], elem->common_window); |
231 | 65.2k | bits += WriteICS(bs, &coder[elem->channels[1]], elem->common_window); |
232 | 65.2k | break; |
233 | 0 | default: break; |
234 | 122k | } |
235 | 122k | return bits; |
236 | 122k | } |
237 | | |
238 | | #if MAX_CHANNELS >= 8 |
239 | | /* The in-band PCE: element id, body, byte alignment and an empty comment. |
240 | | * Two back CPEs match fdkaac's rear-surround convention: the first carries |
241 | | * sides, the second rears. Configuration 7 would instead declare 7.1 wide. |
242 | | * Only the sampling frequency index varies, so it is patched into byte 1 of |
243 | | * an otherwise constant image. */ |
244 | | void BuildPCE(uint8_t pce[PCE_ADTS_BYTES], int sampleRateIdx) |
245 | 1.32k | { |
246 | 1.32k | static const uint8_t image[PCE_ADTS_BYTES] = { |
247 | 1.32k | 0xa0, 0x81, 0x01, 0x20, 0x00, 0x21, 0x19, 0x00, 0x00 |
248 | 1.32k | }; |
249 | 1.32k | memcpy(pce, image, sizeof(image)); |
250 | 1.32k | pce[1] |= (uint8_t)(sampleRateIdx << 3); |
251 | 1.32k | } |
252 | | #endif |
253 | | |
254 | | static int WriteAACFillBits(BitStream *bs, int numBits) |
255 | 36.5k | { |
256 | 36.5k | int left = numBits; |
257 | 69.3k | while (left >= (LEN_SE_ID + 4)) { |
258 | 32.8k | PutBit(bs, ID_FIL, LEN_SE_ID); |
259 | 32.8k | left -= LEN_SE_ID; |
260 | 32.8k | int bc = (left / 8 < 15) ? (left / 8) : 15; |
261 | 32.8k | PutBit(bs, bc, 4); |
262 | 32.8k | left -= 4; |
263 | 32.8k | if (bc == 15) { |
264 | 32.5k | int esc = (left / 8 - 14 < 255) ? (left / 8 - 14) : 255; |
265 | 32.5k | PutBit(bs, esc, 8); |
266 | 32.5k | left -= 8; |
267 | 32.5k | bc = 14 + esc; |
268 | 32.5k | } |
269 | 8.13M | for (int i = 0; i < bc; i++) PutBit(bs, 0, 8); |
270 | 32.8k | left -= bc * 8; |
271 | 32.8k | } |
272 | 36.5k | return left; |
273 | 36.5k | } |
274 | | |
275 | | static int BuildFrame(struct faacEncStruct *hEncoder, CoderInfo *coder, AACElement *elems, int nElems, BitStream *bs) |
276 | 36.5k | { |
277 | 36.5k | int bits = 0; |
278 | 36.5k | if (hEncoder->config.outputFormat == 1) { |
279 | | /* Reserve the header; PatchADTSHeader fills it once the size is known. */ |
280 | 26.6k | bits = ADTS_HEADER_SIZE * 8; |
281 | 26.6k | bs->currentBit += bits; |
282 | 26.6k | } |
283 | 36.5k | #if MAX_CHANNELS >= 8 |
284 | | /* The PCE must open the raw_data_block while the bitstream is still byte |
285 | | * aligned. The DRC fill element is 31 bits, so writing it first would |
286 | | * misalign the memcpy below and corrupt the PCE on 8-channel streams. */ |
287 | 36.5k | if (hEncoder->config.outputFormat == 1 && HasPCE((int)hEncoder->numChannels) |
288 | 11.9k | && ((hEncoder->frameNum - LOOKAHEAD_DEPTH - 1) & (PCE_REPEAT_FRAMES - 1)) == 0) { |
289 | 1.86k | if (bs->data) |
290 | 1.86k | memcpy(bs->data + (bs->currentBit >> 3), hEncoder->pce, sizeof(hEncoder->pce)); |
291 | 1.86k | bs->currentBit += sizeof(hEncoder->pce) * 8; |
292 | 1.86k | bits += sizeof(hEncoder->pce) * 8; |
293 | 1.86k | } |
294 | 36.5k | #endif |
295 | 36.5k | #if FAAC_ENCODER_DRC |
296 | | /* DRC fill element is emitted once per frame before the channel elements. */ |
297 | 36.5k | if (hEncoder->drcInfo.enabled) { |
298 | 14.9k | int drcBits = DrcGetBits(&hEncoder->drcInfo, bs); |
299 | 14.9k | bits += drcBits; |
300 | 14.9k | } |
301 | 36.5k | #endif |
302 | | /* SBR follows each SCE/CPE in a fill element; rate control charges only |
303 | | * the core, so its total is kept aside. */ |
304 | 36.5k | int sbrBits = 0; |
305 | 158k | for (int i = 0; i < nElems; i++) { |
306 | 122k | bits += WriteElement(bs, &elems[i], coder); |
307 | 122k | sbrBits += SbrContextGetBits(hEncoder->sbrContext, bs, |
308 | 122k | &elems[i], (int)hEncoder->config.aacObjectType); |
309 | 122k | } |
310 | 36.5k | hEncoder->rc.sbrBits = sbrBits; |
311 | 36.5k | bits += sbrBits; |
312 | 36.5k | int f = (bits < (8 - LEN_SE_ID)) ? (8 - LEN_SE_ID - bits) : 0; |
313 | 36.5k | f += 6; |
314 | | |
315 | | /* Stuff to the reservoir floor; only the end marker still follows. */ |
316 | 36.5k | hEncoder->rc.stuffedBits = 0; |
317 | 36.5k | if (hEncoder->rc.resMinBits > 0) { |
318 | 10.6k | int hdr = (hEncoder->config.outputFormat == 1) ? ADTS_HEADER_SIZE * 8 : 0; |
319 | 10.6k | int need = hEncoder->rc.resMinBits - (bits - hdr + f + LEN_SE_ID); |
320 | 10.6k | if (need > 0) { |
321 | | /* Fill is byte-granular and rounds down; never land under the floor. */ |
322 | 8.84k | need += 7; |
323 | 8.84k | f += need; |
324 | 8.84k | hEncoder->rc.stuffedBits = need; |
325 | 8.84k | } |
326 | 10.6k | } |
327 | 36.5k | bits += (f - WriteAACFillBits(bs, f)); |
328 | | |
329 | 36.5k | PutBit(bs, ID_END, LEN_SE_ID); |
330 | 36.5k | bits += LEN_SE_ID; |
331 | 36.5k | int pad = (8 - (bits & 7)) & 7; |
332 | 177k | for (int i = 0; i < pad; i++) PutBit(bs, 0, 1); |
333 | 36.5k | return bits + pad; |
334 | 36.5k | } |
335 | | |
336 | | /* Fill the seven reserved ADTS bytes once the frame length is known. |
337 | | * The profile is LC, including for HE-AAC's core; SBR is in its fill elements. |
338 | | * buffer_fullness is the reservoir |
339 | | * after this frame in 32-bit words (ISO/IEC 13818-7 6.2.2); 0x7FF = none. */ |
340 | | static void PatchADTSHeader(struct faacEncStruct *hEncoder, BitStream *bs, int frameBytes) |
341 | 36.5k | { |
342 | 36.5k | if (hEncoder->config.outputFormat == 1 && bs->data) { |
343 | 26.6k | int fullness = 0x7FF; |
344 | 26.6k | int channelConfig = SignaledChannelConfig(CoreChannels(hEncoder->config.aacObjectType, (int)hEncoder->numChannels)); |
345 | 26.6k | if (hEncoder->rc.resMean) |
346 | 20.4k | fullness = RateControlReservoirAfter(&hEncoder->rc, (frameBytes - ADTS_HEADER_SIZE) * 8) >> 5; |
347 | 26.6k | bs->data[0] = 0xFF; |
348 | 26.6k | bs->data[1] = 0xF0 | (hEncoder->config.mpegVersion << 3) | 1; |
349 | 26.6k | bs->data[2] = ((LOW - 1) << 6) | (hEncoder->sampleRateIdx << 2) | (channelConfig >> 2); |
350 | 26.6k | bs->data[3] = ((channelConfig & 3) << 6) | (frameBytes >> 11); |
351 | 26.6k | bs->data[4] = (frameBytes >> 3) & 0xFF; |
352 | 26.6k | bs->data[5] = ((frameBytes & 7) << 5) | (fullness >> 6); |
353 | 26.6k | bs->data[6] = (fullness & 0x3F) << 2; |
354 | 26.6k | } |
355 | 36.5k | } |
356 | | |
357 | | int WriteBitstream(struct faacEncStruct *hEncoder, CoderInfo *coder, AACElement *elems, int nElems, BitStream *bs) |
358 | 36.5k | { |
359 | 36.5k | bs->currentBit = 0; |
360 | 36.5k | int bits = BuildFrame(hEncoder, coder, elems, nElems, bs); |
361 | 36.5k | if (bits < 0) return -1; |
362 | | |
363 | | /* Safe to bounds-check after writing: PutBit refuses to write past |
364 | | * bs->size, so an oversized frame truncates rather than overflowing. */ |
365 | 36.5k | hEncoder->usedBytes = (bits + 7) >> 3; |
366 | 36.5k | if (hEncoder->usedBytes > bs->size) return -1; |
367 | 36.5k | if (hEncoder->usedBytes > ADTS_MAX_FRAME_SIZE) return -1; |
368 | | |
369 | 36.5k | PatchADTSHeader(hEncoder, bs, hEncoder->usedBytes); |
370 | 36.5k | return bits; |
371 | 36.5k | } |