返回 CodeWhale
audio.rs
根目录 / crates / notify / src / audio.rs
1 //! Local audio dispatch. Policy decides the cue; this sink never substitutes a
2 //! bell for a missing/unsupported WAV. Tests inject a sink and never call an OS
3 //! player. A single in-flight WAV keeps repeated categories from stacking audio.
4 use super::sound_policy::SoundCue;
5 use std::io::{self, Write};
6 use std::path::{Path, PathBuf};
7
8 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
9 pub enum AudioOutcome {
10 Emitted,
11 Dispatched,
12 Unsupported,
13 Failed,
14 Busy,
15 }
16
17 pub fn emit_terminal(cue: &SoundCue, out: &mut dyn Write) -> AudioOutcome {
18 let bytes: &[u8] = match cue {
19 SoundCue::Bell | SoundCue::Beep => b"\x07",
20 SoundCue::DoubleBell => b"\x07\x07",
21 SoundCue::Whale | SoundCue::File(_) => return AudioOutcome::Unsupported,
22 };
23 if out.write_all(bytes).and_then(|()| out.flush()).is_ok() {
24 AudioOutcome::Emitted
25 } else {
26 AudioOutcome::Failed
27 }
28 }
29
30 pub const WHALE_WAV: &[u8] = include_bytes!("../assets/audio/codewhale-whale-call.wav");
31
32 /// Resolve an external system helper (the audio players `aplay` and the
33 /// pet's `ffplay`, the Linux browser launcher `xdg-open`) from fixed install
34 /// prefixes. The ambient `PATH` is never consulted: an empty (`::`), relative
35 /// (`.`) or repository-local entry would let a checked-out workspace plant a
36 /// helper that Codewhale then runs with the user's authority.
37 ///
38 /// Known limitation: a helper installed only outside these prefixes (a
39 /// custom `~/bin`, a version manager shim) is refused and the caller reports
40 /// the feature as unavailable. That is deliberate — there is no `PATH`
41 /// fallback.
42 pub fn trusted_system_executable(name: &str) -> io::Result<PathBuf> {
43 trusted_player_in(name, &trusted_player_dirs())
44 }
45
46 fn trusted_player_in(name: &str, dirs: &[PathBuf]) -> io::Result<PathBuf> {
47 let file = if cfg!(windows) {
48 format!("{name}.exe")
49 } else {
50 name.to_owned()
51 };
52 dirs.iter()
53 .filter(|dir| dir.is_absolute())
54 .map(|dir| dir.join(&file))
55 .find(|candidate| is_executable_file(candidate))
56 .ok_or_else(|| {
57 io::Error::new(
58 io::ErrorKind::NotFound,
59 format!("`{name}` is not installed in a trusted system location"),
60 )
61 })
62 }
63
64 fn trusted_player_dirs() -> Vec<PathBuf> {
65 #[cfg(unix)]
66 {
67 [
68 "/usr/bin",
69 "/bin",
70 "/usr/local/bin",
71 "/opt/homebrew/bin",
72 "/home/linuxbrew/.linuxbrew/bin",
73 "/run/current-system/sw/bin",
74 ]
75 .into_iter()
76 .map(PathBuf::from)
77 .collect()
78 }
79 #[cfg(windows)]
80 {
81 // Package-manager shim directories from known folders, never PATH.
82 let mut found = Vec::new();
83 if let Some(local) = dirs::data_local_dir() {
84 found.push(local.join("Microsoft").join("WinGet").join("Links"));
85 }
86 if let Some(home) = dirs::home_dir() {
87 found.push(home.join("scoop").join("shims"));
88 }
89 if let Some(data) = std::env::var_os("ProgramData") {
90 found.push(PathBuf::from(data).join("chocolatey").join("bin"));
91 }
92 found
93 }
94 #[cfg(not(any(unix, windows)))]
95 {
96 Vec::new()
97 }
98 }
99
100 fn is_executable_file(path: &Path) -> bool {
101 #[cfg(unix)]
102 {
103 use std::os::unix::fs::PermissionsExt as _;
104 path.metadata()
105 .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
106 }
107 #[cfg(not(unix))]
108 {
109 path.is_file()
110 }
111 }
112
113 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
114 pub fn dispatch(cue: &SoundCue, out: &mut dyn Write) -> AudioOutcome {
115 #[cfg(target_os = "windows")]
116 if matches!(cue, SoundCue::Bell | SoundCue::Beep | SoundCue::DoubleBell) {
117 use windows::Win32::System::Diagnostics::Debug::MessageBeep;
118 use windows::Win32::UI::WindowsAndMessaging::MESSAGEBOX_STYLE;
119 let count = if *cue == SoundCue::DoubleBell { 2 } else { 1 };
120 for _ in 0..count {
121 if unsafe { MessageBeep(MESSAGEBOX_STYLE(0)) }.is_err() {
122 return AudioOutcome::Failed;
123 }
124 }
125 return AudioOutcome::Emitted;
126 }
127 if matches!(cue, SoundCue::Bell | SoundCue::Beep | SoundCue::DoubleBell) {
128 return emit_terminal(cue, out);
129 }
130 dispatch_wav(cue)
131 }
132
133 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
134 pub fn dispatch(_cue: &SoundCue, _out: &mut dyn Write) -> AudioOutcome {
135 // Production entry points are also fail-closed in library and scoped debug tests.
136 AudioOutcome::Unsupported
137 }
138
139 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
140 static PLAYING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
141
142 #[cfg(any(test, not(all(feature = "test-thread-scoped-state", debug_assertions))))]
143 fn spawn_with_latch(
144 playing: &'static std::sync::atomic::AtomicBool,
145 job: impl FnOnce() -> io::Result<()> + Send + 'static,
146 ) -> AudioOutcome {
147 use std::sync::atomic::Ordering;
148 if playing
149 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
150 .is_err()
151 {
152 return AudioOutcome::Busy;
153 }
154 match std::thread::Builder::new()
155 .name("notification-audio".into())
156 .spawn(move || {
157 struct Reset(&'static std::sync::atomic::AtomicBool);
158 impl Drop for Reset {
159 fn drop(&mut self) {
160 self.0.store(false, Ordering::SeqCst);
161 }
162 }
163 let _reset = Reset(playing);
164 if let Err(error) = job() {
165 // Do not log file names or external-player output (both may contain private data).
166 tracing::warn!(kind = ?error.kind(), "notification audio playback failed");
167 }
168 }) {
169 Ok(_) => AudioOutcome::Dispatched,
170 Err(_) => {
171 playing.store(false, Ordering::SeqCst);
172 AudioOutcome::Failed
173 }
174 }
175 }
176
177 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
178 fn dispatch_wav(cue: &SoundCue) -> AudioOutcome {
179 if !cfg!(any(
180 target_os = "windows",
181 target_os = "macos",
182 target_os = "linux"
183 )) {
184 return AudioOutcome::Unsupported;
185 }
186 let cue = cue.clone();
187 spawn_with_latch(&PLAYING, move || play_wav(&cue))
188 }
189
190 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
191 fn play_wav(cue: &SoundCue) -> io::Result<()> {
192 let mut bundled = None;
193 let path = match cue {
194 SoundCue::Whale => {
195 let mut file = tempfile::Builder::new()
196 .prefix("codewhale-call-")
197 .suffix(".wav")
198 .tempfile()?;
199 file.write_all(WHALE_WAV)?;
200 file.flush()?;
201 let path = file.path().to_path_buf();
202 bundled = Some(file);
203 path
204 }
205 SoundCue::File(path) => std::fs::canonicalize(path)?,
206 _ => return Err(io::Error::other("expected WAV cue")),
207 };
208 // Retain the private temporary file until the synchronous player exits.
209 let result = play_file(&path);
210 drop(bundled);
211 result
212 }
213
214 #[cfg(all(
215 not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))),
216 target_os = "windows"
217 ))]
218 fn play_file(path: &std::path::Path) -> io::Result<()> {
219 use std::os::windows::ffi::OsStrExt;
220 use windows::Win32::Media::Audio::{PlaySoundW, SND_FILENAME, SND_NODEFAULT};
221 use windows::core::PCWSTR;
222 let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
223 // Synchronous in the worker: the bundled file must outlive playback.
224 if unsafe { PlaySoundW(PCWSTR(wide.as_ptr()), None, SND_FILENAME | SND_NODEFAULT) }.as_bool() {
225 Ok(())
226 } else {
227 Err(io::Error::other("audio player failed"))
228 }
229 }
230
231 #[cfg(any(
232 all(test, unix),
233 all(
234 not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))),
235 any(target_os = "macos", target_os = "linux")
236 )
237 ))]
238 fn run_player(player: &Path, path: &Path, timeout: std::time::Duration) -> io::Result<()> {
239 let mut child = std::process::Command::new(player)
240 .arg(path)
241 .stdin(std::process::Stdio::null())
242 .stdout(std::process::Stdio::null())
243 .stderr(std::process::Stdio::null())
244 .spawn()?;
245 let deadline = std::time::Instant::now() + timeout;
246 loop {
247 if let Some(status) = child.try_wait()? {
248 return if status.success() {
249 Ok(())
250 } else {
251 Err(io::Error::other("audio player failed"))
252 };
253 }
254 match deadline.checked_duration_since(std::time::Instant::now()) {
255 Some(remaining) if !remaining.is_zero() => {
256 std::thread::sleep(remaining.min(std::time::Duration::from_millis(25)));
257 }
258 _ => {
259 let _ = child.kill();
260 let _ = child.wait();
261 return Err(io::Error::new(
262 io::ErrorKind::TimedOut,
263 "audio player timed out",
264 ));
265 }
266 }
267 }
268 }
269
270 #[cfg(all(
271 not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))),
272 any(target_os = "macos", target_os = "linux")
273 ))]
274 fn play_file(path: &std::path::Path) -> io::Result<()> {
275 const AUDIO_PLAYER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
276 #[cfg(target_os = "macos")]
277 let player = PathBuf::from("/usr/bin/afplay");
278 #[cfg(target_os = "linux")]
279 let player = trusted_system_executable("aplay")?;
280 run_player(&player, path, AUDIO_PLAYER_TIMEOUT)
281 }
282
283 #[cfg(all(
284 not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))),
285 not(any(target_os = "windows", target_os = "macos", target_os = "linux"))
286 ))]
287 fn play_file(_path: &std::path::Path) -> io::Result<()> {
288 Err(io::Error::new(
289 io::ErrorKind::Unsupported,
290 "WAV playback unsupported",
291 ))
292 }
293
294 #[cfg(test)]
295 mod tests {
296 use super::*;
297
298 #[test]
299 fn bundled_whale_is_the_complete_pcm_wav_without_clipped_samples() {
300 assert_eq!(&WHALE_WAV[..4], b"RIFF");
301 assert_eq!(&WHALE_WAV[8..12], b"WAVE");
302 assert_eq!(WHALE_WAV.len(), 136754);
303 assert_eq!(u16::from_le_bytes(WHALE_WAV[22..24].try_into().unwrap()), 1);
304 assert_eq!(
305 u32::from_le_bytes(WHALE_WAV[24..28].try_into().unwrap()),
306 44100
307 );
308 assert_eq!(
309 u16::from_le_bytes(WHALE_WAV[34..36].try_into().unwrap()),
310 16
311 );
312 let samples: Vec<i16> = WHALE_WAV[44..]
313 .as_chunks::<2>()
314 .0
315 .iter()
316 .copied()
317 .map(i16::from_le_bytes)
318 .collect();
319 assert_eq!(samples.first(), Some(&0));
320 assert_eq!(samples.last(), Some(&0));
321 assert!(
322 samples
323 .iter()
324 .all(|sample| *sample != i16::MIN && *sample != i16::MAX)
325 );
326 }
327
328 #[test]
329 fn terminal_sink_has_exact_bell_bytes_and_no_wav_fallback() {
330 for (cue, bytes) in [
331 (SoundCue::Bell, &b"\x07"[..]),
332 (SoundCue::Beep, &b"\x07"[..]),
333 (SoundCue::DoubleBell, &b"\x07\x07"[..]),
334 ] {
335 let mut out = Vec::new();
336 assert_eq!(emit_terminal(&cue, &mut out), AudioOutcome::Emitted);
337 assert_eq!(out, bytes);
338 }
339 for cue in [SoundCue::Whale, SoundCue::File("missing.wav".into())] {
340 let mut out = Vec::new();
341 assert_eq!(emit_terminal(&cue, &mut out), AudioOutcome::Unsupported);
342 assert!(out.is_empty());
343 }
344 }
345
346 #[test]
347 fn trusted_player_needs_an_executable_file_under_an_absolute_prefix() {
348 assert!(trusted_player_dirs().iter().all(|dir| dir.is_absolute()));
349 let dir = tempfile::tempdir().unwrap();
350 let name = "codewhale-test-player";
351 let file = dir.path().join(if cfg!(windows) {
352 format!("{name}.exe")
353 } else {
354 name.to_string()
355 });
356 let prefixes = [dir.path().to_path_buf()];
357 assert!(trusted_player_in(name, &prefixes).is_err(), "absent");
358 std::fs::write(&file, b"").unwrap();
359 #[cfg(unix)]
360 {
361 use std::os::unix::fs::PermissionsExt as _;
362 assert!(
363 trusted_player_in(name, &prefixes).is_err(),
364 "a non-executable file is not a player"
365 );
366 std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o755)).unwrap();
367 }
368 assert_eq!(trusted_player_in(name, &prefixes).unwrap(), file);
369 }
370
371 #[test]
372 fn production_audio_entry_is_silent_in_library_tests() {
373 let mut out = Vec::new();
374 assert_eq!(
375 dispatch(&SoundCue::Whale, &mut out),
376 AudioOutcome::Unsupported
377 );
378 assert_eq!(
379 dispatch(&SoundCue::Bell, &mut out),
380 AudioOutcome::Unsupported
381 );
382 assert!(out.is_empty());
383 }
384
385 #[test]
386 fn busy_latch_rejects_concurrent_dispatch_and_resets_after_worker_finishes() {
387 use std::sync::atomic::{AtomicBool, Ordering};
388 static LATCH: AtomicBool = AtomicBool::new(false);
389 let (started_tx, started_rx) = std::sync::mpsc::channel();
390 let (release_tx, release_rx) = std::sync::mpsc::channel();
391
392 assert_eq!(
393 spawn_with_latch(&LATCH, move || {
394 started_tx.send(()).unwrap();
395 release_rx.recv().unwrap();
396 Ok(())
397 }),
398 AudioOutcome::Dispatched
399 );
400 started_rx
401 .recv_timeout(std::time::Duration::from_secs(2))
402 .unwrap();
403 assert_eq!(spawn_with_latch(&LATCH, || Ok(())), AudioOutcome::Busy);
404 release_tx.send(()).unwrap();
405
406 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
407 while LATCH.load(Ordering::SeqCst) {
408 assert!(
409 std::time::Instant::now() < deadline,
410 "busy latch never reset"
411 );
412 std::thread::sleep(std::time::Duration::from_millis(10));
413 }
414 assert_eq!(
415 spawn_with_latch(&LATCH, || Ok(())),
416 AudioOutcome::Dispatched
417 );
418 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
419 while LATCH.load(Ordering::SeqCst) {
420 assert!(
421 std::time::Instant::now() < deadline,
422 "second latch never reset"
423 );
424 std::thread::sleep(std::time::Duration::from_millis(10));
425 }
426 }
427
428 #[cfg(unix)]
429 #[test]
430 fn hung_player_is_killed_on_timeout_and_releases_busy_latch() {
431 use std::os::unix::fs::PermissionsExt as _;
432 use std::sync::atomic::{AtomicBool, Ordering};
433 static HUNG_LATCH: AtomicBool = AtomicBool::new(false);
434
435 let dir = tempfile::tempdir().unwrap();
436 let fake_player = dir.path().join("hang-player");
437 std::fs::write(&fake_player, b"#!/bin/sh\nexec sleep 30\n").unwrap();
438 std::fs::set_permissions(&fake_player, std::fs::Permissions::from_mode(0o755)).unwrap();
439 let wav = dir.path().join("cue.wav");
440 std::fs::write(&wav, b"").unwrap();
441
442 let started = std::time::Instant::now();
443 let err = run_player(&fake_player, &wav, std::time::Duration::from_millis(100))
444 .expect_err("hung player must time out");
445 assert_eq!(err.kind(), io::ErrorKind::TimedOut);
446 assert!(started.elapsed() < std::time::Duration::from_secs(2));
447
448 let player_for_worker = fake_player.clone();
449 let wav_for_worker = wav.clone();
450 assert_eq!(
451 spawn_with_latch(&HUNG_LATCH, move || {
452 run_player(
453 &player_for_worker,
454 &wav_for_worker,
455 std::time::Duration::from_millis(150),
456 )
457 }),
458 AudioOutcome::Dispatched
459 );
460 assert_eq!(spawn_with_latch(&HUNG_LATCH, || Ok(())), AudioOutcome::Busy);
461
462 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
463 while HUNG_LATCH.load(Ordering::SeqCst) {
464 assert!(
465 std::time::Instant::now() < deadline,
466 "busy latch remained stuck after hung player timeout"
467 );
468 std::thread::sleep(std::time::Duration::from_millis(15));
469 }
470 assert_eq!(
471 spawn_with_latch(&HUNG_LATCH, || Ok(())),
472 AudioOutcome::Dispatched
473 );
474 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
475 while HUNG_LATCH.load(Ordering::SeqCst) {
476 assert!(std::time::Instant::now() < deadline);
477 std::thread::sleep(std::time::Duration::from_millis(10));
478 }
479 }
480 }
481
481 lines RUST