From 1b522fb3db8a583d6d0dd7b836d8aef944ad5ebc Mon Sep 17 00:00:00 2001 From: "Ram.Type-0" <39725073+RamType0@users.noreply.github.com> Date: Fri, 14 Jan 2022 20:23:30 +0900 Subject: [PATCH] Faster sample format conversion (#618) * Remove branch in `u16::to_i16` and `i16::to_u16` If optimizations are at least at level 1, the conversions compile down to the same code as the old one, but if they are turned off, the new code is faster. * Faster conversion from `f32` to `u16` The new code is faster in release mode. --- src/samples_formats.rs | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/src/samples_formats.rs b/src/samples_formats.rs index 480fc0b..27d48a4 100644 --- a/src/samples_formats.rs +++ b/src/samples_formats.rs @@ -51,11 +51,7 @@ unsafe impl Sample for u16 { #[inline] fn to_i16(&self) -> i16 { - if *self >= 32768 { - (*self - 32768) as i16 - } else { - (*self as i16) - 32767 - 1 - } + (*self as i16).wrapping_add(i16::MIN) } #[inline] @@ -91,11 +87,7 @@ unsafe impl Sample for i16 { #[inline] fn to_u16(&self) -> u16 { - if *self < 0 { - (*self - i16::MIN) as u16 - } else { - (*self as u16) + 32768 - } + self.wrapping_add(i16::MIN) as u16 } #[inline] @@ -106,7 +98,7 @@ unsafe impl Sample for i16 { sample.to_i16() } } - +const F32_TO_16BIT_INT_MULTIPLIER: f32 = u16::MAX as f32 * 0.5; unsafe impl Sample for f32 { const FORMAT: SampleFormat = SampleFormat::F32; @@ -126,7 +118,8 @@ unsafe impl Sample for f32 { #[inline] fn to_u16(&self) -> u16 { - (((*self + 1.0) * 0.5) * u16::MAX as f32).round() as u16 + self.mul_add(F32_TO_16BIT_INT_MULTIPLIER, F32_TO_16BIT_INT_MULTIPLIER) + .round() as u16 } #[inline]