From 76ced9bb9dabaa932e276f71188e5284eebae004 Mon Sep 17 00:00:00 2001 From: Breval Ferrari Date: Mon, 10 Mar 2025 00:31:20 -0400 Subject: [PATCH] raw sound samples --- bingus/Cargo.toml | 2 ++ bingus/src/snd.rs | 3 ++ bingus/src/snd/raw.rs | 79 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 bingus/src/snd/raw.rs diff --git a/bingus/Cargo.toml b/bingus/Cargo.toml index 090a99d..ce8eaa3 100644 --- a/bingus/Cargo.toml +++ b/bingus/Cargo.toml @@ -17,3 +17,5 @@ infer = "0.16" thiserror = "2.0" derive-new = "0.7" strum = { version = "0.26", features = ["derive"] } +dasp_sample = "0.11.0" +derive_wrapper = "0.1" diff --git a/bingus/src/snd.rs b/bingus/src/snd.rs index e69de29..18a8a0f 100644 --- a/bingus/src/snd.rs +++ b/bingus/src/snd.rs @@ -0,0 +1,3 @@ +pub use dasp_sample::Sample; +mod raw; +pub use raw::RawSamples; diff --git a/bingus/src/snd/raw.rs b/bingus/src/snd/raw.rs new file mode 100644 index 0000000..fa7a8c5 --- /dev/null +++ b/bingus/src/snd/raw.rs @@ -0,0 +1,79 @@ +use super::Sample; +use derive_wrapper::{AsRef, From}; +use num::{ + traits::{FromBytes, ToBytes}, + Zero, +}; + +use crate::{Bendable, IntoDataBytes, TryFromDataBytes}; + +#[derive(From, AsRef)] +pub struct RawSamples(Vec) +where + T: Sample; + +impl IntoDataBytes for RawSamples +where + T: Sample + ToBytes, +{ + fn into_bytes(self) -> crate::Bytes { + self.as_ref() + .iter() + .flat_map(|subpixel| subpixel.to_ne_bytes().as_ref().to_vec()) + .collect() + } +} + +impl TryFromDataBytes for RawSamples +where + T: Sample + FromBytes + ToBytes + Zero, + ::Bytes: Sized + for<'a> TryFrom<&'a [u8]>, +{ + type Error = (); + type Format = (); + fn try_from_bytes( + bytes: crate::Bytes, + _format: Self::Format, + crop: crate::Crop, + ) -> Result + where + Self: Sized, + { + Ok(match crop { + crate::Crop::End => bytes + .chunks_exact(T::zero().to_ne_bytes().as_ref().len()) + .map(|p| { + T::from_ne_bytes(&match ::Bytes::try_from(p) { + Ok(v) => v, + Err(_) => unreachable!("you messed up chunk size!"), + }) + }) + .collect::>(), + crate::Crop::Start => bytes + .rchunks_exact(T::zero().to_ne_bytes().as_ref().len()) + .map(|p| { + T::from_ne_bytes(&match ::Bytes::try_from(p) { + Ok(v) => v, + Err(_) => unreachable!("you messed up chunk size!"), + }) + }) + .collect::>(), + } + .into()) + } +} + +impl Bendable for RawSamples +where + T: Sample + FromBytes + ToBytes + Zero, + ::Bytes: Sized + for<'a> TryFrom<&'a [u8]>, +{ + type Unit = T; + fn map Self::Unit + Sync>(mut self, f: F) -> Self { + self.0.iter_mut().for_each(|e| *e = f(e)); + self + } + fn format() -> crate::dynamic::Format { + crate::Format::Sound + } +}