/proc/self/cwd/external/faac/libfaar/polyresample.c
Line | Count | Source |
1 | | /* |
2 | | * FAAR - Freeware Advanced Audio Resampler |
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 "faar.h" |
17 | | #include "libfaar_internal.h" |
18 | | #include "dft_coeffs.h" |
19 | | #include "dft_prefilter.h" |
20 | | #include "../common/atomic.h" |
21 | | #include <limits.h> |
22 | | #if FAAR_RESAMPLER_FLOAT |
23 | | #include "fft_float2.h" |
24 | | #endif |
25 | | #include <stdalign.h> |
26 | | #include <stdio.h> |
27 | | |
28 | | #ifndef M_PI |
29 | | #define M_PI 3.14159265358979323846 |
30 | | #endif |
31 | | |
32 | | |
33 | 1.42k | #define POLYRESAMPLE_NUM_PHASES 64 |
34 | | #define POLYRESAMPLE_MAX_FILTER_LEN 512 /* Upper bound for stack-allocated temporary coefficient buffers */ |
35 | 17.6k | #define POLYRESAMPLE_ALIGNMENT 64 /* 64-byte alignment for AVX-512 / AVX2 / NEON SIMD vector loads */ |
36 | | |
37 | | /* Over-allocate and align by hand so a custom AllocMemory needs no aligned variant. */ |
38 | 5.89k | static void *aligned_malloc(size_t size) { |
39 | 5.89k | if (size > SIZE_MAX - POLYRESAMPLE_ALIGNMENT - sizeof(void *)) return NULL; |
40 | 5.89k | void *ptr = AllocMemory(size + POLYRESAMPLE_ALIGNMENT + sizeof(void *)); |
41 | 5.89k | if (!ptr) return NULL; |
42 | 5.89k | uintptr_t addr = (uintptr_t)ptr + sizeof(void *) + POLYRESAMPLE_ALIGNMENT - 1; |
43 | 5.89k | void *aligned_ptr = (void *)(addr & ~(uintptr_t)(POLYRESAMPLE_ALIGNMENT - 1)); |
44 | 5.89k | ((void **)aligned_ptr)[-1] = ptr; |
45 | 5.89k | return aligned_ptr; |
46 | 5.89k | } |
47 | | |
48 | 10.0k | static void aligned_free(void *ptr) { |
49 | 10.0k | if (!ptr) return; |
50 | 5.89k | FreeMemory(((void **)ptr)[-1]); |
51 | 5.89k | } |
52 | | |
53 | 179k | static double bessel_i0(double x) { |
54 | 179k | double sum = 1.0; |
55 | 179k | double u = 1.0; |
56 | 179k | double half_x = x / 2.0; |
57 | 6.42M | for (int k = 1; k < 100; k++) { |
58 | 6.42M | u *= (half_x / k) * (half_x / k); |
59 | 6.42M | sum += u; |
60 | 6.42M | if (u < sum * 1e-16) break; |
61 | 6.42M | } |
62 | 179k | return sum; |
63 | 179k | } |
64 | | |
65 | 180k | static double kaiser_window(double n, double N, double beta, double denominator) { |
66 | 180k | if (beta <= 0.0) return 1.0; |
67 | 180k | double arg = 2.0 * n / N - 1.0; |
68 | 180k | double sq = 1.0 - arg * arg; |
69 | 180k | if (sq <= 0.0) return 0.0; |
70 | 178k | return bessel_i0(beta * sqrt(sq)) / denominator; |
71 | 180k | } |
72 | | |
73 | 0 | static uint32_t rate_gcd(uint32_t a, uint32_t b) { |
74 | 0 | while (b) { uint32_t remainder = a % b; a = b; b = remainder; } |
75 | 0 | return a; |
76 | 0 | } |
77 | | |
78 | | struct faar_resampler_struct { |
79 | | uint32_t in_rate; |
80 | | uint32_t out_rate; |
81 | | uint16_t channels; |
82 | | faar_quality quality; |
83 | | uint32_t dither; /* 0, FAAR_DITHER_TPDF or FAAR_DITHER_SHAPED */ |
84 | | uint8_t dither_depth; |
85 | | uint32_t prng_state[MAX_CHANNELS]; |
86 | | float error_history[MAX_CHANNELS]; |
87 | | |
88 | | size_t filter_len; |
89 | | size_t num_phases; |
90 | | double ratio; /* out_rate / in_rate */ |
91 | | uint64_t phase; /* Input position in units of 1/out_rate */ |
92 | | uint64_t input_frames; |
93 | | uint64_t output_frames; |
94 | | uint32_t phase_gcd; |
95 | | bool exact_phase_bank; |
96 | | bool half_sample_phase_bank; |
97 | | double beta; |
98 | | faar_sample_t *polyphase_table; /* Half-bank and interpolation guards, shared by all channels */ |
99 | | faar_sample_t *polyphase_reverse_table; /* Reversed exact rows, avoids per-output coefficient copies */ |
100 | | #if FAAR_RESAMPLER_FLOAT |
101 | | float *polyphase_low_table; /* Low words of High's filter coefficients. */ |
102 | | #else |
103 | | double *polyphase_wide_table; /* Replaces polyphase_table for High. */ |
104 | | double *polyphase_wide_reverse; |
105 | | #endif |
106 | | |
107 | | faar_sample_t *hist[MAX_CHANNELS]; /* Keeps sample and coefficient arithmetic at the selected width */ |
108 | | faar_sample_t last_input[MAX_CHANNELS]; /* Retained even when history is fully consumed */ |
109 | | size_t hist_offset; /* Frames before the moving history pointers */ |
110 | | size_t hist_len; /* Unconsumed frames in hist */ |
111 | | size_t hist_cap_per_ch; /* Allocated capacity per channel in frames */ |
112 | | bool prepared; |
113 | | size_t prepared_max_input; |
114 | | |
115 | | size_t delay; |
116 | | size_t history_pad; |
117 | | bool flushed; /* Tracks if flush zero-padding has already been appended */ |
118 | | |
119 | | struct faar_resampler_struct *stage1; |
120 | | struct faar_resampler_struct *stage2; |
121 | | float *cascade_buf; |
122 | | size_t cascade_cap; |
123 | | faar_dft_prefilter *dft_prefilter; |
124 | | size_t dft_expansion; |
125 | | float *dft_intermediate; |
126 | | size_t dft_intermediate_capacity; |
127 | | faar_status last_error; |
128 | | bool shared_coeffs; /* Plan retains immutable banks for this stream. */ |
129 | | faar_design *plan; /* Only the root of a plan-backed stream owns a reference. */ |
130 | | }; |
131 | | |
132 | | struct faar_design_struct { |
133 | | faac_once_t references; /* Atomic refcount, using the platform atomic type. */ |
134 | | faar_resampler *prototype; /* Immutable geometry, coefficients and twiddles. */ |
135 | | uint32_t max_input_frames; /* Per-stream reservation, 0 for none. */ |
136 | | }; |
137 | | |
138 | | static void plan_release(faar_design *plan); |
139 | | |
140 | 0 | static int plan_retain(faar_design *plan) { |
141 | 0 | #if !defined(__STDC_NO_ATOMICS__) && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) |
142 | 0 | int count = atomic_load_explicit(&plan->references, memory_order_relaxed); |
143 | 0 | while (count < INT_MAX) { |
144 | 0 | if (atomic_compare_exchange_weak_explicit(&plan->references, &count, |
145 | 0 | count + 1, memory_order_relaxed, memory_order_relaxed)) return 0; |
146 | 0 | } |
147 | | #elif defined(_MSC_VER) |
148 | | long count = _InterlockedCompareExchange(&plan->references, 0, 0); |
149 | | while (count < LONG_MAX) { |
150 | | long seen = _InterlockedCompareExchange(&plan->references, count + 1, count); |
151 | | if (seen == count) return 0; |
152 | | count = seen; |
153 | | } |
154 | | #else |
155 | | if (plan->references < INT_MAX) { ++plan->references; return 0; } |
156 | | #endif |
157 | 0 | return -1; |
158 | 0 | } |
159 | | |
160 | 10.1k | static void clear_error(faar_resampler * r) { |
161 | 10.1k | if (!r) return; |
162 | 4.27k | r->last_error = FAAR_OK; |
163 | 4.27k | clear_error(r->stage1); |
164 | 4.27k | clear_error(r->stage2); |
165 | 4.27k | } |
166 | | |
167 | 10.1k | static faar_status find_error(const faar_resampler * r) { |
168 | 10.1k | if (!r) return FAAR_OK; |
169 | 4.27k | if (r->last_error != FAAR_OK) return r->last_error; |
170 | 4.27k | faar_status st = find_error(r->stage1); |
171 | 4.27k | return st != FAAR_OK ? st : find_error(r->stage2); |
172 | 4.27k | } |
173 | | |
174 | | static size_t polyresample_process_single(faar_resampler * r, const float * restrict in_samples, size_t in_count, |
175 | | float * restrict out_samples, size_t max_out_count); |
176 | | |
177 | | static size_t polyresample_flush_single(faar_resampler * r, float *out_samples, size_t max_out_count); |
178 | | |
179 | | static size_t process_prefilter_output(faar_resampler *r, size_t capacity, |
180 | | float *out_samples, size_t max_out_count); |
181 | | |
182 | 0 | static int ensure_dft_intermediate(faar_resampler * r, size_t frames) { |
183 | 0 | if (frames <= r->dft_intermediate_capacity) return 0; |
184 | 0 | if (r->prepared) return -1; |
185 | 0 | if (frames > SIZE_MAX / r->channels / sizeof(float)) return -1; |
186 | 0 | float *next = (float *)faar_grow_memory(r->dft_intermediate, |
187 | 0 | r->dft_intermediate_capacity * r->channels * sizeof(float), |
188 | 0 | frames * r->channels * sizeof(float)); |
189 | 0 | if (!next) return -1; |
190 | 0 | r->dft_intermediate = next; |
191 | 0 | r->dft_intermediate_capacity = frames; |
192 | 0 | return 0; |
193 | 0 | } |
194 | | |
195 | | static faar_resampler * create_resampler_internal(uint32_t in_rate, |
196 | | uint32_t out_rate, uint16_t channels, faar_quality quality, |
197 | | uint32_t decimate_factor, size_t filter_len_override, |
198 | | bool force_polyphase, size_t max_phases); |
199 | | static void destroy_internal(faar_resampler *r); |
200 | | static faar_status open_stream(const faar_config *config, faar_resampler **out, |
201 | | bool reserve); |
202 | | static faar_status reserve_stream(faar_resampler *r, size_t max_input_frames); |
203 | | |
204 | | /* Limit padding to the original input duration, without multiplying the |
205 | | * entire recording length by a rate. */ |
206 | 4.27k | static size_t output_capacity(faar_resampler * r, size_t capacity) { |
207 | 4.27k | if (r->flushed) { |
208 | 0 | uint64_t target = (r->input_frames / r->in_rate) * r->out_rate |
209 | 0 | + ((r->input_frames % r->in_rate) * r->out_rate + r->in_rate - 1) / r->in_rate; |
210 | 0 | uint64_t remaining = target > r->output_frames ? target - r->output_frames : 0; |
211 | 0 | if (remaining < capacity) capacity = (size_t)remaining; |
212 | 0 | } |
213 | 4.27k | return capacity; |
214 | 4.27k | } |
215 | | |
216 | | /* Error feedback gives the noise transfer 1 - g*z^-1: -12 dB at DC and |
217 | | * +4.9 dB at Nyquist for g = 0.75, at the cost of 1 + g^2 (+1.9 dB) total |
218 | | * noise power. */ |
219 | | static const float shaping_gain = 0.75f; |
220 | | |
221 | | /* One LSB as a fraction of unity full scale. */ |
222 | | static const float lsb_16 = 1.0f / 32768.0f; |
223 | | static const float lsb_24 = 1.0f / 8388608.0f; |
224 | | |
225 | | /* Golden-ratio increment decorrelates the second xorshift32 stream used for |
226 | | * the triangular (difference of two uniforms) dither. */ |
227 | | static const uint32_t prng_stream_offset = 0x9e3779b9U; |
228 | | static const float inv_2_32 = 1.0f / 4294967296.0f; |
229 | | |
230 | 2.92k | static void apply_dither(faar_resampler * r, float *samples, size_t frames) { |
231 | 2.92k | if (!r->dither || !r->dither_depth) return; |
232 | 0 | uint16_t c = 0; |
233 | 0 | for (size_t i = 0; i < frames * r->channels; i++) { |
234 | 0 | float sum = samples[i]; |
235 | 0 | float lsb_scale = (r->dither_depth == 16) ? lsb_16 : lsb_24; |
236 | 0 | float inv_lsb_scale = 1.0f / lsb_scale; |
237 | |
|
238 | 0 | uint32_t s1 = r->prng_state[c]; |
239 | 0 | s1 ^= s1 << 13; s1 ^= s1 >> 17; s1 ^= s1 << 5; |
240 | 0 | r->prng_state[c] = s1; |
241 | |
|
242 | 0 | uint32_t s2 = s1 + prng_stream_offset; |
243 | 0 | s2 ^= s2 << 13; s2 ^= s2 >> 17; s2 ^= s2 << 5; |
244 | |
|
245 | 0 | float r1 = (float)s1 * inv_2_32; |
246 | 0 | float r2 = (float)s2 * inv_2_32; |
247 | 0 | float tpdf = (r1 - r2) * lsb_scale; |
248 | |
|
249 | 0 | float sample_scaled = sum; |
250 | 0 | if (r->dither == FAAR_DITHER_SHAPED) { |
251 | 0 | sample_scaled -= r->error_history[c] * shaping_gain; |
252 | 0 | } |
253 | |
|
254 | 0 | float quantized = (float)floorf((sample_scaled + tpdf) * inv_lsb_scale + 0.5f) * lsb_scale; |
255 | 0 | r->error_history[c] = quantized - sample_scaled; |
256 | 0 | sum = quantized; |
257 | 0 | samples[i] = sum; |
258 | 0 | if (++c == r->channels) c = 0; |
259 | 0 | } |
260 | 0 | } |
261 | | |
262 | 0 | static bool short_half_rate_route(uint32_t in_rate, uint32_t out_rate) { |
263 | 0 | return (uint64_t)in_rate == 2 * (uint64_t)out_rate |
264 | 0 | && (in_rate == 44100 || in_rate == 48000 || in_rate == 88200 |
265 | 0 | || in_rate == 96000 || in_rate == 176400 || in_rate == 192000); |
266 | 0 | } |
267 | | |
268 | | /* Band edges are fractions of the lower Nyquist frequency. The legacy |
269 | | * polyphase length and Kaiser beta apply when no spec-designed plan does. */ |
270 | | struct preset_spec { |
271 | | double passband, stopband, attenuation; |
272 | | uint16_t legacy_len; |
273 | | float legacy_beta; |
274 | | }; |
275 | | |
276 | | static const struct preset_spec preset_specs[] = { |
277 | | /* Fast preserves 90% bandwidth with 100 dB alias rejection. */ |
278 | | [FAAR_QUALITY_FAST] = {0.90, 1.04, 100.0, 127, 28.0f}, |
279 | | /* Good preserves 96% bandwidth; float arithmetic limits measured rejection |
280 | | * to about 140 dB, so a 145 dB design is the most it can use. */ |
281 | | [FAAR_QUALITY_GOOD] = {0.96, 1.04, 145.0, 255, 32.0f}, |
282 | | [FAAR_QUALITY_HIGH] = {0.96, 1.04, 150.0, 511, 38.0f}, |
283 | | }; |
284 | | |
285 | 2.85k | static const struct preset_spec *preset_spec(faar_quality quality) { |
286 | 2.85k | return &preset_specs[quality <= FAAR_QUALITY_HIGH ? (size_t)quality |
287 | 2.85k | : FAAR_QUALITY_GOOD]; |
288 | 2.85k | } |
289 | | |
290 | | /* Smallest Kaiser margin that keeps every spec-designed filter above its |
291 | | * mask; 5.2 dB falls short at High. */ |
292 | | static const double kaiser_margin_db = 5.3; |
293 | | |
294 | | /* Cascaded plans reserve extra rejection for the shorter final filter's |
295 | | * sidelobes and the added float boundary. */ |
296 | | static const double cascade_reserve_db = 4.7; |
297 | | |
298 | | /* Kaiser's design formulas: taps = (A - kaiser_len_offset) / |
299 | | * (kaiser_len_slope * transition width), beta = kaiser_beta_slope * |
300 | | * (A - kaiser_beta_offset) for A > 50 dB of attenuation. */ |
301 | | static const double kaiser_len_offset = 7.95; |
302 | | static const double kaiser_len_slope = 14.36; |
303 | | static const double kaiser_beta_slope = 0.1102; |
304 | | static const double kaiser_beta_offset = 8.7; |
305 | | |
306 | | /* Legacy polyphase cutoffs in cycles per sample (0.5 is Nyquist): 96% of |
307 | | * Nyquist, or 98% when a caller supplies its own filter length. */ |
308 | | static const double legacy_cutoff = 0.48; |
309 | | static const double legacy_cutoff_custom_len = 0.49; |
310 | | |
311 | | /* Longest bank that stores a time-reversed copy of its exact rows. The |
312 | | * 41-tap upsampling banks repay the extra heap by skipping a per-output |
313 | | * coefficient reversal. */ |
314 | | static const size_t reverse_table_max_len = 64; |
315 | | |
316 | | /* Below this |n| the sinc is evaluated at its limit 2*cutoff. */ |
317 | | static const double sinc_origin_eps = 1e-9; |
318 | | |
319 | | static void design_band(const struct preset_spec *spec, double pb, double sb, |
320 | 0 | size_t alignment, double reserve_db, size_t *tap_count, double *beta, double *cutoff) { |
321 | | /* Edges are cycles per input sample. */ |
322 | 0 | double attenuation = spec->attenuation + kaiser_margin_db + reserve_db; |
323 | 0 | size_t n = (size_t)ceil((attenuation - kaiser_len_offset) / (kaiser_len_slope * (sb - pb))) + 1; |
324 | 0 | *tap_count = ((n - 1 + alignment - 1) / alignment) * alignment + 1; |
325 | 0 | *beta = kaiser_beta_slope * (attenuation - kaiser_beta_offset); |
326 | 0 | *cutoff = 0.5 * (pb + sb); |
327 | 0 | } |
328 | | |
329 | | /* Kaiser length and beta for a preset spec at filter_rate. alignment is the |
330 | | * divisor N-1 must meet so the DFT stage stays centered on input zero. */ |
331 | | static void design_from_spec(faar_quality quality, uint32_t out_rate, |
332 | | uint32_t filter_rate, double stopband, size_t alignment, double reserve_db, |
333 | 0 | size_t *tap_count, double *beta, double *cutoff) { |
334 | 0 | const struct preset_spec *spec = preset_spec(quality); |
335 | 0 | double pb = spec->passband; |
336 | 0 | double sb = stopband > 0.0 ? stopband : spec->stopband; |
337 | 0 | design_band(spec, 0.5 * pb * out_rate / filter_rate, |
338 | 0 | 0.5 * sb * out_rate / filter_rate, alignment, reserve_db, |
339 | 0 | tap_count, beta, cutoff); |
340 | 0 | } |
341 | | |
342 | | struct short_plan { |
343 | | size_t taps, fft, expansion, decimation, bank; |
344 | | double beta, cutoff; |
345 | | size_t max_phases; |
346 | | }; |
347 | | |
348 | | enum short_route { GENERAL, REFERENCE, UP, HALF, QUARTER, DOWN32 }; |
349 | | |
350 | | /* Prefilter designs. High keeps a measured fixed filter where taps is set; |
351 | | * every other preset, and High where taps is zero, designs from the preset |
352 | | * spec, taking the stop edge and FFT size from here for High when nonzero. */ |
353 | | enum short_design { |
354 | | SPEC, SPEC_HIGH_192_44, SPEC_HIGH_48_32, |
355 | | FIXED_HALF, FIXED_QUARTER, FIXED_REFERENCE, FIXED_UP, FIXED_UP_48_96 |
356 | | }; |
357 | | |
358 | | static const struct { |
359 | | double cutoff, beta, stop_edge; |
360 | | uint16_t taps, fft; |
361 | | } short_designs[] = { |
362 | | [SPEC] = {0}, |
363 | | [SPEC_HIGH_192_44] = {0, 0, 1.00045, 0, 32768}, |
364 | | [SPEC_HIGH_48_32] = {0, 0, 1.00625, 0, 0}, |
365 | | [FIXED_HALF] = {0.24889387661163931, 0, 0, 5493, 0}, |
366 | | [FIXED_QUARTER] = {0.124411, 0, 0, 8193, 0}, |
367 | | [FIXED_REFERENCE] = {0.22867124913694359, 0, 0, 5981, 0}, |
368 | | [FIXED_UP] = {0.24889387661163931, 0, 0, 5493, 0}, |
369 | | [FIXED_UP_48_96] = {0.24889387661163931, 18.401802232573989, 0, 5297, 0}, |
370 | | }; |
371 | | |
372 | | static const struct short_route_entry { |
373 | | uint32_t in, out; |
374 | | uint8_t route, expansion, bank, design; |
375 | | } short_routes[] = { |
376 | | {48000, 44100, REFERENCE, 2, 20, FIXED_REFERENCE}, |
377 | | {96000, 44100, REFERENCE, 1, 20, FIXED_REFERENCE}, |
378 | | {192000, 44100, REFERENCE, 1, 20, SPEC_HIGH_192_44}, |
379 | | {192000, 48000, QUARTER, 1, 1, FIXED_QUARTER}, |
380 | | {44100, 32000, DOWN32, 2, 21, SPEC}, |
381 | | {48000, 32000, DOWN32, 2, 1, SPEC_HIGH_48_32}, |
382 | | {44100, 48000, UP, 2, 21, FIXED_UP}, |
383 | | {44100, 88200, UP, 2, 1, FIXED_UP}, |
384 | | {48000, 96000, UP, 2, 1, FIXED_UP_48_96}, |
385 | | {96000, 192000, UP, 2, 1, FIXED_UP_48_96}, |
386 | | {44100, 96000, UP, 2, 41, FIXED_UP}, |
387 | | {48000, 88200, UP, 2, 41, FIXED_UP_48_96}, |
388 | | /* Wider support suppresses phase modulation near input Nyquist. */ |
389 | | {32000, 44100, UP, 2, 41, SPEC}, |
390 | | {32000, 48000, UP, 2, 41, SPEC}, |
391 | | {88200, 96000, UP, 2, 21, FIXED_UP}, |
392 | | }; |
393 | | |
394 | | static const struct short_route_entry *short_dedicated_route(uint32_t in, |
395 | 2.08k | uint32_t out) { |
396 | 32.8k | for (size_t i = 0; i < sizeof(short_routes) / sizeof(*short_routes); ++i) { |
397 | 30.8k | if (in == short_routes[i].in && out == short_routes[i].out) |
398 | 49 | return &short_routes[i]; |
399 | 30.8k | } |
400 | 2.03k | return NULL; |
401 | 2.08k | } |
402 | | |
403 | | /* Bank input must oversample the output by this factor: High's 0.96 Nyquist |
404 | | * residual brackets it in [2.48, 2.52], so take the center. */ |
405 | | static const double bank_oversample = 2.50; |
406 | | |
407 | | /* Upsampling without a dedicated entry designs its 2x prefilter from the |
408 | | * preset spec; this bank interpolates the doubled stream to the output. */ |
409 | | static const size_t general_up_bank = 41; |
410 | | |
411 | | /* Fast and Good meet their masks with 21 taps of the sampled prototype on |
412 | | * every 2x upsampling bank; High keeps 41 for its rejection. */ |
413 | | static const size_t short_up_bank = 21; |
414 | | |
415 | | /* Phase-table ceiling for that bank: rows beyond it are interpolated, so a |
416 | | * coprime rate pair stores 259 rows instead of up to 2051, for under 0.5 dB |
417 | | * of image rejection. */ |
418 | | static const size_t general_up_max_phases = 512; |
419 | | |
420 | | static struct short_plan short_plan(uint32_t in, uint32_t out, |
421 | 0 | faar_quality quality, bool general) { |
422 | 0 | struct short_plan p = {0, 1, 1, 1, 21, 19.078143572239966, 0.0, 0}; |
423 | 0 | enum short_route route = short_half_rate_route(in, out) ? HALF : GENERAL; |
424 | 0 | enum short_design design = route == HALF ? FIXED_HALF : SPEC; |
425 | 0 | const struct short_route_entry *entry = short_dedicated_route(in, out); |
426 | 0 | if (general) { route = GENERAL; design = SPEC; entry = NULL; } |
427 | 0 | else if (!entry && in < out) { |
428 | 0 | route = UP; |
429 | 0 | p.expansion = 2; |
430 | 0 | p.bank = (uint64_t)in * p.expansion == out ? 1 |
431 | 0 | : quality == FAAR_QUALITY_HIGH ? general_up_bank : short_up_bank; |
432 | 0 | p.max_phases = general_up_max_phases; |
433 | 0 | } |
434 | 0 | if (entry) { |
435 | 0 | route = entry->route; |
436 | 0 | design = entry->design; |
437 | 0 | p.expansion = entry->expansion; |
438 | 0 | p.bank = entry->bank; |
439 | 0 | if (route == UP && p.bank == 41 && quality != FAAR_QUALITY_HIGH) |
440 | 0 | p.bank = short_up_bank; |
441 | 0 | } |
442 | 0 | switch (route) { |
443 | 0 | case HALF: |
444 | 0 | p.decimation = 2; |
445 | 0 | p.bank = 1; |
446 | 0 | break; |
447 | 0 | case QUARTER: |
448 | 0 | p.decimation = 4; |
449 | 0 | break; |
450 | 0 | case REFERENCE: |
451 | 0 | case UP: |
452 | 0 | case DOWN32: |
453 | 0 | break; |
454 | 0 | case GENERAL: |
455 | 0 | p.expansion = 2; |
456 | 0 | for (size_t d = 4; d; d /= 2) { |
457 | 0 | for (size_t e = 1; e <= 2; ++e) { |
458 | 0 | if ((uint64_t)in * e % d == 0 |
459 | 0 | && (uint64_t)in * e >= bank_oversample * out * d) { |
460 | 0 | p.decimation = d; |
461 | 0 | p.expansion = e; |
462 | 0 | goto selected; |
463 | 0 | } |
464 | 0 | } |
465 | 0 | } |
466 | 0 | selected: |
467 | | /* Near-unity ratios cannot reach K with 2x expansion; the even |
468 | | * prototype preserves their wider bank bandwidth. */ |
469 | 0 | if ((double)in * p.expansion / p.decimation / out < bank_oversample) |
470 | 0 | p.bank = 20; |
471 | 0 | if ((uint64_t)in * p.expansion % ((uint64_t)out * p.decimation) == 0) |
472 | 0 | p.bank = 1; |
473 | 0 | break; |
474 | 0 | } |
475 | 0 | const bool high = quality == FAAR_QUALITY_HIGH; |
476 | 0 | if (high && short_designs[design].taps) { |
477 | 0 | p.taps = short_designs[design].taps; |
478 | 0 | p.cutoff = short_designs[design].cutoff; |
479 | 0 | if (short_designs[design].beta) p.beta = short_designs[design].beta; |
480 | 0 | } else { |
481 | | /* This stop edge also covers the near-Nyquist alias probe. */ |
482 | 0 | uint32_t lower = in < out ? in : out; |
483 | 0 | double sb = high ? short_designs[design].stop_edge : 0.0; |
484 | 0 | if (high && short_designs[design].fft) p.fft = short_designs[design].fft; |
485 | 0 | size_t alignment = p.expansion == 2 ? 4 : p.decimation; |
486 | 0 | if (alignment < 2) alignment = 2; |
487 | 0 | design_from_spec(quality, lower, in * (uint32_t)p.expansion, sb, |
488 | 0 | alignment, general ? cascade_reserve_db : 0.0, &p.taps, &p.beta, &p.cutoff); |
489 | 0 | } |
490 | 0 | return p; |
491 | 0 | } |
492 | | |
493 | | static faar_resampler * create_staged(uint32_t in_rate, uint32_t out_rate, |
494 | | uint16_t channels, faar_quality quality, |
495 | 0 | const struct short_plan *selected) { |
496 | 0 | struct short_plan plan = *selected; |
497 | 0 | size_t tap_count = plan.taps; |
498 | 0 | size_t fft_size = plan.fft ? plan.fft : 1; |
499 | 0 | size_t expansion = plan.expansion; |
500 | 0 | double beta = plan.beta; |
501 | 0 | while (fft_size < tap_count * 5) { |
502 | 0 | if (fft_size > SIZE_MAX / 2) return NULL; |
503 | 0 | fft_size <<= 1; |
504 | 0 | } |
505 | 0 | double *taps = (double *)AllocMemory(tap_count * sizeof(*taps)); |
506 | 0 | if (!taps) return NULL; |
507 | 0 | double cutoff = plan.cutoff; |
508 | 0 | if (faar_dft_design_lowpass(taps, tap_count, cutoff, beta)) { |
509 | 0 | FreeMemory(taps); |
510 | 0 | return NULL; |
511 | 0 | } |
512 | 0 | if (expansion > 1) { |
513 | 0 | for (size_t i = 0; i < tap_count; ++i) |
514 | 0 | taps[i] *= (double)expansion; |
515 | 0 | } |
516 | 0 | struct faar_resampler_struct *r = |
517 | 0 | (struct faar_resampler_struct *)faar_alloc_zeroed(1, sizeof(*r)); |
518 | 0 | if (!r) { FreeMemory(taps); return NULL; } |
519 | 0 | r->in_rate = in_rate; |
520 | 0 | r->out_rate = out_rate; |
521 | 0 | r->channels = channels; |
522 | 0 | r->quality = quality; |
523 | 0 | r->ratio = (double)out_rate / (double)in_rate; |
524 | 0 | r->dft_expansion = expansion; |
525 | 0 | size_t decimation = plan.decimation; |
526 | 0 | r->dft_prefilter = faar_dft_prefilter_create_stage(channels, taps, |
527 | 0 | tap_count, fft_size, expansion, decimation, selected->fft == 0, |
528 | 0 | quality == FAAR_QUALITY_HIGH); |
529 | 0 | FreeMemory(taps); |
530 | 0 | if (!r->dft_prefilter) { FreeMemory(r); return NULL; } |
531 | 0 | size_t phase_bank_len = plan.bank; |
532 | 0 | if ((uint64_t)in_rate * expansion > UINT32_MAX) { |
533 | 0 | faar_dft_prefilter_destroy(r->dft_prefilter); |
534 | 0 | FreeMemory(r); |
535 | 0 | return NULL; |
536 | 0 | } |
537 | 0 | if (selected->fft == 0) { |
538 | 0 | r->delay = (tap_count - 1) / 2; |
539 | 0 | return r; |
540 | 0 | } |
541 | 0 | uint32_t stage2_rate = in_rate * (uint32_t)expansion |
542 | 0 | / (uint32_t)decimation; |
543 | 0 | r->stage2 = create_resampler_internal(stage2_rate, out_rate, channels, |
544 | 0 | quality, 0, phase_bank_len, true, |
545 | 0 | plan.max_phases); |
546 | 0 | if (!r->stage2) { |
547 | 0 | faar_dft_prefilter_destroy(r->dft_prefilter); |
548 | 0 | FreeMemory(r); |
549 | 0 | return NULL; |
550 | 0 | } |
551 | 0 | r->delay = ((tap_count - 1) / 2 + expansion * decimation - 1) |
552 | 0 | / (expansion * decimation) |
553 | 0 | + (r->stage2->delay + expansion * decimation - 1) |
554 | 0 | / (expansion * decimation); |
555 | 0 | return r; |
556 | 0 | } |
557 | | |
558 | | /* The final bank must not exceed the GENERAL plan's rate or arithmetic cost; |
559 | | * the sharp filter moves to the lowest viable rate. */ |
560 | 0 | static unsigned short_max_halvings(uint32_t in, uint32_t out, faar_quality q) { |
561 | 0 | if (in <= out || short_half_rate_route(in, out) |
562 | 0 | || short_dedicated_route(in, out)) return 0; |
563 | 0 | struct short_plan original = short_plan(in, out, q, true); |
564 | 0 | uint64_t bank = (uint64_t)in * original.expansion / original.decimation; |
565 | 0 | unsigned k = 0; |
566 | 0 | while (!(in & 1) && in / 2 > out) { |
567 | 0 | struct short_plan next = short_plan(in / 2, out, q, true); |
568 | 0 | uint64_t rate = (uint64_t)(in / 2) * next.expansion / next.decimation; |
569 | 0 | if (rate < bank_oversample * out || rate > bank || next.bank > original.bank) break; |
570 | 0 | in /= 2; |
571 | 0 | ++k; |
572 | 0 | } |
573 | 0 | return k; |
574 | 0 | } |
575 | | |
576 | | /* Non-negative least-squares fit of the relative cost terms. */ |
577 | | static const struct { |
578 | | double fir, fft, bank, visited; |
579 | | } work_fit = {0.41445, 0.29928, 0.21198, 0.74921}; |
580 | | |
581 | | /* Estimate relative work from FIR operations, FFT size, bank length, and |
582 | | * input frames visited per output sample. */ |
583 | | static double short_work(uint32_t in, uint32_t out, faar_quality quality, |
584 | 0 | unsigned k, double fir_work, double visited) { |
585 | 0 | struct short_plan p = short_plan(in, out, quality, k != 0); |
586 | 0 | size_t n = p.fft; |
587 | 0 | while (n < p.taps * 5) n *= 2; |
588 | 0 | double forward = (double)n / p.expansion; |
589 | 0 | double inverse = (double)n / p.decimation; |
590 | 0 | double block_input = (double)(n - p.taps + 1) / p.expansion; |
591 | 0 | double fft_work = (forward * log2(forward) + inverse * log2(inverse)) |
592 | 0 | / block_input * in / out; |
593 | 0 | return work_fit.fir * fir_work + work_fit.fft * fft_work |
594 | 0 | + work_fit.bank * p.bank |
595 | 0 | + work_fit.visited * (visited + (double)in / out); |
596 | 0 | } |
597 | | |
598 | | static struct short_plan short_preplan(uint32_t in, uint32_t out, |
599 | 0 | faar_quality quality) { |
600 | 0 | struct short_plan pre = {0, 0, 1, 2, 1, 0, 0, 0}; |
601 | | /* Symmetric edges cover the preset pass edge and reject aliases before |
602 | | * they can land inside 1.04 times FINAL output Nyquist. */ |
603 | 0 | double pb = 0.52 * out / in; |
604 | 0 | design_band(preset_spec(quality), pb, 0.5 - pb, 4, cascade_reserve_db, |
605 | 0 | &pre.taps, &pre.beta, &pre.cutoff); |
606 | 0 | return pre; |
607 | 0 | } |
608 | | |
609 | | static unsigned short_halvings(uint32_t in, uint32_t out, faar_quality q, |
610 | 0 | const struct short_route_entry *entry) { |
611 | 0 | bool reference = entry && entry->route == REFERENCE; |
612 | | /* On these routes sparse half-bands down to below 4:1 measured cheaper |
613 | | than the general cost model's choice, at the same quality. */ |
614 | 0 | bool prefer = (q == FAAR_QUALITY_GOOD |
615 | 0 | && ((!entry && in % out == 0) || reference)) |
616 | 0 | || (q == FAAR_QUALITY_HIGH && reference); |
617 | 0 | if (prefer && (uint64_t)in >= 4 * (uint64_t)out) { |
618 | 0 | unsigned count = 0; |
619 | 0 | while (!(in & 1) && (uint64_t)in >= 4 * (uint64_t)out) { |
620 | 0 | in /= 2; |
621 | 0 | ++count; |
622 | 0 | } |
623 | 0 | return count; |
624 | 0 | } |
625 | 0 | unsigned limit = short_max_halvings(in, out, q), best = 0; |
626 | 0 | if (!limit) return 0; |
627 | 0 | double fir = 0, visited = 0; |
628 | 0 | double minimum = short_work(in, out, q, 0, 0, 0); |
629 | 0 | for (unsigned k = 1; k <= limit; ++k) { |
630 | 0 | struct short_plan pre = short_preplan(in, out, q); |
631 | | /* Paired odd coefficients plus the center, per FINAL output. */ |
632 | 0 | fir += (double)in / (2.0 * out) * (pre.taps / 4 + 1); |
633 | 0 | visited += (double)in / out; |
634 | 0 | in /= 2; |
635 | 0 | double work = short_work(in, out, q, k, fir, visited); |
636 | 0 | if (work < minimum) { minimum = work; best = k; } |
637 | 0 | } |
638 | 0 | return best; |
639 | 0 | } |
640 | | |
641 | | static faar_resampler * short_cascade(uint32_t in, uint32_t out, |
642 | 0 | uint16_t channels, faar_quality quality, unsigned k, bool dedicated) { |
643 | 0 | if (!k) { |
644 | 0 | struct short_plan p = short_plan(in, out, quality, !dedicated); |
645 | 0 | return create_staged(in, out, channels, quality, &p); |
646 | 0 | } |
647 | 0 | struct short_plan pre = short_preplan(in, out, quality); |
648 | 0 | faar_resampler * r = faar_alloc_zeroed(1, sizeof(*r)); |
649 | 0 | if (!r) return NULL; |
650 | 0 | r->in_rate = in; |
651 | 0 | r->out_rate = out; |
652 | 0 | r->channels = channels; |
653 | 0 | r->quality = quality; |
654 | 0 | r->ratio = (double)out / in; |
655 | 0 | r->stage1 = create_staged(in, in / 2, channels, quality, &pre); |
656 | 0 | r->stage2 = short_cascade(in / 2, out, channels, quality, k - 1, dedicated); |
657 | 0 | r->cascade_cap = 4096 * channels; |
658 | 0 | r->cascade_buf = aligned_malloc(r->cascade_cap * sizeof(float)); |
659 | 0 | if (!r->stage1 || !r->stage2 || !r->cascade_buf) { |
660 | 0 | destroy_internal(r); |
661 | 0 | return NULL; |
662 | 0 | } |
663 | 0 | r->delay = r->stage1->delay + 2 * r->stage2->delay; |
664 | 0 | return r; |
665 | 0 | } |
666 | | |
667 | 6.33M | static void store_coefficient(faar_resampler *r, size_t at, double val) { |
668 | 6.33M | #if !FAAR_RESAMPLER_FLOAT |
669 | 6.33M | if (r->polyphase_wide_table) { |
670 | 0 | r->polyphase_wide_table[at] = val; |
671 | 0 | return; |
672 | 0 | } |
673 | 6.33M | #endif |
674 | 6.33M | r->polyphase_table[at] = (faar_sample_t)val; |
675 | | #if FAAR_RESAMPLER_FLOAT |
676 | | if (r->polyphase_low_table) |
677 | | r->polyphase_low_table[at] = (float)(val - (double)r->polyphase_table[at]); |
678 | | #endif |
679 | 6.33M | } |
680 | | |
681 | | static faar_resampler * create_resampler_internal(uint32_t in_rate, uint32_t out_rate, |
682 | | uint16_t channels, faar_quality quality, uint32_t decimate_factor, |
683 | 2.08k | size_t filter_len_override, bool force_polyphase, size_t max_phases) { |
684 | 2.08k | if (in_rate == 0 || out_rate == 0 || channels == 0 || channels > MAX_CHANNELS) return NULL; |
685 | | |
686 | 2.08k | const struct short_route_entry *entry = short_dedicated_route(in_rate, out_rate); |
687 | 2.08k | bool use_staged = in_rate != out_rate || entry; |
688 | | /* The final phase bank must bypass planning to avoid recursive stages. */ |
689 | 2.08k | if (!force_polyphase && use_staged && decimate_factor < 2) { |
690 | 0 | unsigned k = short_halvings(in_rate, out_rate, quality, entry); |
691 | 0 | if (k) return short_cascade(in_rate, out_rate, channels, quality, k, |
692 | 0 | quality == FAAR_QUALITY_GOOD || entry); |
693 | 0 | struct short_plan p = short_plan(in_rate, out_rate, quality, false); |
694 | 0 | return create_staged(in_rate, out_rate, channels, quality, &p); |
695 | 0 | } |
696 | | |
697 | 2.08k | bool force_decimate = (decimate_factor >= 2) || ((uint64_t)in_rate > 2 * (uint64_t)out_rate); |
698 | | |
699 | 2.08k | if (force_decimate && in_rate > out_rate && !filter_len_override) { |
700 | 661 | uint32_t intermediate_rate = in_rate / (decimate_factor >= 2 ? decimate_factor : 2); |
701 | 661 | if (intermediate_rate <= out_rate) intermediate_rate = in_rate / 2; |
702 | 661 | if (intermediate_rate <= out_rate) intermediate_rate = (in_rate + out_rate) / 2; |
703 | | |
704 | 661 | struct faar_resampler_struct *r = (struct faar_resampler_struct *)faar_alloc_zeroed(1, sizeof(struct faar_resampler_struct)); |
705 | 661 | if (!r) return NULL; |
706 | | |
707 | 661 | r->stage1 = create_resampler_internal(in_rate, intermediate_rate, |
708 | 661 | channels, quality, 0, 0, true, 0); |
709 | 661 | r->stage2 = create_resampler_internal(intermediate_rate, out_rate, |
710 | 661 | channels, quality, 0, 0, true, 0); |
711 | | |
712 | 661 | if (!r->stage1 || !r->stage2) { |
713 | 0 | destroy_internal(r->stage1); |
714 | 0 | destroy_internal(r->stage2); |
715 | 0 | FreeMemory(r); |
716 | 0 | return NULL; |
717 | 0 | } |
718 | | |
719 | 661 | r->in_rate = in_rate; |
720 | 661 | r->out_rate = out_rate; |
721 | 661 | r->channels = channels; |
722 | 661 | r->quality = quality; |
723 | 661 | r->ratio = (double)out_rate / (double)in_rate; |
724 | | |
725 | 661 | r->cascade_cap = 4096 * channels; |
726 | 661 | r->cascade_buf = (float *)aligned_malloc(r->cascade_cap * sizeof(float)); |
727 | 661 | if (!r->cascade_buf) { |
728 | 0 | destroy_internal(r->stage1); |
729 | 0 | destroy_internal(r->stage2); |
730 | 0 | FreeMemory(r); |
731 | 0 | return NULL; |
732 | 0 | } |
733 | | |
734 | 661 | r->delay = r->stage1->delay |
735 | 661 | + ((uint64_t)r->stage2->delay * in_rate + intermediate_rate - 1) / intermediate_rate; |
736 | 661 | return r; |
737 | 661 | } |
738 | | |
739 | 1.42k | struct faar_resampler_struct *r = (struct faar_resampler_struct *)faar_alloc_zeroed(1, sizeof(struct faar_resampler_struct)); |
740 | 1.42k | if (!r) return NULL; |
741 | | |
742 | 1.42k | r->in_rate = in_rate; |
743 | 1.42k | r->out_rate = out_rate; |
744 | 1.42k | r->channels = channels; |
745 | 1.42k | r->quality = quality; |
746 | 1.42k | r->ratio = (double)out_rate / (double)in_rate; |
747 | | |
748 | | /* Preset lengths and Kaiser beta; rejection depends on the rate and frequency. */ |
749 | 1.42k | r->filter_len = preset_spec(quality)->legacy_len; |
750 | 1.42k | r->beta = preset_spec(quality)->legacy_beta; |
751 | | |
752 | 1.42k | if (filter_len_override == 20 || filter_len_override == 21 |
753 | 1.42k | || filter_len_override == 41) |
754 | 0 | r->beta = 19.60632601597565; |
755 | | |
756 | 1.42k | if (filter_len_override) { |
757 | 0 | r->filter_len = filter_len_override; |
758 | 0 | size_t exact_phase_count = 2u * (size_t)(out_rate / rate_gcd(in_rate, out_rate)); |
759 | 0 | if (!max_phases) max_phases = 4096; |
760 | 0 | r->num_phases = exact_phase_count <= max_phases ? exact_phase_count : max_phases; |
761 | 0 | r->phase_gcd = rate_gcd(in_rate, out_rate); |
762 | 0 | r->exact_phase_bank = exact_phase_count <= max_phases; |
763 | | /* The even 20-tap bank needs a half-sample clock origin. */ |
764 | 0 | if (filter_len_override == 20) |
765 | 0 | r->half_sample_phase_bank = true; |
766 | 1.42k | } else r->num_phases = POLYRESAMPLE_NUM_PHASES; |
767 | | |
768 | 1.42k | if ((r->filter_len % 2) == 0 |
769 | 0 | && filter_len_override != 20) r->filter_len++; |
770 | 1.42k | assert(r->filter_len <= POLYRESAMPLE_MAX_FILTER_LEN); |
771 | | |
772 | 1.42k | size_t stored_phases = r->num_phases / 2 + 3; |
773 | 1.42k | #if !FAAR_RESAMPLER_FLOAT |
774 | 1.42k | if (quality == FAAR_QUALITY_HIGH) { |
775 | 0 | r->polyphase_wide_table = aligned_malloc(stored_phases * r->filter_len |
776 | 0 | * sizeof(*r->polyphase_wide_table)); |
777 | 0 | if (!r->polyphase_wide_table) { |
778 | 0 | FreeMemory(r); |
779 | 0 | return NULL; |
780 | 0 | } |
781 | 0 | } else |
782 | 1.42k | #endif |
783 | 1.42k | { |
784 | 1.42k | r->polyphase_table = (faar_sample_t *)aligned_malloc(stored_phases * r->filter_len * sizeof(*r->polyphase_table)); |
785 | 1.42k | if (!r->polyphase_table) { |
786 | 0 | FreeMemory(r); |
787 | 0 | return NULL; |
788 | 0 | } |
789 | 1.42k | } |
790 | | /* The short exact banks (up to the 41-tap upsampling banks) repay a |
791 | | * second oriented copy; keep generic banks compact and let their |
792 | | * uncommon exact reverse phase use the stack path. */ |
793 | | #if FAAR_RESAMPLER_FLOAT |
794 | | if (quality == FAAR_QUALITY_HIGH) { |
795 | | size_t bytes = stored_phases * r->filter_len * sizeof(float); |
796 | | r->polyphase_low_table = aligned_malloc(bytes); |
797 | | if (!r->polyphase_low_table) { destroy_internal(r); return NULL; } |
798 | | memset(r->polyphase_low_table, 0, bytes); |
799 | | } |
800 | | #endif |
801 | 1.42k | if (r->exact_phase_bank && r->filter_len <= reverse_table_max_len |
802 | | #if FAAR_RESAMPLER_FLOAT |
803 | | && !r->polyphase_low_table |
804 | | #endif |
805 | 1.42k | ) { |
806 | 0 | #if !FAAR_RESAMPLER_FLOAT |
807 | 0 | if (r->polyphase_wide_table) { |
808 | 0 | r->polyphase_wide_reverse = aligned_malloc(stored_phases * r->filter_len |
809 | 0 | * sizeof(*r->polyphase_wide_reverse)); |
810 | 0 | if (!r->polyphase_wide_reverse) { |
811 | 0 | destroy_internal(r); |
812 | 0 | return NULL; |
813 | 0 | } |
814 | 0 | } else |
815 | 0 | #endif |
816 | 0 | { |
817 | 0 | r->polyphase_reverse_table = (faar_sample_t *)aligned_malloc( |
818 | 0 | stored_phases * r->filter_len * sizeof(*r->polyphase_reverse_table)); |
819 | 0 | if (!r->polyphase_reverse_table) { |
820 | 0 | destroy_internal(r); |
821 | 0 | return NULL; |
822 | 0 | } |
823 | 0 | } |
824 | 0 | } |
825 | | |
826 | 1.42k | double cutoff = (r->ratio < 1.0) |
827 | 1.42k | ? (filter_len_override ? legacy_cutoff_custom_len : legacy_cutoff * r->ratio) |
828 | 1.42k | : legacy_cutoff; |
829 | 1.42k | double half_len = (r->filter_len - 1) / 2.0; |
830 | 1.42k | const bool long_up = filter_len_override == 21 |
831 | 0 | && (uint64_t)r->out_rate * 2 > r->in_rate && r->num_phases >= 2; |
832 | 1.42k | const bool sampled_long_prototype = filter_len_override == 20 || long_up; |
833 | 1.42k | const double window_denominator = r->beta <= 0.0 ? 1.0 : bessel_i0(r->beta); |
834 | 1.42k | double window[POLYRESAMPLE_MAX_FILTER_LEN]; |
835 | 1.42k | if (r->filter_len > 1 && !sampled_long_prototype) { |
836 | 182k | for (size_t j = 0; j < r->filter_len; j++) |
837 | 180k | window[j] = kaiser_window((double)j, |
838 | 180k | (double)r->filter_len - 1.0, r->beta, |
839 | 180k | window_denominator); |
840 | 1.42k | } |
841 | | |
842 | | /* Store phases -1..N/2+1, including guards for cubic interpolation. */ |
843 | 51.3k | for (size_t p = 0; p < stored_phases; p++) { |
844 | 49.8k | double frac = ((double)p - 1.0) / (double)r->num_phases; |
845 | 49.8k | faar_sample_t *phase_coeffs = r->polyphase_table |
846 | 49.8k | ? r->polyphase_table + p * r->filter_len : NULL; |
847 | 49.8k | double sum = 0.0; |
848 | | |
849 | 6.38M | for (size_t j = 0; j < r->filter_len; j++) { |
850 | 6.33M | if (r->filter_len == 1) { |
851 | 0 | store_coefficient(r, p * r->filter_len + j, 1.0); |
852 | 0 | sum = 1.0; |
853 | 0 | continue; |
854 | 0 | } |
855 | 6.33M | if (sampled_long_prototype) { |
856 | | /* Rows are samples of one long prototype; windowing each |
857 | | * as its own FIR would shift the even phase origin. */ |
858 | 0 | const bool bank_147 = filter_len_override == 20; |
859 | 0 | const double up_phases = (double)(r->num_phases / 2); |
860 | 0 | const double prototype_fc = bank_147 |
861 | 0 | ? 0.006075233237773342 : 0.89741699260155768 / up_phases; |
862 | 0 | const double prototype_phases = bank_147 ? 147.0 : up_phases; |
863 | 0 | const double prototype_center = bank_147 ? 1469.0 |
864 | 0 | : (double)r->filter_len * up_phases / 2 - 1; |
865 | 0 | const double prototype_denominator = prototype_center + 0.75; |
866 | 0 | const double prototype_scale = prototype_phases; |
867 | 0 | double phase_count = bank_147 ? 294.0 : (double)r->num_phases; |
868 | 0 | double prototype_index = |
869 | 0 | ((double)(r->filter_len - 1 - j) * prototype_phases) |
870 | 0 | + (frac + 0.5) * phase_count * 0.5 - 1.0; |
871 | 0 | double z = prototype_index - prototype_center; |
872 | 0 | double y = z / prototype_denominator; |
873 | 0 | double radicand = 1.0 - y * y; |
874 | 0 | double sinc = fabs(z) < 1e-14 ? prototype_fc |
875 | 0 | : sin(M_PI * prototype_fc * z) / (M_PI * z); |
876 | 0 | double win = radicand <= 0.0 ? 0.0 |
877 | 0 | : bessel_i0(r->beta * sqrt(radicand)) / window_denominator; |
878 | 0 | double val = sinc * win * prototype_scale; |
879 | 0 | store_coefficient(r, p * r->filter_len + j, val); |
880 | 0 | sum += val; |
881 | 0 | continue; |
882 | 0 | } |
883 | 6.33M | double n = (double)j - half_len - frac; |
884 | 6.33M | double sinc = (fabs(n) < sinc_origin_eps) ? (2.0 * cutoff) : sin(2.0 * M_PI * cutoff * n) / (M_PI * n); |
885 | 6.33M | double win = window[j]; |
886 | 6.33M | double val = sinc * win; |
887 | 6.33M | store_coefficient(r, p * r->filter_len + j, val); |
888 | 6.33M | sum += val; |
889 | 6.33M | } |
890 | | |
891 | 49.8k | bool normalize_phase = true; |
892 | 49.8k | if (sampled_long_prototype) |
893 | 0 | normalize_phase = false; |
894 | 49.8k | #if !FAAR_RESAMPLER_FLOAT |
895 | 49.8k | if (normalize_phase && sum > 0.0 && r->polyphase_wide_table) { |
896 | 0 | double *wide = r->polyphase_wide_table + p * r->filter_len; |
897 | 0 | for (size_t j = 0; j < r->filter_len; j++) |
898 | 0 | wide[j] = wide[j] / sum; |
899 | 0 | } else |
900 | 49.8k | #endif |
901 | 49.8k | if (normalize_phase && sum > 0.0) { |
902 | 6.38M | for (size_t j = 0; j < r->filter_len; j++) { |
903 | 6.33M | #if !FAAR_RESAMPLER_FLOAT |
904 | 6.33M | phase_coeffs[j] /= (float)sum; |
905 | | #else |
906 | | if (r->polyphase_low_table) { |
907 | | size_t at = p * r->filter_len + j; |
908 | | double val = ((double)phase_coeffs[j] + r->polyphase_low_table[at]) / sum; |
909 | | phase_coeffs[j] = (float)val; |
910 | | r->polyphase_low_table[at] = (float)(val - (double)phase_coeffs[j]); |
911 | | } else { |
912 | | phase_coeffs[j] /= (float)sum; |
913 | | } |
914 | | #endif |
915 | 6.33M | } |
916 | 49.8k | } |
917 | 49.8k | } |
918 | 1.42k | if (r->polyphase_reverse_table) { |
919 | 0 | for (size_t p = 0; p < stored_phases; ++p) { |
920 | 0 | const faar_sample_t *source = |
921 | 0 | r->polyphase_table + p * r->filter_len; |
922 | 0 | faar_sample_t *reverse = |
923 | 0 | r->polyphase_reverse_table + p * r->filter_len; |
924 | 0 | for (size_t j = 0; j < r->filter_len; ++j) |
925 | 0 | reverse[j] = source[r->filter_len - 1 - j]; |
926 | 0 | } |
927 | 0 | } |
928 | 1.42k | #if !FAAR_RESAMPLER_FLOAT |
929 | 1.42k | if (r->polyphase_wide_reverse) { |
930 | 0 | for (size_t p = 0; p < stored_phases; ++p) { |
931 | 0 | const double *source = r->polyphase_wide_table + p * r->filter_len; |
932 | 0 | double *reverse = r->polyphase_wide_reverse + p * r->filter_len; |
933 | 0 | for (size_t j = 0; j < r->filter_len; ++j) |
934 | 0 | reverse[j] = source[r->filter_len - 1 - j]; |
935 | 0 | } |
936 | 0 | } |
937 | 1.42k | #endif |
938 | | |
939 | | /* Keep each planar history aligned to 64 bytes for vector-friendly strides. */ |
940 | 1.42k | r->hist_cap_per_ch = (r->filter_len * 2 + 4096 + 15) & ~((size_t)15); |
941 | | |
942 | 5.23k | for (uint16_t c = 0; c < channels; c++) { |
943 | 3.81k | r->hist[c] = (faar_sample_t *)aligned_malloc( |
944 | 3.81k | r->hist_cap_per_ch * sizeof(*r->hist[c])); |
945 | 3.81k | if (!r->hist[c]) { |
946 | 0 | destroy_internal(r); |
947 | 0 | return NULL; |
948 | 0 | } |
949 | 3.81k | memset(r->hist[c], 0, r->hist_cap_per_ch * sizeof(*r->hist[c])); |
950 | 3.81k | } |
951 | | |
952 | 1.42k | r->delay = in_rate == out_rate ? 0 : (size_t)half_len; |
953 | | /* Center the first output on input frame zero. */ |
954 | 1.42k | r->history_pad = r->delay; |
955 | 1.42k | if (filter_len_override == 20) { |
956 | 0 | r->history_pad++; |
957 | 0 | r->phase = out_rate / 2; |
958 | 0 | } |
959 | 1.42k | r->hist_len = in_rate == out_rate ? 0 : r->history_pad; |
960 | 1.42k | return r; |
961 | 1.42k | } |
962 | | |
963 | | /* Map the public flag bits to the internal mode and depth; zero means none. */ |
964 | 764 | static int dither_from_flags(uint32_t flags, uint32_t *dither, uint8_t *bits) { |
965 | 764 | const uint32_t mode_mask = FAAR_DITHER_TPDF | FAAR_DITHER_SHAPED; |
966 | 764 | const uint32_t depth_mask = FAAR_DITHER_16 | FAAR_DITHER_24; |
967 | 764 | if (flags & ~(mode_mask | depth_mask)) return -1; |
968 | 764 | if (flags == 0) { *dither = 0; *bits = 0; return 0; } |
969 | 0 | uint32_t mode = flags & mode_mask; |
970 | 0 | uint32_t depth = flags & depth_mask; |
971 | 0 | if ((mode != FAAR_DITHER_TPDF && mode != FAAR_DITHER_SHAPED) |
972 | 0 | || (depth != FAAR_DITHER_16 && depth != FAAR_DITHER_24)) |
973 | 0 | return -1; |
974 | 0 | *dither = mode; |
975 | 0 | *bits = (uint8_t)(depth == FAAR_DITHER_16 ? 16 : 24); |
976 | 0 | return 0; |
977 | 0 | } |
978 | | |
979 | 1.42k | static int set_dither_internal(faar_resampler * r, uint32_t dither, uint8_t target_bits) { |
980 | 1.42k | if (!r) return -1; |
981 | 1.42k | if (dither != 0 && dither != FAAR_DITHER_TPDF |
982 | 0 | && dither != FAAR_DITHER_SHAPED) return -1; |
983 | 1.42k | if (dither != 0 && target_bits != 16 && target_bits != 24) return -1; |
984 | | |
985 | 1.42k | r->dither = dither; |
986 | 1.42k | r->dither_depth = target_bits; |
987 | 1.42k | if (r->stage2) { |
988 | 661 | return set_dither_internal(r->stage2, dither, target_bits); |
989 | 661 | } |
990 | 2.85k | for (uint16_t c = 0; c < r->channels && c < MAX_CHANNELS; c++) { |
991 | 2.09k | r->prng_state[c] = (uint32_t)(123456789U + c * 987654321U); |
992 | 2.09k | r->error_history[c] = 0.0f; |
993 | 2.09k | } |
994 | 764 | return 0; |
995 | 1.42k | } |
996 | | |
997 | | /* Phase offsets below this are treated as grid-exact: the interpolation |
998 | | * correction would shift the evaluated position by under 1e-6 of a row |
999 | | * spacing, far below the stopband floor. */ |
1000 | | static const faar_sample_t exact_phase_eps = (faar_sample_t)1e-6; |
1001 | | |
1002 | | #include "polyresample_float2.inc" |
1003 | | #include "polyresample_wide.inc" |
1004 | | |
1005 | | /* Keep history contiguous for the FIR, but move it only when an append |
1006 | | * exhausts the trailing space. Draining output never copies queued audio. */ |
1007 | 1.46k | static int reserve_history(faar_resampler *r, size_t additional, bool exact) { |
1008 | 1.46k | if (additional > SIZE_MAX - r->hist_len) { |
1009 | 0 | r->last_error = FAAR_ERR_INVALID_ARGUMENT; |
1010 | 0 | return -1; |
1011 | 0 | } |
1012 | 1.46k | size_t needed = r->hist_len + additional; |
1013 | 1.46k | if (needed <= r->hist_cap_per_ch - r->hist_offset) return 0; |
1014 | 0 | if (r->hist_offset) { |
1015 | 0 | for (uint16_t c = 0; c < r->channels; ++c) { |
1016 | 0 | faar_sample_t *base = r->hist[c] - r->hist_offset; |
1017 | 0 | memmove(base, r->hist[c], r->hist_len * sizeof(*base)); |
1018 | 0 | r->hist[c] = base; |
1019 | 0 | } |
1020 | 0 | r->hist_offset = 0; |
1021 | 0 | } |
1022 | 0 | if (needed <= r->hist_cap_per_ch) return 0; |
1023 | 0 | if (r->prepared) { |
1024 | 0 | r->last_error = FAAR_ERR_NO_MEMORY; |
1025 | 0 | return -1; |
1026 | 0 | } |
1027 | 0 | size_t growth = exact ? 1 : 2; |
1028 | 0 | if (needed > (SIZE_MAX - 15) / growth) { |
1029 | 0 | r->last_error = FAAR_ERR_INVALID_ARGUMENT; |
1030 | 0 | return -1; |
1031 | 0 | } |
1032 | 0 | size_t capacity = (needed * growth + 15) & ~((size_t)15); |
1033 | 0 | if (capacity > SIZE_MAX / sizeof(faar_sample_t)) { |
1034 | 0 | r->last_error = FAAR_ERR_INVALID_ARGUMENT; |
1035 | 0 | return -1; |
1036 | 0 | } |
1037 | | /* All pointers now have the same origin. Grow one channel at a time to |
1038 | | * limit peak memory; on failure every channel still has at least the old |
1039 | | * capacity, and destruction remains safe. */ |
1040 | 0 | for (uint16_t c = 0; c < r->channels; ++c) { |
1041 | 0 | faar_sample_t *next = aligned_malloc(capacity * sizeof(*next)); |
1042 | 0 | if (!next) { |
1043 | 0 | r->last_error = FAAR_ERR_NO_MEMORY; |
1044 | 0 | return -1; |
1045 | 0 | } |
1046 | 0 | memcpy(next, r->hist[c], r->hist_len * sizeof(*next)); |
1047 | 0 | aligned_free(r->hist[c]); |
1048 | 0 | r->hist[c] = next; |
1049 | 0 | } |
1050 | 0 | r->hist_cap_per_ch = capacity; |
1051 | 0 | return 0; |
1052 | 0 | } |
1053 | | |
1054 | 0 | static void set_prepared(faar_resampler *r, bool prepared) { |
1055 | 0 | if (!r) return; |
1056 | 0 | r->prepared = prepared; |
1057 | 0 | faar_dft_prefilter_set_prepared(r->dft_prefilter, prepared); |
1058 | 0 | set_prepared(r->stage1, prepared); |
1059 | 0 | set_prepared(r->stage2, prepared); |
1060 | 0 | } |
1061 | | |
1062 | | /* Ceil(frames * numerator / denominator), without a size_t product overflow. */ |
1063 | | static int scaled_frames(size_t frames, uint32_t numerator, uint32_t denominator, |
1064 | 0 | size_t *out) { |
1065 | 0 | size_t whole = frames / denominator; |
1066 | 0 | uint64_t tail = (uint64_t)(frames % denominator) * numerator; |
1067 | 0 | uint64_t extra = tail / denominator + (tail % denominator != 0); |
1068 | 0 | if (whole > SIZE_MAX / numerator || extra > SIZE_MAX - whole * numerator) |
1069 | 0 | return -1; |
1070 | 0 | *out = whole * numerator + (size_t)extra; |
1071 | 0 | return 0; |
1072 | 0 | } |
1073 | | |
1074 | | /* Burst bounds include retained filter support, transform blocks and flush |
1075 | | * padding. A downstream stage may receive an entire upstream burst before |
1076 | | * the caller's small output buffer has drained it. */ |
1077 | | static faar_status prepare_internal(faar_resampler *r, size_t max_input, |
1078 | 0 | size_t *output_bound) { |
1079 | 0 | if (r->dft_prefilter) { |
1080 | 0 | if (max_input > (SIZE_MAX - 8192) / r->dft_expansion) |
1081 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1082 | 0 | size_t intermediate = max_input * r->dft_expansion + 8192; |
1083 | 0 | if (intermediate > SIZE_MAX / r->channels / sizeof(float)) |
1084 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1085 | 0 | if (!r->stage2) { |
1086 | 0 | if (ensure_dft_intermediate(r, intermediate)) return FAAR_ERR_NO_MEMORY; |
1087 | 0 | memset(r->dft_intermediate, 0, |
1088 | 0 | r->dft_intermediate_capacity * r->channels * sizeof(float)); |
1089 | 0 | } |
1090 | 0 | size_t step = r->stage2 |
1091 | 0 | ? r->stage2->in_rate / r->stage2->out_rate |
1092 | 0 | + (r->stage2->in_rate % r->stage2->out_rate != 0) : 0; |
1093 | 0 | size_t filtered; |
1094 | 0 | faar_status st = faar_dft_prefilter_prepare(r->dft_prefilter, |
1095 | 0 | max_input, step, &filtered); |
1096 | 0 | if (st != FAAR_OK) return st; |
1097 | 0 | if (r->stage2) return prepare_internal(r->stage2, filtered, output_bound); |
1098 | 0 | *output_bound = filtered; |
1099 | 0 | return FAAR_OK; |
1100 | 0 | } |
1101 | 0 | if (r->stage1 && r->stage2) { |
1102 | 0 | memset(r->cascade_buf, 0, r->cascade_cap * sizeof(float)); |
1103 | 0 | size_t middle; |
1104 | 0 | faar_status st = prepare_internal(r->stage1, max_input, &middle); |
1105 | 0 | return st == FAAR_OK ? prepare_internal(r->stage2, middle, output_bound) : st; |
1106 | 0 | } |
1107 | | /* Retained support, a pending discard, and the final boundary tail. */ |
1108 | 0 | size_t support = 3 * r->filter_len; |
1109 | 0 | if (max_input > SIZE_MAX - support) return FAAR_ERR_INVALID_ARGUMENT; |
1110 | 0 | size_t frames = max_input + support; |
1111 | 0 | if (reserve_history(r, frames, true)) return r->last_error; |
1112 | 0 | for (uint16_t c = 0; c < r->channels; ++c) |
1113 | 0 | memset(r->hist[c], 0, r->hist_cap_per_ch * sizeof(faar_sample_t)); |
1114 | 0 | if (scaled_frames(frames, r->out_rate, r->in_rate, output_bound)) |
1115 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1116 | 0 | return FAAR_OK; |
1117 | 0 | } |
1118 | | |
1119 | | static size_t polyresample_process_single(faar_resampler * restrict r, const float * restrict in_samples, size_t in_count, |
1120 | 2.92k | float * restrict out_samples, size_t max_out_count) { |
1121 | 2.92k | if (!r || !out_samples) return 0; |
1122 | | |
1123 | 2.92k | const size_t filter_len = r->filter_len; |
1124 | 2.92k | const size_t half_len = (filter_len - 1) / 2; |
1125 | 2.92k | const faar_sample_t * restrict poly_table = r->polyphase_table |
1126 | 2.92k | ? r->polyphase_table + filter_len : NULL; |
1127 | | |
1128 | 2.92k | assert(filter_len <= POLYRESAMPLE_MAX_FILTER_LEN); |
1129 | | |
1130 | 2.92k | if (in_samples && in_count > 0) { |
1131 | 1.46k | if (reserve_history(r, in_count, false)) return 0; |
1132 | | |
1133 | 1.46k | if (r->channels == 1) { |
1134 | 698k | for (size_t i = 0; i < in_count; ++i) |
1135 | 697k | r->hist[0][r->hist_len + i] = (faar_sample_t)in_samples[i]; |
1136 | 423 | #if MAX_CHANNELS >= 2 |
1137 | 1.03k | } else if (r->channels == 2) { |
1138 | 578 | faar_sample_t * restrict h0 = r->hist[0] + r->hist_len; |
1139 | 578 | faar_sample_t * restrict h1 = r->hist[1] + r->hist_len; |
1140 | 975k | for (size_t i = 0; i < in_count; i++) { |
1141 | 974k | h0[i] = (faar_sample_t)in_samples[i * 2 + 0]; |
1142 | 974k | h1[i] = (faar_sample_t)in_samples[i * 2 + 1]; |
1143 | 974k | } |
1144 | 578 | #endif |
1145 | 578 | #if MAX_CHANNELS >= 6 |
1146 | 578 | } else if (r->channels == 6) { |
1147 | 63 | faar_sample_t * restrict h0 = r->hist[0] + r->hist_len; |
1148 | 63 | faar_sample_t * restrict h1 = r->hist[1] + r->hist_len; |
1149 | 63 | faar_sample_t * restrict h2 = r->hist[2] + r->hist_len; |
1150 | 63 | faar_sample_t * restrict h3 = r->hist[3] + r->hist_len; |
1151 | 63 | faar_sample_t * restrict h4 = r->hist[4] + r->hist_len; |
1152 | 63 | faar_sample_t * restrict h5 = r->hist[5] + r->hist_len; |
1153 | 100k | for (size_t i = 0; i < in_count; i++) { |
1154 | 99.9k | h0[i] = (faar_sample_t)in_samples[i * 6 + 0]; |
1155 | 99.9k | h1[i] = (faar_sample_t)in_samples[i * 6 + 1]; |
1156 | 99.9k | h2[i] = (faar_sample_t)in_samples[i * 6 + 2]; |
1157 | 99.9k | h3[i] = (faar_sample_t)in_samples[i * 6 + 3]; |
1158 | 99.9k | h4[i] = (faar_sample_t)in_samples[i * 6 + 4]; |
1159 | 99.9k | h5[i] = (faar_sample_t)in_samples[i * 6 + 5]; |
1160 | 99.9k | } |
1161 | 63 | #endif |
1162 | 397 | } else { |
1163 | 644k | for (size_t i = 0; i < in_count; i++) { |
1164 | 3.92M | for (uint16_t c = 0; c < r->channels; c++) { |
1165 | 3.27M | r->hist[c][r->hist_len + i] = |
1166 | 3.27M | (faar_sample_t)in_samples[i * r->channels + c]; |
1167 | 3.27M | } |
1168 | 644k | } |
1169 | 397 | } |
1170 | | /* Initialize the virtual past only once, independently of chunk size. */ |
1171 | 1.46k | if (!r->input_frames && !r->flushed) { |
1172 | 5.23k | for (uint16_t c = 0; c < r->channels; c++) { |
1173 | 3.81k | faar_sample_t first = r->hist[c][r->history_pad]; |
1174 | 244k | for (size_t j = 0; j < r->history_pad; j++) r->hist[c][j] = first; |
1175 | 3.81k | } |
1176 | 1.42k | } |
1177 | 1.46k | r->hist_len += in_count; |
1178 | 1.46k | if (!r->flushed) { |
1179 | 5.43k | for (uint16_t c = 0; c < r->channels; c++) |
1180 | 3.97k | r->last_input[c] = r->hist[c][r->hist_len - 1]; |
1181 | 1.46k | r->input_frames += in_count; |
1182 | 1.46k | } |
1183 | 1.46k | } |
1184 | | |
1185 | 2.92k | max_out_count = output_capacity(r, max_out_count); |
1186 | 2.92k | if (r->in_rate == r->out_rate) { |
1187 | 0 | size_t frames = r->hist_len < max_out_count ? r->hist_len : max_out_count; |
1188 | 0 | for (uint16_t c = 0; c < r->channels; c++) { |
1189 | 0 | for (size_t j = 0; j < frames; j++) { |
1190 | 0 | out_samples[j * r->channels + c] = (float)r->hist[c][j]; |
1191 | 0 | } |
1192 | 0 | r->hist[c] += frames; |
1193 | 0 | } |
1194 | 0 | r->hist_offset += frames; |
1195 | 0 | r->hist_len -= frames; |
1196 | 0 | r->output_frames += frames; |
1197 | 0 | apply_dither(r, out_samples, frames); |
1198 | 0 | return frames; |
1199 | 0 | } |
1200 | | |
1201 | 2.92k | size_t out_frames = 0; |
1202 | | /* Split the rational clock once per call. Updating quotient and remainder |
1203 | | * per output avoids a 64-bit divide/modulo pair in the sample loop. */ |
1204 | 2.92k | size_t base_idx = (size_t)(r->phase / r->out_rate); |
1205 | 2.92k | uint64_t phase_remainder = r->phase % r->out_rate; |
1206 | 2.92k | const uint64_t step_whole = r->in_rate / r->out_rate; |
1207 | 2.92k | const uint64_t step_remainder = r->in_rate % r->out_rate; |
1208 | 2.92k | uint64_t phase_slot = r->exact_phase_bank |
1209 | 2.92k | ? (r->half_sample_phase_bank |
1210 | 0 | ? (2 * phase_remainder) / r->phase_gcd |
1211 | 2.92k | : phase_remainder / r->phase_gcd) : 0; |
1212 | 2.92k | const uint64_t phase_slot_step = r->exact_phase_bank |
1213 | 2.92k | ? (r->half_sample_phase_bank |
1214 | 0 | ? (2 * step_remainder) / r->phase_gcd |
1215 | 2.92k | : step_remainder / r->phase_gcd) : 0; |
1216 | 2.92k | const uint64_t phase_slot_modulus = r->exact_phase_bank |
1217 | 2.92k | ? (r->half_sample_phase_bank |
1218 | 0 | ? (2 * r->out_rate) / r->phase_gcd |
1219 | 2.92k | : r->out_rate / r->phase_gcd) : 0; |
1220 | | |
1221 | | #if defined(_MSC_VER) |
1222 | | __declspec(align(64)) faar_sample_t temp_coeffs[POLYRESAMPLE_MAX_FILTER_LEN]; |
1223 | | #else |
1224 | 2.92k | alignas(64) faar_sample_t temp_coeffs[POLYRESAMPLE_MAX_FILTER_LEN]; |
1225 | 2.92k | #endif |
1226 | | |
1227 | 1.79M | while (out_frames < max_out_count) { |
1228 | 1.79M | size_t sample_base_idx = base_idx; |
1229 | 1.79M | faar_sample_t frac = 0; |
1230 | 1.79M | bool reverse; |
1231 | 1.79M | size_t p_idx; |
1232 | 1.79M | faar_sample_t delta; |
1233 | | #if FAAR_RESAMPLER_FLOAT |
1234 | | faar_float2 precise_delta = ff2(0); |
1235 | | #else |
1236 | 1.79M | double wide_delta = 0; |
1237 | 1.79M | #endif |
1238 | 1.79M | if (r->exact_phase_bank) { |
1239 | | /* The doubled grid represents the 20-tap bank's half-sample |
1240 | | * origin; all other exact banks use the ordinary reduced grid. */ |
1241 | 0 | uint64_t mapped = phase_slot; |
1242 | 0 | reverse = mapped * 2 > phase_slot_modulus; |
1243 | 0 | if (reverse) { |
1244 | 0 | sample_base_idx++; |
1245 | 0 | mapped = phase_slot_modulus - mapped; |
1246 | 0 | } |
1247 | 0 | uint64_t phase_index = r->half_sample_phase_bank |
1248 | 0 | ? mapped : 2 * mapped; |
1249 | 0 | if (phase_index < r->num_phases / 2) { |
1250 | 0 | p_idx = (size_t)phase_index; |
1251 | 0 | delta = 0; |
1252 | 0 | } else { |
1253 | 0 | p_idx = r->num_phases / 2 - 1; |
1254 | 0 | delta = 1; |
1255 | 0 | } |
1256 | 0 | } |
1257 | | #if FAAR_RESAMPLER_FLOAT |
1258 | | else if (r->polyphase_low_table) { |
1259 | | reverse = 2 * phase_remainder > r->out_rate; |
1260 | | uint32_t numerator = (uint32_t)(reverse ? r->out_rate - phase_remainder : phase_remainder); |
1261 | | if (reverse) sample_base_idx++; |
1262 | | faar_float2 position = ff2_mulf(ff2_div(ff2_uint32(numerator), |
1263 | | ff2_uint32(r->out_rate)), (float)r->num_phases); |
1264 | | p_idx = (size_t)position.hi; |
1265 | | if (p_idx >= r->num_phases / 2) p_idx = r->num_phases / 2 - 1; |
1266 | | precise_delta = ff2_sub(position, ff2((float)p_idx)); |
1267 | | if (ff2_round(precise_delta) < 0.0f && p_idx) { |
1268 | | --p_idx; |
1269 | | precise_delta = ff2_add(precise_delta, ff2(1)); |
1270 | | } |
1271 | | delta = ff2_round(precise_delta); |
1272 | | } |
1273 | | #else |
1274 | 1.79M | else if (r->polyphase_wide_table) { |
1275 | 0 | double position = (double)phase_remainder / r->out_rate; |
1276 | 0 | reverse = position > 0.5; |
1277 | 0 | if (reverse) { |
1278 | 0 | sample_base_idx++; |
1279 | 0 | position = 1 - position; |
1280 | 0 | } |
1281 | 0 | position *= (double)r->num_phases; |
1282 | 0 | p_idx = (size_t)position; |
1283 | 0 | if (p_idx >= r->num_phases / 2) |
1284 | 0 | p_idx = r->num_phases / 2 - 1; |
1285 | 0 | wide_delta = position - (double)p_idx; |
1286 | 0 | delta = (faar_sample_t)wide_delta; |
1287 | 0 | } |
1288 | 1.79M | #endif |
1289 | 1.79M | else { |
1290 | 1.79M | frac = (faar_sample_t)phase_remainder / r->out_rate; |
1291 | | /* Reflection changes the sign of fractional delay. Anchor negative |
1292 | | phases at the next input sample so the evaluated position agrees. */ |
1293 | 1.79M | reverse = frac > (faar_sample_t)0.5; |
1294 | 1.79M | if (reverse) { |
1295 | 323k | sample_base_idx++; |
1296 | 323k | frac = 1 - frac; |
1297 | 323k | } |
1298 | 1.79M | faar_sample_t phase_exact = frac * (faar_sample_t)r->num_phases; |
1299 | 1.79M | p_idx = (size_t)phase_exact; |
1300 | 1.79M | if (p_idx >= r->num_phases / 2) |
1301 | 412k | p_idx = r->num_phases / 2 - 1; |
1302 | 1.79M | delta = phase_exact - (faar_sample_t)p_idx; |
1303 | 1.79M | } |
1304 | 1.79M | if (sample_base_idx + filter_len > r->hist_len) { |
1305 | 2.92k | break; |
1306 | 2.92k | } |
1307 | | |
1308 | | #if FAAR_RESAMPLER_FLOAT |
1309 | | if (r->polyphase_low_table) { |
1310 | | if (r->exact_phase_bank) precise_delta = ff2(delta); |
1311 | | filter_precise_phase(r, sample_base_idx, p_idx, precise_delta, reverse, |
1312 | | out_samples + out_frames * r->channels); |
1313 | | goto advance_output; |
1314 | | } |
1315 | | #else |
1316 | 1.79M | if (r->polyphase_wide_table) { |
1317 | 0 | if (r->exact_phase_bank) wide_delta = delta; |
1318 | 0 | filter_wide_phase(r, sample_base_idx, p_idx, wide_delta, reverse, |
1319 | 0 | out_samples + out_frames * r->channels); |
1320 | 0 | goto advance_output; |
1321 | 0 | } |
1322 | 1.79M | #endif |
1323 | 1.79M | if ((filter_len & 1) && p_idx == 0 && delta < exact_phase_eps) { |
1324 | 736k | const faar_sample_t * restrict coeffs = poly_table; |
1325 | 736k | const faar_sample_t center_coeff = coeffs[half_len]; |
1326 | | |
1327 | 2.79M | for (uint16_t c = 0; c < r->channels; c++) { |
1328 | 2.05M | const faar_sample_t * restrict h = &r->hist[c][sample_base_idx]; |
1329 | 2.05M | faar_sample_t sum = (faar_sample_t)center_coeff * h[half_len]; |
1330 | | |
1331 | 131M | for (size_t j = 0; j < half_len; j++) { |
1332 | 129M | sum += (faar_sample_t)coeffs[j] * ((faar_sample_t)h[j] + h[filter_len - 1 - j]); |
1333 | 129M | } |
1334 | | |
1335 | 2.05M | out_samples[out_frames * r->channels + c] = sum; |
1336 | 2.05M | } |
1337 | 1.05M | } else { |
1338 | 1.05M | const faar_sample_t * restrict c1 = poly_table + p_idx * filter_len; |
1339 | 1.05M | const faar_sample_t * restrict c0 = c1 - filter_len; |
1340 | 1.05M | const faar_sample_t * restrict c2 = c1 + filter_len; |
1341 | 1.05M | const faar_sample_t * restrict c3 = c2 + filter_len; |
1342 | 1.05M | const faar_sample_t * restrict coeffs; |
1343 | | |
1344 | | /* Exact rational phases need no four-row interpolation. */ |
1345 | 1.05M | if (delta < exact_phase_eps) { |
1346 | 0 | if (reverse && r->polyphase_reverse_table) { |
1347 | 0 | coeffs = r->polyphase_reverse_table |
1348 | 0 | + filter_len + p_idx * filter_len; |
1349 | 0 | } else if (reverse) { |
1350 | 0 | for (size_t j = 0; j < filter_len; j++) |
1351 | 0 | temp_coeffs[filter_len - 1 - j] = c1[j]; |
1352 | 0 | coeffs = temp_coeffs; |
1353 | 0 | } else { |
1354 | 0 | coeffs = c1; |
1355 | 0 | } |
1356 | 1.05M | } else { |
1357 | | /* Four-point Lagrange weights reproduce cubics exactly, allowing |
1358 | | * a smaller phase bank without the leading cubic phase error. */ |
1359 | 1.05M | faar_sample_t d = delta; |
1360 | 1.05M | faar_sample_t d2 = d * d; |
1361 | 1.05M | faar_sample_t d3 = d2 * d; |
1362 | 1.05M | faar_sample_t w0 = (-d3 + 3 * d2 - 2 * d) / 6; |
1363 | 1.05M | faar_sample_t w1 = (d3 - 2 * d2 - d + 2) / 2; |
1364 | 1.05M | faar_sample_t w2 = (-d3 + d2 + 2 * d) / 2; |
1365 | 1.05M | faar_sample_t w3 = (d3 - d) / 6; |
1366 | | |
1367 | | |
1368 | 135M | for (size_t j = 0; j < filter_len; j++) { |
1369 | 134M | size_t target = reverse ? filter_len - 1 - j : j; |
1370 | 134M | temp_coeffs[target] = (faar_sample_t)(w0 * c0[j] + w1 * c1[j] + w2 * c2[j] + w3 * c3[j]); |
1371 | 134M | } |
1372 | 1.05M | coeffs = temp_coeffs; |
1373 | 1.05M | } |
1374 | | |
1375 | 3.96M | for (uint16_t c = 0; c < r->channels; c++) { |
1376 | 2.91M | const faar_sample_t * restrict h = &r->hist[c][sample_base_idx]; |
1377 | 2.91M | faar_sample_t accumulator0 = 0, accumulator1 = 0; |
1378 | 2.91M | faar_sample_t accumulator2 = 0, accumulator3 = 0; |
1379 | 2.91M | size_t j = 0; |
1380 | 93.1M | for (; j + 3 < filter_len; j += 4) { |
1381 | 90.2M | accumulator0 += (faar_sample_t)h[j] * coeffs[j]; |
1382 | 90.2M | accumulator1 += (faar_sample_t)h[j + 1] * coeffs[j + 1]; |
1383 | 90.2M | accumulator2 += (faar_sample_t)h[j + 2] * coeffs[j + 2]; |
1384 | 90.2M | accumulator3 += (faar_sample_t)h[j + 3] * coeffs[j + 3]; |
1385 | 90.2M | } |
1386 | 2.91M | faar_sample_t accumulator = accumulator0 + accumulator1 |
1387 | 2.91M | + accumulator2 + accumulator3; |
1388 | 11.6M | for (; j < filter_len; ++j) |
1389 | 8.73M | accumulator += (faar_sample_t)h[j] * coeffs[j]; |
1390 | 2.91M | out_samples[out_frames * r->channels + c] = (float)accumulator; |
1391 | 2.91M | } |
1392 | 1.05M | } |
1393 | | |
1394 | 1.79M | advance_output: |
1395 | 1.79M | out_frames++; |
1396 | 1.79M | base_idx += (size_t)step_whole; |
1397 | 1.79M | phase_remainder += step_remainder; |
1398 | 1.79M | if (phase_remainder >= r->out_rate) { |
1399 | 735k | phase_remainder -= r->out_rate; |
1400 | 735k | ++base_idx; |
1401 | 735k | } |
1402 | 1.79M | if (r->exact_phase_bank) { |
1403 | 0 | phase_slot += phase_slot_step; |
1404 | 0 | if (phase_slot >= phase_slot_modulus) |
1405 | 0 | phase_slot -= phase_slot_modulus; |
1406 | 0 | } |
1407 | 1.79M | } |
1408 | | |
1409 | 2.92k | r->output_frames += out_frames; |
1410 | 2.92k | size_t consumed = base_idx; |
1411 | 2.92k | r->phase = (uint64_t)base_idx * r->out_rate + phase_remainder; |
1412 | | /* The next clock position may be beyond currently buffered input |
1413 | | * (notably a 1-tap bank with an integral sampling step). Discard all |
1414 | | * available history, preserving the pending skip in the phase clock. */ |
1415 | 2.92k | size_t discard = consumed < r->hist_len ? consumed : r->hist_len; |
1416 | 2.92k | if (discard && (discard >= filter_len / 2 |
1417 | 1.46k | || r->hist_len - discard < filter_len)) { |
1418 | 5.43k | for (uint16_t c = 0; c < r->channels; ++c) |
1419 | 3.97k | r->hist[c] += discard; |
1420 | 1.46k | r->hist_offset += discard; |
1421 | 1.46k | r->hist_len -= discard; |
1422 | 1.46k | r->phase -= (uint64_t)discard * r->out_rate; |
1423 | 1.46k | } |
1424 | | |
1425 | 2.92k | apply_dither(r, out_samples, out_frames); |
1426 | 2.92k | return out_frames; |
1427 | 2.92k | } |
1428 | | |
1429 | | static size_t process_internal(faar_resampler * restrict r, const float * restrict in_samples, size_t in_count, |
1430 | 4.27k | float * restrict out_samples, size_t max_out_count) { |
1431 | 4.27k | if (!r || !out_samples || (r->flushed && in_samples && in_count)) return 0; |
1432 | | /* Flushing may drain a cascaded stage through a zero-frame process call. */ |
1433 | 4.27k | if (r->flushed && !in_samples && !in_count) return 0; |
1434 | | |
1435 | 4.27k | if (r->dft_prefilter) { |
1436 | 0 | if (in_count > (SIZE_MAX - 8192) / r->dft_expansion |
1437 | 0 | || in_count * r->dft_expansion + 8192 |
1438 | 0 | > SIZE_MAX / r->channels / sizeof(float)) { |
1439 | 0 | r->last_error = FAAR_ERR_INVALID_ARGUMENT; |
1440 | 0 | return 0; |
1441 | 0 | } |
1442 | 0 | size_t temp_capacity = in_count * r->dft_expansion + 8192; |
1443 | 0 | if (!r->stage2 && ensure_dft_intermediate(r, temp_capacity)) { |
1444 | 0 | r->last_error = FAAR_ERR_NO_MEMORY; |
1445 | 0 | return 0; |
1446 | 0 | } |
1447 | 0 | size_t filtered = 0; |
1448 | 0 | if (in_samples) r->input_frames += in_count; |
1449 | 0 | if (faar_dft_prefilter_process(r->dft_prefilter, in_samples, in_count, |
1450 | 0 | r->dft_intermediate, r->stage2 ? 0 |
1451 | 0 | : (max_out_count < temp_capacity ? max_out_count : temp_capacity), |
1452 | 0 | &filtered)) { r->last_error = FAAR_ERR_PROCESSING; return 0; } |
1453 | 0 | size_t produced; |
1454 | 0 | if (r->stage2) { |
1455 | 0 | produced = process_prefilter_output(r, temp_capacity, |
1456 | 0 | out_samples, max_out_count); |
1457 | 0 | } else { |
1458 | 0 | produced = filtered; |
1459 | 0 | for (size_t i = 0; i < filtered; ++i) |
1460 | 0 | for (uint16_t c = 0; c < r->channels; ++c) |
1461 | 0 | out_samples[i * r->channels + c] = r->dft_intermediate[c * filtered + i]; |
1462 | 0 | apply_dither(r, out_samples, produced); |
1463 | 0 | } |
1464 | 0 | r->output_frames += produced; |
1465 | 0 | return produced; |
1466 | 0 | } |
1467 | | |
1468 | 4.27k | if (r->stage1 && r->stage2) { |
1469 | 1.35k | size_t produced = 0, stage1_produced; |
1470 | 1.35k | size_t capacity = r->cascade_cap / r->channels; |
1471 | 1.35k | if (in_samples) r->input_frames += in_count; |
1472 | 1.35k | max_out_count = output_capacity(r, max_out_count); |
1473 | 1.35k | do { |
1474 | 1.35k | stage1_produced = process_internal(r->stage1, in_samples, in_count, r->cascade_buf, capacity); |
1475 | 1.35k | produced += process_internal(r->stage2, r->cascade_buf, stage1_produced, |
1476 | 1.35k | out_samples + produced * r->channels, max_out_count - produced); |
1477 | 1.35k | in_samples = NULL; |
1478 | 1.35k | in_count = 0; |
1479 | 1.35k | } while (stage1_produced == capacity); |
1480 | 1.35k | r->output_frames += produced; |
1481 | 1.35k | return produced; |
1482 | 1.35k | } |
1483 | | |
1484 | 2.92k | return polyresample_process_single(r, in_samples, in_count, out_samples, max_out_count); |
1485 | 4.27k | } |
1486 | | |
1487 | | /* The prefilter FIFO is already planar. Drain directly into the downstream |
1488 | | * append area, then advance the same history and boundary state as an input |
1489 | | * copy would. Reserve only the actual burst, including during flush. */ |
1490 | | static size_t process_prefilter_output(faar_resampler *parent, size_t capacity, |
1491 | 0 | float *out_samples, size_t max_out_count) { |
1492 | 0 | faar_resampler *r = parent->stage2; |
1493 | 0 | size_t in_count = faar_dft_prefilter_pending(parent->dft_prefilter); |
1494 | 0 | if (in_count > capacity) in_count = capacity; |
1495 | 0 | if (in_count) { |
1496 | 0 | if (reserve_history(r, in_count, false)) return 0; |
1497 | 0 | float *planes[MAX_CHANNELS]; |
1498 | 0 | for (uint16_t c = 0; c < r->channels; ++c) |
1499 | 0 | planes[c] = r->hist[c] + r->hist_len; |
1500 | 0 | faar_dft_prefilter_drain_planes(parent->dft_prefilter, planes, in_count); |
1501 | 0 | if (!r->input_frames && !r->flushed) { |
1502 | 0 | for (uint16_t c = 0; c < r->channels; ++c) { |
1503 | 0 | faar_sample_t first = r->hist[c][r->history_pad]; |
1504 | 0 | for (size_t j = 0; j < r->history_pad; ++j) |
1505 | 0 | r->hist[c][j] = first; |
1506 | 0 | } |
1507 | 0 | } |
1508 | 0 | r->hist_len += in_count; |
1509 | 0 | if (!r->flushed) { |
1510 | 0 | for (uint16_t c = 0; c < r->channels; ++c) |
1511 | 0 | r->last_input[c] = r->hist[c][r->hist_len - 1]; |
1512 | 0 | r->input_frames += in_count; |
1513 | 0 | } |
1514 | 0 | } |
1515 | 0 | return polyresample_process_single(r, NULL, 0, out_samples, max_out_count); |
1516 | 0 | } |
1517 | | |
1518 | 0 | static size_t polyresample_flush_single(faar_resampler * r, float *out_samples, size_t max_out_count) { |
1519 | 0 | if (!r || !out_samples) return 0; |
1520 | | |
1521 | 0 | if (r->in_rate == r->out_rate) { |
1522 | 0 | r->flushed = true; |
1523 | 0 | return polyresample_process_single(r, NULL, 0, out_samples, max_out_count); |
1524 | 0 | } |
1525 | 0 | if (!r->flushed) { |
1526 | 0 | size_t tail_len = (r->filter_len - 1) / 2 + 1; |
1527 | 0 | if (r->filter_len == 20) ++tail_len; |
1528 | 0 | if (reserve_history(r, tail_len, false)) return 0; |
1529 | 0 | for (uint16_t c = 0; c < r->channels; ++c) { |
1530 | 0 | faar_sample_t last = r->input_frames ? r->last_input[c] : 0.0f; |
1531 | 0 | for (size_t j = 0; j < tail_len; ++j) |
1532 | 0 | r->hist[c][r->hist_len + j] = last; |
1533 | 0 | } |
1534 | 0 | r->hist_len += tail_len; |
1535 | 0 | r->flushed = true; |
1536 | 0 | } |
1537 | | |
1538 | 0 | return polyresample_process_single(r, NULL, 0, out_samples, max_out_count); |
1539 | 0 | } |
1540 | | |
1541 | 0 | static size_t flush_internal(faar_resampler * r, float *out_samples, size_t max_out_count) { |
1542 | 0 | if (!r || !out_samples) return 0; |
1543 | | |
1544 | 0 | if (r->dft_prefilter) { |
1545 | 0 | r->flushed = true; |
1546 | 0 | max_out_count = output_capacity(r, max_out_count); |
1547 | 0 | const size_t temp_capacity = 8192; |
1548 | 0 | if (!r->stage2 && ensure_dft_intermediate(r, temp_capacity)) { |
1549 | 0 | r->last_error = FAAR_ERR_NO_MEMORY; |
1550 | 0 | return 0; |
1551 | 0 | } |
1552 | 0 | size_t produced = 0, filtered; |
1553 | 0 | if (!r->stage2) { |
1554 | 0 | size_t capacity = max_out_count < temp_capacity ? max_out_count : temp_capacity; |
1555 | 0 | if (faar_dft_prefilter_flush(r->dft_prefilter, r->dft_intermediate, |
1556 | 0 | capacity, &filtered)) { r->last_error = FAAR_ERR_PROCESSING; return 0; } |
1557 | 0 | for (size_t i = 0; i < filtered; ++i) |
1558 | 0 | for (uint16_t c = 0; c < r->channels; ++c) |
1559 | 0 | out_samples[i * r->channels + c] = r->dft_intermediate[c * filtered + i]; |
1560 | 0 | r->output_frames += filtered; |
1561 | 0 | apply_dither(r, out_samples, filtered); |
1562 | 0 | return filtered; |
1563 | 0 | } |
1564 | 0 | do { |
1565 | 0 | filtered = 0; |
1566 | 0 | if (faar_dft_prefilter_flush(r->dft_prefilter, NULL, 0, &filtered)) { |
1567 | 0 | r->last_error = FAAR_ERR_PROCESSING; |
1568 | 0 | return 0; |
1569 | 0 | } |
1570 | 0 | filtered = faar_dft_prefilter_pending(r->dft_prefilter); |
1571 | 0 | if (filtered > temp_capacity) filtered = temp_capacity; |
1572 | 0 | produced += process_prefilter_output(r, temp_capacity, |
1573 | 0 | out_samples + produced * r->channels, max_out_count - produced); |
1574 | 0 | if (r->stage2->last_error != FAAR_OK) return 0; |
1575 | 0 | } while (filtered == temp_capacity); |
1576 | 0 | produced += flush_internal(r->stage2, |
1577 | 0 | out_samples + produced * r->channels, |
1578 | 0 | max_out_count - produced); |
1579 | 0 | r->output_frames += produced; |
1580 | 0 | return produced; |
1581 | 0 | } |
1582 | | |
1583 | 0 | if (r->stage1 && r->stage2) { |
1584 | 0 | size_t produced = 0, stage1_flushed; |
1585 | 0 | size_t capacity = r->cascade_cap / r->channels; |
1586 | 0 | r->flushed = true; |
1587 | 0 | max_out_count = output_capacity(r, max_out_count); |
1588 | 0 | do { |
1589 | 0 | stage1_flushed = flush_internal(r->stage1, r->cascade_buf, capacity); |
1590 | 0 | if (stage1_flushed) |
1591 | 0 | produced += process_internal(r->stage2, r->cascade_buf, |
1592 | 0 | stage1_flushed, out_samples + produced * r->channels, |
1593 | 0 | max_out_count - produced); |
1594 | 0 | } while (stage1_flushed == capacity); |
1595 | 0 | produced += flush_internal(r->stage2, out_samples + produced * r->channels, max_out_count - produced); |
1596 | 0 | r->output_frames += produced; |
1597 | 0 | return produced; |
1598 | 0 | } |
1599 | | |
1600 | 0 | return polyresample_flush_single(r, out_samples, max_out_count); |
1601 | 0 | } |
1602 | | |
1603 | 2.08k | static void destroy_internal(faar_resampler * r) { |
1604 | 2.08k | if (!r) return; |
1605 | 2.08k | if (r->stage1) destroy_internal(r->stage1); |
1606 | 2.08k | if (r->stage2) destroy_internal(r->stage2); |
1607 | 2.08k | if (r->dft_prefilter) faar_dft_prefilter_destroy(r->dft_prefilter); |
1608 | 2.08k | FreeMemory(r->dft_intermediate); |
1609 | 2.08k | if (r->cascade_buf) aligned_free(r->cascade_buf); |
1610 | 7.61k | for (uint16_t c = 0; c < r->channels && c < MAX_CHANNELS; c++) { |
1611 | 5.53k | if (r->hist[c]) aligned_free(r->hist[c] - r->hist_offset); |
1612 | 5.53k | } |
1613 | 2.08k | if (!r->shared_coeffs) { |
1614 | 2.08k | if (r->polyphase_reverse_table) aligned_free(r->polyphase_reverse_table); |
1615 | 2.08k | if (r->polyphase_table) aligned_free(r->polyphase_table); |
1616 | 2.08k | #if !FAAR_RESAMPLER_FLOAT |
1617 | 2.08k | aligned_free(r->polyphase_wide_table); |
1618 | 2.08k | aligned_free(r->polyphase_wide_reverse); |
1619 | | #else |
1620 | | if (r->polyphase_low_table) aligned_free(r->polyphase_low_table); |
1621 | | #endif |
1622 | 2.08k | } |
1623 | 2.08k | faar_design *plan = r->plan; |
1624 | 2.08k | FreeMemory(r); |
1625 | 2.08k | if (plan) plan_release(plan); |
1626 | 2.08k | } |
1627 | | |
1628 | 0 | static void plan_release(faar_design *plan) { |
1629 | 0 | #if !defined(__STDC_NO_ATOMICS__) && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) |
1630 | 0 | int last = atomic_fetch_sub_explicit(&plan->references, 1, memory_order_acq_rel) == 1; |
1631 | | #elif defined(_MSC_VER) |
1632 | | int last = _InterlockedDecrement(&plan->references) == 0; |
1633 | | #else |
1634 | | int last = --plan->references == 0; |
1635 | | #endif |
1636 | 0 | if (last) { |
1637 | 0 | destroy_internal(plan->prototype); |
1638 | 0 | FreeMemory(plan); |
1639 | 0 | } |
1640 | 0 | } |
1641 | | |
1642 | | /* Retain only immutable design state. Capacities and initial stream counters |
1643 | | * remain as geometry for clones; every mutable allocation is released. */ |
1644 | 0 | static void release_plan_workspace(faar_resampler *r) { |
1645 | 0 | if (r->stage1) release_plan_workspace(r->stage1); |
1646 | 0 | if (r->stage2) release_plan_workspace(r->stage2); |
1647 | 0 | if (r->dft_prefilter) faar_dft_prefilter_release_workspace(r->dft_prefilter); |
1648 | 0 | FreeMemory(r->dft_intermediate); |
1649 | 0 | r->dft_intermediate = NULL; |
1650 | 0 | aligned_free(r->cascade_buf); |
1651 | 0 | r->cascade_buf = NULL; |
1652 | 0 | for (uint16_t c = 0; c < r->channels; ++c) { |
1653 | 0 | if (r->hist[c]) aligned_free(r->hist[c] - r->hist_offset); |
1654 | 0 | r->hist[c] = NULL; |
1655 | 0 | } |
1656 | 0 | r->hist_offset = 0; |
1657 | 0 | } |
1658 | | |
1659 | 0 | static faar_resampler *clone_plan_internal(const faar_resampler *source) { |
1660 | 0 | faar_resampler *r = AllocMemory(sizeof(*r)); |
1661 | 0 | if (!r) return NULL; |
1662 | 0 | *r = *source; |
1663 | 0 | r->shared_coeffs = true; |
1664 | 0 | r->plan = NULL; |
1665 | 0 | r->stage1 = r->stage2 = NULL; |
1666 | 0 | r->dft_prefilter = NULL; |
1667 | 0 | r->cascade_buf = NULL; |
1668 | 0 | r->dft_intermediate = NULL; |
1669 | 0 | r->hist_offset = 0; |
1670 | 0 | memset(r->hist, 0, sizeof(r->hist)); |
1671 | 0 | if (source->stage1 && !(r->stage1 = clone_plan_internal(source->stage1))) goto fail; |
1672 | 0 | if (source->stage2 && !(r->stage2 = clone_plan_internal(source->stage2))) goto fail; |
1673 | 0 | if (source->dft_prefilter && !(r->dft_prefilter = |
1674 | 0 | faar_dft_prefilter_clone_filter(source->dft_prefilter))) goto fail; |
1675 | 0 | if (r->cascade_cap) { |
1676 | 0 | r->cascade_buf = aligned_malloc(r->cascade_cap * sizeof(float)); |
1677 | 0 | if (!r->cascade_buf) goto fail; |
1678 | 0 | } |
1679 | 0 | if (r->hist_cap_per_ch) { |
1680 | 0 | for (uint16_t c = 0; c < r->channels; ++c) { |
1681 | 0 | r->hist[c] = aligned_malloc(r->hist_cap_per_ch * sizeof(*r->hist[c])); |
1682 | 0 | if (!r->hist[c]) goto fail; |
1683 | 0 | memset(r->hist[c], 0, r->hist_cap_per_ch * sizeof(*r->hist[c])); |
1684 | 0 | } |
1685 | 0 | } |
1686 | 0 | return r; |
1687 | 0 | fail: |
1688 | 0 | destroy_internal(r); |
1689 | 0 | return NULL; |
1690 | 0 | } |
1691 | | |
1692 | 0 | FAARAPI faar_status faar_design_open(const faar_config *config, faar_design **out) { |
1693 | 0 | if (!out) return FAAR_ERR_INVALID_ARGUMENT; |
1694 | 0 | *out = NULL; |
1695 | 0 | faar_resampler *prototype = NULL; |
1696 | 0 | faar_status status = open_stream(config, &prototype, false); |
1697 | 0 | if (status != FAAR_OK) return status; |
1698 | 0 | faar_design *plan = AllocMemory(sizeof(*plan)); |
1699 | 0 | if (!plan) { destroy_internal(prototype); return FAAR_ERR_NO_MEMORY; } |
1700 | 0 | #if !defined(__STDC_NO_ATOMICS__) && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) |
1701 | 0 | atomic_init(&plan->references, 1); |
1702 | | #else |
1703 | | plan->references = 1; |
1704 | | #endif |
1705 | 0 | plan->prototype = prototype; |
1706 | 0 | plan->max_input_frames = config->max_input_frames; |
1707 | 0 | release_plan_workspace(prototype); |
1708 | 0 | *out = plan; |
1709 | 0 | return FAAR_OK; |
1710 | 0 | } |
1711 | | |
1712 | 0 | FAARAPI faar_status faar_design_close(faar_design **design) { |
1713 | 0 | if (!design) return FAAR_ERR_INVALID_ARGUMENT; |
1714 | 0 | if (*design) plan_release(*design); |
1715 | 0 | *design = NULL; |
1716 | 0 | return FAAR_OK; |
1717 | 0 | } |
1718 | | |
1719 | | FAARAPI faar_status faar_resampler_open_from_design(faar_design *design, |
1720 | 0 | faar_resampler **out) { |
1721 | 0 | if (!out) return FAAR_ERR_INVALID_ARGUMENT; |
1722 | 0 | *out = NULL; |
1723 | 0 | if (!design) return FAAR_ERR_INVALID_ARGUMENT; |
1724 | 0 | if (plan_retain(design)) return FAAR_ERR_NO_MEMORY; |
1725 | 0 | faar_resampler *r = clone_plan_internal(design->prototype); |
1726 | 0 | if (!r) { plan_release(design); return FAAR_ERR_NO_MEMORY; } |
1727 | 0 | r->plan = design; |
1728 | 0 | if (design->max_input_frames) { |
1729 | 0 | faar_status st = reserve_stream(r, design->max_input_frames); |
1730 | 0 | if (st != FAAR_OK) { destroy_internal(r); return st; } |
1731 | 0 | } |
1732 | 0 | *out = r; |
1733 | 0 | return FAAR_OK; |
1734 | 0 | } |
1735 | | |
1736 | 764 | FAARAPI faar_status faar_config_init(faar_config *config, uint32_t caller_size) { |
1737 | 764 | faar_config defaults; |
1738 | 764 | if (!config || caller_size < FAAR_CONFIG_BASELINE) |
1739 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1740 | 764 | memset(&defaults, 0, sizeof(defaults)); |
1741 | 764 | defaults.quality = FAAR_QUALITY_GOOD; |
1742 | 764 | uint32_t n = caller_size < sizeof(defaults) ? caller_size : sizeof(defaults); |
1743 | 764 | defaults.struct_size = n; |
1744 | 764 | memcpy(config, &defaults, n); |
1745 | 764 | return FAAR_OK; |
1746 | 764 | } |
1747 | | |
1748 | 0 | FAARAPI faar_status faar_get_library_info(faar_library_info *out_info) { |
1749 | 0 | if (!out_info || out_info->struct_size < FAAR_LIBRARY_INFO_BASELINE) |
1750 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1751 | 0 | uint32_t caller_size = out_info->struct_size; |
1752 | 0 | faar_library_info info = {0}; |
1753 | 0 | info.max_channels = MAX_CHANNELS; |
1754 | | #if FAAR_RESAMPLER_FLOAT |
1755 | | info.flags |= FAAR_LIB_FLOAT_ONLY; |
1756 | | #endif |
1757 | 0 | info.version = FAAR_VERSION_STRING; |
1758 | 0 | info.copyright = |
1759 | 0 | "FAAR - Freeware Advanced Audio Resampler (https://freewareadvancedaudio.github.io)\n" |
1760 | 0 | " Copyright (C) 2026, Nils Schimmelmann"; |
1761 | 0 | uint32_t n = caller_size < sizeof(info) ? caller_size : sizeof(info); |
1762 | 0 | info.struct_size = n; |
1763 | 0 | memcpy(out_info, &info, n); |
1764 | 0 | return FAAR_OK; |
1765 | 0 | } |
1766 | | |
1767 | 0 | FAARAPI const char *faar_strerror(faar_status status) { |
1768 | 0 | switch (status) { |
1769 | 0 | case FAAR_OK: return "success"; |
1770 | 0 | case FAAR_ERR_INVALID_ARGUMENT: return "invalid argument or state"; |
1771 | 0 | case FAAR_ERR_UNSUPPORTED: return "unsupported configuration"; |
1772 | 0 | case FAAR_ERR_NO_MEMORY: return "out of memory"; |
1773 | 0 | case FAAR_ERR_PROCESSING: return "resampling failed; discard this stream"; |
1774 | 0 | default: return "unknown FAAR status"; |
1775 | 0 | } |
1776 | 0 | } |
1777 | | |
1778 | | static faar_status open_stream(const faar_config *config, faar_resampler **out, |
1779 | 764 | bool reserve) { |
1780 | 764 | if (!out) return FAAR_ERR_INVALID_ARGUMENT; |
1781 | 764 | *out = NULL; |
1782 | 764 | if (!config || config->struct_size < FAAR_CONFIG_BASELINE) |
1783 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1784 | 764 | faar_config cfg = {0}; |
1785 | 764 | uint32_t n = config->struct_size < sizeof(cfg) ? config->struct_size : sizeof(cfg); |
1786 | 764 | memcpy(&cfg, config, n); |
1787 | 764 | uint32_t dither; |
1788 | 764 | uint8_t dither_depth; |
1789 | 764 | if (cfg.in_rate == 0 || cfg.out_rate == 0 |
1790 | 764 | || cfg.channels == 0 || cfg.channels > MAX_CHANNELS |
1791 | 764 | || cfg.quality < FAAR_QUALITY_FAST || cfg.quality > FAAR_QUALITY_HIGH |
1792 | 764 | || dither_from_flags(cfg.flags, &dither, &dither_depth) != 0) |
1793 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1794 | 764 | faar_resampler * r = create_resampler_internal(cfg.in_rate, cfg.out_rate, |
1795 | 764 | (uint16_t)cfg.channels, cfg.quality, cfg.decimate_factor, 0, false, 0); |
1796 | 764 | if (!r) return FAAR_ERR_NO_MEMORY; |
1797 | 764 | if (set_dither_internal(r, dither, dither_depth) != 0) { |
1798 | 0 | destroy_internal(r); |
1799 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1800 | 0 | } |
1801 | 764 | if (reserve && cfg.max_input_frames) { |
1802 | 0 | faar_status st = reserve_stream(r, cfg.max_input_frames); |
1803 | 0 | if (st != FAAR_OK) { destroy_internal(r); return st; } |
1804 | 0 | } |
1805 | 764 | *out = r; |
1806 | 764 | return FAAR_OK; |
1807 | 764 | } |
1808 | | |
1809 | | FAARAPI faar_status faar_resampler_open(const faar_config *config, |
1810 | 764 | faar_resampler **out) { |
1811 | 764 | return open_stream(config, out, true); |
1812 | 764 | } |
1813 | | |
1814 | 0 | static faar_status reserve_stream(faar_resampler *r, size_t max_input_frames) { |
1815 | 0 | if (max_input_frames > SIZE_MAX / r->channels / sizeof(float)) |
1816 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1817 | 0 | clear_error(r); |
1818 | 0 | size_t output_bound; |
1819 | 0 | faar_status st = prepare_internal(r, max_input_frames, &output_bound); |
1820 | 0 | if (st != FAAR_OK) return st; |
1821 | 0 | r->prepared_max_input = max_input_frames; |
1822 | 0 | set_prepared(r, true); |
1823 | 0 | return FAAR_OK; |
1824 | 0 | } |
1825 | | |
1826 | 764 | FAARAPI faar_status faar_resampler_close(faar_resampler **resampler) { |
1827 | 764 | if (!resampler) return FAAR_ERR_INVALID_ARGUMENT; |
1828 | 764 | destroy_internal(*resampler); |
1829 | 764 | *resampler = NULL; |
1830 | 764 | return FAAR_OK; |
1831 | 764 | } |
1832 | | |
1833 | | FAARAPI faar_status faar_resampler_get_info(const faar_resampler *resampler, |
1834 | 0 | faar_resampler_info *out_info) { |
1835 | 0 | if (!resampler || !out_info || out_info->struct_size < FAAR_RESAMPLER_INFO_BASELINE) |
1836 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1837 | 0 | uint32_t caller_size = out_info->struct_size; |
1838 | 0 | faar_resampler_info info = {0}; |
1839 | 0 | info.decimate_factor = 1; |
1840 | 0 | for (const faar_resampler *s = resampler; s && s->stage1; s = s->stage2) |
1841 | 0 | info.decimate_factor *= (uint32_t)((s->in_rate + s->stage1->out_rate / 2) |
1842 | 0 | / s->stage1->out_rate); |
1843 | 0 | info.delay_frames = (uint32_t)resampler->delay; |
1844 | 0 | uint32_t n = caller_size < sizeof(info) ? caller_size : sizeof(info); |
1845 | 0 | info.struct_size = n; |
1846 | 0 | memcpy(out_info, &info, n); |
1847 | 0 | return FAAR_OK; |
1848 | 0 | } |
1849 | | |
1850 | | FAARAPI faar_status faar_resampler_process(faar_resampler *resampler, |
1851 | | const float *in_samples, size_t in_count, float *out_samples, |
1852 | 1.57k | size_t max_out_count, size_t *out_count) { |
1853 | 1.57k | if (!out_count) return FAAR_ERR_INVALID_ARGUMENT; |
1854 | 1.57k | *out_count = 0; |
1855 | 1.57k | if (!resampler || !out_samples || (in_count && !in_samples) |
1856 | 1.57k | || (resampler->flushed && in_count) |
1857 | 1.57k | || (resampler->prepared && in_count > resampler->prepared_max_input) |
1858 | 1.57k | || in_count > SIZE_MAX / resampler->channels / sizeof(float) |
1859 | 1.57k | || max_out_count > SIZE_MAX / resampler->channels / sizeof(float)) |
1860 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1861 | 1.57k | clear_error(resampler); |
1862 | 1.57k | *out_count = process_internal(resampler, in_samples, in_count, |
1863 | 1.57k | out_samples, max_out_count); |
1864 | 1.57k | faar_status status = find_error(resampler); |
1865 | 1.57k | if (status != FAAR_OK) *out_count = 0; |
1866 | 1.57k | return status; |
1867 | 1.57k | } |
1868 | | |
1869 | | FAARAPI faar_status faar_resampler_finalize(faar_resampler *resampler, |
1870 | 0 | float *out_samples, size_t max_out_count, size_t *out_count) { |
1871 | 0 | if (!out_count) return FAAR_ERR_INVALID_ARGUMENT; |
1872 | 0 | *out_count = 0; |
1873 | 0 | if (!resampler || !out_samples |
1874 | 0 | || max_out_count > SIZE_MAX / resampler->channels / sizeof(float)) |
1875 | 0 | return FAAR_ERR_INVALID_ARGUMENT; |
1876 | 0 | clear_error(resampler); |
1877 | 0 | *out_count = flush_internal(resampler, out_samples, max_out_count); |
1878 | 0 | faar_status status = find_error(resampler); |
1879 | 0 | if (status != FAAR_OK) *out_count = 0; |
1880 | 0 | return status; |
1881 | 0 | } |