nsh_core/audio.rs
1//! Audio playback (`nsh`'s `Sound` and `AudioPlayer`;
2//! `docs/dev/audio-design.md`): short sounds decoded once and played any
3//! number of times, overlapping, and long audio streamed by a player.
4//!
5//! The two are two things on every platform, as kira's static and
6//! streaming sounds are: a **sound** is its bytes, decoded by the platform
7//! into memory at [`AudioCommand::Load`] and played from there by
8//! [`AudioCommand::Play`], each play a voice of its own on the platform's
9//! mixer, so `play` opens, fetches and decodes nothing. A **player** streams
10//! its source as `<Video>` does, on the same engines, and has a player's
11//! state: position, duration, pause, seek, rate, loop.
12//!
13//! Every sound and player is an object of the engine with an id the core
14//! gives it ([`ids`]); its events come from the platform as
15//! [`EventKind::Audio`](crate::EventKind::Audio)s on the root
16//! ([`EventPayload::Audio`](crate::EventPayload::Audio)), or from an
17//! [`AudioBackend`] the embedding app gave the core
18//! ([`Core::set_audio`](crate::Core::set_audio), `EngineConfig::audio`),
19//! which then plays everything and the platform nothing. Tests fake it the
20//! same way.
21//!
22//! The limits are the core's ([`MAX_SOUND_BYTES`], [`MAX_SOUND_DURATION`],
23//! [`MAX_SOUNDS`], [`MAX_DECODED_BYTES`]), so a bundle cannot raise them;
24//! the decoded length travels to the platform ([`AudioCommand::Load`]'s
25//! `max_duration`) so a small file that expands to minutes is never decoded
26//! whole, and the core checks what the platform reports.
27
28use std::{
29 collections::VecDeque,
30 sync::{Arc, Mutex},
31 task::{Poll, Waker},
32 time::Duration,
33};
34
35use crate::image::ImageData;
36
37/// The largest sound, encoded (its file, its `data:` URI's bytes).
38pub const MAX_SOUND_BYTES: usize = 8 << 20;
39
40/// The longest sound, decoded: longer audio is a player's.
41pub const MAX_SOUND_DURATION: Duration = Duration::from_secs(5);
42
43/// Sounds loaded at once per engine (a source loaded twice counts once).
44pub const MAX_SOUNDS: usize = 64;
45
46/// Decoded audio of the sounds loaded at once per engine.
47pub const MAX_DECODED_BYTES: u64 = 16 << 20;
48
49/// Voices of sounds playing at once per engine: past it the platform stops
50/// the oldest.
51pub const MAX_VOICES: usize = 32;
52
53/// How often a player playing reports its position.
54pub const PROGRESS_INTERVAL: Duration = Duration::from_millis(250);
55
56/// The lowest and highest volume (silent, as recorded).
57pub const VOLUME: std::ops::RangeInclusive<f32> = 0.0..=1.0;
58
59/// The slowest and fastest playback rate.
60pub const RATE: std::ops::RangeInclusive<f32> = 0.5..=2.0;
61
62/// The media type a sound file's first bytes say it is, for bytes the app
63/// gives without a name ([`crate::element::SoundSource::Bytes`]): the
64/// decoders that go by a file's name or type read it from this.
65/// `application/octet-stream` when no format is recognized (the platform's
66/// decoder looks at the bytes alone).
67pub(crate) fn sniff(bytes: &[u8]) -> &'static str {
68 let at = |offset: usize, magic: &[u8]| bytes.get(offset..offset + magic.len()) == Some(magic);
69 if at(0, b"RIFF") && at(8, b"WAVE") {
70 "audio/wav"
71 } else if at(0, b"FORM") && (at(8, b"AIFF") || at(8, b"AIFC")) {
72 "audio/aiff"
73 } else if at(0, b"caff") {
74 "audio/x-caf"
75 } else if at(0, b"fLaC") {
76 "audio/flac"
77 } else if at(0, b"OggS") {
78 "audio/ogg"
79 } else if at(4, b"ftyp") {
80 "audio/mp4"
81 } else if at(0, b"ID3") {
82 "audio/mpeg"
83 } else if let [0xFF, second, ..] = bytes {
84 // An MPEG audio frame's sync word: layer bits 00 are AAC's ADTS,
85 // the others MP3's.
86 match second & 0xF6 {
87 0xF0 => "audio/aac",
88 _ if second & 0xE0 == 0xE0 => "audio/mpeg",
89 _ => "application/octet-stream",
90 }
91 } else {
92 "application/octet-stream"
93 }
94}
95
96/// What the core asks of the platform (on the root,
97/// [`crate::Command::Audio`]). Ids are the engine's: a sound's and a
98/// player's are never the same.
99#[derive(Debug, Clone, PartialEq)]
100#[non_exhaustive]
101pub enum AudioCommand {
102 /// Decode sound `id`'s bytes into memory, at most `max_duration` of
103 /// them, and report [`AudioEvent::Loaded`] (with `truncated` when there
104 /// was more) or [`AudioEvent::Failed`].
105 Load {
106 /// The sound.
107 id: u32,
108 /// Its encoded bytes.
109 bytes: ImageData,
110 /// Its file name or URL, for decoders that go by the extension.
111 hint: String,
112 /// How much to decode at most.
113 max_duration: Duration,
114 },
115 /// Fetch sound `id`'s bytes from `url` (an `asset:/` URI, or an
116 /// `http(s)` URL the core checked) and decode them as
117 /// [`Self::Load`] does: where the platform fetches and the core reads
118 /// nothing (the web). More than `max_bytes` fails with
119 /// [`AudioError::QuotaExceeded`].
120 LoadUrl {
121 /// The sound.
122 id: u32,
123 /// Where its bytes are.
124 url: String,
125 /// The most bytes it may have, encoded.
126 max_bytes: usize,
127 /// How much to decode at most.
128 max_duration: Duration,
129 },
130 /// Start a voice of sound `id`, over the ones playing.
131 Play {
132 /// The sound.
133 id: u32,
134 /// Its volume, in [`VOLUME`].
135 volume: f32,
136 /// Its rate, in [`RATE`] (the pitch goes with it).
137 rate: f32,
138 },
139 /// Stop every voice of sound `id`.
140 Stop {
141 /// The sound.
142 id: u32,
143 },
144 /// Free sound `id`'s decoded audio, its voices stopped. Nothing is
145 /// reported of it after this.
146 Unload {
147 /// The sound.
148 id: u32,
149 },
150 /// Make player `id` for `src` (a URL the core checked, or an
151 /// `asset:/` URI), loading nothing yet.
152 Open {
153 /// The player.
154 id: u32,
155 /// What it plays.
156 src: String,
157 /// How it plays.
158 settings: PlayerSettings,
159 },
160 /// Load player `id` if it has not, without playing: its
161 /// [`AudioEvent::Load`] comes when it knows its duration.
162 Preload {
163 /// The player.
164 id: u32,
165 },
166 /// Play player `id` from where it is (loading it first if needed),
167 /// reporting [`AudioEvent::Playing`].
168 Resume {
169 /// The player.
170 id: u32,
171 },
172 /// Pause player `id`, reporting [`AudioEvent::Paused`].
173 Pause {
174 /// The player.
175 id: u32,
176 },
177 /// Move player `id` to `position` (clamped to its duration).
178 Seek {
179 /// The player.
180 id: u32,
181 /// Where to.
182 position: Duration,
183 },
184 /// Change player `id`'s settings.
185 Set {
186 /// The player.
187 id: u32,
188 /// Its settings now.
189 settings: PlayerSettings,
190 },
191 /// Stop and free player `id`. Nothing is reported of it after this.
192 Close {
193 /// The player.
194 id: u32,
195 },
196}
197
198impl AudioCommand {
199 /// The sound or player the command is about.
200 pub fn id(&self) -> u32 {
201 match self {
202 AudioCommand::Load { id, .. }
203 | AudioCommand::LoadUrl { id, .. }
204 | AudioCommand::Play { id, .. }
205 | AudioCommand::Stop { id }
206 | AudioCommand::Unload { id }
207 | AudioCommand::Open { id, .. }
208 | AudioCommand::Preload { id }
209 | AudioCommand::Resume { id }
210 | AudioCommand::Pause { id }
211 | AudioCommand::Seek { id, .. }
212 | AudioCommand::Set { id, .. }
213 | AudioCommand::Close { id } => *id,
214 }
215 }
216
217 /// Whether nothing is reported of the object after it.
218 pub fn ends(&self) -> bool {
219 matches!(
220 self,
221 AudioCommand::Unload { .. } | AudioCommand::Close { .. }
222 )
223 }
224}
225
226/// How a player plays.
227#[derive(Debug, Clone, Copy, PartialEq)]
228#[non_exhaustive]
229pub struct PlayerSettings {
230 /// Its volume, in [`VOLUME`].
231 pub volume: f32,
232 /// Its rate, in [`RATE`] (the pitch kept where the platform can).
233 pub rate: f32,
234 /// It starts again at its end, without an [`AudioEvent::Ended`].
235 pub looped: bool,
236}
237
238impl Default for PlayerSettings {
239 fn default() -> Self {
240 Self {
241 volume: 1.0,
242 rate: 1.0,
243 looped: false,
244 }
245 }
246}
247
248/// What the platform reports of a sound or a player.
249#[derive(Debug, Clone, PartialEq)]
250#[non_exhaustive]
251pub enum AudioEvent {
252 /// A sound decoded ([`AudioCommand::Load`]).
253 Loaded {
254 /// How long it plays (what was decoded of it).
255 duration: Duration,
256 /// The size of its decoded audio, for the engine's budget.
257 bytes: u64,
258 /// It was longer than the `max_duration` asked for: only that was
259 /// decoded.
260 truncated: bool,
261 },
262 /// A player knows its duration (`None`: a live stream).
263 Load {
264 /// How long it plays.
265 duration: Option<Duration>,
266 },
267 /// A player plays.
268 Playing,
269 /// A player paused.
270 Paused,
271 /// Where a player is, every [`PROGRESS_INTERVAL`] while it plays and
272 /// after a seek.
273 Progress {
274 /// Its position.
275 position: Duration,
276 /// Its duration, when known.
277 duration: Option<Duration>,
278 },
279 /// A player started or stopped waiting for its data.
280 Buffer {
281 /// It waits.
282 buffering: bool,
283 },
284 /// A player played to its end (never while it loops).
285 Ended,
286 /// A sound did not load, or a player failed: it plays nothing more
287 /// until it is told again.
288 Failed {
289 /// Why.
290 error: AudioError,
291 /// The platform's words.
292 message: String,
293 },
294}
295
296/// Why a sound or a player failed (TS: the `error`'s `code`, named as the
297/// Web's `MediaError`).
298#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
299#[non_exhaustive]
300pub enum AudioError {
301 /// The app's capabilities, or the browser before a gesture, do not
302 /// allow it (`not-allowed`).
303 NotAllowed,
304 /// Its source could not be fetched (`network`).
305 Network,
306 /// Its bytes are not audio the platform decodes (`decode`).
307 Decode,
308 /// Its format is not one the platform plays (`not-supported`).
309 NotSupported,
310 /// Past a limit of the engine's (`quota-exceeded`).
311 QuotaExceeded,
312 /// Nothing plays sound here (`unavailable`).
313 Unavailable,
314 /// Another reason, such as the output going away (`failed`).
315 Failed,
316}
317
318impl AudioError {
319 /// Every error, in declaration order.
320 pub const ALL: [AudioError; 7] = [
321 AudioError::NotAllowed,
322 AudioError::Network,
323 AudioError::Decode,
324 AudioError::NotSupported,
325 AudioError::QuotaExceeded,
326 AudioError::Unavailable,
327 AudioError::Failed,
328 ];
329
330 /// Its name, as JS gets it (`not-allowed`).
331 pub fn as_str(self) -> &'static str {
332 match self {
333 AudioError::NotAllowed => "not-allowed",
334 AudioError::Network => "network",
335 AudioError::Decode => "decode",
336 AudioError::NotSupported => "not-supported",
337 AudioError::QuotaExceeded => "quota-exceeded",
338 AudioError::Unavailable => "unavailable",
339 AudioError::Failed => "failed",
340 }
341 }
342
343 /// The error named `name` ([`Self::as_str`]).
344 pub fn from_name(name: &str) -> Option<Self> {
345 Self::ALL.into_iter().find(|e| e.as_str() == name)
346 }
347}
348
349/// Where the events of one sound or player go: the app (through the core),
350/// from any thread. After [`Self::close`] it takes nothing more.
351#[derive(Clone)]
352pub struct AudioSink {
353 channel: Arc<Mutex<Channel>>,
354}
355
356#[derive(Default)]
357struct Channel {
358 events: VecDeque<AudioEvent>,
359 waker: Option<Waker>,
360 closed: bool,
361}
362
363impl std::fmt::Debug for AudioSink {
364 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
365 f.debug_struct("AudioSink")
366 .field("closed", &self.is_closed())
367 .finish()
368 }
369}
370
371impl AudioSink {
372 /// Reports `event`; `false` (and nothing reported) once closed.
373 pub fn send(&self, event: AudioEvent) -> bool {
374 let waker = {
375 let mut channel = self.channel.lock().expect("audio channel");
376 if channel.closed {
377 return false;
378 }
379 channel.events.push_back(event);
380 channel.waker.take()
381 };
382 if let Some(waker) = waker {
383 waker.wake();
384 }
385 true
386 }
387
388 /// Takes nothing more: the object was unloaded or closed.
389 pub fn close(&self) {
390 let waker = {
391 let mut channel = self.channel.lock().expect("audio channel");
392 channel.closed = true;
393 channel.waker.take()
394 };
395 if let Some(waker) = waker {
396 waker.wake();
397 }
398 }
399
400 /// Whether it was closed.
401 pub fn is_closed(&self) -> bool {
402 self.channel.lock().expect("audio channel").closed
403 }
404}
405
406/// The receiving end of an [`AudioSink`], polled on the engine thread.
407pub(crate) struct AudioEvents {
408 channel: Arc<Mutex<Channel>>,
409}
410
411impl AudioEvents {
412 /// The next event; `None` once the sink is closed and drained.
413 pub(crate) fn poll_next(
414 &mut self,
415 cx: &mut std::task::Context<'_>,
416 ) -> Poll<Option<AudioEvent>> {
417 let mut channel = self.channel.lock().expect("audio channel");
418 if let Some(event) = channel.events.pop_front() {
419 return Poll::Ready(Some(event));
420 }
421 if channel.closed {
422 return Poll::Ready(None);
423 }
424 channel.waker = Some(cx.waker().clone());
425 Poll::Pending
426 }
427}
428
429/// An object's sink and the events it reports.
430pub(crate) fn channel() -> (AudioSink, AudioEvents) {
431 let channel = Arc::new(Mutex::new(Channel::default()));
432 (
433 AudioSink {
434 channel: channel.clone(),
435 },
436 AudioEvents { channel },
437 )
438}
439
440/// Plays sound in place of the platform: an embedding app's own audio
441/// stack, or a test's fake.
442pub trait AudioBackend: Send + Sync {
443 /// Whether it plays sound now (TS: `Sound.available()`).
444 fn available(&self) -> bool {
445 true
446 }
447
448 /// Carries out `command`, reporting what happens to the object it is
449 /// about to `events` (from any thread). The core sends a command only
450 /// for an object it opened with a [`AudioCommand::Load`] or
451 /// [`AudioCommand::Open`] and has not closed, and drops what is
452 /// reported after [`AudioCommand::Unload`] / [`AudioCommand::Close`].
453 fn command(&self, command: AudioCommand, events: &AudioSink);
454}
455
456/// The ids of a process's sounds and players: unique, so an event of an
457/// object a backend closed late never reaches another.
458pub(crate) fn ids() -> u32 {
459 static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
460 NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
461}
462
463/// Checks a volume: in [`VOLUME`], or why not.
464pub fn check_volume(volume: f32) -> Result<f32, String> {
465 if VOLUME.contains(&volume) {
466 Ok(volume)
467 } else {
468 Err(format!("`volume` must be from 0 to 1, not {volume}"))
469 }
470}
471
472/// Checks a rate: in [`RATE`], or why not.
473pub fn check_rate(rate: f32) -> Result<f32, String> {
474 if RATE.contains(&rate) {
475 Ok(rate)
476 } else {
477 Err(format!("`rate` must be from 0.5 to 2, not {rate}"))
478 }
479}
480
481#[cfg(test)]
482mod tests {
483 use std::task::{Context, Wake};
484
485 use super::*;
486
487 struct Count(Mutex<u32>);
488
489 impl Wake for Count {
490 fn wake(self: Arc<Self>) {
491 *self.0.lock().unwrap() += 1;
492 }
493 }
494
495 #[test]
496 fn bytes_say_their_format() {
497 let wav = [b"RIFF".as_slice(), &[0; 4], b"WAVEfmt "].concat();
498 assert_eq!(sniff(&wav), "audio/wav");
499 assert_eq!(sniff(b"FORM\0\0\0\0AIFC"), "audio/aiff");
500 assert_eq!(sniff(b"caff\0\x01"), "audio/x-caf");
501 assert_eq!(sniff(b"fLaC\0"), "audio/flac");
502 assert_eq!(sniff(b"OggS\0"), "audio/ogg");
503 assert_eq!(sniff(b"\0\0\0\x20ftypM4A "), "audio/mp4");
504 assert_eq!(sniff(b"ID3\x04"), "audio/mpeg");
505 assert_eq!(sniff(&[0xFF, 0xFB, 0x90]), "audio/mpeg");
506 assert_eq!(sniff(&[0xFF, 0xF1, 0x50]), "audio/aac");
507 assert_eq!(sniff(b"RIFF"), "application/octet-stream");
508 assert_eq!(sniff(&[]), "application/octet-stream");
509 assert_eq!(sniff(&[0xFF, 0x00]), "application/octet-stream");
510 }
511
512 #[test]
513 fn names() {
514 for error in AudioError::ALL {
515 assert_eq!(AudioError::from_name(error.as_str()), Some(error));
516 }
517 assert_eq!(AudioError::NotAllowed.as_str(), "not-allowed");
518 assert_eq!(AudioError::from_name("aborted"), None);
519 }
520
521 #[test]
522 fn ranges() {
523 assert_eq!(check_volume(0.0), Ok(0.0));
524 assert!(check_volume(1.5).is_err());
525 assert!(check_volume(f32::NAN).is_err());
526 assert_eq!(check_rate(2.0), Ok(2.0));
527 assert!(check_rate(0.25).is_err());
528 assert!(check_rate(f32::INFINITY).is_err());
529 }
530
531 /// Events come in order, wake the receiver, and stop once closed.
532 #[test]
533 fn nothing_after_close() {
534 let (sink, mut events) = channel();
535 let count = Arc::new(Count(Mutex::new(0)));
536 let waker = Waker::from(count.clone());
537 let mut cx = Context::from_waker(&waker);
538 assert_eq!(events.poll_next(&mut cx), Poll::Pending);
539 assert!(sink.send(AudioEvent::Playing));
540 assert_eq!(*count.0.lock().unwrap(), 1);
541 assert!(sink.send(AudioEvent::Ended));
542 sink.clone().close();
543 assert!(sink.is_closed());
544 assert!(!sink.send(AudioEvent::Paused));
545 assert_eq!(
546 events.poll_next(&mut cx),
547 Poll::Ready(Some(AudioEvent::Playing))
548 );
549 assert_eq!(
550 events.poll_next(&mut cx),
551 Poll::Ready(Some(AudioEvent::Ended))
552 );
553 assert_eq!(events.poll_next(&mut cx), Poll::Ready(None));
554 }
555
556 #[test]
557 fn commands_name_their_object() {
558 assert_eq!(AudioCommand::Stop { id: 7 }.id(), 7);
559 assert!(AudioCommand::Close { id: 1 }.ends());
560 assert!(!AudioCommand::Pause { id: 1 }.ends());
561 }
562}