From db61f78e5a8bf317f6c1e6d07aa912981ccdc252 Mon Sep 17 00:00:00 2001 From: KubaPro010 Date: Sun, 3 Aug 2025 16:03:15 +0200 Subject: [PATCH] introduce soft clipping into bs412 --- filter/bs412.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/filter/bs412.c b/filter/bs412.c index c784581..2c01d35 100644 --- a/filter/bs412.c +++ b/filter/bs412.c @@ -26,6 +26,15 @@ void init_bs412(BS412Compressor* mpx, float mpx_deviation, float target_power, f #endif } +float soft_clip_tanh(float sample, float threshold) { + if (fabsf(sample) <= threshold) { + return sample; // Linear region + } + float sign = (sample >= 0) ? 1.0f : -1.0f; + float excess = fabsf(sample) - threshold; + return sign * (threshold + tanhf(excess) * (1.0f - threshold)); +} + float bs412_compress(BS412Compressor* mpx, float sample) { mpx->average += sample * sample * mpx->mpx_deviation * mpx->mpx_deviation; mpx->average_counter++; @@ -57,5 +66,9 @@ float bs412_compress(BS412Compressor* mpx, float sample) { mpx->gain = fmaxf(0.0f, fminf(mpx->max, mpx->gain)); + float output_sample = sample * mpx->gain; + float limit_threshold = dbr_to_deviation(mpx->target + 0.1f) / mpx->mpx_deviation; + output_sample = soft_clip_tanh(output_sample, limit_threshold); + return sample * mpx->gain; }