| 1 | use crate::audio::FRAME_SAMPLES; |
| 2 | |
| 3 | pub fn mix_frames(microphone: &[i16], computer: &[i16], microphone_muted: bool) -> Vec<i16> { |
| 4 | (0..FRAME_SAMPLES) |
| 5 | .map(|index| { |
| 6 | let mic = if microphone_muted { 0 } else { i32::from(microphone.get(index).copied().unwrap_or(0)) }; |
| 7 | let sound = i32::from(computer.get(index).copied().unwrap_or(0)); |
| 8 | (mic + sound).clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16 |
| 9 | }) |
| 10 | .collect() |
| 11 | } |
| 12 | |
| 13 | #[cfg(test)] |
| 14 | mod tests { |
| 15 | use super::*; |
| 16 | |
| 17 | #[test] |
| 18 | fn the_two_sources_are_summed() { |
| 19 | let mixed = mix_frames(&[100; FRAME_SAMPLES], &[-30; FRAME_SAMPLES], false); |
| 20 | assert_eq!(mixed.len(), FRAME_SAMPLES); |
| 21 | assert!(mixed.iter().all(|&sample| sample == 70)); |
| 22 | } |
| 23 | |
| 24 | #[test] |
| 25 | fn the_sum_clips_instead_of_wrapping() { |
| 26 | let loud = [i16::MAX - 10; FRAME_SAMPLES]; |
| 27 | assert!(mix_frames(&loud, &loud, false).iter().all(|&sample| sample == i16::MAX)); |
| 28 | let low = [i16::MIN + 10; FRAME_SAMPLES]; |
| 29 | assert!(mix_frames(&low, &low, false).iter().all(|&sample| sample == i16::MIN)); |
| 30 | } |
| 31 | |
| 32 | #[test] |
| 33 | fn muting_drops_only_the_microphone() { |
| 34 | let mixed = mix_frames(&[500; FRAME_SAMPLES], &[200; FRAME_SAMPLES], true); |
| 35 | assert!(mixed.iter().all(|&sample| sample == 200)); |
| 36 | } |
| 37 | |
| 38 | #[test] |
| 39 | fn a_short_source_counts_as_silence_for_the_rest() { |
| 40 | let mixed = mix_frames(&[10; 4], &[1; FRAME_SAMPLES], false); |
| 41 | assert_eq!(&mixed[..5], &[11, 11, 11, 11, 1]); |
| 42 | } |
| 43 | } |