#[cfg(target_arch = "wasm32")]
use std::sync::Mutex;
use std::{
fmt::{Debug, Formatter},
path::{Path, PathBuf},
sync::Arc,
};
#[cfg(target_arch = "wasm32")]
use js_sys::Uint8Array;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsCast;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::JsFuture;
#[cfg(target_arch = "wasm32")]
use web_sys::Response;
#[cfg(target_arch = "wasm32")]
use crate::SoundscapeError;
#[derive(Clone)]
pub struct SoundAsset {
native_path: PathBuf,
wasm_url: String,
#[cfg(target_arch = "wasm32")]
browser_bytes: Arc<Mutex<Option<Arc<[u8]>>>>,
}
impl Debug for SoundAsset {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("SoundAsset")
.field("native_path", &self.native_path)
.field("wasm_url", &self.wasm_url)
.finish()
}
}
#[cfg(target_arch = "wasm32")]
fn browser_asset_error(error: impl std::fmt::Debug) -> SoundscapeError {
SoundscapeError::BrowserAsset(format!("{error:?}"))
}
#[cfg(target_arch = "wasm32")]
pub async fn fetch_browser_asset(url: &str) -> Result<Arc<[u8]>, SoundscapeError> {
let window = web_sys::window().ok_or_else(|| {
SoundscapeError::BrowserAsset("browser window is unavailable".to_string())
})?;
let response = JsFuture::from(window.fetch_with_str(url))
.await
.map_err(browser_asset_error)?
.dyn_into::<Response>()
.map_err(browser_asset_error)?;
if !response.ok() {
return Err(SoundscapeError::BrowserAsset(format!(
"request returned HTTP status {} {}",
response.status(),
response.status_text()
)));
}
let buffer = JsFuture::from(response.array_buffer().map_err(browser_asset_error)?)
.await
.map_err(browser_asset_error)?;
let array = Uint8Array::new(&buffer);
let mut bytes = Arc::<[u8]>::new_uninit_slice(array.length() as usize);
array.copy_to_uninit(Arc::get_mut(&mut bytes).unwrap());
Ok(unsafe { bytes.assume_init() })
}
impl SoundAsset {
pub fn new(native_path: impl Into<PathBuf>, wasm_url: impl Into<String>) -> Self {
Self {
native_path: native_path.into(),
wasm_url: wasm_url.into(),
#[cfg(target_arch = "wasm32")]
browser_bytes: Arc::new(Mutex::new(None)),
}
}
pub fn native_path(&self) -> &Path {
&self.native_path
}
pub fn wasm_url(&self) -> &str {
&self.wasm_url
}
pub fn clear_browser_cache(&self) {
#[cfg(target_arch = "wasm32")]
self.browser_bytes.lock().unwrap().take();
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn cached_browser_bytes(&self) -> Option<Arc<[u8]>> {
self.browser_bytes.lock().unwrap().clone()
}
#[cfg(target_arch = "wasm32")]
pub(crate) async fn load_browser_bytes(&self) -> Result<Arc<[u8]>, SoundscapeError> {
if let Some(bytes) = self.cached_browser_bytes() {
return Ok(bytes);
}
let bytes = fetch_browser_asset(self.wasm_url()).await?;
let mut browser_bytes = self.browser_bytes.lock().unwrap();
if let Some(cached_bytes) = browser_bytes.as_ref() {
return Ok(cached_bytes.clone());
}
*browser_bytes = Some(bytes.clone());
Ok(bytes)
}
}
#[derive(Clone, Debug, Default)]
pub enum SoundSource {
#[default]
Empty,
StaticBytes(&'static [u8]),
SharedBytes(Arc<[u8]>),
#[cfg(not(target_arch = "wasm32"))]
File(PathBuf),
Asset(SoundAsset),
}
impl PartialEq for SoundSource {
fn eq(&self, other: &Self) -> bool {
self.same_resource(other)
}
}
impl SoundSource {
pub(crate) fn same_resource(&self, other: &Self) -> bool {
match (self, other) {
(Self::Empty, Self::Empty) => true,
(Self::StaticBytes(left), Self::StaticBytes(right)) => std::ptr::eq(*left, *right),
(Self::SharedBytes(left), Self::SharedBytes(right)) => Arc::ptr_eq(left, right),
#[cfg(not(target_arch = "wasm32"))]
(Self::File(left), Self::File(right)) => left == right,
(Self::Asset(left), Self::Asset(right)) => {
left.native_path == right.native_path && left.wasm_url == right.wasm_url
}
_ => false,
}
}
pub fn empty() -> Self {
Self::Empty
}
pub fn static_bytes(bytes: &'static [u8]) -> Self {
Self::StaticBytes(bytes)
}
pub fn shared_bytes(bytes: impl AsRef<[u8]>) -> Self {
Self::SharedBytes(Arc::from(bytes.as_ref()))
}
pub fn shared_arc_bytes(bytes: Arc<[u8]>) -> Self {
Self::SharedBytes(bytes)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn file(path: impl Into<PathBuf>) -> Self {
Self::File(path.into())
}
pub fn asset(asset: SoundAsset) -> Self {
Self::Asset(asset)
}
pub fn len(&self) -> Option<u64> {
match self {
Self::Empty => Some(0),
Self::StaticBytes(bytes) => Some(bytes.len() as u64),
Self::SharedBytes(bytes) => Some(bytes.len() as u64),
#[cfg(not(target_arch = "wasm32"))]
Self::File(path) => std::fs::metadata(path).ok().map(|metadata| metadata.len()),
Self::Asset(asset) => {
#[cfg(not(target_arch = "wasm32"))]
{
std::fs::metadata(asset.native_path())
.ok()
.map(|metadata| metadata.len())
}
#[cfg(target_arch = "wasm32")]
{
asset.cached_browser_bytes().map(|bytes| bytes.len() as u64)
}
}
}
}
pub fn is_empty(&self) -> bool {
matches!(self, Self::Empty)
}
}
impl From<&'static [u8]> for SoundSource {
fn from(bytes: &'static [u8]) -> Self {
Self::static_bytes(bytes)
}
}
impl From<Arc<[u8]>> for SoundSource {
fn from(bytes: Arc<[u8]>) -> Self {
Self::shared_arc_bytes(bytes)
}
}
impl From<Vec<u8>> for SoundSource {
fn from(bytes: Vec<u8>) -> Self {
Self::SharedBytes(bytes.into())
}
}
impl From<SoundAsset> for SoundSource {
fn from(asset: SoundAsset) -> Self {
Self::asset(asset)
}
}
#[cfg(not(target_arch = "wasm32"))]
impl From<PathBuf> for SoundSource {
fn from(path: PathBuf) -> Self {
Self::File(path)
}
}