Skip to main content

nsh_core/runtime/
audio.rs

1//! `nsh`'s `Sound` and `AudioPlayer` ([`crate::audio`],
2//! `docs/dev/audio-design.md`): short sounds decoded into memory and played
3//! any number of times, and long audio streamed by a player. Needs the
4//! `audio` capability when the app declares capabilities: without it
5//! `Sound.load` rejects and `new AudioPlayer` throws `ERR_ACCESS_DENIED`
6//! (checked here, in the call; the core also refuses Rust components'
7//! sounds and players, which fail with `not-allowed`).
8
9use std::{
10    cell::{Cell, RefCell},
11    rc::{Rc, Weak},
12    task::{Poll, Waker},
13    time::Duration,
14};
15
16use crate::{
17    audio::{AudioError, AudioEvent, PlayerSettings, check_rate, check_volume},
18    element::{
19        AudioFailure, CallCx, Callback, Cleanup, JsError, JsHost, JsIn, JsObject, JsOwned, JsValue,
20        Later, PropEnum, PropError, Ret, SoundSource, Stop, System, TsTypes, class, codes,
21    },
22};
23
24/// The error a failure rejects or reports with: its `code` the
25/// runtime's (`ERR_ACCESS_DENIED`, `ERR_NSH_QUOTA_EXCEEDED`,
26/// `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`) where it has one, else an
27/// `Error` with the audio error's name as `code`.
28fn thrown(failure: AudioFailure, src: &str) -> JsError {
29    match failure.error {
30        AudioError::NotAllowed => {
31            let permission = permission_of(&failure);
32            JsError::access_denied(failure.message, permission, src)
33        }
34        AudioError::QuotaExceeded => {
35            JsError::Error(failure.message).with_code(codes::QUOTA_EXCEEDED)
36        }
37        AudioError::Unavailable => JsError::Error(failure.message).with_code(codes::UNAVAILABLE),
38        error => JsError::Error(failure.message).with_code(error.as_str()),
39    }
40}
41
42/// The capability a refusal names: the one the core recorded, or, for a
43/// player's, the one its message ends with (the core words it without the
44/// app's text, [`crate::core::SOURCE_NOT_GRANTED`]); else as before.
45fn permission_of(failure: &AudioFailure) -> &'static str {
46    if let Some(permission) = failure.permission {
47        return permission;
48    }
49    match failure
50        .message
51        .strip_prefix(crate::core::SOURCE_NOT_GRANTED)
52    {
53        Some("fs") => "fs",
54        Some(_) => "network",
55        None if failure.message.contains("network") => "network",
56        None => "audio",
57    }
58}
59
60/// Whether the app may make sound and load `src`: why not when it may not.
61fn granted(sys: &System, src: &str) -> Result<(), JsError> {
62    if !sys.access.allows_audio() {
63        return Err(JsError::access_denied(
64            "sound is not granted: add `\"audio\": true` to capabilities in nsh.json",
65            "audio",
66            src,
67        ));
68    }
69    let remote = src.starts_with("http://") || src.starts_with("https://");
70    if remote && !sys.access.allows_media(src) {
71        return Err(JsError::access_denied(
72            format!("`{src}` is not granted by capabilities.network in nsh.json"),
73            "network",
74            src,
75        ));
76    }
77    Ok(())
78}
79
80/// A volume from JS, checked.
81fn volume(value: Option<f64>) -> Result<f32, JsError> {
82    value.map_or(Ok(1.0), |v| check_volume(v as f32).map_err(JsError::Range))
83}
84
85/// A rate from JS, checked.
86fn rate(value: Option<f64>) -> Result<f32, JsError> {
87    value.map_or(Ok(1.0), |v| check_rate(v as f32).map_err(JsError::Range))
88}
89
90/// A sound's source from JS: a URL or path, or a sound file's bytes.
91impl JsValue for SoundSource {
92    fn ts_type(_types: &mut TsTypes) -> String {
93        "string | Uint8Array".into()
94    }
95
96    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
97        if let Some(src) = value.as_string() {
98            return Ok(Self::Url(src));
99        }
100        value
101            .as_bytes()
102            .map(Self::from)
103            .ok_or_else(|| value.expected("a string or a Uint8Array"))
104    }
105
106    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
107        match self {
108            Self::Url(src) => src.to_js(host),
109            Self::Bytes(bytes) => bytes.to_vec().to_js(host),
110        }
111    }
112}
113
114/// A short sound decoded into memory, played any number of times,
115/// overlapping: feedback, alerts, notices. Load it ahead with
116/// `Sound.load`, then `play()` starts at once. Sounds are at most 5 s
117/// long and 8 MB encoded; longer audio is an `AudioPlayer`'s. Freed by
118/// `dispose()`, or when what loaded it goes (a component).
119#[class]
120pub(crate) struct Sound {
121    /// The loaded sound; `None` once what loaded it went.
122    sound: Rc<RefCell<Option<crate::element::Sound>>>,
123}
124
125#[class]
126impl Sound {
127    /// Resolves with whether sound plays here: `false` where nothing plays
128    /// it, and `load` then rejects with
129    /// `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`.
130    pub(crate) fn available() -> Later<bool> {
131        Later::new(async { Ok::<_, JsError>(crate::element::audio_available().await) })
132    }
133
134    /// Loads a sound and decodes it into memory: from `src`, a bundled
135    /// asset's path, `file:`, `data:`, or an `http(s)` URL `network`
136    /// grants, or the encoded bytes of a sound file (a `Uint8Array`: one the
137    /// app made or downloaded), whose format is read from them. Loading a
138    /// source (or bytes) loaded already shares it. Rejects with
139    /// `ERR_ACCESS_DENIED` when the `audio` capability (or `network`, for a
140    /// remote source) is not granted, `ERR_NSH_QUOTA_EXCEEDED` past a
141    /// limit (8 MB encoded, 5 s long, 64 sounds, 16 MB decoded in all),
142    /// `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` where nothing plays sound, and
143    /// an `Error` with `code` `"network"`, `"decode"` or `"not-supported"`
144    /// when it cannot be read or decoded.
145    pub(crate) fn load(src: SoundSource, sys: System, cx: CallCx<'_>) -> Later<Sound> {
146        // What a denial names: the source, or nothing for bytes.
147        let resource = match &src {
148            SoundSource::Url(src) => src.clone(),
149            _ => String::new(),
150        };
151        let checked = granted(&sys, &resource);
152        let slot: Rc<RefCell<Option<crate::element::Sound>>> = Rc::default();
153        // What loaded it goes: the sound goes with it.
154        let cleanup = cx.on_cleanup({
155            let slot = Rc::downgrade(&slot);
156            move || {
157                if let Some(slot) = slot.upgrade() {
158                    slot.borrow_mut().take();
159                }
160            }
161        });
162        Later::new(async move {
163            checked?;
164            match crate::element::load_sound(src).await {
165                Ok(sound) => {
166                    *slot.borrow_mut() = Some(sound);
167                    // Kept: the owner frees it.
168                    drop(cleanup);
169                    Ok(Sound { sound: slot })
170                }
171                Err(failure) => {
172                    cleanup.release();
173                    Err(thrown(failure, &resource))
174                }
175            }
176        })
177    }
178
179    /// Plays the sound over what plays, at `volume` (0 to 1, 1 when not
180    /// given) and `rate` (0.5 to 2, 1 when not given; the pitch goes with
181    /// it). Throws a `RangeError` for a value out of range; a muted device
182    /// is silence, not an error. Nothing once it was freed.
183    pub(crate) fn play(&self, options: Option<PlayOptions>) -> Result<(), JsError> {
184        let options = options.unwrap_or_default();
185        let volume = volume(options.volume)?;
186        let rate = rate(options.rate)?;
187        if let Some(sound) = &*self.sound.borrow() {
188            sound.play(volume, rate);
189        }
190        Ok(())
191    }
192
193    /// Stops every play of the sound.
194    pub(crate) fn stop(&self) {
195        if let Some(sound) = &*self.sound.borrow() {
196            sound.stop();
197        }
198    }
199
200    /// How long it plays, in seconds (0 once freed).
201    #[getter]
202    pub(crate) fn duration(&self) -> f64 {
203        self.sound
204            .borrow()
205            .as_ref()
206            .map_or(0.0, |s| s.duration().as_secs_f64())
207    }
208}
209
210/// How `Sound.play` plays.
211#[derive(Debug, Clone, Default, PartialEq, JsObject)]
212#[prop(exact)]
213pub(crate) struct PlayOptions {
214    /// From 0 (silent) to 1 (as recorded, when not given).
215    volume: Option<f64>,
216    /// From 0.5 to 2 (1 when not given); the pitch goes with it.
217    rate: Option<f64>,
218}
219
220/// How an `AudioPlayer` plays.
221#[derive(Debug, Clone, Default, PartialEq, JsObject)]
222#[prop(exact)]
223pub(crate) struct AudioPlayerOptions {
224    /// From 0 (silent) to 1 (as recorded, when not given).
225    volume: Option<f64>,
226    /// From 0.5 to 2 (1 when not given); the pitch is kept where the
227    /// platform can.
228    rate: Option<f64>,
229    /// Starts again at its end, without `end` (false when not given).
230    r#loop: Option<bool>,
231}
232
233/// Where a player is.
234#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
235pub(crate) enum AudioPlayerState {
236    /// Nothing asked yet, or failed (`error` said why).
237    Idle,
238    /// Loading its source, or waiting for data.
239    Loading,
240    /// Playing.
241    Playing,
242    /// Paused.
243    Paused,
244    /// Played to its end.
245    Ended,
246}
247
248/// A player's events.
249#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
250pub(crate) enum AudioPlayerEvent {
251    Load,
252    Progress,
253    Buffer,
254    End,
255    Error,
256}
257
258/// The event a player knows its duration with (`on`'s first overload).
259#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
260pub(crate) enum AudioLoadEvent {
261    Load,
262}
263
264/// The event a player reports where it is with (`on`'s second overload).
265#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
266pub(crate) enum AudioProgressEvent {
267    Progress,
268}
269
270/// The event a player waits for data with (`on`'s third overload).
271#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
272pub(crate) enum AudioBufferEvent {
273    Buffer,
274}
275
276/// The event a player ends with (`on`'s fourth overload).
277#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
278pub(crate) enum AudioEndEvent {
279    End,
280}
281
282/// The event a player fails with (`on`'s fifth overload).
283#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
284pub(crate) enum AudioErrorEvent {
285    Error,
286}
287
288/// A player knows its duration (the `load` event).
289#[derive(Debug, Clone, Default, PartialEq, JsObject)]
290pub(crate) struct AudioLoad {
291    /// In seconds; `Infinity` for a live stream.
292    duration: f64,
293}
294
295/// Where a player is (the `progress` event).
296#[derive(Debug, Clone, Default, PartialEq, JsObject)]
297pub(crate) struct AudioProgress {
298    /// Its position, in seconds.
299    current_time: f64,
300    /// Its duration, in seconds (`NaN` while unknown, `Infinity` live).
301    duration: f64,
302}
303
304/// A player waits for data, or stopped waiting (the `buffer` event).
305#[derive(Debug, Clone, Default, PartialEq, JsObject)]
306pub(crate) struct AudioBuffering {
307    /// It waits.
308    buffering: bool,
309}
310
311/// Why a player failed (the `error` event).
312#[derive(Debug, Clone, Default, PartialEq, JsObject)]
313pub(crate) struct AudioErrorInfo {
314    /// `"not-allowed"`, `"network"`, `"decode"`, `"not-supported"`,
315    /// `"quota-exceeded"`, `"unavailable"` or `"failed"`.
316    code: String,
317    /// What happened, in words.
318    message: String,
319}
320
321/// What a listener gets.
322#[derive(Debug, Clone)]
323pub(crate) enum Payload {
324    Load(AudioLoad),
325    Progress(AudioProgress),
326    Buffer(AudioBuffering),
327    End,
328    Error(AudioErrorInfo),
329}
330
331impl JsValue for Payload {
332    fn ts_type(types: &mut TsTypes) -> String {
333        format!(
334            "{} | {} | {} | {}",
335            <AudioLoad as JsValue>::ts_type(types),
336            <AudioProgress as JsValue>::ts_type(types),
337            <AudioBuffering as JsValue>::ts_type(types),
338            <AudioErrorInfo as JsValue>::ts_type(types)
339        )
340    }
341
342    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
343        Err(value.expected("no value (a payload goes to JS only)"))
344    }
345
346    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
347        match self {
348            Payload::Load(load) => load.to_js(host),
349            Payload::Progress(progress) => progress.to_js(host),
350            Payload::Buffer(buffer) => buffer.to_js(host),
351            Payload::End => Ret::into_js((), host),
352            Payload::Error(error) => error.to_js(host),
353        }
354    }
355}
356
357/// Listeners per event of one player, at most.
358const MAX_LISTENERS: usize = 64;
359
360/// A player's listeners with their ids, by [`AudioPlayerEvent`].
361type Listeners = [Vec<(u32, Callback<Payload>)>; 5];
362
363/// What a call made before the task opened the player asks of it.
364#[derive(Debug, Clone, Copy)]
365enum Queued {
366    Play,
367    Preload,
368    Pause,
369    Seek(Duration),
370}
371
372/// A `play()` waiting for the player to play.
373type PlayWait = Rc<RefCell<(Option<Result<(), JsError>>, Option<Waker>)>>;
374
375/// One player as its object and its task see it.
376#[derive(Default)]
377struct State {
378    src: String,
379    listeners: RefCell<Listeners>,
380    next_listener: Cell<u32>,
381    /// The core's player, once the task opened it; `None` again when it
382    /// closed.
383    player: RefCell<Option<crate::element::AudioPlayer>>,
384    /// What came before the task opened it.
385    queued: RefCell<Vec<Queued>>,
386    settings: Cell<PlayerSettings>,
387    /// The volume and rate as the app gave them (the settings hold `f32`s,
388    /// which would read back as `0.800000011920929`).
389    given: Cell<(f64, f64)>,
390    state: Cell<Option<AudioPlayerState>>,
391    position: Cell<Duration>,
392    /// `None` while unknown, `Some(None)` a live stream.
393    duration: Cell<Option<Option<Duration>>>,
394    plays: RefCell<Vec<PlayWait>>,
395    /// The platform said it plays, and has not paused, ended or failed.
396    playing: Cell<bool>,
397    closed: Cell<bool>,
398}
399
400impl State {
401    fn post(&self, event: AudioPlayerEvent, payload: Payload) {
402        for (_, listener) in &self.listeners.borrow()[event as usize] {
403            listener.post(payload.clone());
404        }
405    }
406
407    fn state(&self) -> AudioPlayerState {
408        self.state.get().unwrap_or(AudioPlayerState::Idle)
409    }
410
411    fn act(&self, queued: Queued) {
412        if self.closed.get() {
413            return;
414        }
415        match &*self.player.borrow() {
416            Some(player) => match queued {
417                Queued::Play => player.play(),
418                Queued::Preload => player.preload(),
419                Queued::Pause => player.pause(),
420                Queued::Seek(position) => player.seek(position),
421            },
422            None => self.queued.borrow_mut().push(queued),
423        }
424    }
425
426    fn set(&self, settings: PlayerSettings) {
427        self.settings.set(settings);
428        if let Some(player) = &*self.player.borrow() {
429            player.set_settings(settings);
430        }
431    }
432
433    fn settle(&self, result: Result<(), JsError>) {
434        for wait in self.plays.take() {
435            let waker = {
436                let mut wait = wait.borrow_mut();
437                wait.0 = Some(result.clone());
438                wait.1.take()
439            };
440            if let Some(waker) = waker {
441                waker.wake();
442            }
443        }
444    }
445
446    /// Stops and frees the player; its listeners go, and `play()`s waiting
447    /// reject.
448    fn close(&self) {
449        if self.closed.replace(true) {
450            return;
451        }
452        let player = self.player.borrow_mut().take();
453        drop(player);
454        self.listeners.take();
455        self.state.set(Some(AudioPlayerState::Idle));
456        self.settle(Err(JsError::Error("the player was closed".into())));
457    }
458
459    fn seconds(duration: Option<Option<Duration>>) -> f64 {
460        match duration {
461            None => f64::NAN,
462            Some(None) => f64::INFINITY,
463            Some(Some(d)) => d.as_secs_f64(),
464        }
465    }
466}
467
468/// Opens the core's player and follows its events until it closes.
469async fn run(state: Rc<State>, cleanup: Cleanup) {
470    if !state.closed.get() {
471        let player = crate::element::audio_player(&state.src, state.settings.get());
472        *state.player.borrow_mut() = Some(player);
473        for queued in state.queued.take() {
474            state.act(queued);
475        }
476        loop {
477            let event = std::future::poll_fn(|cx| match &mut *state.player.borrow_mut() {
478                Some(player) => player.poll_next(cx),
479                None => Poll::Ready(None),
480            })
481            .await;
482            let Some(event) = event else { break };
483            match event {
484                AudioEvent::Load { duration } => {
485                    state.duration.set(Some(duration));
486                    state.post(
487                        AudioPlayerEvent::Load,
488                        Payload::Load(AudioLoad {
489                            duration: State::seconds(Some(duration)),
490                        }),
491                    );
492                }
493                AudioEvent::Playing => {
494                    state.playing.set(true);
495                    state.state.set(Some(AudioPlayerState::Playing));
496                    state.settle(Ok(()));
497                }
498                AudioEvent::Paused => {
499                    state.playing.set(false);
500                    state.state.set(Some(AudioPlayerState::Paused));
501                }
502                AudioEvent::Progress { position, duration } => {
503                    state.position.set(position);
504                    if duration.is_some() {
505                        state.duration.set(Some(duration));
506                    }
507                    state.post(
508                        AudioPlayerEvent::Progress,
509                        Payload::Progress(AudioProgress {
510                            current_time: position.as_secs_f64(),
511                            duration: State::seconds(state.duration.get()),
512                        }),
513                    );
514                }
515                AudioEvent::Buffer { buffering } => {
516                    // Waiting for data while playing is loading; playing
517                    // again once it came.
518                    match (buffering, state.state()) {
519                        (true, AudioPlayerState::Playing) => {
520                            state.state.set(Some(AudioPlayerState::Loading));
521                        }
522                        (false, AudioPlayerState::Loading) if state.playing.get() => {
523                            state.state.set(Some(AudioPlayerState::Playing));
524                        }
525                        _ => {}
526                    }
527                    state.post(
528                        AudioPlayerEvent::Buffer,
529                        Payload::Buffer(AudioBuffering { buffering }),
530                    );
531                }
532                AudioEvent::Ended => {
533                    state.playing.set(false);
534                    state.state.set(Some(AudioPlayerState::Ended));
535                    if let Some(Some(duration)) = state.duration.get() {
536                        state.position.set(duration);
537                    }
538                    state.post(AudioPlayerEvent::End, Payload::End);
539                }
540                AudioEvent::Failed { error, message } => {
541                    state.playing.set(false);
542                    state.state.set(Some(AudioPlayerState::Idle));
543                    state.settle(Err(thrown(
544                        AudioFailure {
545                            error,
546                            message: message.clone(),
547                            permission: None,
548                        },
549                        &state.src,
550                    )));
551                    state.post(
552                        AudioPlayerEvent::Error,
553                        Payload::Error(AudioErrorInfo {
554                            code: error.as_str().into(),
555                            message,
556                        }),
557                    );
558                }
559                _ => {}
560            }
561        }
562    }
563    // An owner that lives long must not collect one cleanup per player.
564    cleanup.release();
565}
566
567/// A player of long audio, streamed from its source as it plays: music,
568/// voice messages, recordings. Nothing loads until `play()` or
569/// `preload()`. Stops and frees what plays it with `dispose()`, or when
570/// what made it goes (a component): keep it while it plays.
571#[class]
572pub(crate) struct AudioPlayer {
573    state: Rc<State>,
574}
575
576impl Drop for AudioPlayer {
577    fn drop(&mut self) {
578        self.state.close();
579    }
580}
581
582#[class]
583impl AudioPlayer {
584    /// A player of `src` (a bundled asset's path, `file:`, or an `http(s)`
585    /// URL `network` grants). Throws `ERR_ACCESS_DENIED` when the `audio`
586    /// capability (or `network`, for a remote source) is not granted, a
587    /// `RangeError` for a volume or rate out of range.
588    pub(crate) fn new(
589        src: String,
590        options: Option<AudioPlayerOptions>,
591        sys: System,
592        cx: CallCx<'_>,
593    ) -> Result<Self, JsError> {
594        let options = options.unwrap_or_default();
595        let settings = PlayerSettings {
596            volume: volume(options.volume)?,
597            rate: rate(options.rate)?,
598            looped: options.r#loop.unwrap_or(false),
599        };
600        granted(&sys, &src)?;
601        let state = Rc::new(State {
602            src,
603            settings: Cell::new(settings),
604            given: Cell::new((options.volume.unwrap_or(1.0), options.rate.unwrap_or(1.0))),
605            ..State::default()
606        });
607        let cleanup = cx.on_cleanup({
608            let state = Rc::downgrade(&state);
609            move || {
610                if let Some(state) = state.upgrade() {
611                    state.close();
612                }
613            }
614        });
615        cx.start(run(state.clone(), cleanup));
616        Ok(AudioPlayer { state })
617    }
618
619    /// Resolves with whether sound plays here (`Sound.available()`).
620    pub(crate) fn available() -> Later<bool> {
621        Later::new(async { Ok::<_, JsError>(crate::element::audio_available().await) })
622    }
623
624    /// Calls `listener` in JS's next turn: `load` once it knows its
625    /// duration; `progress` about 4 times a second while it plays, and
626    /// after a seek; `buffer` when it starts or stops waiting for data;
627    /// `end` when it played to its end (never while it loops); `error`
628    /// when it failed, with a `code` (`not-allowed`, `network`, `decode`,
629    /// `not-supported`, `unavailable`, `failed`). Returns a function that
630    /// stops it; it also stops when what called `on` goes (a component).
631    #[overload(fn(event: AudioLoadEvent, #[args(load)] listener: Callback<AudioLoad>) -> Stop)]
632    #[overload(fn(event: AudioProgressEvent, #[args(progress)] listener: Callback<AudioProgress>) -> Stop)]
633    #[overload(fn(event: AudioBufferEvent, #[args(buffer)] listener: Callback<AudioBuffering>) -> Stop)]
634    #[overload(fn(event: AudioEndEvent, listener: Callback<()>) -> Stop)]
635    #[overload(fn(event: AudioErrorEvent, #[args(error)] listener: Callback<AudioErrorInfo>) -> Stop)]
636    pub(crate) fn on(
637        &self,
638        event: AudioPlayerEvent,
639        #[args(payload)] listener: Callback<Payload>,
640    ) -> Result<Stop, JsError> {
641        if self.state.closed.get() {
642            return Ok(Stop::new(|| {}));
643        }
644        let id = self.state.next_listener.get();
645        self.state.next_listener.set(id.wrapping_add(1));
646        let mut listeners = self.state.listeners.borrow_mut();
647        let list = &mut listeners[event as usize];
648        if list.len() >= MAX_LISTENERS {
649            return Err(JsError::Error(format!(
650                "a player takes at most {MAX_LISTENERS} listeners per event"
651            ))
652            .with_code(codes::QUOTA_EXCEEDED));
653        }
654        list.push((id, listener));
655        let state: Weak<State> = Rc::downgrade(&self.state);
656        Ok(Stop::new(move || {
657            if let Some(state) = state.upgrade() {
658                state.listeners.borrow_mut()[event as usize].retain(|(i, _)| *i != id);
659            }
660        }))
661    }
662
663    /// Plays from where it is, loading first if needed; resolves once it
664    /// plays. Rejects as `error` reports when it fails (on the web, with
665    /// `code` `"not-allowed"` before the user's first gesture), and when
666    /// the player is disposed first.
667    pub(crate) fn play(&self) -> Later<()> {
668        let wait: PlayWait = Rc::default();
669        if self.state.closed.get() {
670            wait.borrow_mut().0 = Some(Err(JsError::Error("the player was closed".into())));
671        } else {
672            if self.state.state() != AudioPlayerState::Playing {
673                self.state.state.set(Some(AudioPlayerState::Loading));
674            }
675            self.state.plays.borrow_mut().push(wait.clone());
676            self.state.act(Queued::Play);
677        }
678        Later::new(std::future::poll_fn(move |cx| {
679            let mut wait = wait.borrow_mut();
680            match wait.0.take() {
681                Some(result) => Poll::Ready(result),
682                None => {
683                    wait.1 = Some(cx.waker().clone());
684                    Poll::Pending
685                }
686            }
687        }))
688    }
689
690    /// Starts loading without playing, so the first `play()` starts at
691    /// once.
692    pub(crate) fn preload(&self) {
693        self.state.act(Queued::Preload);
694    }
695
696    /// Pauses.
697    pub(crate) fn pause(&self) {
698        self.state.act(Queued::Pause);
699    }
700
701    /// Moves to `seconds` (past the end: the end). Throws a `RangeError`
702    /// for a negative, non-finite or unrepresentable time.
703    pub(crate) fn seek(&self, seconds: f64) -> Result<(), JsError> {
704        // `try_`: a finite time can still be too large for a `Duration`
705        // (`seek(1e30)`), which `from_secs_f64` panics on.
706        let Ok(position) = Duration::try_from_secs_f64(seconds) else {
707            return Err(JsError::Range(format!(
708                "`seek` takes a time of 0 seconds or more, not {seconds}"
709            )));
710        };
711        self.state.position.set(position);
712        self.state.act(Queued::Seek(position));
713        Ok(())
714    }
715
716    /// Its volume, from 0 (silent) to 1 (as recorded). Setting it out of
717    /// range throws a `RangeError`.
718    #[getter]
719    pub(crate) fn volume(&self) -> f64 {
720        self.state.given.get().0
721    }
722
723    #[setter]
724    pub(crate) fn set_volume(&self, value: f64) -> Result<(), JsError> {
725        let settings = PlayerSettings {
726            volume: volume(Some(value))?,
727            ..self.state.settings.get()
728        };
729        self.state.given.set((value, self.state.given.get().1));
730        self.state.set(settings);
731        Ok(())
732    }
733
734    /// Its rate, from 0.5 to 2 (the pitch kept where the platform can).
735    /// Setting it out of range throws a `RangeError`.
736    #[getter]
737    pub(crate) fn rate(&self) -> f64 {
738        self.state.given.get().1
739    }
740
741    #[setter]
742    pub(crate) fn set_rate(&self, value: f64) -> Result<(), JsError> {
743        let settings = PlayerSettings {
744            rate: rate(Some(value))?,
745            ..self.state.settings.get()
746        };
747        self.state.given.set((self.state.given.get().0, value));
748        self.state.set(settings);
749        Ok(())
750    }
751
752    /// Whether it starts again at its end (without `end`).
753    #[getter]
754    pub(crate) fn r#loop(&self) -> bool {
755        self.state.settings.get().looped
756    }
757
758    #[setter]
759    pub(crate) fn set_loop(&self, value: bool) {
760        let settings = PlayerSettings {
761            looped: value,
762            ..self.state.settings.get()
763        };
764        self.state.set(settings);
765    }
766
767    /// Its position, in seconds (the last `progress`'s, or a seek's).
768    #[getter]
769    pub(crate) fn current_time(&self) -> f64 {
770        self.state.position.get().as_secs_f64()
771    }
772
773    /// Its duration, in seconds: `NaN` until `load`, `Infinity` for a live
774    /// stream.
775    #[getter]
776    pub(crate) fn duration(&self) -> f64 {
777        State::seconds(self.state.duration.get())
778    }
779
780    /// `"idle"`, `"loading"`, `"playing"`, `"paused"` or `"ended"`.
781    #[getter]
782    pub(crate) fn state(&self) -> AudioPlayerState {
783        self.state.state()
784    }
785}
786
787#[cfg(test)]
788mod tests {
789    use super::{AudioError, AudioFailure, permission_of};
790
791    /// A refusal names the capability that would grant it, never one read
792    /// from the app's text in its message.
793    #[test]
794    fn refusals_name_the_capability_that_grants_them() {
795        let refused = |capability, message: &str| AudioFailure::refused(capability, message);
796        assert_eq!(
797            permission_of(&refused(
798                "network",
799                "`https://x/capabilities.fs` is not granted"
800            )),
801            "network"
802        );
803        assert_eq!(
804            permission_of(&refused("fs", "`/a/network.wav` is not granted")),
805            "fs"
806        );
807        assert_eq!(
808            permission_of(&refused("audio", "sound is not granted")),
809            "audio"
810        );
811        // A player's, as the core words it.
812        let player = |message: &str| AudioFailure {
813            error: AudioError::NotAllowed,
814            message: message.into(),
815            permission: None,
816        };
817        for (capability, expected) in [("fs", "fs"), ("network", "network")] {
818            let message = format!("{}{capability}", crate::core::SOURCE_NOT_GRANTED);
819            assert_eq!(permission_of(&player(&message)), expected);
820        }
821        assert_eq!(permission_of(&player("sound is not granted")), "audio");
822    }
823}