BlueGit

ict rusty-teams

Files

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

linux_sound.rs

linux_sound.rs 5.2 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
48 .id()
49 .ok()
50 .map(|id| id.1)
51 .unwrap_or_default();
52 let name = device
53 .description()
54 .ok()
55 .map(|description| description.name().to_owned())
56 .unwrap_or_default();
57 device_matches_key(&id, &name, key)
58 })
59 {
60 match rodio::DeviceSinkBuilder::from_device(device).and_then(|builder| builder.open_stream())
61 {
62 Ok(sink) => return Ok(sink),
63 Err(error) => crate::diagnostics::record(format!(
64 "sound: selected output {key:?} failed ({error}), using system default"
65 )),
66 }
67 } else {
68 crate::diagnostics::record(format!(
69 "sound: selected output {key:?} not found, using system default"
70 ));
71 }
72 }
73 rodio::DeviceSinkBuilder::open_default_sink()
74 .map_err(|e| format!("cannot open audio output: {e}"))
75}
76
77fn play(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) -> Result<(), String> {
78 if stop.load(Ordering::SeqCst) {
79 return Ok(());
80 }
81 let mut sink = open_sink()?;
82 sink.log_on_drop(false);
83 loop {
84 if stop.load(Ordering::SeqCst) {
85 return Ok(());
86 }
87 let player = rodio::play(sink.mixer(), Cursor::new(bytes.clone()))
88 .map_err(|e| format!("cannot decode notification sound: {e}"))?;
89 while !player.empty() {
90 if stop.load(Ordering::SeqCst) {
91 player.stop();
92 return Ok(());
93 }
94 std::thread::sleep(POLL);
95 }
96 if !looped {
97 return Ok(());
98 }
99 }
100}
101
102pub fn play_mp3_until(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) {
103 std::thread::spawn(move || {
104 if let Err(error) = play(bytes, looped, stop) {
105 crate::diagnostics::record(format!("sound: {error}"));
106 }
107 });
108}
109
110pub fn play_mp3(bytes: Vec<u8>) {
111 play_mp3_until(bytes, false, Arc::new(AtomicBool::new(false)));
112}
113
114pub fn play_sound() {
115 play_mp3(SOUND_BYTES.to_vec());
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121
122 #[test]
123 fn bundled_notification_decodes_to_audible_samples() {
124 let decoded = rodio::Decoder::try_from(Cursor::new(SOUND_BYTES)).unwrap();
125 assert!(decoded.take(48000).any(|sample| sample.abs() > 0.001));
126 }
127
128 #[test]
129 fn cancelled_playback_does_not_open_a_device_or_decode_audio() {
130 assert!(play(Vec::new(), true, Arc::new(AtomicBool::new(true))).is_ok());
131 }
132
133 #[test]
134 fn call_output_keys_match_cpal_ids_and_friendly_names() {
135 assert!(device_matches_key("sink-a", "Front Speakers", "Front Speakers"));
136 assert!(device_matches_key("sink-a", "Front Speakers", "sink-a"));
137 assert!(device_matches_key("sink-a", "Front Speakers", "front speakers"));
138 assert!(device_matches_key(
139 "alsa_output.pci-0000_00_1f.3.analog-stereo",
140 "Built-in Audio Analog Stereo",
141 "alsa_output.pci-0000_00_1f.3.analog-stereo"
142 ));
143 assert!(!device_matches_key("sink-a", "Front Speakers", "Headphones"));
144 assert!(!device_matches_key("id", "Speaker", ""));
145 }
146
147 #[test]
148 #[ignore = "plays a short notification on the real default audio output"]
149 fn notification_plays_on_default_output() {
150 play(
151 SOUND_BYTES.to_vec(),
152 false,
153 Arc::new(AtomicBool::new(false)),
154 )
155 .unwrap();
156 }
157}