Skip to main content

nsh_core/element/
audio.rs

1//! Sound for Rust components and the runtime's `Sound` / `AudioPlayer`
2//! ([`crate::audio`]): loading a sound (its bytes through the image
3//! loader, one decode per source per engine, the engine's limits), its
4//! plays, and players.
5//!
6//! The limits are kept here, on the engine thread, so what JS asks never
7//! raises them: [`MAX_SOUND_BYTES`](crate::audio::MAX_SOUND_BYTES) before the
8//! platform sees the bytes, [`MAX_SOUNDS`](crate::audio::MAX_SOUNDS) before a
9//! load starts, and the decoded length and size the platform reports.
10
11#[cfg(not(target_arch = "wasm32"))]
12use std::sync::{Arc, Mutex};
13use std::{
14    cell::{Cell, RefCell},
15    collections::HashMap,
16    rc::{Rc, Weak},
17    task::{Poll, Waker},
18    time::Duration,
19};
20
21use super::{Action, AudioAction, Executor, ambient::executor};
22#[cfg(not(target_arch = "wasm32"))]
23use crate::image::loader::{self, Location, Priority};
24use crate::{
25    audio::{
26        AudioCommand, AudioError, AudioEvent, AudioEvents, MAX_DECODED_BYTES, MAX_SOUND_BYTES,
27        MAX_SOUND_DURATION, MAX_SOUNDS, PlayerSettings,
28    },
29    image::ImageData,
30};
31
32/// Why a sound did not load, or a player failed.
33#[derive(Debug, Clone, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct AudioFailure {
36    /// What kind of failure.
37    pub error: AudioError,
38    /// What happened, in words.
39    pub message: String,
40    /// For [`AudioError::NotAllowed`]: the capability that would grant it
41    /// (`audio`, `network`, `fs`), when the core refused it here.
42    pub(crate) permission: Option<&'static str>,
43}
44
45impl Default for AudioFailure {
46    fn default() -> Self {
47        Self::new(AudioError::Failed, "")
48    }
49}
50
51impl AudioFailure {
52    fn new(error: AudioError, message: impl Into<String>) -> Self {
53        Self {
54            error,
55            message: message.into(),
56            permission: None,
57        }
58    }
59
60    /// A refusal for want of `capability` (made where the core reads a
61    /// sound itself, off the web).
62    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
63    pub(crate) fn refused(capability: &'static str, message: impl Into<String>) -> Self {
64        Self {
65            permission: Some(capability),
66            ..Self::new(AudioError::NotAllowed, message)
67        }
68    }
69}
70
71impl std::fmt::Display for AudioFailure {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        write!(f, "{} ({})", self.message, self.error.as_str())
74    }
75}
76
77/// An engine's sounds: one decoded buffer per source, and what they hold.
78#[derive(Default)]
79pub(crate) struct Sounds {
80    /// By source key: loaded (held by the [`Sound`]s over it) or loading.
81    sources: HashMap<String, Source>,
82    /// The decoded audio of the buffers loaded.
83    decoded: u64,
84}
85
86enum Source {
87    Loading(Rc<Pending>),
88    Loaded(Weak<Buffer>),
89}
90
91impl Sounds {
92    /// Sources loaded or loading: what [`MAX_SOUNDS`] counts.
93    fn len(&self) -> usize {
94        self.sources
95            .values()
96            .filter(|s| match s {
97                Source::Loading(_) => true,
98                Source::Loaded(buffer) => buffer.strong_count() > 0,
99            })
100            .count()
101    }
102}
103
104/// A load in flight that later loads of the same source wait for.
105#[derive(Default)]
106struct Pending {
107    result: RefCell<Option<Result<Rc<Buffer>, AudioFailure>>>,
108    wakers: RefCell<Vec<Waker>>,
109}
110
111impl Pending {
112    fn finish(&self, result: Result<Rc<Buffer>, AudioFailure>) {
113        *self.result.borrow_mut() = Some(result);
114        for waker in self.wakers.take() {
115            waker.wake();
116        }
117    }
118}
119
120/// One decoded sound on the platform; unloaded with the last [`Sound`].
121struct Buffer {
122    id: u32,
123    key: String,
124    duration: Duration,
125    bytes: u64,
126    executor: Weak<Executor>,
127}
128
129impl Drop for Buffer {
130    fn drop(&mut self) {
131        let Some(executor) = self.executor.upgrade() else {
132            return;
133        };
134        {
135            let mut sounds = executor.sounds.borrow_mut();
136            sounds.decoded = sounds.decoded.saturating_sub(self.bytes);
137            if matches!(sounds.sources.get(&self.key), Some(Source::Loaded(_))) {
138                sounds.sources.remove(&self.key);
139            }
140        }
141        executor.act(Action::Audio(AudioAction::Command(AudioCommand::Unload {
142            id: self.id,
143        })));
144    }
145}
146
147/// Whether sound plays here (TS: `Sound.available()`): the platform plays
148/// sound, or the embedding app gave the core its own audio stack. To await
149/// in a task.
150pub fn audio_available() -> super::Answer<bool> {
151    let (answer, slot) = super::Answer::new();
152    executor().act(Action::Audio(AudioAction::Available(slot)));
153    answer
154}
155
156/// What a sound is loaded from ([`load_sound`]; TS: `Sound.load`'s
157/// `string | Uint8Array`): where its file is, or the file's bytes.
158#[derive(Debug, Clone, PartialEq)]
159#[non_exhaustive]
160pub enum SoundSource {
161    /// A bundled asset (`asset!(...)`'s `uri`), a relative path, `file:`,
162    /// `data:` or an `http(s)` URL.
163    Url(String),
164    /// The encoded bytes of a sound file (WAV, AAC, MP3, ...): one the app
165    /// embeds (`include_bytes!`) or makes. Its format is read from the
166    /// bytes; equal bytes share one decoded sound.
167    Bytes(ImageData),
168}
169
170impl From<&str> for SoundSource {
171    fn from(src: &str) -> Self {
172        Self::Url(src.to_owned())
173    }
174}
175
176impl From<&String> for SoundSource {
177    fn from(src: &String) -> Self {
178        Self::Url(src.clone())
179    }
180}
181
182impl From<String> for SoundSource {
183    fn from(src: String) -> Self {
184        Self::Url(src)
185    }
186}
187
188impl From<ImageData> for SoundSource {
189    fn from(bytes: ImageData) -> Self {
190        Self::Bytes(bytes)
191    }
192}
193
194impl From<Vec<u8>> for SoundSource {
195    fn from(bytes: Vec<u8>) -> Self {
196        Self::Bytes(ImageData::new(bytes))
197    }
198}
199
200impl From<&'static [u8]> for SoundSource {
201    fn from(bytes: &'static [u8]) -> Self {
202        Self::Bytes(ImageData::new(bytes))
203    }
204}
205
206impl<const N: usize> From<&'static [u8; N]> for SoundSource {
207    fn from(bytes: &'static [u8; N]) -> Self {
208        Self::Bytes(ImageData::new(bytes.as_slice()))
209    }
210}
211
212/// Loads a sound (TS: `Sound.load`), to await in a task: its bytes (read
213/// from a bundled asset, a relative path, `file:`, `data:` or `http(s)`, or
214/// given) decoded by the platform into memory, so [`Sound::play`] starts at
215/// once. Loading a source (or bytes) this engine has loaded already shares
216/// its decoded audio. Fails when the app's capabilities do not grant
217/// `audio` (or `network` for a remote source), past the engine's limits
218/// ([`crate::audio`]'s), when the bytes cannot be read or decoded, and
219/// where nothing plays sound.
220pub async fn load_sound(src: impl Into<SoundSource>) -> Result<Sound, AudioFailure> {
221    let executor = executor();
222    let src = src.into();
223    // Before any byte is read (the core checks again, and alone on the web,
224    // where the platform fetches).
225    #[cfg(not(target_arch = "wasm32"))]
226    let granted = {
227        let context = loader::context();
228        match &src {
229            SoundSource::Url(src) => Some(granted_uri(
230                &context.access,
231                &context.media_files,
232                src,
233                asset_uri(src),
234            )?),
235            SoundSource::Bytes(_) => {
236                audio_granted(&context.access)?;
237                None
238            }
239        }
240    };
241    // Nothing to read for where nothing plays it.
242    if !audio_available().await {
243        return Err(AudioFailure::new(
244            AudioError::Unavailable,
245            "nothing plays sound here",
246        ));
247    }
248    let (location, src) = match src {
249        SoundSource::Url(src) => {
250            // The URL the check granted: the one loaded (the web's
251            // platform fetches and checks alone).
252            #[cfg(not(target_arch = "wasm32"))]
253            let uri = granted.unwrap_or_else(|| asset_uri(&src));
254            #[cfg(target_arch = "wasm32")]
255            let uri = asset_uri(&src);
256            (
257                locate(&uri).ok_or_else(|| {
258                    AudioFailure::new(AudioError::NotSupported, format!("no sound at `{src}`"))
259                })?,
260                src,
261            )
262        }
263        SoundSource::Bytes(bytes) => {
264            too_big(bytes.len(), "the sound's bytes")?;
265            // Named by its format and a digest of its bytes: the decoders
266            // that go by a name read the format from it, and equal bytes
267            // share one load.
268            let name = crate::image::data_key(crate::audio::sniff(&bytes), &bytes);
269            (Fetch::Bytes(bytes, name.clone()), name)
270        }
271    };
272    let src = src.as_str();
273    let key = location.key();
274    // Loaded or loading already: share it.
275    let existing = match executor.sounds.borrow().sources.get(&key) {
276        Some(Source::Loaded(buffer)) => buffer.upgrade().map(Ok),
277        Some(Source::Loading(pending)) => Some(Err(pending.clone())),
278        None => None,
279    };
280    match existing {
281        Some(Ok(buffer)) => return Ok(Sound::new(buffer)),
282        Some(Err(pending)) => return wait(&pending).await.map(Sound::new),
283        None => {}
284    }
285    if executor.sounds.borrow().len() >= MAX_SOUNDS {
286        return Err(AudioFailure::new(
287            AudioError::QuotaExceeded,
288            format!("an app loads at most {MAX_SOUNDS} sounds at once"),
289        ));
290    }
291    let pending = Rc::new(Pending::default());
292    executor
293        .sounds
294        .borrow_mut()
295        .sources
296        .insert(key.clone(), Source::Loading(pending.clone()));
297    // Ends the load for the ones waiting on it whatever happens to this
298    // task, dropped included.
299    let mut guard = LoadGuard {
300        pending: pending.clone(),
301        executor: Rc::downgrade(&executor),
302        key: key.clone(),
303        done: false,
304    };
305    let result = decode(&executor, location, key, src).await;
306    guard.done = true;
307    {
308        let mut sounds = executor.sounds.borrow_mut();
309        match &result {
310            Ok(buffer) => {
311                sounds
312                    .sources
313                    .insert(buffer.key.clone(), Source::Loaded(Rc::downgrade(buffer)));
314            }
315            Err(_) => {
316                sounds.sources.remove(&guard.key);
317            }
318        }
319    }
320    pending.finish(result.clone());
321    result.map(Sound::new)
322}
323
324/// Ends a load others wait on when its task goes before it finished.
325struct LoadGuard {
326    pending: Rc<Pending>,
327    executor: Weak<Executor>,
328    key: String,
329    done: bool,
330}
331
332impl Drop for LoadGuard {
333    fn drop(&mut self) {
334        if self.done {
335            return;
336        }
337        if let Some(executor) = self.executor.upgrade() {
338            executor.sounds.borrow_mut().sources.remove(&self.key);
339        }
340        self.pending.finish(Err(AudioFailure::new(
341            AudioError::Failed,
342            "the load was cancelled",
343        )));
344    }
345}
346
347async fn wait(pending: &Pending) -> Result<Rc<Buffer>, AudioFailure> {
348    std::future::poll_fn(|cx| match &*pending.result.borrow() {
349        Some(result) => Poll::Ready(result.clone()),
350        None => {
351            pending.wakers.borrow_mut().push(cx.waker().clone());
352            Poll::Pending
353        }
354    })
355    .await
356}
357
358/// Refuses sound to an app whose capabilities do not grant `audio`.
359#[cfg(not(target_arch = "wasm32"))]
360fn audio_granted(access: &crate::access::Access) -> Result<(), AudioFailure> {
361    if access.allows_audio() {
362        return Ok(());
363    }
364    Err(AudioFailure::refused(
365        "audio",
366        "sound is not granted: add `\"audio\": true` to capabilities in nsh.json",
367    ))
368}
369
370/// What a sound loads from `uri` (`src` as the loader names it), if the app
371/// may load it: the URL the check granted (`Access::media_url`).
372#[cfg(not(target_arch = "wasm32"))]
373fn granted_uri(
374    access: &crate::access::Access,
375    files: &crate::access::MediaFiles,
376    src: &str,
377    uri: String,
378) -> Result<String, AudioFailure> {
379    audio_granted(access)?;
380    match access.media_url(&uri, None, Some(files)) {
381        Some(std::borrow::Cow::Owned(granted)) => Ok(granted),
382        Some(std::borrow::Cow::Borrowed(_)) => Ok(uri),
383        None => {
384            let capability = crate::access::media_capability(&uri, None);
385            Err(AudioFailure::refused(
386                capability,
387                format!(
388                    "`{src}` is not granted by capabilities.{capability}: {}",
389                    crate::access::media_grant_advice(&uri, None)
390                ),
391            ))
392        }
393    }
394}
395
396/// `src` as the loader names it: a relative path is the app's asset.
397fn asset_uri(src: &str) -> String {
398    let has_scheme = src
399        .split_once(':')
400        .is_some_and(|(scheme, _)| !scheme.is_empty() && !scheme.contains('/'));
401    if has_scheme || src.starts_with('/') {
402        src.to_owned()
403    } else {
404        format!("asset:/{}", src.trim_start_matches("./"))
405    }
406}
407
408/// Where a sound's bytes come from.
409enum Fetch {
410    /// Read here, through the image loader.
411    #[cfg(not(target_arch = "wasm32"))]
412    Read(Location),
413    /// A `data:` URI's bytes, decoded here.
414    Data(String),
415    /// Bytes the app gave, and the name they go by.
416    Bytes(ImageData, String),
417    /// Fetched by the platform from this URL (an `asset:/` URI or an
418    /// `http(s)` URL the core checked): the web, where the browser fetches
419    /// and the image loader has no threads.
420    #[cfg(target_arch = "wasm32")]
421    Url(String),
422}
423
424impl Fetch {
425    fn key(&self) -> String {
426        match self {
427            #[cfg(not(target_arch = "wasm32"))]
428            Fetch::Read(location) => location.key(),
429            Fetch::Data(uri) => uri.clone(),
430            Fetch::Bytes(_, name) => name.clone(),
431            #[cfg(target_arch = "wasm32")]
432            Fetch::Url(url) => url.clone(),
433        }
434    }
435}
436
437/// Where `uri`'s bytes come from: inline bytes are decoded everywhere,
438/// other sources read by the image loader, or on the web fetched by the
439/// browser.
440fn locate(uri: &str) -> Option<Fetch> {
441    if uri.starts_with("data:") {
442        return Some(Fetch::Data(uri.to_owned()));
443    }
444    #[cfg(target_arch = "wasm32")]
445    return Some(Fetch::Url(uri.to_owned()));
446    #[cfg(not(target_arch = "wasm32"))]
447    loader::context().resolve(uri).map(Fetch::Read)
448}
449
450/// Refuses encoded bytes past [`MAX_SOUND_BYTES`]; `what` names them.
451fn too_big(len: usize, what: &str) -> Result<(), AudioFailure> {
452    if len > MAX_SOUND_BYTES {
453        return Err(AudioFailure::new(
454            AudioError::QuotaExceeded,
455            format!("{what} is {len} bytes: a sound is at most {MAX_SOUND_BYTES}"),
456        ));
457    }
458    Ok(())
459}
460
461/// Has the platform decode the sound (its bytes read here first, or
462/// fetched by the platform) and checks what it reports against the
463/// engine's limits.
464async fn decode(
465    executor: &Rc<Executor>,
466    fetch: Fetch,
467    key: String,
468    src: &str,
469) -> Result<Rc<Buffer>, AudioFailure> {
470    let id = crate::audio::ids();
471    let fetch_url = match &fetch {
472        #[cfg(target_arch = "wasm32")]
473        Fetch::Url(url) => url.clone(),
474        _ => String::new(),
475    };
476    let bytes = match fetch {
477        #[cfg(not(target_arch = "wasm32"))]
478        Fetch::Read(location) => Some(read(location).await?),
479        Fetch::Data(uri) => Some(
480            crate::image::decode_data_uri(&uri)
481                .map(|(_, bytes)| ImageData::from(bytes))
482                .map_err(|message| AudioFailure::new(AudioError::NotSupported, message))?,
483        ),
484        Fetch::Bytes(bytes, _) => Some(bytes),
485        #[cfg(target_arch = "wasm32")]
486        Fetch::Url(_) => None,
487    };
488    let command = match (bytes, fetch_url) {
489        (Some(bytes), _) => {
490            too_big(bytes.len(), &format!("`{src}`"))?;
491            AudioCommand::Load {
492                id,
493                bytes,
494                hint: src.to_owned(),
495                max_duration: MAX_SOUND_DURATION,
496            }
497        }
498        (None, url) => AudioCommand::LoadUrl {
499            id,
500            url,
501            max_bytes: MAX_SOUND_BYTES,
502            max_duration: MAX_SOUND_DURATION,
503        },
504    };
505    let (sink, mut events) = crate::audio::channel();
506    executor.act(Action::Audio(AudioAction::Open { command, sink }));
507    let unload = || {
508        executor.act(Action::Audio(AudioAction::Command(AudioCommand::Unload {
509            id,
510        })));
511    };
512    let event = std::future::poll_fn(|cx| events.poll_next(cx)).await;
513    match event {
514        Some(AudioEvent::Loaded {
515            duration,
516            bytes,
517            truncated,
518        }) => {
519            if truncated || duration > MAX_SOUND_DURATION {
520                unload();
521                return Err(AudioFailure::new(
522                    AudioError::QuotaExceeded,
523                    format!(
524                        "`{src}` is longer than {} s: play it with an AudioPlayer",
525                        MAX_SOUND_DURATION.as_secs()
526                    ),
527                ));
528            }
529            let mut sounds = executor.sounds.borrow_mut();
530            if sounds.decoded + bytes > MAX_DECODED_BYTES {
531                drop(sounds);
532                unload();
533                return Err(AudioFailure::new(
534                    AudioError::QuotaExceeded,
535                    format!(
536                        "the sounds loaded would take more than {MAX_DECODED_BYTES} bytes decoded"
537                    ),
538                ));
539            }
540            sounds.decoded += bytes;
541            Ok(Rc::new(Buffer {
542                id,
543                key,
544                duration,
545                bytes,
546                executor: Rc::downgrade(executor),
547            }))
548        }
549        Some(AudioEvent::Failed { error, message }) => {
550            unload();
551            Err(AudioFailure::new(error, message))
552        }
553        Some(other) => {
554            unload();
555            Err(AudioFailure::new(
556                AudioError::Failed,
557                format!("the platform answered a load with {other:?}"),
558            ))
559        }
560        // The core refused it: the sink said why before it closed.
561        None => Err(AudioFailure::new(
562            AudioError::Failed,
563            "the sound did not load",
564        )),
565    }
566}
567
568/// `location`'s bytes through the image loader (its limits, cache and
569/// redirect checks), read on its threads.
570#[cfg(not(target_arch = "wasm32"))]
571async fn read(location: Location) -> Result<ImageData, AudioFailure> {
572    type Slot = Arc<Mutex<(Option<Result<ImageData, String>>, Option<Waker>)>>;
573    let slot: Slot = Arc::default();
574    let remote = matches!(location, Location::Url(_));
575    let context = loader::context();
576    let ticket = loader::loader().read(location, &context, Priority::Normal, None, {
577        let slot = slot.clone();
578        Box::new(move |result| {
579            let waker = {
580                let mut slot = slot.lock().expect("sound read");
581                slot.0 = Some(result);
582                slot.1.take()
583            };
584            if let Some(waker) = waker {
585                waker.wake();
586            }
587        })
588    });
589    let result = std::future::poll_fn(|cx| {
590        let mut slot = slot.lock().expect("sound read");
591        match slot.0.take() {
592            Some(result) => Poll::Ready(result),
593            None => {
594                slot.1 = Some(cx.waker().clone());
595                Poll::Pending
596            }
597        }
598    })
599    .await;
600    drop(ticket);
601    result.map_err(|message| {
602        let error = if remote {
603            AudioError::Network
604        } else {
605            AudioError::NotSupported
606        };
607        AudioFailure::new(error, message)
608    })
609}
610
611/// A sound loaded into memory ([`load_sound`]): play it any number of
612/// times, overlapping. Its decoded audio is freed with the last `Sound`
613/// over its source.
614#[derive(Clone)]
615pub struct Sound {
616    buffer: Rc<Buffer>,
617}
618
619impl std::fmt::Debug for Sound {
620    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
621        f.debug_struct("Sound")
622            .field("id", &self.buffer.id)
623            .field("duration", &self.buffer.duration)
624            .finish()
625    }
626}
627
628impl Sound {
629    fn new(buffer: Rc<Buffer>) -> Self {
630        Self { buffer }
631    }
632
633    /// How long it plays.
634    pub fn duration(&self) -> Duration {
635        self.buffer.duration
636    }
637
638    /// Plays it over the voices playing, at `volume` (0 to 1) and `rate`
639    /// (0.5 to 2), clamped. Nothing is reported: a muted device or a voice
640    /// the platform drops is silence, not an error.
641    pub fn play(&self, volume: f32, rate: f32) {
642        let volume = if volume.is_nan() {
643            1.0
644        } else {
645            volume.clamp(0.0, 1.0)
646        };
647        let rate = if rate.is_nan() {
648            1.0
649        } else {
650            rate.clamp(0.5, 2.0)
651        };
652        self.act(AudioCommand::Play {
653            id: self.buffer.id,
654            volume,
655            rate,
656        });
657    }
658
659    /// Stops every voice of it.
660    pub fn stop(&self) {
661        self.act(AudioCommand::Stop { id: self.buffer.id });
662    }
663
664    fn act(&self, command: AudioCommand) {
665        if let Some(executor) = self.buffer.executor.upgrade() {
666            executor.act(Action::Audio(AudioAction::Command(command)));
667        }
668    }
669}
670
671/// Where a player is ([`AudioPlayer::state`]).
672#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
673#[non_exhaustive]
674pub enum PlayerState {
675    /// Nothing asked yet, or failed and waiting to be told again.
676    #[default]
677    Idle,
678    /// Loading its source, or waiting for data.
679    Loading,
680    /// Playing.
681    Playing,
682    /// Paused.
683    Paused,
684    /// Played to its end.
685    Ended,
686}
687
688/// A player of long audio (TS: `AudioPlayer`; [`audio_player`]): streamed
689/// from its source as it plays. Closed when dropped.
690pub struct AudioPlayer {
691    id: u32,
692    events: AudioEvents,
693    executor: Weak<Executor>,
694    settings: Cell<PlayerSettings>,
695}
696
697impl std::fmt::Debug for AudioPlayer {
698    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
699        f.debug_struct("AudioPlayer")
700            .field("id", &self.id)
701            .finish_non_exhaustive()
702    }
703}
704
705/// Makes a player of `src` (a bundled asset, a relative path, `file:` or
706/// `http(s)`), loading nothing until [`AudioPlayer::play`] or
707/// [`AudioPlayer::preload`]. Its events come from [`AudioPlayer::next`];
708/// the first is [`AudioEvent::Failed`] (and then nothing) when the app's
709/// capabilities do not grant `audio` or the source, or where nothing plays
710/// sound.
711pub fn audio_player(src: &str, settings: PlayerSettings) -> AudioPlayer {
712    let executor = executor();
713    let id = crate::audio::ids();
714    let (sink, events) = crate::audio::channel();
715    executor.act(Action::Audio(AudioAction::Open {
716        command: AudioCommand::Open {
717            id,
718            src: asset_uri(src),
719            settings,
720        },
721        sink,
722    }));
723    AudioPlayer {
724        id,
725        events,
726        executor: Rc::downgrade(&executor),
727        settings: Cell::new(settings),
728    }
729}
730
731impl AudioPlayer {
732    /// Its next event; `None` once it is closed.
733    pub async fn next(&mut self) -> Option<AudioEvent> {
734        std::future::poll_fn(|cx| self.poll_next(cx)).await
735    }
736
737    /// Polls for its next event ([`Self::next`]).
738    pub fn poll_next(&mut self, cx: &mut std::task::Context<'_>) -> Poll<Option<AudioEvent>> {
739        self.events.poll_next(cx)
740    }
741
742    /// Plays from where it is, loading first if needed.
743    pub fn play(&self) {
744        self.act(AudioCommand::Resume { id: self.id });
745    }
746
747    /// Starts loading without playing.
748    pub fn preload(&self) {
749        self.act(AudioCommand::Preload { id: self.id });
750    }
751
752    /// Pauses.
753    pub fn pause(&self) {
754        self.act(AudioCommand::Pause { id: self.id });
755    }
756
757    /// Moves to `position` (clamped to its duration).
758    pub fn seek(&self, position: Duration) {
759        self.act(AudioCommand::Seek {
760            id: self.id,
761            position,
762        });
763    }
764
765    /// Its settings.
766    pub fn settings(&self) -> PlayerSettings {
767        self.settings.get()
768    }
769
770    /// Changes its settings (volume and rate clamped to their ranges).
771    pub fn set_settings(&self, mut settings: PlayerSettings) {
772        settings.volume = settings.volume.clamp(0.0, 1.0);
773        settings.rate = settings.rate.clamp(0.5, 2.0);
774        if settings == self.settings.get() {
775            return;
776        }
777        self.settings.set(settings);
778        self.act(AudioCommand::Set {
779            id: self.id,
780            settings,
781        });
782    }
783
784    /// Stops it and frees what plays it; nothing comes after.
785    pub fn close(&self) {
786        self.act(AudioCommand::Close { id: self.id });
787    }
788
789    fn act(&self, command: AudioCommand) {
790        if let Some(executor) = self.executor.upgrade() {
791            executor.act(Action::Audio(AudioAction::Command(command)));
792        }
793    }
794}
795
796impl Drop for AudioPlayer {
797    fn drop(&mut self) {
798        self.close();
799    }
800}
801
802#[cfg(test)]
803mod tests {
804    use super::asset_uri;
805
806    #[test]
807    fn relative_paths_are_assets() {
808        assert_eq!(asset_uri("sounds/click.wav"), "asset:/sounds/click.wav");
809        assert_eq!(asset_uri("./click.wav"), "asset:/click.wav");
810        assert_eq!(asset_uri("asset:/click.wav"), "asset:/click.wav");
811        assert_eq!(asset_uri("https://a.com/x.mp3"), "https://a.com/x.mp3");
812        assert_eq!(
813            asset_uri("data:audio/wav;base64,AA"),
814            "data:audio/wav;base64,AA"
815        );
816        assert_eq!(asset_uri("/tmp/x.wav"), "/tmp/x.wav");
817    }
818
819    /// A sound loads the URL the check granted, as WHATWG's parser reads
820    /// the source.
821    #[test]
822    fn sounds_load_the_url_the_check_granted() {
823        use super::granted_uri;
824        let access = crate::access::Access {
825            declared: crate::access::Capabilities::from_json(&serde_json::json!({
826                "audio": true,
827                "network": { "http": [{ "host": "example.com", "pathPrefix": "/public" }] }
828            }))
829            .unwrap(),
830            granted: None,
831        };
832        let files = crate::access::MediaFiles::default();
833        let load =
834            |src: &str| granted_uri(&access, &files, src, asset_uri(src)).map_err(|f| f.error);
835        assert_eq!(
836            load("https://EXAMPLE.com/private/../public/a.wav"),
837            Ok("https://example.com/public/a.wav".to_owned())
838        );
839        assert!(load("https://example.com/public/../private/a.wav").is_err());
840        assert!(load("https://example.com/public/%2e%2e/private/a.wav").is_err());
841        assert!(load("//example.com/public/a.wav").is_err());
842        assert_eq!(load("click.wav"), Ok("asset:/click.wav".to_owned()));
843    }
844
845    /// A local sound is read under `capabilities.fs.read`, and a refusal
846    /// says so.
847    #[cfg(unix)]
848    #[test]
849    fn local_sounds_need_an_fs_read_grant() {
850        use super::granted_uri;
851        let base =
852            std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, std::path::PathBuf::from);
853        let dir = base.join(format!("sound-files-{}", std::process::id()));
854        std::fs::create_dir_all(dir.join("sounds")).unwrap();
855        let dir = crate::access::canonicalize(&dir).unwrap();
856        let sounds = dir.join("sounds").to_str().unwrap().to_owned();
857        let access = crate::access::Access {
858            declared: crate::access::Capabilities::from_json(
859                &serde_json::json!({ "audio": true, "fs": { "read": [sounds.clone()] } }),
860            )
861            .unwrap(),
862            granted: None,
863        };
864        let files = crate::access::MediaFiles::new(
865            &access,
866            None,
867            &crate::access::TrustedPaths::default(),
868            true,
869        );
870        let load = |src: &str| granted_uri(&access, &files, src, asset_uri(src));
871        assert_eq!(
872            load(&format!("{sounds}/x/../a.wav")).ok(),
873            Some(format!("{sounds}/a.wav"))
874        );
875        let refused = load(&format!("{sounds}/../b.wav")).unwrap_err();
876        assert!(
877            refused.message.contains("capabilities.fs"),
878            "{}",
879            refused.message
880        );
881        // A relative path is a bundled file, which stays in the app's files.
882        assert_eq!(
883            load("sfx/click.wav").ok(),
884            Some("asset:/sfx/click.wav".to_owned())
885        );
886        assert!(load("../outside.wav").is_err());
887        let _ = std::fs::remove_dir_all(&dir);
888    }
889}