ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
spectral.c
Go to the documentation of this file.
2#include <ascii-chat/common.h>
5#include <fftw3.h>
6#include <math.h>
7#include <string.h>
8
9#define SPECTRAL_MAX_SIZE 2048
10#define SPECTRAL_MAX_BINS (SPECTRAL_MAX_SIZE / 2 + 1)
11
36
37// FFTW execution is independent per instance; planning and destruction share
38// state.
40
42 return (spectral_config_t){.sample_rate = sample_rate,
43 .fft_size = 1024,
44 .noise_gate = true,
45 .reduction_db = 18.0f,
46 .crossovers = {250, 2000, 8000},
47 .thresholds_db = {-18, -18, -18, -18},
48 .ratios = {2, 3, 3, 2}};
49}
50
52 if (!p)
53 return;
54 memset(p->input, 0, sizeof(p->input));
55 memset(p->overlap, 0, sizeof(p->overlap));
56 memset(p->ready, 0, sizeof(p->ready));
57 memset(p->noise, 0, sizeof(p->noise));
58 memset(p->smoothed, 0, sizeof(p->smoothed));
59 memset(p->magnitude, 0, sizeof(p->magnitude));
60 memset(p->band_average, 0, sizeof(p->band_average));
61 for (int i = 0; i < SPECTRAL_MAX_BINS; ++i)
62 p->gains[i] = 1;
63 for (int i = 0; i < 4; ++i)
64 p->band_gain[i] = p->eq_gain[i] = 1;
65 p->pending = p->cursor = 0;
66 memset(p->previous_phase, 0, sizeof(p->previous_phase));
67 memset(p->synthesis_phase, 0, sizeof(p->synthesis_phase));
68 p->pitch_hz = 0;
69 p->auto_gain = 1;
70 p->frames = 0;
71}
72
75 if (!out)
76 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing spectral output pointer");
77 *out = NULL;
78 if (!c || c->sample_rate < 16000 || c->sample_rate > 192000 ||
79 (c->fft_size != 512 && c->fft_size != 1024 && c->fft_size != 2048) ||
80 !isfinite(c->reduction_db) || c->reduction_db < 0 || c->reduction_db > 60)
81 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid spectral configuration");
82 for (int b = 0; b < 4; ++b) {
83 if (!isfinite(c->ratios[b]) || c->ratios[b] < 1 || c->ratios[b] > 20 ||
84 !isfinite(c->thresholds_db[b]) || c->thresholds_db[b] > 0 ||
85 c->thresholds_db[b] < -90)
86 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid spectral compressor band");
87 if (b < 3 && (!isfinite(c->crossovers[b]) || c->crossovers[b] <= 0 ||
88 c->crossovers[b] > c->sample_rate / 2.0f ||
89 (b && c->crossovers[b] <= c->crossovers[b - 1])))
90 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid spectral crossover");
91 }
93 if (!p)
94 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate spectral processor");
95 p->config = *c;
96 (void)NAMED_REGISTER_MUTEX(&audio_fftw_planner_lock, "audio.fftw_planner",
97 NULL);
98 static_mutex_lock(&audio_fftw_planner_lock);
99 p->forward =
100 fftwf_plan_dft_r2c_1d(c->fft_size, p->time, p->frequency, FFTW_ESTIMATE);
101 p->inverse = fftwf_plan_dft_c2r_1d(c->fft_size, p->frequency, p->restored,
102 FFTW_ESTIMATE);
103 static_mutex_unlock(&audio_fftw_planner_lock);
104 if (!p->forward || !p->inverse) {
106 return SET_ERRNO(ERROR_MEMORY, "Cannot create FFTW plans");
107 }
108 for (int i = 0; i < c->fft_size; ++i)
109 p->window[i] =
110 (float)(0.5 - 0.5 * cos(6.283185307179586 * i / c->fft_size));
112 *out = p;
113 return ASCIICHAT_OK;
114}
115
117 if (!p)
118 return;
119 static_mutex_lock(&audio_fftw_planner_lock);
120 if (p->forward)
121 fftwf_destroy_plan(p->forward);
122 if (p->inverse)
123 fftwf_destroy_plan(p->inverse);
124 static_mutex_unlock(&audio_fftw_planner_lock);
125 SAFE_FREE(p);
126}
127
128static int band_for(const spectral_processor_t *p, int bin) {
129 float hz = (float)bin * p->config.sample_rate / p->config.fft_size;
130 int band = 0;
131 while (band < 3 && hz >= p->config.crossovers[band])
132 ++band;
133 return band;
134}
135
136// Normalized autocorrelation with a two-period minimum observation window.
137static float detect_pitch(spectral_processor_t *p) {
138 int n = p->config.fft_size;
139 int first = p->config.sample_rate / 500;
140 int last = n / 2;
141 if (last > p->config.sample_rate / 70)
142 last = p->config.sample_rate / 70;
143 float correlation[SPECTRAL_MAX_SIZE / 2 + 1] = {0};
144 double mean = 0, power = 0;
145 for (int i = 0; i < n; ++i)
146 mean += p->input[i] / (double)n;
147 for (int i = 0; i < n; ++i)
148 power += (p->input[i] - mean) * (p->input[i] - mean);
149 if (power / n < 1e-6)
150 return 0;
151 float best = 0;
152 for (int lag = first; lag <= last; ++lag) {
153 double cross = 0, a = 0, b = 0;
154 for (int i = 0; i < n - lag; ++i) {
155 double x = p->input[i] - mean, y = p->input[i + lag] - mean;
156 cross += x * y;
157 a += x * x;
158 b += y * y;
159 }
160 correlation[lag] = (float)(cross / sqrt(a * b + 1e-20));
161 if (correlation[lag] > best)
162 best = correlation[lag];
163 }
164 if (best < 0.85f)
165 return 0;
166 for (int lag = first + 1; lag < last; ++lag) {
167 float value = correlation[lag];
168 if (value > 0.95f * best && value > correlation[lag - 1] &&
169 value >= correlation[lag + 1]) {
170 float delta = 0.5f * (correlation[lag - 1] - correlation[lag + 1]) /
171 (correlation[lag - 1] - 2 * value + correlation[lag + 1]);
172 return p->config.sample_rate / (lag + delta);
173 }
174 }
175 return 0;
176}
177
178static void correct_pitch(spectral_processor_t *p) {
179 const double two_pi = 6.283185307179586;
180 int n = p->config.fft_size, hop = n / 4;
181 double factor = 1;
182 if (p->pitch_hz > 0) {
183 double note = round(69 + 12 * log2(p->pitch_hz / 440.0));
184 factor = 440 * pow(2, (note - 69) / 12) / p->pitch_hz;
185 }
186 memset(p->shifted_magnitude, 0, sizeof(p->shifted_magnitude));
187 memset(p->shifted_frequency, 0, sizeof(p->shifted_frequency));
188 for (int k = 0; k <= n / 2; ++k) {
189 double phase = atan2(p->frequency[k][1], p->frequency[k][0]);
190 double expected = two_pi * k * hop / n;
191 double delta = remainder(phase - p->previous_phase[k] - expected, two_pi);
192 p->previous_phase[k] = phase;
193 double frequency = (expected + delta) / hop;
194 int target = (int)round(k * factor);
195 if (target <= n / 2) {
196 double re = p->frequency[k][0];
197 double im = p->frequency[k][1];
198 double magnitude = sqrt(re * re + im * im);
199 p->shifted_magnitude[target] += magnitude;
200 p->shifted_frequency[target] += magnitude * frequency * factor;
201 }
202 }
203 for (int k = 0; k <= n / 2; ++k) {
204 double magnitude = p->shifted_magnitude[k];
205 double frequency = magnitude > 1e-15 ? p->shifted_frequency[k] / magnitude
206 : two_pi * k / n;
207 p->synthesis_phase[k] =
208 remainder(p->synthesis_phase[k] + frequency * hop, two_pi);
209 p->frequency[k][0] = (float)(magnitude * cos(p->synthesis_phase[k]));
210 p->frequency[k][1] = (float)((k == 0 || k == n / 2)
211 ? 0.0
212 : magnitude * sin(p->synthesis_phase[k]));
213 }
214}
215
216static void process_frame(spectral_processor_t *p) {
217 int n = p->config.fft_size, hop = n / 4;
218 float dt = (float)hop / p->config.sample_rate;
219 for (int i = 0; i < n; ++i)
220 p->time[i] = p->input[i] * p->window[i];
221 fftwf_execute(p->forward);
222 float energy[SPECTRAL_BAND_COUNT] = {0};
223 for (int k = 0; k <= n / 2; ++k) {
224 double re = p->frequency[k][0], im = p->frequency[k][1];
225 float power = (float)(re * re + im * im);
226 p->magnitude[k] = sqrtf(power) * ((k == 0 || k == n / 2) ? 2.0f : 4.0f) / n;
227 // Parseval normalization includes the periodic Hann window's mean square
228 // (3/8).
229 energy[band_for(p, k)] +=
230 power * ((k == 0 || k == n / 2) ? 1 : 2) / (n * n * 0.375f);
231 if (p->config.noise_gate) {
232 float level = p->magnitude[k];
233 // Learn only after a complete input window. Falling noise estimates track
234 // quickly; rising estimates move slowly so speech is not learned as
235 // noise.
236 p->smoothed[k] += (1 - expf(-dt / 0.05f)) * (level - p->smoothed[k]);
237 size_t warmup = 3 + (size_t)(0.25f / dt);
238 if (p->frames >= 3 && p->frames < warmup)
239 p->noise[k] += (level - p->noise[k]) / (float)(p->frames - 2);
240 if (p->noise[k] < 1e-9f && level > 1e-9f)
241 p->noise[k] = level;
242 if (p->frames >= warmup) {
243 float tau = p->smoothed[k] < p->noise[k] ? 0.5f : 8.0f;
244 p->noise[k] += (1 - expf(-dt / tau)) * (p->smoothed[k] - p->noise[k]);
245 float ratio = level / fmaxf(p->noise[k], 1e-10f);
246 float floor = powf(10.0f, -p->config.reduction_db / 20.0f);
247 float target =
248 floor + (1 - floor) * fminf(1, fmaxf(0, (ratio - 1.5f) / 2.5f));
249 float coefficient =
250 1 - expf(-dt / (target > p->gains[k] ? 0.005f : 0.08f));
251 p->gains[k] += coefficient * (target - p->gains[k]);
252 }
253 }
254 }
255 float total = energy[0] + energy[1] + energy[2] + energy[3];
256 if (p->config.pitch_correct)
257 p->pitch_hz = detect_pitch(p);
258 if (p->config.auto_gain) {
259 float desired =
260 total > 1e-5f ? fminf(4, fmaxf(0.25f, 0.15f / sqrtf(total))) : 1;
261 p->auto_gain += (1 - expf(-dt / (desired < p->auto_gain ? 0.01f : 0.5f))) *
262 (desired - p->auto_gain);
263 }
264 for (int b = 0; b < 4; ++b) {
265 float db = 10 * log10f(fmaxf(energy[b], 1e-12f));
266 float reduction = fmaxf(0, db - p->config.thresholds_db[b]) *
267 (1 - 1 / p->config.ratios[b]);
268 float target = powf(10, -reduction / 20);
269 p->band_gain[b] +=
270 (1 - expf(-dt / (target < p->band_gain[b] ? 0.01f : 0.15f))) *
271 (target - p->band_gain[b]);
272 // Bounded spectral balancing; no claim of measured room-response inversion.
273 if (total > 1e-6f) {
274 p->band_average[b] +=
275 (1 - expf(-dt / 3)) * (energy[b] - p->band_average[b]);
276 float average = 0;
277 for (int j = 0; j < 4; ++j)
278 average += p->band_average[j] / 4;
279 float eq = sqrtf(average / fmaxf(p->band_average[b], 1e-10f));
280 eq = fminf(1.41254f, fmaxf(0.70795f, eq));
281 p->eq_gain[b] += (1 - expf(-dt / 1)) * (eq - p->eq_gain[b]);
282 }
283 }
284 for (int k = 0; k <= n / 2; ++k) {
285 int b = band_for(p, k);
286 float gain = p->config.noise_gate ? p->gains[k] : 1;
287 if (p->config.compressor)
288 gain *= p->band_gain[b];
289 if (p->config.adaptive_eq)
290 gain *= p->eq_gain[b];
291 if (p->config.auto_gain)
292 gain *= p->auto_gain;
293 p->frequency[k][0] *= gain;
294 p->frequency[k][1] *= gain;
295 }
296 if (p->config.pitch_correct)
297 correct_pitch(p);
298 fftwf_execute(p->inverse);
299 // Four overlapping periodic Hann windows have a constant squared sum of 1.5.
300 for (int i = 0; i < n; ++i)
301 p->overlap[i] += (float)(p->restored[i] * p->window[i] / (n * 1.5));
302 memcpy(p->ready, p->overlap, (size_t)hop * sizeof(float));
303 memmove(p->overlap, p->overlap + hop, (size_t)(n - hop) * sizeof(float));
304 memset(p->overlap + n - hop, 0, (size_t)hop * sizeof(float));
305 memmove(p->input, p->input + hop, (size_t)(n - hop) * sizeof(float));
306 p->frames++;
307}
308
310 float *output, size_t count) {
311 if (!p || (!input && count) || (!output && count))
312 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid spectral buffer");
313 int n = p->config.fft_size, hop = n / 4;
314 for (size_t i = 0; i < count; ++i) {
315 float sample = input[i];
316 output[i] = p->ready[p->cursor++];
317 p->input[n - hop + p->pending++] = isfinite(sample) ? sample : 0;
318 if (p->pending == hop) {
319 process_frame(p);
320 p->pending = p->cursor = 0;
321 }
322 }
323 return ASCIICHAT_OK;
324}
325
326const float *spectral_spectrum(const spectral_processor_t *p, size_t *bins) {
327 if (bins)
328 *bins = p ? (size_t)p->config.fft_size / 2 + 1 : 0;
329 return p ? p->magnitude : NULL;
330}
331
333 return p ? p->pitch_hz : 0;
334}
#define SET_ERRNO(code,...)
Platform initialization and static synchronization helpers.
Named object registry for debugging — log identifiable resource names.
#define SAFE_FREE(ptr)
#define SAFE_CALLOC(count, size, cast)
#define NAMED_REGISTER_MUTEX(mutex, name, parent_ptr)
Register a mutex with automatic format specifier.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define STATIC_MUTEX_INIT
⚙️ Common definitions, error codes, macros, and types shared throughout the application
🔢 Mathematical Utility Functions
static bool size_t gotel_query_t * out
Definition queries.h:10
#define SPECTRAL_MAX_SIZE
Definition spectral.c:9
asciichat_error_t spectral_create(const spectral_config_t *c, spectral_processor_t **out)
Definition spectral.c:73
asciichat_error_t spectral_process(spectral_processor_t *p, const float *input, float *output, size_t count)
Definition spectral.c:309
float spectral_pitch_hz(const spectral_processor_t *p)
Definition spectral.c:332
spectral_config_t spectral_default_config(int sample_rate)
Definition spectral.c:41
static_mutex_t audio_fftw_planner_lock
Definition spectral.c:39
#define SPECTRAL_MAX_BINS
Definition spectral.c:10
void spectral_destroy(spectral_processor_t *p)
Definition spectral.c:116
const float * spectral_spectrum(const spectral_processor_t *p, size_t *bins)
Definition spectral.c:326
void spectral_reset(spectral_processor_t *p)
Definition spectral.c:51
struct spectral_processor spectral_processor_t
Definition spectral.h:15
#define SPECTRAL_BAND_COUNT
Definition spectral.h:4
🔤 String Manipulation and Shell Escaping Utilities
For spectral config, this is the live record that ties sample_rate, fft_size, noise_gate,...
Definition spectral.h:22
float ratios[4]
Definition spectral.h:34
float crossovers[4 - 1]
Definition spectral.h:32
float thresholds_db[4]
Definition spectral.h:33
spectral processor keeps the values that move through the subsystem: config, forward,...
Definition spectral.c:18
float band_gain[SPECTRAL_BAND_COUNT]
Definition spectral.c:28
fftwf_plan forward
Definition spectral.c:20
spectral_config_t config
Definition spectral.c:19
double shifted_frequency[(2048/2+1)]
Definition spectral.c:31
double previous_phase[(2048/2+1)]
Definition spectral.c:29
float band_average[4]
Definition spectral.c:28
float overlap[2048]
Definition spectral.c:23
float eq_gain[4]
Definition spectral.c:28
float restored[2048]
Definition spectral.c:21
float window[2048]
Definition spectral.c:25
float time[2048]
Definition spectral.c:21
float input[2048]
Definition spectral.c:23
float smoothed[(2048/2+1)]
Definition spectral.c:26
double synthesis_phase[(2048/2+1)]
Definition spectral.c:29
fftwf_complex frequency[(2048/2+1)]
Definition spectral.c:22
float gains[(2048/2+1)]
Definition spectral.c:27
double shifted_magnitude[(2048/2+1)]
Definition spectral.c:30
float magnitude[(2048/2+1)]
Definition spectral.c:25
float noise[(2048/2+1)]
Definition spectral.c:26
fftwf_plan inverse
Definition spectral.c:20
float ready[2048/4]
Definition spectral.c:24
Static mutex structure for global mutexes requiring static initialization.
Definition common/sync.h:51