1#[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#[derive(Debug, Clone, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct AudioFailure {
36 pub error: AudioError,
38 pub message: String,
40 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 #[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#[derive(Default)]
79pub(crate) struct Sounds {
80 sources: HashMap<String, Source>,
82 decoded: u64,
84}
85
86enum Source {
87 Loading(Rc<Pending>),
88 Loaded(Weak<Buffer>),
89}
90
91impl Sounds {
92 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#[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
120struct 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
147pub 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#[derive(Debug, Clone, PartialEq)]
159#[non_exhaustive]
160pub enum SoundSource {
161 Url(String),
164 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
212pub async fn load_sound(src: impl Into<SoundSource>) -> Result<Sound, AudioFailure> {
221 let executor = executor();
222 let src = src.into();
223 #[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 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 #[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 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 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 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
324struct 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#[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#[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
396fn 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
408enum Fetch {
410 #[cfg(not(target_arch = "wasm32"))]
412 Read(Location),
413 Data(String),
415 Bytes(ImageData, String),
417 #[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
437fn 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
450fn 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
461async 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 None => Err(AudioFailure::new(
562 AudioError::Failed,
563 "the sound did not load",
564 )),
565 }
566}
567
568#[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#[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 pub fn duration(&self) -> Duration {
635 self.buffer.duration
636 }
637
638 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
673#[non_exhaustive]
674pub enum PlayerState {
675 #[default]
677 Idle,
678 Loading,
680 Playing,
682 Paused,
684 Ended,
686}
687
688pub 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
705pub 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 pub async fn next(&mut self) -> Option<AudioEvent> {
734 std::future::poll_fn(|cx| self.poll_next(cx)).await
735 }
736
737 pub fn poll_next(&mut self, cx: &mut std::task::Context<'_>) -> Poll<Option<AudioEvent>> {
739 self.events.poll_next(cx)
740 }
741
742 pub fn play(&self) {
744 self.act(AudioCommand::Resume { id: self.id });
745 }
746
747 pub fn preload(&self) {
749 self.act(AudioCommand::Preload { id: self.id });
750 }
751
752 pub fn pause(&self) {
754 self.act(AudioCommand::Pause { id: self.id });
755 }
756
757 pub fn seek(&self, position: Duration) {
759 self.act(AudioCommand::Seek {
760 id: self.id,
761 position,
762 });
763 }
764
765 pub fn settings(&self) -> PlayerSettings {
767 self.settings.get()
768 }
769
770 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 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 #[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 #[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 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}