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 <stdlib.h> |
17 | | #include <string.h> |
18 | | #include <math.h> |
19 | | #include <assert.h> |
20 | | |
21 | | #include "sbr.h" |
22 | | #include "sbr_tables.h" |
23 | | #include "sbr_huff_tables.h" |
24 | | #include "util.h" |
25 | | #include "sbr_analysis.h" |
26 | | #include "resample.h" |
27 | | #include "bitstream.h" |
28 | | #include "sbr_internal.h" |
29 | | #include "faac_internal.h" |
30 | | #include "channels.h" |
31 | | #include "stats.h" |
32 | | |
33 | | /* SBR master frequency band table (ISO/IEC 14496-3:2005 §4.6.18.3.2). kx/k2 are |
34 | | * spec-mandatory: the decoder reconstructs them from the sample rate alone, so |
35 | | * these must match its table exactly or the envelope band count desyncs. The |
36 | | * rate here is the full output rate (= 2*core), which is what the decoder uses. */ |
37 | | |
38 | | /* SBR start frequency (kx). Crossover alignment prevents aliasing/gaps. */ |
39 | | static int compute_kx(int sampleRate, int bs_start_freq) |
40 | 996 | { |
41 | 996 | int temp = (sampleRate < 32000) ? 3000 : (sampleRate < 64000) ? 4000 : 5000; |
42 | 996 | int start_min = ((temp << 7) + (sampleRate >> 1)) / sampleRate; |
43 | 996 | int row = (sampleRate <= 16000) ? 0 : (sampleRate <= 22050) ? 1 : (sampleRate <= 24000) ? 2 : (sampleRate <= 32000) ? 3 : (sampleRate <= 64000) ? 4 : 5; |
44 | 996 | return clamp_int(start_min + sbr_offset[row][bs_start_freq & 15], 1, 63); |
45 | 996 | } |
46 | | |
47 | 22.7k | static int cmp_int16(const void *a, const void *b) { return (int)(*(const short *)a) - (int)(*(const short *)b); } |
48 | 9.60k | static int cmp_int(const void *a, const void *b) { return *(const int *)a - *(const int *)b; } |
49 | | |
50 | | /* Fewest QMF bands between kx and k2 that still yield an envelope band at |
51 | | * every freq_scale; above 64 kHz the 20 kHz target can fall below kx. */ |
52 | 21.2k | #define SBR_MIN_SPAN 4 |
53 | | |
54 | | /* Widest k2 - kx decoders accept (§4.6.18.3.2.1). */ |
55 | | static int max_sbr_span(int sampleRate) |
56 | 10.7k | { |
57 | 10.7k | return (sampleRate <= 32000) ? 48 : (sampleRate <= 44100) ? 35 : 32; |
58 | 10.7k | } |
59 | | |
60 | | /* Smallest stop-frequency index reaching targetHz, or the widest one decoders |
61 | | * accept; *k2_out receives its QMF band. Searched rather than tabulated: the |
62 | | * index-to-frequency mapping shifts with sample rate, so a fixed table would |
63 | | * overshoot at some rates. Decoders derive k2 from bs_stop_freq alone (ISO |
64 | | * 14496-3 §4.6.18.3.2.1), so the table is rebuilt as the spec defines it: |
65 | | * stop_min plus the sf narrowest of 13 geometric steps. */ |
66 | | static int pick_stop_freq(int sampleRate, int kx, int targetHz, int *k2_out) |
67 | 996 | { |
68 | 996 | int temp = (sampleRate < 32000) ? 3000 : (sampleRate < 64000) ? 4000 : 5000; |
69 | 996 | int stop_min = ((temp << 8) + (sampleRate >> 1)) / sampleRate; |
70 | 996 | short stop_dk[13]; |
71 | 996 | float prod = (float)stop_min; |
72 | 996 | int prev = stop_min; |
73 | 996 | float base = powf(64.0f / (float)stop_min, (float)(1.0f / 13.0f)); |
74 | 12.9k | for (int i = 0; i < 12; i++) { |
75 | 11.9k | prod *= base; |
76 | 11.9k | int present = (int)lrintf(prod); |
77 | 11.9k | stop_dk[i] = (short)(present - prev); |
78 | 11.9k | prev = present; |
79 | 11.9k | } |
80 | 996 | stop_dk[12] = (short)(64 - prev); |
81 | 996 | qsort(stop_dk, 13, sizeof(short), cmp_int16); |
82 | | |
83 | 996 | int two_region = sampleRate >= SBR_TWO_REGION_MIN_RATE && sampleRate <= SBR_TWO_REGION_MAX_RATE; |
84 | 996 | int best = SBR_STOP_FREQ_MIN, best_k2 = stop_min, k2 = stop_min; |
85 | 10.9k | for (int sf = SBR_STOP_FREQ_MIN; sf <= SBR_STOP_FREQ_MAX; sf++) { |
86 | 10.8k | if (sf > 0) k2 += stop_dk[sf - 1]; |
87 | 10.8k | if ((!two_region && k2 * SBR_ONE_REGION_DEN > SBR_ONE_REGION_NUM * kx) || k2 - kx > max_sbr_span(sampleRate)) break; |
88 | 10.6k | best = sf; |
89 | 10.6k | best_k2 = k2; |
90 | 10.6k | if (k2 - kx >= SBR_MIN_SPAN && (long)k2 * sampleRate / (2 * SBR_QMF_BANDS_64) >= targetHz) break; |
91 | 10.6k | } |
92 | 996 | *k2_out = best_k2; |
93 | 996 | return best; |
94 | 996 | } |
95 | | |
96 | 8.35k | static int sbr_round_f(float v) { return (int)floorf(v + 0.5f); } |
97 | | |
98 | | static int build_log_band_widths(int k_start, int k_end, int bands_per_octave, float warp, int *vdk) |
99 | 1.30k | { |
100 | 1.30k | int nb = 2 * sbr_round_f(bands_per_octave * log2f((float)k_end / (float)k_start) / (2.0f * warp)); |
101 | 1.30k | nb = clamp_int(nb, 1, SBR_MAX_BANDS); |
102 | 1.30k | int prev = k_start; |
103 | 1.30k | int i = 0; |
104 | 7.04k | do { |
105 | 7.04k | int cur = sbr_round_f(k_start * powf((float)k_end / (float)k_start, (float)(i + 1) / (float)nb)); |
106 | 7.04k | vdk[i] = cur - prev; |
107 | 7.04k | prev = cur; |
108 | 7.04k | } while (++i < nb); |
109 | 1.30k | qsort(vdk, nb, sizeof(int), cmp_int); |
110 | 1.30k | return nb; |
111 | 1.30k | } |
112 | | |
113 | | /* Master table (ISO 14496-3 §4.6.18.3.2.1). bs_freq_scale 1/2/3: |
114 | | * log-spaced with 12/10/8 bands per octave, widths of a geometric series |
115 | | * rounded and sorted so the narrow bands sit at the bottom. When k2/kx |
116 | | * exceeds 2.2449, the table splits at k1 = 2*kx into lower and upper regions, |
117 | | * warped by bs_alter_scale and re-sorted. */ |
118 | | int build_freq_table(SBRInfo *sbr) |
119 | 996 | { |
120 | 996 | int kx = sbr->kx, k2 = sbr->k2; |
121 | 996 | int *edges = sbr->bandEdges; |
122 | 996 | int bands_per_octave = 14 - 2 * sbr->bs_freq_scale; /* 12, 10, 8 for bs_freq_scale 1, 2, 3 */ |
123 | 996 | int two_region = (float)k2 / (float)kx > SBR_TWO_REGION_RATIO; |
124 | 996 | int k1 = two_region ? 2 * kx : k2; |
125 | 996 | int widths[2 * SBR_MAX_BANDS]; |
126 | 996 | int n_master = build_log_band_widths(kx, k1, bands_per_octave, 1.0f, widths); |
127 | | |
128 | 996 | if (two_region) { |
129 | 309 | int *upper = widths + n_master; |
130 | 309 | float warp = sbr->bs_alter_scale ? SBR_UPPER_REGION_WARP : 1.0f; |
131 | 309 | int nb1 = build_log_band_widths(k1, k2, bands_per_octave, warp, upper); |
132 | 309 | if (upper[0] < widths[n_master - 1]) { |
133 | 3 | int change = widths[n_master - 1] - upper[0]; |
134 | 3 | int half = (upper[nb1 - 1] - upper[0]) / 2; |
135 | 3 | if (change > half) change = half; |
136 | 3 | upper[0] += change; |
137 | 3 | upper[nb1 - 1] -= change; |
138 | 3 | qsort(upper, nb1, sizeof(int), cmp_int); |
139 | 3 | } |
140 | 309 | n_master += nb1; |
141 | 309 | } |
142 | | |
143 | 996 | edges[0] = kx; |
144 | 8.04k | for (int i = 0; i < n_master; i++) edges[i + 1] = edges[i] + widths[i]; |
145 | | |
146 | 996 | sbr->numBands = n_master; |
147 | | |
148 | 996 | return n_master; |
149 | 996 | } |
150 | | |
151 | | SBRInfo *SbrInit(int channels, int sampleRate, unsigned long bitRate) |
152 | 996 | { |
153 | 996 | size_t size = sizeof(SBRInfo) + channels * sizeof(SBRChannel); |
154 | 996 | SBRInfo *sbr = (SBRInfo *)AllocMemory(size); |
155 | 996 | if (!sbr) return NULL; |
156 | 996 | memset(sbr, 0, size); |
157 | 996 | sbr->numChannels = channels; |
158 | 996 | sbr->sampleRate = sampleRate; |
159 | | |
160 | | /* Pre-calculate twiddle factors for the FFT-based QMF analysis. |
161 | | * These coefficients rotate the subband indices into the odd-frequency |
162 | | * DFT space required by the SBR modulation kernel. */ |
163 | 64.7k | for (int m = 0; m < SBR_QMF_BANDS_64; m++) { |
164 | 63.7k | sbr->twidCos[m] = (float)cos(M_PI_DOUBLE * m / 64.0); |
165 | 63.7k | sbr->twidSin[m] = (float)sin(M_PI_DOUBLE * m / 64.0); |
166 | 63.7k | sbr->oddCos[m] = (float)cos(M_PI_DOUBLE * (2 * m + 1) / 128.0); |
167 | 63.7k | sbr->oddSin[m] = (float)sin(M_PI_DOUBLE * (2 * m + 1) / 128.0); |
168 | 63.7k | } |
169 | 996 | SbrUpdate(sbr, bitRate); |
170 | 996 | return sbr; |
171 | 996 | } |
172 | | |
173 | | /* Re-resolve SBR operational parameters (crossover, resolution) when the |
174 | | * bitrate or sample rate changes, avoiding handle reallocation. */ |
175 | | void SbrUpdate(SBRInfo *sbr, unsigned long bitRate) |
176 | 996 | { |
177 | 996 | int sampleRate = sbr->sampleRate; |
178 | 996 | unsigned long rate_per_ch = bitRate / sbr->numChannels; |
179 | 996 | sbr->numEnvFixFix = (rate_per_ch >= SBR_FOUR_ENV_BITRATE_BPS) ? 4 : 1; |
180 | 996 | sbr->rich = rate_per_ch >= SBR_RICH_BPS; |
181 | | /* A crossover near the core ceiling (~11.6 kHz) maximizes MOS while the |
182 | | * core is bit-starved: parametric reconstruction below 10 kHz is audible |
183 | | * and generally inferior to that core. A rich core can afford SBR from |
184 | | * about 8 kHz (SBR_RICH_BPS). */ |
185 | 996 | sbr->bs_start_freq = sbr->rich ? SBR_START_FREQ_RICH : SBR_START_FREQ_DEFAULT; |
186 | | /* Log-spaced envelope bands, fewer per octave while bits are scarce: |
187 | | * what they save, rate control hands to the core. */ |
188 | 996 | sbr->bs_freq_scale = (rate_per_ch >= SBR_FREQ_SCALE_COARSE_BPS) ? 3 : 2; |
189 | 996 | sbr->bs_alter_scale = 0; /* only warps a two-region table; see build_freq_table */ |
190 | 996 | sbr->kx = compute_kx(sampleRate, sbr->bs_start_freq); |
191 | | |
192 | | /* Where the reconstruction stops. Aim at hearing rather than k2's ceiling: |
193 | | * bands above the target cost the same envelope bits as the ones below, so |
194 | | * there's no reason to stop short of what's audible. */ |
195 | 996 | sbr->bs_stop_freq = pick_stop_freq(sampleRate, sbr->kx, |
196 | 996 | (rate_per_ch < SBR_NARROW_STOP_BPS && sampleRate > SBR_NARROW_STOP_MIN_RATE) ? SBR_STOP_FREQ_TARGET_NARROW_HZ : SBR_STOP_FREQ_TARGET_HZ, |
197 | 996 | &sbr->k2); |
198 | | |
199 | 996 | build_freq_table(sbr); |
200 | 996 | } |
201 | | |
202 | | void SbrEnd(SBRInfo *sbr) |
203 | 996 | { |
204 | 996 | if (!sbr) return; |
205 | 996 | FreeMemory(sbr); |
206 | 996 | } |
207 | | |
208 | | /* What analyzing a silent frame yields. Needed because zeroed memory is not a |
209 | | * legal payload: numEnvelopes == 0 encodes no grid at all. */ |
210 | | static void sbr_frame_silence(SbrFrameData *fd, int channels) |
211 | 6.96k | { |
212 | 6.96k | memset(fd, 0, sizeof(*fd) + channels * sizeof(fd->ch[0])); |
213 | 6.96k | fd->numEnvelopes = 1; |
214 | 6.96k | fd->eff_amp_res = 0; |
215 | 6.96k | fd->frameClass = SBR_FRAME_CLASS_FIXFIX; |
216 | 6.96k | fd->tEnv[0] = 0; |
217 | 6.96k | fd->tEnv[1] = SBR_NUM_TIME_SLOTS; |
218 | 6.96k | } |
219 | | |
220 | | SBRContext *SbrContextInit(int channels) |
221 | 996 | { |
222 | 996 | size_t frameSize = sizeof(SbrFrameData) + channels * sizeof(((SbrFrameData *)0)->ch[0]); |
223 | 996 | SBRContext *sbrCtx = (SBRContext *)AllocMemory(sizeof(SBRContext) + SBR_FRAME_FIFO * frameSize); |
224 | 996 | if (sbrCtx) { |
225 | 996 | memset(sbrCtx, 0, sizeof(SBRContext)); |
226 | 996 | sbrCtx->resampler = ResampleInit(channels); |
227 | 996 | size_t size = sizeof(SignalAnalysis) + channels * sizeof(SignalAnalysisChannel); |
228 | 996 | sbrCtx->signalAnalysis = AllocMemory(size); |
229 | 996 | if (!sbrCtx->resampler || !sbrCtx->signalAnalysis) { |
230 | 0 | SbrContextEnd(sbrCtx); |
231 | 0 | return NULL; |
232 | 0 | } |
233 | 996 | memset(sbrCtx->signalAnalysis, 0, size); |
234 | | /* The first access units carry the core's silent lead-in, so the ring |
235 | | * has to start full of payloads that describe silence. */ |
236 | 4.98k | for (int i = 0; i < SBR_FRAME_FIFO; i++) { |
237 | 3.98k | sbrCtx->frameFIFO[i] = (SbrFrameData *)(sbrCtx->frameData + i * frameSize); |
238 | 3.98k | sbr_frame_silence(sbrCtx->frameFIFO[i], channels); |
239 | 3.98k | } |
240 | 996 | } |
241 | 996 | return sbrCtx; |
242 | 996 | } |
243 | | |
244 | | void SbrContextEnd(SBRContext *sbrCtx) |
245 | 996 | { |
246 | 996 | if (!sbrCtx) return; |
247 | 996 | if (sbrCtx->sbrInfo) { |
248 | 996 | SbrEnd(sbrCtx->sbrInfo); |
249 | 996 | } |
250 | 996 | if (sbrCtx->resampler) { |
251 | 996 | ResampleEnd(sbrCtx->resampler); |
252 | 996 | } |
253 | 996 | FreeMemory(sbrCtx->signalAnalysis); |
254 | 996 | FreeMemory(sbrCtx); |
255 | 996 | } |
256 | | |
257 | | unsigned int SbrContextGetFullRateIdx(SBRContext *sCtx) |
258 | 996 | { |
259 | 996 | return sCtx->fullSampleRateIdx; |
260 | 996 | } |
261 | | |
262 | | #if FAAC_ENCODER_DRC |
263 | | unsigned long SbrContextGetFullRate(SBRContext *sCtx, unsigned long defaultRate) |
264 | 681 | { |
265 | 681 | return (sCtx && sCtx->fullSampleRate) ? sCtx->fullSampleRate : defaultRate; |
266 | 681 | } |
267 | | #endif |
268 | | |
269 | | unsigned int SbrContextGetXOverBandwidth(SBRContext *sbrCtx) |
270 | 996 | { |
271 | 996 | if (!sbrCtx || !sbrCtx->sbrInfo) return 0; |
272 | | /* kx * Fs / (2*64): each QMF band is Fs/(2*SBR_QMF_BANDS_64) Hz wide. |
273 | | * Matching core bandwidth to the SBR crossover avoids a gap or overlap. */ |
274 | 996 | return (unsigned int)((sbrCtx->sbrInfo->kx * sbrCtx->fullSampleRate) / |
275 | 996 | (2 * SBR_QMF_BANDS_64)); |
276 | 996 | } |
277 | | |
278 | | int SbrContextUpdateConfig(SBRContext *sCtx, int channels, unsigned long bitrate, int aacObjectType, int rateLimited) |
279 | 996 | { |
280 | 996 | sCtx->sbrInfo = SbrInit(channels, sCtx->fullSampleRate, bitrate); |
281 | 996 | if (!sCtx->sbrInfo) return 0; |
282 | 996 | PsConfigure(sCtx->sbrInfo, IsPS(aacObjectType), bitrate, rateLimited); |
283 | 996 | return 1; |
284 | 996 | } |
285 | | |
286 | | void SbrContextProcessFrame(SBRContext *sCtx, int numChannels, const bool *isLfe, int realPerCh, int flushTick, float *inputFifo[MAX_CHANNELS], float *heHalfRate[MAX_CHANNELS]) |
287 | 6.80k | { |
288 | 6.80k | unsigned int channel; |
289 | 6.80k | Resampler *rs = sCtx->resampler; |
290 | 6.80k | float *fullPtrs[MAX_CHANNELS]; |
291 | | |
292 | | /* SbrEncode quantizes into the new head; SbrWrite (via SbrContextGetBits) |
293 | | * emits the oldest slot, which is the payload for this frame's core audio. */ |
294 | 6.80k | sCtx->frameHead = (sCtx->frameHead + 1) % SBR_FRAME_FIFO; |
295 | 6.80k | SbrFrameData *fd = sCtx->frameFIFO[sCtx->frameHead]; |
296 | 6.80k | sCtx->sbrInfo->headerDecided = 0; |
297 | | |
298 | | /* Tick 1 still has real signal in the QMF overlap and the decimation FIR; |
299 | | * by tick 2 both are zero, so the rest of the drain is known silence. */ |
300 | 6.80k | if (realPerCh == 0 && flushTick > 1) { |
301 | 17.6k | for (channel = 0; channel < (unsigned int)numChannels; channel++) { |
302 | 14.6k | rs->halfRate[channel] = inputFifo[channel]; |
303 | 14.6k | memset(rs->halfRate[channel], 0, FRAME_LEN * sizeof(float)); |
304 | 14.6k | heHalfRate[channel] = rs->halfRate[channel]; |
305 | 14.6k | } |
306 | 2.98k | sbr_frame_silence(fd, numChannels); |
307 | 2.98k | if (PsIsActive(sCtx->sbrInfo)) PsNoteSilence(sCtx->sbrInfo, fd); |
308 | 3.82k | } else { |
309 | 21.9k | for (channel = 0; channel < (unsigned int)numChannels; channel++) { |
310 | | /* SBR finishes before the FIR overwrites the consumed FIFO front. */ |
311 | 18.1k | float *fullRate = inputFifo[channel]; |
312 | 18.1k | rs->fullRate[channel] = rs->halfRate[channel] = fullRate; |
313 | 18.1k | fullPtrs[channel] = fullRate; |
314 | | /* Final partial frame: silence-pad the unfilled full-rate tail to |
315 | | * prevent the resampler from consuming stale data. */ |
316 | 18.1k | if (realPerCh < 2 * FRAME_LEN) |
317 | 17.6k | memset(fullRate + realPerCh, 0, (2 * FRAME_LEN - realPerCh) * sizeof(float)); |
318 | 18.1k | heHalfRate[channel] = rs->halfRate[channel]; |
319 | 18.1k | } |
320 | | |
321 | | /* Always the full padded frame, never [0, realPerCh): the grid unconditionally |
322 | | * claims SBR_NUM_TIME_SLOTS, so normalizing a short frame over fewer slots |
323 | | * would inflate its levels, and the QMF-overlap save below reads the last |
324 | | * SBR_QMF_OVL_LEN_64 samples -- behind the buffer for a short frame. */ |
325 | 3.82k | if (PsIsActive(sCtx->sbrInfo)) PsPrepareCarrier(sCtx, fullPtrs); |
326 | 3.82k | SbrAnalyze(sCtx->signalAnalysis, fullPtrs, numChannels, isLfe, 2 * FRAME_LEN, sCtx->sbrInfo); |
327 | 3.82k | SbrEncode(sCtx->sbrInfo, fullPtrs, numChannels, isLfe, 2 * FRAME_LEN, sCtx->signalAnalysis, fd); |
328 | | /* Dual-rate decimation: produces the halved-rate core signal. */ |
329 | 3.82k | if (PsIsActive(sCtx->sbrInfo)) PsCommitCarrier(sCtx, rs->fullRate[0]); |
330 | 3.82k | Resample(rs, 2 * FRAME_LEN); |
331 | 3.82k | } |
332 | 6.80k | } |
333 | | |
334 | | /* Dual-rate SBR: the AAC core encodes at Fs/2 while SBR reconstructs the top |
335 | | * octave back to the full rate. Halve the core rate here; the full rate is kept |
336 | | * in the context for SBR and the ASC. */ |
337 | | void SbrContextResolveRate(SBRContext *sCtx, unsigned long *sampleRate, unsigned int *sampleRateIdx, SR_INFO **srInfoPtr) |
338 | 996 | { |
339 | 996 | if (sCtx->fullSampleRate == 0) { |
340 | 996 | sCtx->fullSampleRate = *sampleRate; |
341 | 996 | sCtx->fullSampleRateIdx = *sampleRateIdx; |
342 | 996 | *sampleRate = *sampleRate / 2; |
343 | 996 | *sampleRateIdx = GetSRIndex(*sampleRate); |
344 | 996 | *srInfoPtr = &srInfo[*sampleRateIdx]; |
345 | 996 | } |
346 | 996 | } |
347 | | |
348 | | int SbrContextIsPresent(SBRContext *sCtx) |
349 | 6.80k | { |
350 | 6.80k | return (sCtx && sCtx->sbrInfo) ? 1 : 0; |
351 | 6.80k | } |
352 | | |
353 | | /* Optimized log2 approximation for energy-to-decibel conversion. |
354 | | * Precision is sufficient for the 1.5/3.0 dB envelope quantizer. */ |
355 | 265k | #define FAST_LOG2_A 1.3424f |
356 | 265k | #define FAST_LOG2_B 0.3427f |
357 | 265k | #define FAST_LOG2_MANT_NORM (1.0f / (1 << 23)) /* 23-bit mantissa → [0, 1) */ |
358 | | static inline float fast_log2(float x) |
359 | 265k | { |
360 | 265k | union { float f; int32_t i; } vx; |
361 | 265k | vx.f = (float)x; |
362 | 265k | int32_t exp = (vx.i >> 23) & 0xFF; |
363 | 265k | float m = (float)(vx.i & 0x7FFFFF) * FAST_LOG2_MANT_NORM; |
364 | 265k | return (float)(exp - 127) + (float)(m * (FAST_LOG2_A - FAST_LOG2_B * m)); |
365 | 265k | } |
366 | | |
367 | | /* 64-band subband analysis using a 64-point complex FFT. |
368 | | * Leverages conjugate symmetry to extract two 64-point real-subsequence |
369 | | * DFTs from one complex transform, reducing FLOPs by ~50% compared to |
370 | | * a standard 128-point implementation. y receives the FFT spectrum. */ |
371 | | static inline void qmf_transform(const SBRInfo *sbr, const float *ovl_pos, float *y) |
372 | 522k | { |
373 | 522k | float x[128]; |
374 | 522k | float * restrict xr = x, * restrict xi = x + 64; |
375 | | /* The filter is symmetric except at offsets 128/512 and 256/384. |
376 | | * Compute the contiguous polyphase outputs before the complex rotation, |
377 | | * using the FFT output buffer as workspace. */ |
378 | 67.4M | for (int n = 0; n < 128; n++) { |
379 | 66.9M | y[n] = qmf_c[n] * ovl_pos[639 - n] |
380 | 66.9M | + qmf_c[128 + n] * ovl_pos[511 - n] |
381 | 66.9M | + qmf_c[256 + n] * ovl_pos[383 - n] |
382 | 66.9M | + qmf_c[256 - n] * ovl_pos[255 - n] |
383 | 66.9M | + qmf_c[128 - n] * ovl_pos[127 - n]; |
384 | 66.9M | } |
385 | | /* Tap zero uses the two sign exceptions to the mirror rule. */ |
386 | 522k | y[0] = qmf_c[0] * ovl_pos[639] |
387 | 522k | + qmf_c[128] * ovl_pos[511] |
388 | 522k | + qmf_c[256] * ovl_pos[383] |
389 | 522k | + (-qmf_c[256]) * ovl_pos[255] |
390 | 522k | + (-qmf_c[128]) * ovl_pos[127]; |
391 | 33.9M | for (int m = 0; m < 64; m++) { |
392 | 33.4M | float a = y[2 * m], b = y[2 * m + 1]; |
393 | 33.4M | xr[m] = a * sbr->twidCos[m] - b * sbr->twidSin[m]; |
394 | 33.4M | xi[m] = -(a * sbr->twidSin[m] + b * sbr->twidCos[m]); |
395 | 33.4M | } |
396 | 522k | fft(x, y, FFT_LOGM_SHORT); |
397 | 522k | } |
398 | | |
399 | | /* Band k of the complex QMF output. */ |
400 | | static inline void qmf_band(const SBRInfo *sbr, const float *y, int k, float *re, float *im) |
401 | 10.4M | { |
402 | 10.4M | const float * restrict yr = y, * restrict yi = y + 64; |
403 | 10.4M | int kr = 63 - k; |
404 | | /* Separate the two real-subsequence DFTs by conjugate symmetry. */ |
405 | 10.4M | float Ar = 0.5f * (yr[k] + yr[kr]); |
406 | 10.4M | float Ai = 0.5f * (yi[kr] - yi[k]); |
407 | 10.4M | float Br = -0.5f * (yi[k] + yi[kr]); |
408 | 10.4M | float Bi = 0.5f * (yr[kr] - yr[k]); |
409 | | /* Sr = Ar + w_k_real * Br - w_k_imag * Bi |
410 | | * Si = Ai + w_k_real * Bi + w_k_imag * Br */ |
411 | 10.4M | float wr = sbr->oddCos[k]; |
412 | 10.4M | float wi = sbr->oddSin[k]; |
413 | 10.4M | float Sr = Ar + wr * Br - wi * Bi; |
414 | 10.4M | float Si = Ai + wr * Bi + wi * Br; |
415 | 10.4M | *re = Sr; |
416 | 10.4M | *im = Si; |
417 | 10.4M | } |
418 | | |
419 | | #if FAAC_ENCODER_PS |
420 | | void SbrQmfAnalysisComplex(SBRInfo *sbr, const float *ovl_pos, float *real, float *imag, int kx, int k2) |
421 | | { |
422 | | float y[128]; |
423 | | qmf_transform(sbr, ovl_pos, y); |
424 | | for (int k = kx; k < k2; k++) qmf_band(sbr, y, k, &real[k], &imag[k]); |
425 | | } |
426 | | #endif |
427 | | |
428 | | /* The SBR bitstream only transmits envelope magnitudes, so the energy path |
429 | | * discards phase. */ |
430 | | void SbrQmfAnalysis(SBRInfo *sbr, const float * restrict ovl_pos, float * restrict energy, int kx, int k2) |
431 | 522k | { |
432 | 522k | float y[128]; |
433 | 522k | qmf_transform(sbr, ovl_pos, y); |
434 | 10.9M | for (int k = kx; k < k2; k++) { |
435 | 10.4M | float Sr, Si; |
436 | 10.4M | qmf_band(sbr, y, k, &Sr, &Si); |
437 | 10.4M | energy[k] += Sr * Sr + Si * Si; |
438 | 10.4M | } |
439 | 522k | } |
440 | | |
441 | | static void sbr_adopt_envelope_grid(const struct SignalAnalysis *sa, SbrFrameData *fd) |
442 | 3.82k | { |
443 | 3.82k | fd->numEnvelopes = sa->numEnvelopes; |
444 | 3.82k | fd->frameClass = sa->frameClass; |
445 | 17.3k | for (int i = 0; i <= sa->numEnvelopes; i++) fd->tEnv[i] = sa->tEnv[i]; |
446 | 3.82k | fd->eff_amp_res = (fd->numEnvelopes == 1) ? 0 : SBR_AMP_RES; |
447 | 3.82k | } |
448 | | |
449 | | static void sbr_quantize_envelopes(const SBRInfo *sbr, int nch, const bool *isLfe, |
450 | | const struct SignalAnalysis *sa, SbrFrameData *fd) |
451 | 3.82k | { |
452 | | #if MAX_CHANNELS < 6 |
453 | | (void)isLfe; |
454 | | #endif |
455 | 3.82k | int n_env = fd->numEnvelopes; |
456 | | /* Must match write_sbr_envelope's table, or the decoder desyncs. */ |
457 | 3.82k | int nb = sbr->numBands; |
458 | 3.82k | const int *edges = sbr->bandEdges; |
459 | | |
460 | 21.9k | for (int ch = 0; ch < nch; ch++) { |
461 | 18.1k | #if MAX_CHANNELS >= 6 |
462 | 18.1k | if (isLfe[ch]) continue; |
463 | 16.3k | #endif |
464 | | /* Read-only alias; the quantizer never writes back through it. */ |
465 | 16.3k | const float (* restrict bandE)[SBR_QMF_BANDS_64] = sa->ch[ch].bandE; |
466 | 16.3k | int dlav = fd->eff_amp_res ? SBR_ENV_DELTA_LIMIT_HIRES : SBR_ENV_DELTA_LIMIT_LORES; |
467 | 53.8k | for (int e = 0; e < n_env; e++) { |
468 | 37.4k | int prevLevel = -1; |
469 | 302k | for (int b = 0; b < nb; b++) { |
470 | 265k | int k_lo = edges[b], k_hi = edges[b+1]; |
471 | | /* Weight energy by the number of QMF slots per envelope to |
472 | | * maintain normalized power levels across variable borders. */ |
473 | 265k | int e_slots = sa->envSampled[e]; |
474 | 265k | if (e_slots < 1) e_slots = 1; |
475 | 265k | float E = 0; |
476 | 1.09M | for (int k = k_lo; k < k_hi; k++) E += bandE[e][k]; |
477 | 265k | E /= (float)(e_slots * (k_hi - k_lo)); |
478 | 265k | float factor = fd->eff_amp_res ? 1.0f : 2.0f; |
479 | 265k | int level = lrintf(factor * (fast_log2(E + SBR_LOG_ENERGY_FLOOR) - SBR_ENV_LEVEL_LOG2_OFFSET)); |
480 | 265k | int raw_level = clamp_int(level, 0, 127); |
481 | | /* Clamped so the frequency-delta chain stays codable. */ |
482 | 265k | if (prevLevel < 0) |
483 | 37.4k | raw_level = clamp_int(raw_level, 0, fd->eff_amp_res ? 63 : 127); |
484 | 227k | else |
485 | 227k | raw_level = clamp_int(raw_level, prevLevel - dlav, prevLevel + dlav); |
486 | 265k | fd->ch[ch].envData[e][b] = prevLevel = raw_level; |
487 | 265k | } |
488 | 37.4k | } |
489 | 16.3k | } |
490 | 3.82k | } |
491 | | |
492 | | void SbrEncode(SBRInfo *sbr, float *timeDomain[MAX_CHANNELS], int numChannels, const bool *isLfe, int numSamples, struct SignalAnalysis *sa, SbrFrameData *fd) |
493 | 3.82k | { |
494 | | #if MAX_CHANNELS < 6 |
495 | | (void)isLfe; |
496 | | #endif |
497 | 21.9k | for (int ch = 0; ch < numChannels; ch++) |
498 | 18.1k | #if MAX_CHANNELS >= 6 |
499 | 18.1k | if (!isLfe[ch]) |
500 | 16.3k | #endif |
501 | 16.3k | memcpy(sbr->ch[ch].qmfOvl64, timeDomain[ch] + numSamples - SBR_QMF_HIST_LEN, SBR_QMF_HIST_LEN * sizeof(float)); |
502 | | |
503 | 3.82k | sbr_adopt_envelope_grid(sa, fd); |
504 | 3.82k | int coreChannels = numChannels; |
505 | 3.82k | if (PsIsActive(sbr)) { |
506 | 0 | PsAnalyze(sbr, sa, fd); |
507 | 0 | coreChannels = 1; |
508 | 0 | } |
509 | 3.82k | sbr_quantize_envelopes(sbr, coreChannels, isLfe, sa, fd); |
510 | | |
511 | | #ifdef FAAC_STATS |
512 | | g_faacStats.sbrFrames++; |
513 | | if (fd->frameClass != SBR_FRAME_CLASS_FIXFIX) { |
514 | | g_faacStats.sbrTransientFrames++; |
515 | | } |
516 | | for (int ch = 0; ch < numChannels; ch++) { |
517 | | #if MAX_CHANNELS >= 6 |
518 | | if (isLfe[ch]) continue; |
519 | | #endif |
520 | | g_faacStats.sbrInvfSum += sbr->rich ? SBR_INVF_MODE_RICH : SBR_INVF_MODE; |
521 | | g_faacStats.sbrInvfCount++; |
522 | | } |
523 | | #endif |
524 | 3.82k | } |
525 | | |
526 | | /* SBR bitstream writer. Emits the SBR fill element payload into the bitstream. |
527 | | * Replays the write sequence into a counting sink during rate control to |
528 | | * ensure accurate bit budget allocation. */ |