BlueGit

ict rusty-teams

Files

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

linux_sound.rs

linux_sound.rs 15.9 KiB Download Raw
1//! Linux and macOS notification and ringtone playback.
2//!
3//! On Linux the saved call output is a Pulse sink description or name. Tones go to that
4//! sink. When the Pulse daemon is not running, Linux uses the same cpal lookup as macOS.
5//! A sink that disappears while a tone is playing falls back to the system default.
6
7use std::collections::HashSet;
8use std::io::Cursor;
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::{Arc, LazyLock, Mutex};
11use std::time::Duration;
12
13use rodio::Source;
14use rodio::cpal::traits::{DeviceTrait, HostTrait};
15
16const SOUND_BYTES: &[u8] = include_bytes!("../../../../app/assets/sounds/notification.mp3");
17const POLL: Duration = Duration::from_millis(20);
18static SOUND_OUTPUT: Mutex<Option<String>> = Mutex::new(None);
19static LOGGED_MISSES: LazyLock<Mutex<HashSet<String>>> =
20 LazyLock::new(|| Mutex::new(HashSet::new()));
21
22pub fn set_sound_output(device_key: Option<String>) {
23 *SOUND_OUTPUT.lock().unwrap_or_else(|p| p.into_inner()) = device_key;
24}
25
26/// One Pulse sink, as listed by the daemon.
27#[derive(Clone)]
28pub(crate) struct PulseSink {
29 pub name: String,
30 pub description: String,
31}
32
33/// Trim, drop one leading `default:` prefix, then ASCII-lowercase.
34pub(crate) fn normalized_audio_key(value: &str) -> String {
35 let trimmed = value.trim();
36 let rest = strip_default_prefix(trimmed).trim();
37 rest.to_ascii_lowercase()
38}
39
40fn strip_default_prefix(value: &str) -> &str {
41 const PREFIX: &str = "default:";
42 if value.len() >= PREFIX.len() && value[..PREFIX.len()].eq_ignore_ascii_case(PREFIX) {
43 &value[PREFIX.len()..]
44 } else {
45 value
46 }
47}
48
49/// Exact name or description match. A Game sink does not satisfy a Chat key.
50pub(crate) fn matching_sink<'a>(sinks: &'a [PulseSink], key: &str) -> Option<&'a PulseSink> {
51 let key = normalized_audio_key(key);
52 if key.is_empty() {
53 return None;
54 }
55 sinks.iter().find(|sink| {
56 normalized_audio_key(&sink.name) == key || normalized_audio_key(&sink.description) == key
57 })
58}
59
60/// True the first time this key is reported missing.
61fn claim_miss(key: &str) -> bool {
62 LOGGED_MISSES
63 .lock()
64 .unwrap_or_else(|p| p.into_inner())
65 .insert(key.to_owned())
66}
67
68fn note_missing_once(key: &str, message: String) {
69 if claim_miss(key) {
70 crate::diagnostics::record(message);
71 }
72}
73
74/// True when a call-output key names this cpal device (id or friendly name).
75pub(crate) fn device_matches_key(device_id: &str, device_name: &str, key: &str) -> bool {
76 let key = key.trim();
77 if key.is_empty() {
78 return false;
79 }
80 if device_id == key || device_name == key {
81 return true;
82 }
83 let key_lower = key.to_ascii_lowercase();
84 let id_lower = device_id.to_ascii_lowercase();
85 let name_lower = device_name.to_ascii_lowercase();
86 id_lower == key_lower
87 || name_lower == key_lower
88 || (!key_lower.contains(' ') && id_lower.contains(&key_lower))
89 || (key_lower.len() >= 4 && name_lower.contains(&key_lower))
90}
91
92struct Decoded {
93 rate: u32,
94 channels: u16,
95 samples: Vec<f32>,
96}
97
98fn decode(bytes: &[u8]) -> Result<Decoded, String> {
99 let decoder = rodio::Decoder::try_from(Cursor::new(bytes.to_vec()))
100 .map_err(|error| format!("cannot decode notification sound: {error}"))?;
101 let rate = decoder.sample_rate().get();
102 let channels = decoder.channels().get();
103 let samples = decoder.collect();
104 Ok(Decoded {
105 rate,
106 channels,
107 samples,
108 })
109}
110
111fn play_on_rodio(
112 sink: &mut rodio::MixerDeviceSink,
113 bytes: Vec<u8>,
114 looped: bool,
115 stop: &AtomicBool,
116) -> Result<(), String> {
117 sink.log_on_drop(false);
118 loop {
119 if stop.load(Ordering::SeqCst) {
120 return Ok(());
121 }
122 let player = rodio::play(sink.mixer(), Cursor::new(bytes.clone()))
123 .map_err(|error| format!("cannot decode notification sound: {error}"))?;
124 while !player.empty() {
125 if stop.load(Ordering::SeqCst) {
126 player.stop();
127 return Ok(());
128 }
129 std::thread::sleep(POLL);
130 }
131 if !looped {
132 return Ok(());
133 }
134 }
135}
136
137fn open_default_and_play(bytes: Vec<u8>, looped: bool, stop: &AtomicBool) -> Result<(), String> {
138 let mut sink = rodio::DeviceSinkBuilder::open_default_sink()
139 .map_err(|error| format!("cannot open audio output: {error}"))?;
140 play_on_rodio(&mut sink, bytes, looped, stop)
141}
142
143fn open_sink() -> Result<rodio::MixerDeviceSink, String> {
144 let chosen = SOUND_OUTPUT
145 .lock()
146 .unwrap_or_else(|poisoned| poisoned.into_inner())
147 .clone();
148 if let Some(key) = chosen.as_ref() {
149 if let Some(device) = rodio::cpal::default_host()
150 .output_devices()
151 .ok()
152 .into_iter()
153 .flatten()
154 .find(|device| {
155 let id = device.id().ok().map(|id| id.1).unwrap_or_default();
156 let name = device
157 .description()
158 .ok()
159 .map(|description| description.name().to_owned())
160 .unwrap_or_default();
161 device_matches_key(&id, &name, key)
162 })
163 {
164 match rodio::DeviceSinkBuilder::from_device(device)
165 .and_then(|builder| builder.open_stream())
166 {
167 Ok(sink) => return Ok(sink),
168 Err(error) => crate::diagnostics::record(format!(
169 "sound: selected output {key:?} failed ({error}), using system default"
170 )),
171 }
172 } else {
173 crate::diagnostics::record(format!(
174 "sound: selected output {key:?} not found, using system default"
175 ));
176 }
177 }
178 rodio::DeviceSinkBuilder::open_default_sink()
179 .map_err(|error| format!("cannot open audio output: {error}"))
180}
181
182#[cfg(target_os = "linux")]
183fn pulse_sinks() -> Option<Vec<PulseSink>> {
184 use libpulse_binding::callbacks::ListResult;
185 use libpulse_binding::context::{Context, FlagSet, State};
186 use libpulse_binding::mainloop::standard::Mainloop;
187
188 let mut mainloop = Mainloop::new()?;
189 let mut context = Context::new(&mainloop, "rusty-teams")?;
190 context.connect(None, FlagSet::NOAUTOSPAWN, None).ok()?;
191 let deadline = std::time::Instant::now() + Duration::from_millis(400);
192 loop {
193 if std::time::Instant::now() > deadline {
194 return None;
195 }
196 let _ = mainloop.iterate(false);
197 match context.get_state() {
198 State::Ready => break,
199 State::Failed | State::Terminated => return None,
200 _ => std::thread::sleep(Duration::from_millis(5)),
201 }
202 }
203 let found = Arc::new(Mutex::new(Vec::new()));
204 let done = Arc::new(AtomicBool::new(false));
205 let found_cb = Arc::clone(&found);
206 let done_cb = Arc::clone(&done);
207 let operation = context
208 .introspect()
209 .get_sink_info_list(move |item| match item {
210 ListResult::Item(info) => found_cb
211 .lock()
212 .unwrap_or_else(|poisoned| poisoned.into_inner())
213 .push(PulseSink {
214 name: info.name.as_deref().unwrap_or("").to_owned(),
215 description: info.description.as_deref().unwrap_or("").to_owned(),
216 }),
217 ListResult::End | ListResult::Error => done_cb.store(true, Ordering::SeqCst),
218 });
219 while !done.load(Ordering::SeqCst) {
220 if std::time::Instant::now() > deadline {
221 return None;
222 }
223 let _ = mainloop.iterate(false);
224 std::thread::sleep(Duration::from_millis(5));
225 }
226 drop(operation);
227 Some(
228 found
229 .lock()
230 .unwrap_or_else(|poisoned| poisoned.into_inner())
231 .clone(),
232 )
233}
234
235#[cfg(target_os = "linux")]
236fn play_on_pulse(
237 sink_name: &str,
238 decoded: &Decoded,
239 looped: bool,
240 stop: &AtomicBool,
241) -> Result<(), String> {
242 use libpulse_binding::sample::{Format, Spec};
243 use libpulse_binding::stream::Direction;
244 use libpulse_simple_binding::Simple;
245
246 let channels =
247 u8::try_from(decoded.channels).map_err(|_| "too many audio channels".to_owned())?;
248 let spec = Spec {
249 format: Format::FLOAT32NE,
250 channels,
251 rate: decoded.rate,
252 };
253 if !spec.is_valid() {
254 return Err(format!(
255 "pulse cannot play {} Hz {} ch",
256 decoded.rate, decoded.channels
257 ));
258 }
259 let simple = Simple::new(
260 None,
261 "rusty-teams",
262 Direction::Playback,
263 Some(sink_name),
264 "call tone",
265 &spec,
266 None,
267 None,
268 )
269 .map_err(|error| format!("pulse open {sink_name}: {error}"))?;
270 let frame = decoded.channels as usize;
271 let chunk = (decoded.rate as usize / 10).max(1) * frame.max(1);
272 loop {
273 for piece in decoded.samples.chunks(chunk.max(1)) {
274 if stop.load(Ordering::SeqCst) {
275 return Ok(());
276 }
277 let mut bytes = Vec::with_capacity(piece.len() * 4);
278 for sample in piece {
279 bytes.extend_from_slice(&sample.to_ne_bytes());
280 }
281 simple
282 .write(&bytes)
283 .map_err(|error| format!("pulse write: {error}"))?;
284 }
285 if !looped {
286 simple
287 .drain()
288 .map_err(|error| format!("pulse drain: {error}"))?;
289 return Ok(());
290 }
291 }
292}
293
294#[cfg(target_os = "linux")]
295fn play_linux(bytes: Vec<u8>, looped: bool, stop: &AtomicBool) -> Result<(), String> {
296 let key = SOUND_OUTPUT
297 .lock()
298 .unwrap_or_else(|poisoned| poisoned.into_inner())
299 .clone();
300 if let Some(key) = key.filter(|key| !normalized_audio_key(key).is_empty()) {
301 match pulse_sinks() {
302 Some(sinks) => {
303 if let Some(sink) = matching_sink(&sinks, &key) {
304 let decoded = decode(&bytes)?;
305 match play_on_pulse(&sink.name, &decoded, looped, stop) {
306 Ok(()) => return Ok(()),
307 Err(error)
308 if error.starts_with("pulse open ")
309 || error.starts_with("pulse cannot play")
310 || error.starts_with("pulse write")
311 || error.starts_with("pulse drain") =>
312 {
313 note_missing_once(
314 &key,
315 format!(
316 "sound: selected output {key:?} failed ({error}), using system default"
317 ),
318 );
319 }
320 Err(error) => return Err(error),
321 }
322 } else {
323 note_missing_once(
324 &key,
325 format!("sound: selected output {key:?} not found, using system default"),
326 );
327 }
328 }
329 None => {
330 note_missing_once(
331 &format!("pulse:{key}"),
332 format!("sound: pulse unavailable for {key:?}, trying the device list"),
333 );
334 let mut sink = open_sink()?;
335 return play_on_rodio(&mut sink, bytes, looped, stop);
336 }
337 }
338 }
339 open_default_and_play(bytes, looped, stop)
340}
341
342fn play(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) -> Result<(), String> {
343 if stop.load(Ordering::SeqCst) {
344 return Ok(());
345 }
346 #[cfg(target_os = "linux")]
347 {
348 return play_linux(bytes, looped, &stop);
349 }
350 #[cfg(not(target_os = "linux"))]
351 {
352 let mut sink = open_sink()?;
353 play_on_rodio(&mut sink, bytes, looped, &stop)
354 }
355}
356
357pub fn play_mp3_until(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) {
358 std::thread::spawn(move || {
359 if let Err(error) = play(bytes, looped, stop) {
360 crate::diagnostics::record(format!("sound: {error}"));
361 }
362 });
363}
364
365pub fn play_mp3(bytes: Vec<u8>) {
366 play_mp3_until(bytes, false, Arc::new(AtomicBool::new(false)));
367}
368
369pub fn play_sound() {
370 play_mp3(SOUND_BYTES.to_vec());
371}
372
373#[cfg(test)]
374mod tests {
375 use super::*;
376
377 fn sink(name: &str, description: &str) -> PulseSink {
378 PulseSink {
379 name: name.to_owned(),
380 description: description.to_owned(),
381 }
382 }
383
384 fn headset_sinks() -> Vec<PulseSink> {
385 vec![
386 sink("alsa_output.headset.mono-chat", "Headset Chat"),
387 sink("alsa_output.headset.stereo-game", "Headset Game"),
388 ]
389 }
390
391 #[test]
392 fn bundled_notification_decodes_to_audible_samples() {
393 let decoded = rodio::Decoder::try_from(Cursor::new(SOUND_BYTES)).unwrap();
394 assert!(decoded.take(48000).any(|sample| sample.abs() > 0.001));
395 }
396
397 #[test]
398 fn cancelled_playback_does_not_open_a_device_or_decode_audio() {
399 assert!(play(Vec::new(), true, Arc::new(AtomicBool::new(true))).is_ok());
400 }
401
402 #[test]
403 fn call_output_keys_match_cpal_ids_and_friendly_names() {
404 assert!(device_matches_key(
405 "sink-a",
406 "Front Speakers",
407 "Front Speakers"
408 ));
409 assert!(device_matches_key("sink-a", "Front Speakers", "sink-a"));
410 assert!(device_matches_key(
411 "sink-a",
412 "Front Speakers",
413 "front speakers"
414 ));
415 assert!(device_matches_key(
416 "alsa_output.pci-0000_00_1f.3.analog-stereo",
417 "Built-in Audio Analog Stereo",
418 "alsa_output.pci-0000_00_1f.3.analog-stereo"
419 ));
420 assert!(!device_matches_key(
421 "sink-a",
422 "Front Speakers",
423 "Headphones"
424 ));
425 assert!(!device_matches_key("id", "Speaker", ""));
426 }
427
428 #[test]
429 fn a_pulse_description_selects_that_sink_and_not_the_other_output() {
430 let sinks = headset_sinks();
431 let game = matching_sink(&sinks, "Headset Game").unwrap();
432 assert_eq!(game.name, "alsa_output.headset.stereo-game");
433 let prefixed = matching_sink(&sinks, "default: Headset Game").unwrap();
434 assert_eq!(prefixed.name, "alsa_output.headset.stereo-game");
435 let chat = matching_sink(&sinks, "Headset Chat").unwrap();
436 assert_eq!(chat.name, "alsa_output.headset.mono-chat");
437 assert!(matching_sink(&sinks, "Headset Game").unwrap().name != chat.name);
438 assert!(matching_sink(&sinks, "missing output").is_none());
439 assert!(matching_sink(&sinks, "Game").is_none());
440 }
441
442 #[test]
443 fn a_missing_key_is_noted_once() {
444 let key = format!("missing-output-{}", std::process::id());
445 assert!(claim_miss(&key));
446 assert!(!claim_miss(&key));
447 assert!(claim_miss(&format!("{key}-other")));
448 }
449
450 #[test]
451 #[ignore = "plays a short notification on the real default audio output"]
452 fn notification_plays_on_default_output() {
453 play(
454 SOUND_BYTES.to_vec(),
455 false,
456 Arc::new(AtomicBool::new(false)),
457 )
458 .unwrap();
459 }
460
461 #[cfg(target_os = "linux")]
462 #[test]
463 #[ignore = "plays a short tone on the Pulse sink named by CALL_OUTPUT_KEY"]
464 fn selected_pulse_sink_plays_the_tone() {
465 let key = std::env::var("CALL_OUTPUT_KEY").expect("CALL_OUTPUT_KEY");
466 let sinks = pulse_sinks().expect("pulse");
467 let sink = matching_sink(&sinks, &key).unwrap_or_else(|| {
468 panic!(
469 "no sink for {key:?}; have {}",
470 sinks
471 .iter()
472 .map(|sink| format!("{} ({})", sink.description, sink.name))
473 .collect::<Vec<_>>()
474 .join(", ")
475 )
476 });
477 eprintln!("pulse sink {} ({})", sink.name, sink.description);
478 set_sound_output(Some(key));
479 play(
480 SOUND_BYTES.to_vec(),
481 false,
482 Arc::new(AtomicBool::new(false)),
483 )
484 .unwrap();
485 }
486}