diff --git a/src/samples_formats.rs b/src/samples_formats.rs index e11db03..63d5950 100644 --- a/src/samples_formats.rs +++ b/src/samples_formats.rs @@ -44,7 +44,7 @@ impl Sample for u16 { if value >= 32768 { (value - 32768) as i16 } else { - (value as i16) - 32767 + (value as i16) - 32767 - 1 } }).collect()) } @@ -70,7 +70,7 @@ impl Sample for i16 { fn to_vec_u16(input: &[i16]) -> Cow, [u16]> { Cow::Owned(input.iter().map(|&value| { if value < 0 { - (value + 32767) as u16 + (value + 32767) as u16 + 1 } else { (value as u16) + 32768 } @@ -79,7 +79,11 @@ impl Sample for i16 { fn to_vec_f32(input: &[i16]) -> Cow, [f32]> { Cow::Owned(input.iter().map(|&value| { - value as f32 / 32768.0 + if value > 0 { + value as f32 / 32767.0 + } else { + value as f32 / 32768.0 + } }).collect()) } } @@ -101,3 +105,64 @@ impl Sample for f32 { Cow::Borrowed(input) } } + +#[cfg(test)] +mod test { + use super::Sample; + + #[test] + fn i16_to_i16() { + let out = Sample::to_vec_i16(&[0i16, -467, 32767, -32768]).into_owned(); + assert_eq!(out, vec![0, -467, 32767, -32768]); + } + + #[test] + fn i16_to_u16() { + let out = Sample::to_vec_u16(&[0i16, -16384, 32767, -32768]).into_owned(); + assert_eq!(out, vec![32768, 16384, 65535, 0]); + } + + #[test] + fn i16_to_f32() { + let out = Sample::to_vec_f32(&[0i16, -16384, 32767, -32768]).into_owned(); + assert_eq!(out, vec![0.0, -0.5, 1.0, -1.0]); + } + + #[test] + fn u16_to_i16() { + let out = Sample::to_vec_i16(&[32768u16, 16384, 65535, 0]).into_owned(); + assert_eq!(out, vec![0, -16384, 32767, -32768]); + } + + #[test] + fn u16_to_u16() { + let out = Sample::to_vec_u16(&[0u16, 467, 32767, 65535]).into_owned(); + assert_eq!(out, vec![0, 467, 32767, 65535]); + } + + #[test] + fn u16_to_f32() { + let out = Sample::to_vec_f32(&[0u16, 32768, 65535]).into_owned(); + assert_eq!(out, vec![-1.0, 0.0, 1.0]); + } + + #[test] + #[ignore] // TODO: not yet implemented + fn f32_to_i16() { + let out = Sample::to_vec_i16(&[0.0f32, -0.5, 1.0, -1.0]).into_owned(); + assert_eq!(out, vec![0, -16384, 32767, -32768]); + } + + #[test] + #[ignore] // TODO: not yet implemented + fn f32_to_u16() { + let out = Sample::to_vec_u16(&[-1.0f32, 0.0, 1.0]).into_owned(); + assert_eq!(out, vec![0, 32768, 65535]); + } + + #[test] + fn f32_to_f32() { + let out = Sample::to_vec_f32(&[0.1f32, -0.7, 1.0]).into_owned(); + assert_eq!(out, vec![0.1, -0.7, 1.0]); + } +}