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 <math.h> |
17 | | #include <string.h> |
18 | | #include "frame.h" |
19 | | #include "coder.h" |
20 | | #include "tns.h" |
21 | | #include "util.h" |
22 | | |
23 | | /* Per-sample-rate scalefactor-band range TNS is allowed to filter over, from |
24 | | * ISO/IEC 13818-7/14496-3's TNS tool tables (indexed by sampleRateIdx). Not |
25 | | * an original heuristic: this is the spec's fixed table. */ |
26 | | static const struct { |
27 | | uint8_t min; |
28 | | uint8_t max; |
29 | | } tns_sfb_range[12] = { |
30 | | {11, 31}, {12, 31}, {15, 34}, {16, 40}, {17, 42}, {20, 51}, |
31 | | {25, 46}, {26, 46}, {24, 42}, {28, 42}, {30, 42}, {31, 39} |
32 | | }; |
33 | | |
34 | 32.3k | #define TNS_LPC_ORDER 8 /* fixed filter order; the spec allows up to 20, but higher orders rarely paid for themselves here */ |
35 | | _Static_assert(TNS_LPC_ORDER <= TNS_MAX_ORDER, |
36 | | "coder.h's TNS array bound must cover the order tns.c actually fits"); |
37 | 4.53k | #define TNS_GAIN_LIMIT 1.4f /* Levinson-Durbin prediction gain below this isn't worth the filter's bit cost */ |
38 | 4.36k | #define TNS_MEASURED_GAIN 1.4f /* post-quantization re-check: same bar as TNS_GAIN_LIMIT, applied to the filter actually being transmitted */ |
39 | | |
40 | | /* Below this, a band's spectral energy is indistinguishable from float |
41 | | * rounding noise, so there's nothing real for TNS to whiten. Also reused |
42 | | * below as the floor for RMS-normalization and the LPC residual check, |
43 | | * rather than inventing a separate near-zero constant for each. */ |
44 | 734k | #define TNS_MIN_ENERGY 1e-9f |
45 | | /* SFM (geomean/arithmean of per-band RMS) near 1.0 means the band is |
46 | | * noise-like, which PNS (quantize.c) is about to replace anyway -- skip |
47 | | * TNS's LPC work there; it only pays off on tonal/peaky bands. */ |
48 | 9.27k | #define TNS_PNS_SFM_SKIP 0.85f |
49 | | |
50 | | static void calc_autocorr_f(int order, int length, const float * work, float * r) |
51 | 4.53k | { |
52 | 4.53k | int lag, i; |
53 | | |
54 | 45.3k | for (lag = 0; lag <= order; lag++) { |
55 | 40.8k | float acc = 0.0f; |
56 | 40.8k | const float * p1 = work; |
57 | 40.8k | const float * p2 = work + lag; |
58 | 40.8k | int n = length - lag; |
59 | | |
60 | 25.2M | for (i = 0; i < n; i++) |
61 | 25.2M | acc += p1[i] * p2[i]; |
62 | 40.8k | r[lag] = acc; |
63 | 40.8k | } |
64 | 4.53k | } |
65 | | |
66 | | /* Reflection coefficients are clamped to +-0.999, short of the unstable |
67 | | * +-1 limit, so the resulting filter is guaranteed stable regardless of |
68 | | * input. The returned prediction gain (r[0]/final residual error) lets |
69 | | * TnsEncode reject a bad fit before spending any bits on coefficients -- |
70 | | * free to report here, since the recursion already has both numbers. */ |
71 | | static float compute_lpc(int order, const float * r, float * k) |
72 | 4.53k | { |
73 | 4.53k | float a[TNS_MAX_ORDER + 1]; |
74 | 4.53k | float err; |
75 | 4.53k | int i, j; |
76 | | |
77 | 4.53k | if (r[0] <= 0.0f) { |
78 | 0 | for (i = 1; i <= order; i++) |
79 | 0 | k[i] = 0.0f; |
80 | 0 | return 1.0f; |
81 | 0 | } |
82 | | |
83 | 4.53k | err = r[0]; |
84 | 4.53k | a[0] = 1.0f; |
85 | 40.8k | for (i = 1; i <= order; i++) { |
86 | 36.2k | float lambda = r[i]; |
87 | 36.2k | float rc; |
88 | 36.2k | int half; |
89 | | |
90 | 163k | for (j = 1; j < i; j++) |
91 | 126k | lambda += a[j] * r[i - j]; |
92 | | |
93 | 36.2k | if (err <= 0.0f) { |
94 | 0 | for (; i <= order; i++) |
95 | 0 | k[i] = 0.0f; |
96 | 0 | break; |
97 | 0 | } |
98 | | |
99 | 36.2k | rc = -lambda / err; |
100 | 36.2k | if (rc > 0.999f) rc = 0.999f; |
101 | 36.2k | else if (rc < -0.999f) rc = -0.999f; |
102 | 36.2k | k[i] = rc; |
103 | | |
104 | 36.2k | half = (i + 1) / 2; |
105 | 90.6k | for (j = 1; j < half; j++) { |
106 | 54.4k | float t1 = a[j]; |
107 | 54.4k | float t2 = a[i - j]; |
108 | 54.4k | a[j] = t1 + rc * t2; |
109 | 54.4k | a[i - j] = t2 + rc * t1; |
110 | 54.4k | } |
111 | 36.2k | if (i % 2 == 0) |
112 | 18.1k | a[i / 2] += rc * a[i / 2]; |
113 | 36.2k | a[i] = rc; |
114 | | |
115 | 36.2k | err *= (1.0f - rc * rc); |
116 | 36.2k | if (err <= 0.0f) |
117 | 0 | break; |
118 | 36.2k | } |
119 | | |
120 | | /* err collapsing to ~0 means a (near-)perfect fit, which for real audio |
121 | | * means a degenerate input rather than a genuinely great filter. Report |
122 | | * infinite gain so the caller's isfinite() check rejects it, instead of |
123 | | * dividing by ~0. */ |
124 | 4.53k | if (err <= TNS_MIN_ENERGY) |
125 | 0 | return INFINITY; |
126 | 4.53k | return r[0] / err; |
127 | 4.53k | } |
128 | | |
129 | | /* Reflection coefficients live in (-1, 1); arcsine-warp them before |
130 | | * quantizing so equal code steps land closer to equal perceptual steps |
131 | | * near the +-1 ends, per the tns_data() coefficient law in the spec. */ |
132 | | static void quantize_coeffs(int order, int res, float * k, int8_t * idx) |
133 | 4.36k | { |
134 | 4.36k | const float s_p = (float)(((1 << (res - 1)) - 0.5f) / (M_PI / 2)); |
135 | 4.36k | const float s_n = (float)(((1 << (res - 1)) + 0.5f) / (M_PI / 2)); |
136 | 4.36k | const int i_max = (1 << (res - 1)) - 1; |
137 | 4.36k | const int i_min = -(1 << (res - 1)); |
138 | 4.36k | int i; |
139 | | |
140 | 39.2k | for (i = 1; i <= order; i++) { |
141 | 34.8k | float val = k[i]; |
142 | 34.8k | float s = (val >= 0.0f) ? s_p : s_n; |
143 | 34.8k | int q = (int)(asinf(val) * s + ((val >= 0.0f) ? 0.5f : -0.5f)); |
144 | | |
145 | 34.8k | if (q > i_max) q = i_max; |
146 | 34.8k | else if (q < i_min) q = i_min; |
147 | 34.8k | idx[i] = q; |
148 | | |
149 | | /* Re-derive k[] from the quantized index (not the original float) |
150 | | * so finalize_filter below builds the same filter the decoder will, |
151 | | * from the same lossy coefficients that actually get transmitted. */ |
152 | 34.8k | s = (q >= 0) ? s_p : s_n; |
153 | 34.8k | k[i] = sinf((float)q / s); |
154 | 34.8k | } |
155 | 4.36k | } |
156 | | |
157 | | /* filter_spec's recursion needs direct-form polynomial coefficients, not |
158 | | * reflection coefficients, so this runs the standard lattice-to-direct |
159 | | * step-up. Called after quantize_coeffs so the polynomial matches what's |
160 | | * actually transmitted, not the pre-quantization float values. */ |
161 | | static void finalize_filter(int order, const float * k, float * a) |
162 | 4.36k | { |
163 | 4.36k | int i, m; |
164 | | |
165 | | /* Each step consumes k[m] before updating only earlier coefficients, |
166 | | * so the reflection-coefficient storage can also hold the polynomial. */ |
167 | 4.36k | a[0] = 1.0f; |
168 | 31.4k | for (m = 1; m <= order; m++) { |
169 | 27.0k | float km = k[m]; |
170 | 27.0k | int half = (m + 1) / 2; |
171 | | |
172 | 60.2k | for (i = 1; i < half; i++) { |
173 | 33.2k | float t1 = a[i]; |
174 | 33.2k | float t2 = a[m - i]; |
175 | 33.2k | a[i] = t1 + km * t2; |
176 | 33.2k | a[m - i] = t2 + km * t1; |
177 | 33.2k | } |
178 | 27.0k | if (m % 2 == 0) |
179 | 12.6k | a[m / 2] += km * a[m / 2]; |
180 | 27.0k | a[m] = km; |
181 | 27.0k | } |
182 | 4.36k | } |
183 | | |
184 | | static void filter_spec(int length, int order, const float * a, const float * src, float * dst) |
185 | 8.63k | { |
186 | 8.63k | int i, j; |
187 | 8.63k | int limit = order < length ? order : length; |
188 | | |
189 | 62.0k | for (i = 0; i < limit; i++) { |
190 | 53.4k | float acc = src[i]; |
191 | 209k | for (j = 1; j <= i; j++) |
192 | 156k | acc += a[j] * src[i - j]; |
193 | 53.4k | dst[i] = acc; |
194 | 53.4k | } |
195 | 5.35M | for (; i < length; i++) { |
196 | 5.34M | float acc = src[i]; |
197 | 38.3M | for (j = 1; j <= order; j++) |
198 | 33.0M | acc += a[j] * src[i - j]; |
199 | 5.34M | dst[i] = acc; |
200 | 5.34M | } |
201 | 8.63k | } |
202 | | |
203 | | void TnsInit(faacEncStruct* hEncoder) |
204 | 2.94k | { |
205 | 2.94k | unsigned int ch; |
206 | 2.94k | int fs = hEncoder->sampleRateIdx; |
207 | | |
208 | 19.0k | for (ch = 0; ch < hEncoder->numChannels; ch++) { |
209 | 16.1k | TnsInfo *info = &hEncoder->coderInfo[ch].tnsInfo; |
210 | | |
211 | 16.1k | info->tnsMaxBandsLong = tns_sfb_range[fs].max; |
212 | 16.1k | info->tnsNumSwbLong = hEncoder->srInfo->num_cb_long; |
213 | 16.1k | info->tnsMinBandNumberLong = tns_sfb_range[fs].min; |
214 | 16.1k | } |
215 | 2.94k | } |
216 | | |
217 | | /* Fits one TNS filter over scalefactor bands [b_start, b_stop) and, if it |
218 | | * earns its place, whitens that range of `spec` in place and fills *filter. |
219 | | * Returns 1 when a filter was written, 0 otherwise. */ |
220 | | static int tns_fit_range(int b_start, int b_stop, const int *sfbOffsetTable, |
221 | | float *spec, TnsFilterData *filter) |
222 | 14.6k | { |
223 | 14.6k | int i_start = sfbOffsetTable[b_start]; |
224 | 14.6k | int length = sfbOffsetTable[b_stop] - i_start; |
225 | 14.6k | float *band; |
226 | 14.6k | float wspec[BLOCK_LEN_LONG]; |
227 | 14.6k | float trial[BLOCK_LEN_LONG]; |
228 | 14.6k | float r[TNS_MAX_ORDER + 1] = {0}; |
229 | 14.6k | float k[TNS_MAX_ORDER + 1] = {0}; |
230 | 14.6k | float gain; |
231 | 14.6k | int order, limit, i; |
232 | | |
233 | 14.6k | if (length <= TNS_LPC_ORDER) |
234 | 95 | return 0; |
235 | | |
236 | 14.5k | band = spec + i_start; |
237 | | |
238 | | /* Per-band RMS-normalize into wspec, floored at 1% of the loudest band's |
239 | | * RMS. Un-normalized, Levinson-Durbin would fit whatever band has the |
240 | | * most energy and ignore quieter ones -- but pre-echo is audible in |
241 | | * quiet bands too, so the filter needs to whiten across the whole range, |
242 | | * not just the peak. */ |
243 | 14.5k | { |
244 | 14.5k | float maxrms = 0.0f, floorrms; |
245 | 14.5k | float sum_rms = 0.0f, sum_log_rms = 0.0f; |
246 | 14.5k | float total_energy = 0.0f; |
247 | 14.5k | int nbands = b_stop - b_start; |
248 | 14.5k | float rms_band[MAX_SCFAC_BANDS]; |
249 | 14.5k | int b; |
250 | | |
251 | 315k | for (b = b_start; b < b_stop; b++) { |
252 | 300k | int s0 = sfbOffsetTable[b], s1 = sfbOffsetTable[b + 1]; |
253 | 300k | float e = 0.0f, rms, rms_fl; |
254 | | |
255 | 9.71M | for (i = s0; i < s1; i++) |
256 | 9.41M | e += (float)(spec[i] * spec[i]); |
257 | 300k | total_energy += e; |
258 | 300k | rms = sqrtf(e / (float)(s1 - s0)); |
259 | 300k | rms_band[b - b_start] = rms; |
260 | 300k | if (rms > maxrms) maxrms = rms; |
261 | | |
262 | | /* rms_fl keeps logf() away from 0 for silent bands; folded into |
263 | | * the same loop as maxrms rather than a second pass. */ |
264 | 300k | rms_fl = rms > TNS_MIN_ENERGY ? rms : TNS_MIN_ENERGY; |
265 | 300k | sum_rms += rms_fl; |
266 | 300k | sum_log_rms += logf(rms_fl); |
267 | 300k | } |
268 | | |
269 | 14.5k | if (total_energy < TNS_MIN_ENERGY) |
270 | 5.23k | return 0; |
271 | | |
272 | | /* Spectral flatness (geomean/arithmean of per-band RMS) near 1.0 |
273 | | * means the band is noise-like, which PNS (quantize.c) is about to |
274 | | * replace anyway -- skip the LPC work; it only pays off on |
275 | | * tonal/peaky bands. */ |
276 | 9.27k | if (expf(sum_log_rms / (float)nbands) / (sum_rms / (float)nbands) > TNS_PNS_SFM_SKIP) |
277 | 4.73k | return 0; |
278 | | |
279 | 4.53k | floorrms = maxrms * 0.01f; |
280 | 4.53k | if (floorrms < TNS_MIN_ENERGY) floorrms = TNS_MIN_ENERGY; |
281 | | |
282 | 105k | for (b = b_start; b < b_stop; b++) { |
283 | 100k | int s0 = sfbOffsetTable[b], s1 = sfbOffsetTable[b + 1]; |
284 | 100k | float rms = rms_band[b - b_start]; |
285 | 100k | float wgt = 1.0f / (rms > floorrms ? rms : floorrms); |
286 | 2.92M | for (i = s0; i < s1; i++) |
287 | 2.82M | wspec[i - i_start] = (float)spec[i] * wgt; |
288 | 100k | } |
289 | 4.53k | } |
290 | | |
291 | 4.53k | calc_autocorr_f(TNS_LPC_ORDER, length, wspec, r); |
292 | 4.53k | gain = compute_lpc(TNS_LPC_ORDER, r, k); |
293 | 4.53k | if (gain < TNS_GAIN_LIMIT) |
294 | 172 | return 0; |
295 | | /* No upper bound: compute_lpc clamps reflection coefficients to +-0.999, |
296 | | * so a high gain can't mean an unstable filter; isfinite() catches the |
297 | | * genuinely degenerate (near-zero-error) fits instead. */ |
298 | 4.36k | if (!isfinite(gain)) |
299 | 0 | return 0; |
300 | | |
301 | 4.36k | quantize_coeffs(TNS_LPC_ORDER, DEF_TNS_COEFF_RES, k, filter->index); |
302 | | |
303 | | /* Drop trailing taps that quantized away to ~nothing: they cost bits |
304 | | * without changing what the filter does. */ |
305 | 4.36k | order = TNS_LPC_ORDER; |
306 | 12.1k | while (order > 0 && fabsf(k[order]) < (float)DEF_TNS_COEFF_THRESH) |
307 | 7.83k | order--; |
308 | 4.36k | if (order == 0) |
309 | 0 | return 0; |
310 | | |
311 | 4.36k | filter->order = order; |
312 | | |
313 | | /* Fixed at 0, not chosen: calc_autocorr_f is invariant under sequence |
314 | | * reversal, so both directions give the same LPC fit and prediction gain. |
315 | | * Picking the right one needs the time-domain transient position, which |
316 | | * this function never sees. */ |
317 | 4.36k | filter->direction = 0; |
318 | | |
319 | | /* Coefficients that all fit in one fewer bit each can be transmitted at |
320 | | * reduced resolution; the spec's coefCompress flag signals that. */ |
321 | 4.36k | filter->coefCompress = 1; |
322 | 4.36k | limit = 1 << (DEF_TNS_COEFF_RES - 2); |
323 | 11.6k | for (i = 1; i <= order; i++) { |
324 | 11.1k | if (filter->index[i] < -limit || filter->index[i] >= limit) { |
325 | 3.92k | filter->coefCompress = 0; |
326 | 3.92k | break; |
327 | 3.92k | } |
328 | 11.1k | } |
329 | | |
330 | 4.36k | finalize_filter(order, k, k); |
331 | | |
332 | | /* compute_lpc's gain estimate was on the un-quantized coefficients; |
333 | | * quantization can erode it enough that the filter actually being |
334 | | * transmitted no longer pays for itself. Re-check on a trial run of the |
335 | | * real (quantized) filter before committing to writing it out. */ |
336 | 4.36k | { |
337 | | /* The unfiltered energy is r[0]: calc_autocorr_f's lag-0 term is the |
338 | | * same sum(wspec[i]^2) over the same range, and compute_lpc only reads |
339 | | * r. Only the filtered energy needs a pass here. */ |
340 | 4.36k | float filt_e = 0.0f; |
341 | | |
342 | 4.36k | filter_spec(length, order, k, wspec, trial); |
343 | 2.73M | for (i = 0; i < length; i++) |
344 | 2.72M | filt_e += trial[i] * trial[i]; |
345 | 4.36k | if (filt_e < TNS_MIN_ENERGY) |
346 | 0 | filt_e = TNS_MIN_ENERGY; |
347 | 4.36k | if (r[0] < TNS_MEASURED_GAIN * filt_e) |
348 | 94 | return 0; |
349 | 4.36k | } |
350 | | |
351 | 4.26k | filter_spec(length, order, k, band, trial); |
352 | 4.26k | memcpy(band, trial, length * sizeof(float)); |
353 | 4.26k | return 1; |
354 | 4.36k | } |
355 | | |
356 | | void TnsEncode(CoderInfo *coderInfo, float *spec) |
357 | 14.8k | { |
358 | 14.8k | TnsInfo *tnsInfo = &coderInfo->tnsInfo; |
359 | 14.8k | int numBands = coderInfo->sfbn; |
360 | 14.8k | const int *sfbOffsetTable = coderInfo->sfb_offset; |
361 | 14.8k | int b_start, b_stop; |
362 | | |
363 | | /* Long blocks only: the caller screens ONLY_SHORT_WINDOW out, since short |
364 | | * windows already have the temporal resolution to not need TNS. */ |
365 | 14.8k | tnsInfo->tnsDataPresent = 0; |
366 | 14.8k | tnsInfo->windowData.numFilters = 0; |
367 | | |
368 | | /* Frame-invariant: the band limits come from the sample rate's TNS table and |
369 | | * numBands is aacquantCfg.max_cbl for every long channel. Recomputed rather |
370 | | * than latched in TnsInit only because TnsInit runs before CalcBW. */ |
371 | 14.8k | b_start = min(tnsInfo->tnsMinBandNumberLong, numBands); |
372 | 14.8k | b_stop = min(tnsInfo->tnsMaxBandsLong, numBands); |
373 | 14.8k | if (b_stop <= b_start) |
374 | 280 | return; |
375 | | |
376 | 14.6k | if (!tns_fit_range(b_start, b_stop, sfbOffsetTable, spec, |
377 | 14.6k | &tnsInfo->windowData.tnsFilter[0])) |
378 | 10.3k | return; |
379 | | |
380 | | #ifdef FAAC_STATS |
381 | | g_faacStats.longBlocksTNS++; |
382 | | #endif |
383 | | |
384 | | /* Declared from b_start to the top of the spectrum rather than to b_stop, |
385 | | * over-declaring the region. */ |
386 | 4.26k | tnsInfo->windowData.tnsFilter[0].length = tnsInfo->tnsNumSwbLong - b_start; |
387 | 4.26k | tnsInfo->windowData.numFilters = 1; |
388 | 4.26k | tnsInfo->windowData.coefResolution = DEF_TNS_COEFF_RES; |
389 | 4.26k | tnsInfo->tnsDataPresent = 1; |
390 | 4.26k | } |