From c614536b6d2fb9f57271aacc8d032d34607bfc7e Mon Sep 17 00:00:00 2001 From: Kuba <132459354+KubaPro010@users.noreply.github.com> Date: Fri, 8 Aug 2025 22:12:10 +0200 Subject: [PATCH] Update iir.c --- filter/iir.c | 52 ++++++++++++++-------------------------------------- 1 file changed, 14 insertions(+), 38 deletions(-) diff --git a/filter/iir.c b/filter/iir.c index 7a022d5..9b62699 100644 --- a/filter/iir.c +++ b/filter/iir.c @@ -15,47 +15,23 @@ inline float apply_preemphasis(ResistorCapacitor *filter, float sample) { return out; } -void tilt_init(TiltCorrectionFilter* filter, float correction_strength) { - // This filter is a first-order IIR low-shelf filter. - // The difference equation is: y[n] = b0*x[n] + b1*x[n-1] - a1*y[n-1] - // We simplify it to y[n] = x[n] - a1*y[n-1] which acts as a leaky integrator. +void tilt_init(TiltCorrectionFilter* filter, float cutoff_freq, float sample_rate) { + // High-pass filter: H(z) = (1 - z^-1) / (1 - α*z^-1) + float dt = 1.0f / sample_rate; + float tau = 1.0f / (2.0f * M_PI * cutoff_freq); + float alpha = tau / (tau + dt); - // The "correction_strength" is our leaky factor. It is the pole of the filter. - // A value close to 1.0 places the pole very close to the unit circle, - // providing a large boost to low frequencies (and DC). - - if (correction_strength >= 1.0f) { - correction_strength = 0.99999f; // Prevent instability - } - - filter->b0 = 1.0f; - filter->b1 = 0.0f; - filter->a1 = -correction_strength; // The feedback coefficient - - // Reset filter state + filter->alpha = alpha; filter->x_prev = 0.0f; filter->y_prev = 0.0f; } -float tilt(TiltCorrectionFilter* filter, float input_sample) { - // Apply the difference equation: y[n] = b0*x[n] + b1*x[n-1] - a1*y[n-1] - float output_sample = filter->b0 * input_sample + filter->b1 * filter->x_prev - filter->a1 * filter->y_prev; - - // Important: Prevent output from running away due to DC offset accumulation - // This is a simple guard. If the filter becomes unstable or the output - // grows too large, it gets reset. For square waves, the absolute value of the - // output should not significantly exceed the absolute value of the input. - if (fabsf(output_sample) > 2.0f * fabsf(input_sample) && fabsf(input_sample) > 0.001f) { - // This condition indicates the filter state might be diverging. Resetting it. - // You may need to adjust the '2.0f' factor based on your signal. - filter->y_prev = 0; - output_sample = input_sample; - } - - - // Update the state for the next iteration - filter->x_prev = input_sample; - filter->y_prev = output_sample; +float tilt(TiltCorrectionFilter* filter, float input) { + // High-pass filter: y[n] = α*y[n-1] + (x[n] - x[n-1]) + float output = filter->alpha * filter->y_prev + (input - filter->x_prev); - return output_sample; -} \ No newline at end of file + filter->x_prev = input; + filter->y_prev = output; + + return output; +}