Skip to main content

wavegraph_sample/
lib.rs

1// WaveGraph removed the unused alloc import and updated crate paths in the examples.
2//! Use the [**Sample**](./trait.Sample.html) trait to remain generic over sample types, easily
3//! access sample type conversions, apply basic audio operations and more.
4//!
5//! The **Sample** trait is the core abstraction throughout dasp on which most other abstractions
6//! are based.
7
8#![cfg_attr(not(feature = "std"), no_std)]
9
10pub use conv::{Duplex, FromSample, ToSample};
11pub use types::{I24, I48, U24, U48};
12
13pub mod conv;
14mod ops;
15pub mod types;
16
17/// A trait for working generically across different **Sample** format types.
18///
19/// Provides methods for converting to and from any type that implements the
20/// [`FromSample`](./trait.FromSample.html) trait and provides methods for performing signal
21/// amplitude addition and multiplication.
22///
23/// # Example
24///
25/// ```rust
26/// use wavegraph_sample::{I24, Sample};
27///
28/// fn main() {
29///     assert_eq!((-1.0).to_sample::<u8>(), 0);
30///     assert_eq!(0.0.to_sample::<u8>(), 128);
31///     assert_eq!(0i32.to_sample::<u32>(), 2_147_483_648);
32///     assert_eq!(I24::new(0).unwrap(), Sample::from_sample(0.0));
33///     assert_eq!(0.0, Sample::EQUILIBRIUM);
34/// }
35/// ```
36pub trait Sample: Copy + Clone + PartialOrd + PartialEq {
37    /// When summing two samples of a signal together, it is necessary for both samples to be
38    /// represented in some signed format. This associated `Addition` type represents the format to
39    /// which `Self` should be converted for optimal `Addition` performance.
40    ///
41    /// For example, u32's optimal `Addition` type would be i32, u8's would be i8, f32's would be
42    /// f32, etc.
43    ///
44    /// Specifying this as an associated type allows us to automatically determine the optimal,
45    /// lossless Addition format type for summing any two unique `Sample` types together.
46    ///
47    /// As a user of the `sample` crate, you will never need to be concerned with this type unless
48    /// you are defining your own unique `Sample` type(s).
49    type Signed: SignedSample + Duplex<Self>;
50
51    /// When multiplying two samples of a signal together, it is necessary for both samples to be
52    /// represented in some signed, floating-point format. This associated `Multiplication` type
53    /// represents the format to which `Self` should be converted for optimal `Multiplication`
54    /// performance.
55    ///
56    /// For example, u32's optimal `Multiplication` type would be f32, u64's would be f64, i8's
57    /// would be f32, etc.
58    ///
59    /// Specifying this as an associated type allows us to automatically determine the optimal,
60    /// lossless Multiplication format type for multiplying any two unique `Sample` types together.
61    ///
62    /// As a user of the `sample` crate, you will never need to be concerned with this type unless
63    /// you are defining your own unique `Sample` type(s).
64    type Float: FloatSample + Duplex<Self>;
65
66    /// The equilibrium value for the wave that this `Sample` type represents. This is normally the
67    /// value that is equal distance from both the min and max ranges of the sample.
68    ///
69    /// # Example
70    ///
71    /// ```rust
72    /// use wavegraph_sample::Sample;
73    ///
74    /// fn main() {
75    ///     assert_eq!(0.0, f32::EQUILIBRIUM);
76    ///     assert_eq!(0, i32::EQUILIBRIUM);
77    ///     assert_eq!(128, u8::EQUILIBRIUM);
78    ///     assert_eq!(32_768_u16, Sample::EQUILIBRIUM);
79    /// }
80    /// ```
81    ///
82    /// **Note:** This will likely be changed to an "associated const" if the feature lands.
83    const EQUILIBRIUM: Self;
84
85    /// The multiplicative identity of the signal.
86    ///
87    /// In other words: A value which when used to scale/multiply the amplitude or frequency of a
88    /// signal, returns the same signal.
89    ///
90    /// This is useful as a default, non-affecting amplitude or frequency multiplier.
91    ///
92    /// # Example
93    ///
94    /// ```rust
95    /// use wavegraph_sample::{Sample, U48};
96    ///
97    /// fn main() {
98    ///     assert_eq!(1.0, f32::IDENTITY);
99    ///     assert_eq!(1.0, i8::IDENTITY);
100    ///     assert_eq!(1.0, u8::IDENTITY);
101    ///     assert_eq!(1.0, U48::IDENTITY);
102    /// }
103    /// ```
104    const IDENTITY: Self::Float = <Self::Float as FloatSample>::IDENTITY;
105
106    /// Convert `self` to any type that implements `FromSample<Self>`.
107    ///
108    /// Find more details on type-specific conversion ranges and caveats in the `conv` module.
109    ///
110    /// # Example
111    ///
112    /// ```rust
113    /// use wavegraph_sample::Sample;
114    ///
115    /// fn main() {
116    ///     assert_eq!(0.0.to_sample::<i32>(), 0);
117    ///     assert_eq!(0.0.to_sample::<u8>(), 128);
118    ///     assert_eq!((-1.0).to_sample::<u8>(), 0);
119    /// }
120    /// ```
121    #[inline]
122    fn to_sample<S>(self) -> S
123    where
124        Self: ToSample<S>,
125    {
126        self.to_sample_()
127    }
128
129    /// Create a `Self` from any type that implements `ToSample<Self>`.
130    ///
131    /// Find more details on type-specific conversion ranges and caveats in the `conv` module.
132    ///
133    /// # Example
134    ///
135    /// ```rust
136    /// use wavegraph_sample::{Sample, I24};
137    ///
138    /// fn main() {
139    ///     assert_eq!(f32::from_sample(128_u8), 0.0);
140    ///     assert_eq!(i8::from_sample(-1.0), -128);
141    ///     assert_eq!(I24::from_sample(0.0), I24::new(0).unwrap());
142    /// }
143    /// ```
144    #[inline]
145    fn from_sample<S>(s: S) -> Self
146    where
147        Self: FromSample<S>,
148    {
149        FromSample::from_sample_(s)
150    }
151
152    /// Converts `self` to the equivalent `Sample` in the associated `Signed` format.
153    ///
154    /// This is a simple wrapper around `Sample::to_sample` which may provide extra convenience in
155    /// some cases, particularly for assisting type inference.
156    ///
157    /// # Example
158    ///
159    /// ```rust
160    /// use wavegraph_sample::Sample;
161    ///
162    /// fn main() {
163    ///     assert_eq!(128_u8.to_signed_sample(), 0i8);
164    /// }
165    /// ```
166    fn to_signed_sample(self) -> Self::Signed {
167        self.to_sample()
168    }
169
170    /// Converts `self` to the equivalent `Sample` in the associated `Float` format.
171    ///
172    /// This is a simple wrapper around `Sample::to_sample` which may provide extra convenience in
173    /// some cases, particularly for assisting type inference.
174    ///
175    /// # Example
176    ///
177    /// ```rust
178    /// use wavegraph_sample::Sample;
179    ///
180    /// fn main() {
181    ///     assert_eq!(128_u8.to_float_sample(), 0.0);
182    /// }
183    /// ```
184    fn to_float_sample(self) -> Self::Float {
185        self.to_sample()
186    }
187
188    /// Adds (or "offsets") the amplitude of the `Sample` by the given signed amplitude.
189    ///
190    /// `Self` will be converted to `Self::Signed`, the addition will occur and then the result
191    /// will be converted back to `Self`. These conversions allow us to correctly handle the
192    /// addition of unsigned signal formats.
193    ///
194    /// # Example
195    ///
196    /// ```rust
197    /// use wavegraph_sample::Sample;
198    ///
199    /// fn main() {
200    ///     assert_eq!(0.25.add_amp(0.5), 0.75);
201    ///     assert_eq!(192u8.add_amp(-128), 64);
202    /// }
203    /// ```
204    #[inline]
205    fn add_amp(self, amp: Self::Signed) -> Self {
206        let self_s = self.to_signed_sample();
207        (self_s + amp).to_sample()
208    }
209
210    /// Multiplies (or "scales") the amplitude of the `Sample` by the given float amplitude.
211    ///
212    /// - `amp` > 1.0 amplifies the sample.
213    /// - `amp` < 1.0 attenuates the sample.
214    /// - `amp` == 1.0 yields the same sample.
215    /// - `amp` == 0.0 yields the `Sample::EQUILIBRIUM`.
216    ///
217    /// `Self` will be converted to `Self::Float`, the multiplication will occur and then the
218    /// result will be converted back to `Self`. These conversions allow us to correctly handle the
219    /// multiplication of integral signal formats.
220    ///
221    /// # Example
222    ///
223    /// ```rust
224    /// use wavegraph_sample::Sample;
225    ///
226    /// fn main() {
227    ///     assert_eq!(64_i8.mul_amp(0.5), 32);
228    ///     assert_eq!(0.5.mul_amp(-2.0), -1.0);
229    ///     assert_eq!(64_u8.mul_amp(0.0), 128);
230    /// }
231    /// ```
232    #[inline]
233    fn mul_amp(self, amp: Self::Float) -> Self {
234        let self_f = self.to_float_sample();
235        (self_f * amp).to_sample()
236    }
237}
238
239/// A macro used to simplify the implementation of `Sample`.
240macro_rules! impl_sample {
241    ($($T:ty:
242       Signed: $Addition:ty,
243       Float: $Modulation:ty,
244       EQUILIBRIUM: $EQUILIBRIUM:expr),*) =>
245    {
246        $(
247            impl Sample for $T {
248                type Signed = $Addition;
249                type Float = $Modulation;
250                const EQUILIBRIUM: Self = $EQUILIBRIUM;
251            }
252        )*
253    }
254}
255
256// Expands to `Sample` implementations for all of the following types.
257impl_sample! {
258    i8:  Signed: i8,  Float: f32, EQUILIBRIUM: 0,
259    i16: Signed: i16, Float: f32, EQUILIBRIUM: 0,
260    I24: Signed: I24, Float: f32, EQUILIBRIUM: types::i24::EQUILIBRIUM,
261    i32: Signed: i32, Float: f32, EQUILIBRIUM: 0,
262    I48: Signed: I48, Float: f64, EQUILIBRIUM: types::i48::EQUILIBRIUM,
263    i64: Signed: i64, Float: f64, EQUILIBRIUM: 0,
264    u8:  Signed: i8,  Float: f32, EQUILIBRIUM: 128,
265    u16: Signed: i16, Float: f32, EQUILIBRIUM: 32_768,
266    U24: Signed: i32, Float: f32, EQUILIBRIUM: types::u24::EQUILIBRIUM,
267    u32: Signed: i32, Float: f32, EQUILIBRIUM: 2_147_483_648,
268    U48: Signed: i64, Float: f64, EQUILIBRIUM: types::u48::EQUILIBRIUM,
269    u64: Signed: i64, Float: f64, EQUILIBRIUM: 9_223_372_036_854_775_808,
270    f32: Signed: f32, Float: f32, EQUILIBRIUM: 0.0,
271    f64: Signed: f64, Float: f64, EQUILIBRIUM: 0.0
272}
273
274/// Integral and floating-point **Sample** format types whose equilibrium is at 0.
275///
276/// **Sample**s often need to be converted to some mutual **SignedSample** type for signal
277/// addition.
278pub trait SignedSample:
279    Sample<Signed = Self>
280    + core::ops::Add<Output = Self>
281    + core::ops::Sub<Output = Self>
282    + core::ops::Neg<Output = Self>
283{
284}
285macro_rules! impl_signed_sample { ($($T:ty)*) => { $( impl SignedSample for $T {} )* } }
286impl_signed_sample!(i8 i16 I24 i32 I48 i64 f32 f64);
287
288/// Sample format types represented as floating point numbers.
289///
290/// **Sample**s often need to be converted to some mutual **FloatSample** type for signal scaling
291/// and modulation.
292pub trait FloatSample:
293    Sample<Signed = Self, Float = Self>
294    + SignedSample
295    + core::ops::Mul<Output = Self>
296    + core::ops::Div<Output = Self>
297    + Duplex<f32>
298    + Duplex<f64>
299{
300    /// Represents the multiplicative identity of the floating point signal.
301    const IDENTITY: Self;
302    /// Calculate the square root of `Self`.
303    fn sample_sqrt(self) -> Self;
304}
305
306impl FloatSample for f32 {
307    const IDENTITY: Self = 1.0;
308    #[inline]
309    fn sample_sqrt(self) -> Self {
310        ops::f32::sqrt(self)
311    }
312}
313
314impl FloatSample for f64 {
315    const IDENTITY: Self = 1.0;
316    #[inline]
317    fn sample_sqrt(self) -> Self {
318        ops::f64::sqrt(self)
319    }
320}