BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / mixer.rs

mixer.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
mixer.rs 1.7 KiB Download Raw
1use crate::audio::FRAME_SAMPLES;
2
3pub 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 {
7 0
8 } else {
9 i32::from(microphone.get(index).copied().unwrap_or(0))
10 };
11 let sound = i32::from(computer.get(index).copied().unwrap_or(0));
12 (mic + sound).clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
13 })
14 .collect()
15}
16
17#[cfg(test)]
18mod tests {
19 use super::*;
20
21 #[test]
22 fn the_two_sources_are_summed() {
23 let mixed = mix_frames(&[100; FRAME_SAMPLES], &[-30; FRAME_SAMPLES], false);
24 assert_eq!(mixed.len(), FRAME_SAMPLES);
25 assert!(mixed.iter().all(|&sample| sample == 70));
26 }
27
28 #[test]
29 fn the_sum_clips_instead_of_wrapping() {
30 let loud = [i16::MAX - 10; FRAME_SAMPLES];
31 assert!(
32 mix_frames(&loud, &loud, false)
33 .iter()
34 .all(|&sample| sample == i16::MAX)
35 );
36 let low = [i16::MIN + 10; FRAME_SAMPLES];
37 assert!(
38 mix_frames(&low, &low, false)
39 .iter()
40 .all(|&sample| sample == i16::MIN)
41 );
42 }
43
44 #[test]
45 fn muting_drops_only_the_microphone() {
46 let mixed = mix_frames(&[500; FRAME_SAMPLES], &[200; FRAME_SAMPLES], true);
47 assert!(mixed.iter().all(|&sample| sample == 200));
48 }
49
50 #[test]
51 fn a_short_source_counts_as_silence_for_the_rest() {
52 let mixed = mix_frames(&[10; 4], &[1; FRAME_SAMPLES], false);
53 assert_eq!(&mixed[..5], &[11, 11, 11, 11, 1]);
54 }
55}