ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
effects.c
Go to the documentation of this file.
3#include <math.h>
4
5#ifndef M_PI
6#define M_PI 3.14159265358979323846
7#endif
8
9// Utility functions
10float db_to_linear(float db) { return powf(10.0f, db / 20.0f); }
11
12float linear_to_db(float linear) {
13 return 20.0f * log10f(fmaxf(linear, 1e-12f));
14}
15
16float clamp_float(float value, float min, float max) {
17 if (value < min) {
18 return min;
19 }
20 if (value > max) {
21 return max;
22 }
23 return value;
24}
25
26// Compressor implementation
27void compressor_init(compressor_t *comp, float sample_rate) {
28 comp->sample_rate = sample_rate;
29 comp->envelope = 0.0f;
30 comp->gain_lin = 1.0f;
31
32 // Set default parameters with 0dB makeup gain (unity)
33 // Soft clip at 0.7 provides 3dB headroom to prevent hard clipping
34 // Ducking and crowd scaling naturally reduce volume, no compensation needed
35 compressor_set_params(comp, -10.0f, 4.0f, 10 * NS_PER_MS_INT,
36 100 * NS_PER_MS_INT, 0.0f);
37}
38
39void compressor_set_params(compressor_t *comp, float threshold_dB, float ratio,
40 uint64_t attack_ns, uint64_t release_ns,
41 float makeup_dB) {
42 comp->threshold_dB = threshold_dB;
43 comp->ratio = ratio;
44 comp->attack_ns = attack_ns;
45 comp->release_ns = release_ns;
46 comp->makeup_dB = makeup_dB;
47 comp->knee_dB = 2.0f; // Fixed soft knee
48
49 // Calculate time constants
50 float attack_tau = (float)attack_ns / (float)NS_PER_SEC;
51 float release_tau = (float)release_ns / (float)NS_PER_SEC;
52 comp->attack_coeff = expf(-1.0f / (attack_tau * comp->sample_rate + 1e-12f));
53 comp->release_coeff =
54 expf(-1.0f / (release_tau * comp->sample_rate + 1e-12f));
55}
56
57static float compressor_gain_reduction_db(const compressor_t *comp,
58 float level_dB) {
59 float over = level_dB - comp->threshold_dB;
60 float knee = comp->knee_dB;
61
62 if (knee > 0.0f) {
63 if (over <= -knee * 0.5f)
64 return 0.0f;
65 if (over >= knee * 0.5f)
66 return (1.0f / comp->ratio - 1.0f) * over;
67 float x = over + knee * 0.5f;
68 return (1.0f / comp->ratio - 1.0f) * (x * x) / (2.0f * knee);
69 }
70 if (over <= 0.0f) {
71 return 0.0f;
72 }
73 return (1.0f / comp->ratio - 1.0f) * over;
74}
75
76float compressor_process_sample(compressor_t *comp, float sidechain) {
77 float x = fabsf(sidechain);
78
79 // Update envelope with attack/release
80 if (x > comp->envelope)
81 comp->envelope =
82 comp->attack_coeff * comp->envelope + (1.0f - comp->attack_coeff) * x;
83 else
84 comp->envelope =
85 comp->release_coeff * comp->envelope + (1.0f - comp->release_coeff) * x;
86
87 // Calculate gain reduction
88 float level_dB = linear_to_db(comp->envelope);
89 float gr_dB = compressor_gain_reduction_db(comp, level_dB);
90 float target_lin = db_to_linear(gr_dB + comp->makeup_dB);
91
92 // Smooth gain changes
93 if (target_lin < comp->gain_lin)
94 comp->gain_lin = comp->attack_coeff * comp->gain_lin +
95 (1.0f - comp->attack_coeff) * target_lin;
96 else
97 comp->gain_lin = comp->release_coeff * comp->gain_lin +
98 (1.0f - comp->release_coeff) * target_lin;
99
100 return comp->gain_lin;
101}
102
103/* ============================================================================
104 * Noise Gate Implementation
105 * ============================================================================
106 */
107
108void noise_gate_init(noise_gate_t *gate, float sample_rate) {
109 if (!gate)
110 return;
111
112 gate->sample_rate = sample_rate;
113 gate->envelope = 0.0f;
114 gate->gate_open = false;
115
116 // Default parameters
117 // Slower attack (10ms) prevents clicking artifacts during gate transitions
118 // threshold=0.01, attack=10ms, release=50ms, hysteresis=0.9
119 noise_gate_set_params(gate, 0.01f, 10 * NS_PER_MS_INT, 50 * NS_PER_MS_INT,
120 0.9f);
121}
122
123void noise_gate_set_params(noise_gate_t *gate, float threshold,
124 uint64_t attack_ns, uint64_t release_ns,
125 float hysteresis) {
126 if (!gate)
127 return;
128
129 gate->threshold = threshold;
130 gate->attack_ns = attack_ns;
131 gate->release_ns = release_ns;
132 gate->hysteresis = hysteresis;
133
134 // Calculate coefficients for envelope follower
135 // Using exponential moving average: coeff = 1 - exp(-1 / (time_s *
136 // sample_rate))
137 float attack_s = (float)attack_ns / (float)NS_PER_SEC;
138 float release_s = (float)release_ns / (float)NS_PER_SEC;
139 gate->attack_coeff =
140 1.0f - expf(-1.0f / (attack_s * gate->sample_rate + 1e-12f));
141 gate->release_coeff =
142 1.0f - expf(-1.0f / (release_s * gate->sample_rate + 1e-12f));
143}
144
146 float peak_amplitude) {
147 if (!gate)
148 return input;
149
150 // Determine target state with hysteresis
151 float target;
152 if (gate->gate_open) {
153 // Gate is open - use lower threshold (hysteresis) to close
154 target =
155 (peak_amplitude > gate->threshold * gate->hysteresis) ? 1.0f : 0.0f;
156 } else {
157 // Gate is closed - use normal threshold to open
158 target = (peak_amplitude > gate->threshold) ? 1.0f : 0.0f;
159 }
160
161 // Update gate state
162 gate->gate_open = (target > 0.5f);
163
164 // Update envelope with appropriate coefficient
165 float coeff =
166 (target > gate->envelope) ? gate->attack_coeff : gate->release_coeff;
167 gate->envelope += coeff * (target - gate->envelope);
168
169 // Apply gate
170 return input * gate->envelope;
171}
172
173void noise_gate_process_buffer(noise_gate_t *gate, float *buffer,
174 int num_samples) {
175 if (!gate || !buffer || num_samples <= 0)
176 return;
177
178 // First pass: find peak amplitude
179 float peak = 0.0f;
180 for (int i = 0; i < num_samples; i++) {
181 float abs_sample = fabsf(buffer[i]);
182 if (abs_sample > peak) {
183 peak = abs_sample;
184 }
185 }
186
187 // Second pass: apply gate
188 for (int i = 0; i < num_samples; i++) {
189 buffer[i] = noise_gate_process_sample(gate, buffer[i], peak);
190 }
191}
192
194 return gate ? gate->gate_open : false;
195}
196
197/* ============================================================================
198 * High-Pass Filter Implementation
199 * ============================================================================
200 */
201
202void highpass_filter_init(highpass_filter_t *filter, float cutoff_hz,
203 float sample_rate) {
204 if (!filter)
205 return;
206
207 filter->cutoff_hz = cutoff_hz;
208 filter->sample_rate = sample_rate;
209
210 // Calculate filter coefficient
211 // alpha = 1 / (1 + 2*pi*fc/fs)
212 filter->alpha = 1.0f / (1.0f + 2.0f * (float)M_PI * cutoff_hz / sample_rate);
213
214 highpass_filter_reset(filter);
215}
216
218 if (!filter)
219 return;
220
221 filter->prev_input = 0.0f;
222 filter->prev_output = 0.0f;
223}
224
226 if (!filter)
227 return input;
228
229 // First-order high-pass filter
230 // y[n] = alpha * (y[n-1] + x[n] - x[n-1])
231 float output =
232 filter->alpha * (filter->prev_output + input - filter->prev_input);
233
234 filter->prev_input = input;
235 filter->prev_output = output;
236
237 return output;
238}
239
241 int num_samples) {
242 if (!filter || !buffer || num_samples <= 0)
243 return;
244
245 for (int i = 0; i < num_samples; i++) {
246 buffer[i] = highpass_filter_process_sample(filter, buffer[i]);
247 }
248}
249
250/* ============================================================================
251 * Low-Pass Filter Implementation
252 * ============================================================================
253 */
254
255void lowpass_filter_init(lowpass_filter_t *filter, float cutoff_hz,
256 float sample_rate) {
257 if (!filter)
258 return;
259
260 filter->cutoff_hz = cutoff_hz;
261 filter->sample_rate = sample_rate;
262
263 // Calculate filter coefficient using RC time constant formula
264 // alpha = dt / (RC + dt) where RC = 1 / (2 * pi * fc)
265 float dt = 1.0f / sample_rate;
266 float rc = 1.0f / (2.0f * (float)M_PI * cutoff_hz);
267 filter->alpha = dt / (rc + dt);
268
269 lowpass_filter_reset(filter);
270}
271
273 if (!filter)
274 return;
275
276 filter->prev_output = 0.0f;
277}
278
280 if (!filter)
281 return input;
282
283 // First-order IIR low-pass filter: y[n] = alpha * x[n] + (1 - alpha) * y[n-1]
284 float output =
285 filter->alpha * input + (1.0f - filter->alpha) * filter->prev_output;
286
287 filter->prev_output = output;
288
289 return output;
290}
291
293 int num_samples) {
294 if (!filter || !buffer || num_samples <= 0)
295 return;
296
297 for (int i = 0; i < num_samples; i++) {
298 buffer[i] = lowpass_filter_process_sample(filter, buffer[i]);
299 }
300}
301
302/* ============================================================================
303 * Soft Clipping Implementation
304 * ============================================================================
305 */
306
307float soft_clip(float sample, float threshold, float steepness) {
308 if (sample > threshold) {
309 // Soft clip positive values using tanh curve
310 // Maps samples above threshold asymptotically toward 1.0
311 return threshold +
312 (1.0f - threshold) * tanhf((sample - threshold) * steepness);
313 }
314 if (sample < -threshold) {
315 // Soft clip negative values symmetrically
316 return -threshold +
317 (-1.0f + threshold) * tanhf((sample + threshold) * steepness);
318 }
319 return sample;
320}
321
322void soft_clip_buffer(float *buffer, int num_samples, float threshold,
323 float steepness) {
324 if (!buffer || num_samples <= 0)
325 return;
326
327 for (int i = 0; i < num_samples; i++) {
328 buffer[i] = soft_clip(buffer[i], threshold, steepness);
329 }
330}
331
332/* ============================================================================
333 * Buffer Utility Functions
334 * ============================================================================
335 */
336
337float smoothstep(float t) {
338 if (t <= 0.0f)
339 return 0.0f;
340 if (t >= 1.0f)
341 return 1.0f;
342 return t * t * (3.0f - 2.0f * t);
343}
344
345int16_t float_to_int16(float sample) {
346 // Clamp to [-1, 1] then scale to int16 range
347 if (sample > 1.0f)
348 sample = 1.0f;
349 if (sample < -1.0f)
350 sample = -1.0f;
351 return (int16_t)(sample * 32767.0f);
352}
353
354float int16_to_float(int16_t sample) { return (float)sample / 32768.0f; }
355
356void buffer_float_to_int16(const float *src, int16_t *dst, int count) {
357 if (!src || !dst || count <= 0)
358 return;
359 for (int i = 0; i < count; i++) {
360 dst[i] = float_to_int16(src[i]);
361 }
362}
363
364void buffer_int16_to_float(const int16_t *src, float *dst, int count) {
365 if (!src || !dst || count <= 0)
366 return;
367 for (int i = 0; i < count; i++) {
368 dst[i] = int16_to_float(src[i]);
369 }
370}
371
372float buffer_peak(const float *buffer, int count) {
373 if (!buffer || count <= 0)
374 return 0.0f;
375
376 float peak = 0.0f;
377 for (int i = 0; i < count; i++) {
378 float abs_sample = fabsf(buffer[i]);
379 if (abs_sample > peak)
380 peak = abs_sample;
381 }
382 return peak;
383}
384
385void apply_gain_buffer(float *buffer, int count, float gain) {
386 if (!buffer || count <= 0)
387 return;
388
389 for (int i = 0; i < count; i++) {
390 buffer[i] *= gain;
391 }
392}
393
394void fade_buffer(float *buffer, int count, float start_gain, float end_gain) {
395 if (!buffer || count <= 0)
396 return;
397
398 float step = (end_gain - start_gain) / (float)count;
399 float gain = start_gain;
400 for (int i = 0; i < count; i++) {
401 buffer[i] *= gain;
402 gain += step;
403 }
404}
405
406void fade_buffer_smooth(float *buffer, int count, bool fade_in) {
407 if (!buffer || count <= 0)
408 return;
409
410 for (int i = 0; i < count; i++) {
411 float t = (float)i / (float)(count - 1);
412 float gain = smoothstep(fade_in ? t : (1.0f - t));
413 buffer[i] *= gain;
414 }
415}
416
417void copy_buffer_with_gain(const float *src, float *dst, int count,
418 float gain) {
419 if (!src || !dst || count <= 0)
420 return;
421
422 for (int i = 0; i < count; i++) {
423 dst[i] = src[i] * gain;
424 }
425}
#define M_PI
Definition effects.c:6
float hysteresis
Hysteresis factor (0-1, prevents gate chatter).
Definition mixer.h:195
float release_coeff
Release coefficient (converted from release_ms).
Definition mixer.h:204
bool noise_gate_is_open(const noise_gate_t *gate)
Check if noise gate is currently open.
Definition effects.c:193
void copy_buffer_with_gain(const float *src, float *dst, int count, float gain)
Copy buffer with gain scaling.
Definition effects.c:417
void noise_gate_process_buffer(noise_gate_t *gate, float *buffer, int num_samples)
Process a buffer of samples through noise gate.
Definition effects.c:173
void buffer_float_to_int16(const float *src, int16_t *dst, int count)
Convert float buffer to int16 buffer.
Definition effects.c:356
float alpha
Filter coefficient alpha (calculated from cutoff_hz).
Definition mixer.h:236
float clamp_float(float value, float min, float max)
Clamp a float value to a range.
Definition effects.c:16
float ratio
Compression ratio (e.g., 4.0 for 4:1 compression).
Definition mixer.h:145
void highpass_filter_reset(highpass_filter_t *filter)
Reset high-pass filter state.
Definition effects.c:217
float sample_rate
Sample rate in Hz (set during initialization).
Definition mixer.h:233
void soft_clip_buffer(float *buffer, int num_samples, float threshold, float steepness)
Apply soft clipping to a buffer.
Definition effects.c:322
float prev_input
Previous input sample (filter state).
Definition mixer.h:238
float prev_output
Previous output sample (filter state).
Definition mixer.h:269
float highpass_filter_process_sample(highpass_filter_t *filter, float input)
Process a single sample through high-pass filter.
Definition effects.c:225
float envelope
Current envelope follower state (linear, 0-1).
Definition mixer.h:156
float cutoff_hz
Cutoff frequency in Hz (frequencies above this are attenuated).
Definition mixer.h:262
void apply_gain_buffer(float *buffer, int count, float gain)
Apply gain to buffer in-place.
Definition effects.c:385
void noise_gate_init(noise_gate_t *gate, float sample_rate)
Initialize a noise gate.
Definition effects.c:108
float buffer_peak(const float *buffer, int count)
Find peak absolute value in buffer.
Definition effects.c:372
float cutoff_hz
Cutoff frequency in Hz (frequencies below this are attenuated).
Definition mixer.h:231
float soft_clip(float sample, float threshold, float steepness)
Apply soft clipping to a sample.
Definition effects.c:307
float sample_rate
Sample rate in Hz (set during initialization).
Definition mixer.h:198
float knee_dB
Knee width in dB for soft knee (e.g., 2.0).
Definition mixer.h:143
void fade_buffer(float *buffer, int count, float start_gain, float end_gain)
Apply linear fade to buffer in-place.
Definition effects.c:394
void compressor_init(compressor_t *comp, float sample_rate)
Initialize a compressor.
Definition effects.c:27
float alpha
Filter coefficient alpha (calculated from cutoff_hz).
Definition mixer.h:267
void compressor_set_params(compressor_t *comp, float threshold_dB, float ratio, uint64_t attack_ns, uint64_t release_ns, float makeup_dB)
Set compressor parameters.
Definition effects.c:39
uint64_t attack_ns
Attack time in nanoseconds (how fast gate opens).
Definition mixer.h:191
void highpass_filter_init(highpass_filter_t *filter, float cutoff_hz, float sample_rate)
Initialize a high-pass filter.
Definition effects.c:202
float int16_to_float(int16_t sample)
Convert int16 sample to float.
Definition effects.c:354
float threshold_dB
Compression threshold in dB (e.g., -10.0).
Definition mixer.h:141
float envelope
Current envelope follower state (linear, 0-1).
Definition mixer.h:200
float sample_rate
Sample rate in Hz (set during initialization).
Definition mixer.h:154
bool gate_open
True if gate is currently open (allowing audio through).
Definition mixer.h:206
float smoothstep(float t)
Compute smoothstep interpolation.
Definition effects.c:337
void fade_buffer_smooth(float *buffer, int count, bool fade_in)
Apply smoothstep fade to buffer in-place.
Definition effects.c:406
int16_t float_to_int16(float sample)
Convert float sample to int16 (WebRTC format).
Definition effects.c:345
float sample_rate
Sample rate in Hz (set during initialization).
Definition mixer.h:264
void lowpass_filter_init(lowpass_filter_t *filter, float cutoff_hz, float sample_rate)
Initialize a low-pass filter.
Definition effects.c:255
float db_to_linear(float db)
Convert decibels to linear gain.
Definition effects.c:10
void lowpass_filter_process_buffer(lowpass_filter_t *filter, float *buffer, int num_samples)
Process a buffer of samples through low-pass filter.
Definition effects.c:292
uint64_t release_ns
Release time in nanoseconds (how fast gate closes).
Definition mixer.h:193
void highpass_filter_process_buffer(highpass_filter_t *filter, float *buffer, int num_samples)
Process a buffer of samples through high-pass filter.
Definition effects.c:240
float makeup_dB
Makeup gain in dB (compensates for gain reduction).
Definition mixer.h:151
float compressor_process_sample(compressor_t *comp, float sidechain)
Process a single sample through compressor.
Definition effects.c:76
uint64_t attack_ns
Attack time in nanoseconds (how fast compression kicks in).
Definition mixer.h:147
float lowpass_filter_process_sample(lowpass_filter_t *filter, float input)
Process a single sample through low-pass filter.
Definition effects.c:279
void noise_gate_set_params(noise_gate_t *gate, float threshold, uint64_t attack_ns, uint64_t release_ns, float hysteresis)
Set noise gate parameters.
Definition effects.c:123
float linear_to_db(float linear)
Convert linear gain to decibels.
Definition effects.c:12
uint64_t release_ns
Release time in nanoseconds (how fast compression releases).
Definition mixer.h:149
void lowpass_filter_reset(lowpass_filter_t *filter)
Reset low-pass filter state.
Definition effects.c:272
float attack_coeff
Attack coefficient (converted from attack_ms).
Definition mixer.h:160
void buffer_int16_to_float(const int16_t *src, float *dst, int count)
Convert int16 buffer to float buffer.
Definition effects.c:364
float threshold
Gate threshold in linear units (e.g., 0.01f for -40dB).
Definition mixer.h:189
float prev_output
Previous output sample (filter state).
Definition mixer.h:240
float release_coeff
Release coefficient (converted from release_ms).
Definition mixer.h:162
float gain_lin
Current gain multiplier (linear, calculated from envelope).
Definition mixer.h:158
float attack_coeff
Attack coefficient (converted from attack_ms).
Definition mixer.h:202
float noise_gate_process_sample(noise_gate_t *gate, float input, float peak_amplitude)
Process a single sample through noise gate.
Definition effects.c:145
unsigned long long uint64_t
#define NS_PER_MS_INT
Definition time.h:172
#define NS_PER_SEC
Definition time.h:164
🔢 Mathematical Utility Functions
Multi-Source Audio Mixing and Processing System.
Dynamic range compressor settings and state.
Definition mixer.h:139
noise gate keeps the values that move through the subsystem: threshold, attack_ns,...
Definition mixer.h:229
This is the handoff point for highpass filter. Callers fill cutoff_hz, sample_rate,...
Definition mixer.h:260
This is the handoff point for compressor. Callers fill threshold_dB, knee_dB, ratio,...
Definition mixer.h:187
⏱️ High-precision timing utilities using sokol_time.h and uthash