BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / notify / platform / linux_sound.rs

linux_sound.rs

78236dde History
linux_sound.rs 5.3 KiB Download Raw
1//! Linux and macOS notification and ringtone playback through the system audio output.
2use std::io::Cursor;
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::{Arc, Mutex};
5use std::time::Duration;
6
7use rodio::cpal::traits::{DeviceTrait, HostTrait};
8
9const SOUND_BYTES: &[u8] = include_bytes!("../../../../app/assets/sounds/notification.mp3");
10const POLL: Duration = Duration::from_millis(20);
11static SOUND_OUTPUT: Mutex<Option<String>> = Mutex::new(None);
12
13pub fn set_sound_output(device_key: Option<String>) {
14 *SOUND_OUTPUT.lock().unwrap_or_else(|p| p.into_inner()) = device_key;
15}
16
17/// True when a call-output key names this cpal device (id, friendly name, or Pulse-style id).
18pub(crate) fn device_matches_key(device_id: &str, device_name: &str, key: &str) -> bool {
19 let key = key.trim();
20 if key.is_empty() {
21 return false;
22 }
23 if device_id == key || device_name == key {
24 return true;
25 }
26 let key_lower = key.to_ascii_lowercase();
27 let id_lower = device_id.to_ascii_lowercase();
28 let name_lower = device_name.to_ascii_lowercase();
29 id_lower == key_lower
30 || name_lower == key_lower
31 || (!key_lower.contains(' ') && id_lower.contains(&key_lower))
32 || (key_lower.len() >= 4 && name_lower.contains(&key_lower))
33}
34
35fn open_sink() -> Result<rodio::MixerDeviceSink, String> {
36 let chosen = SOUND_OUTPUT
37 .lock()
38 .unwrap_or_else(|p| p.into_inner())
39 .clone();
40 if let Some(key) = chosen.as_ref() {
41 if let Some(device) = rodio::cpal::default_host()
42 .output_devices()
43 .ok()
44 .into_iter()
45 .flatten()
46 .find(|device| {
47 let id = device.id().ok().map(|id| id.1).unwrap_or_default();
48 let name = device
49 .description()
50 .ok()
51 .map(|description| description.name().to_owned())
52 .unwrap_or_default();
53 device_matches_key(&id, &name, key)
54 })
55 {
56 match rodio::DeviceSinkBuilder::from_device(device)
57 .and_then(|builder| builder.open_stream())
58 {
59 Ok(sink) => return Ok(sink),
60 Err(error) => crate::diagnostics::record(format!(
61 "sound: selected output {key:?} failed ({error}), using system default"
62 )),
63 }
64 } else {
65 crate::diagnostics::record(format!(
66 "sound: selected output {key:?} not found, using system default"
67 ));
68 }
69 }
70 rodio::DeviceSinkBuilder::open_default_sink()
71 .map_err(|e| format!("cannot open audio output: {e}"))
72}
73
74fn play(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) -> Result<(), String> {
75 if stop.load(Ordering::SeqCst) {
76 return Ok(());
77 }
78 let mut sink = open_sink()?;
79 sink.log_on_drop(false);
80 loop {
81 if stop.load(Ordering::SeqCst) {
82 return Ok(());
83 }
84 let player = rodio::play(sink.mixer(), Cursor::new(bytes.clone()))
85 .map_err(|e| format!("cannot decode notification sound: {e}"))?;
86 while !player.empty() {
87 if stop.load(Ordering::SeqCst) {
88 player.stop();
89 return Ok(());
90 }
91 std::thread::sleep(POLL);
92 }
93 if !looped {
94 return Ok(());
95 }
96 }
97}
98
99pub fn play_mp3_until(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) {
100 std::thread::spawn(move || {
101 if let Err(error) = play(bytes, looped, stop) {
102 crate::diagnostics::record(format!("sound: {error}"));
103 }
104 });
105}
106
107pub fn play_mp3(bytes: Vec<u8>) {
108 play_mp3_until(bytes, false, Arc::new(AtomicBool::new(false)));
109}
110
111pub fn play_sound() {
112 play_mp3(SOUND_BYTES.to_vec());
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118
119 #[test]
120 fn bundled_notification_decodes_to_audible_samples() {
121 let decoded = rodio::Decoder::try_from(Cursor::new(SOUND_BYTES)).unwrap();
122 assert!(decoded.take(48000).any(|sample| sample.abs() > 0.001));
123 }
124
125 #[test]
126 fn cancelled_playback_does_not_open_a_device_or_decode_audio() {
127 assert!(play(Vec::new(), true, Arc::new(AtomicBool::new(true))).is_ok());
128 }
129
130 #[test]
131 fn call_output_keys_match_cpal_ids_and_friendly_names() {
132 assert!(device_matches_key(
133 "sink-a",
134 "Front Speakers",
135 "Front Speakers"
136 ));
137 assert!(device_matches_key("sink-a", "Front Speakers", "sink-a"));
138 assert!(device_matches_key(
139 "sink-a",
140 "Front Speakers",
141 "front speakers"
142 ));
143 assert!(device_matches_key(
144 "alsa_output.pci-0000_00_1f.3.analog-stereo",
145 "Built-in Audio Analog Stereo",
146 "alsa_output.pci-0000_00_1f.3.analog-stereo"
147 ));
148 assert!(!device_matches_key(
149 "sink-a",
150 "Front Speakers",
151 "Headphones"
152 ));
153 assert!(!device_matches_key("id", "Speaker", ""));
154 }
155
156 #[test]
157 #[ignore = "plays a short notification on the real default audio output"]
158 fn notification_plays_on_default_output() {
159 play(
160 SOUND_BYTES.to_vec(),
161 false,
162 Arc::new(AtomicBool::new(false)),
163 )
164 .unwrap();
165 }
166}