From 83d8c7a9f4e75dda9e181a94109af93f44fdcad3 Mon Sep 17 00:00:00 2001 From: Robbert van der Helm Date: Wed, 20 Jul 2022 20:11:24 +0200 Subject: [PATCH] Add a formatter for compression ratios --- src/formatters.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/formatters.rs b/src/formatters.rs index 5c0f6958..697a5504 100644 --- a/src/formatters.rs +++ b/src/formatters.rs @@ -36,6 +36,30 @@ pub fn s2v_f32_percentage() -> Arc Option + Send + Sync> { }) } +/// Format a positive number as a compression ratio. A value of 4 will be formatted as `4.0:1` while +/// 0.25 is formatted as `1:4.0`. +pub fn v2s_compression_ratio(digits: usize) -> Arc String + Send + Sync> { + Arc::new(move |value| { + if value >= 1.0 { + format!("{:.digits$}:1", value) + } else { + format!("1:{:.digits$}", value.recip()) + } + }) +} + +/// Parse a `x:y` compression ratio back to a floating point number. Used in conjunction with +/// [`v2s_compression_ratio()`]. +pub fn s2v_compression_ratio() -> Arc Option + Send + Sync> { + Arc::new(|string| { + let (numerator, denominator) = string.trim().split_once(':')?; + let numerator: f32 = numerator.trim().parse().ok()?; + let denominator: f32 = denominator.trim().parse().ok()?; + + Some(numerator / denominator) + }) +} + /// Turn an `f32` value from voltage gain to decibels using the semantics described in /// [`util::gain_to_db()]. You should use either `" dB"` or `" dBFS"` for the parameter's unit. pub fn v2s_f32_gain_to_db(digits: usize) -> Arc String + Send + Sync> {