/proc/self/cwd/external/faac/libfaar/dft_coeffs.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 | | /* Independently implemented Kaiser-windowed low-pass coefficient designer. */ |
16 | | #include "dft_coeffs.h" |
17 | | |
18 | | #include <math.h> |
19 | | |
20 | | #ifndef M_PI |
21 | | #define M_PI 3.14159265358979323846264338327950288 |
22 | | #endif |
23 | | |
24 | 0 | static double bessel_i0(double x) { |
25 | 0 | const double half = x * 0.5; |
26 | 0 | double sum = 1.0, term = 1.0; |
27 | 0 | for (unsigned k = 1; k < 256; ++k) { |
28 | 0 | term *= (half / (double)k) * (half / (double)k); |
29 | 0 | sum += term; |
30 | 0 | if (term <= sum * 2.0e-16) break; |
31 | 0 | } |
32 | 0 | return sum; |
33 | 0 | } |
34 | | |
35 | | int faar_dft_design_lowpass(double *taps, size_t tap_count, |
36 | 0 | double cutoff, double beta) { |
37 | 0 | if (!taps || tap_count < 3 || !(tap_count & 1) |
38 | 0 | || !isfinite(cutoff) || cutoff <= 0.0 || cutoff >= 0.5 |
39 | 0 | || !isfinite(beta) || beta < 0.0 || beta > 50.0) |
40 | 0 | return -1; |
41 | | |
42 | 0 | const double center = (double)(tap_count - 1) * 0.5; |
43 | 0 | const double window_denominator = bessel_i0(beta); |
44 | 0 | double sum = 0.0; |
45 | 0 | for (size_t i = 0; i < tap_count; ++i) { |
46 | 0 | const double x = (double)i - center; |
47 | 0 | const double arg = 2.0 * cutoff * x; |
48 | 0 | const double ideal = x == 0.0 ? 2.0 * cutoff |
49 | 0 | : sin(M_PI * arg) / (M_PI * x); |
50 | 0 | const double position = x / center; |
51 | 0 | const double radicand = 1.0 - position * position; |
52 | 0 | const double window = bessel_i0(beta * sqrt(radicand > 0.0 |
53 | 0 | ? radicand : 0.0)) |
54 | 0 | / window_denominator; |
55 | 0 | taps[i] = ideal * window; |
56 | 0 | sum += taps[i]; |
57 | 0 | } |
58 | 0 | if (!isfinite(sum) || fabs(sum) < 1.0e-15) return -1; |
59 | 0 | for (size_t i = 0; i < tap_count; ++i) taps[i] /= sum; |
60 | 0 | return 0; |
61 | 0 | } |