1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! A crate of fundamentals for audio PCM DSP.
//!
//! - Use the [**Sample** trait](./trait.Sample.html) to remain generic across bit-depth.
//! - Use the [**Frame** trait](./frame/trait.Frame.html) to remain generic over channel layout.
//! - Use the [**Signal** trait](./signal/trait.Signal.html) for working with **Iterators** that yield **Frames**.
//! - Use the [**slice** module](./slice/index.html) for working with slices of **Samples** and **Frames**.
//! - See the [**conv** module](./conv/index.html) for fast conversions between slices, frames and samples.
//! - See the [**types** module](./types/index.html) for provided custom sample types.
//! - See the [**rate** module](./rate/index.html) for sample rate conversion and scaling.

#![recursion_limit="512"]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(alloc, collections, core_intrinsics))]

#[cfg(feature = "std")]
extern crate core;

#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(not(feature = "std"))]
#[macro_use]
extern crate collections;

#[cfg(not(feature = "std"))]
type Vec<T> = collections::vec::Vec<T>;
#[cfg(feature = "std")]
type Vec<T> = std::vec::Vec<T>;

#[cfg(not(feature = "std"))]
type VecDeque<T> = collections::vec_deque::VecDeque<T>;
#[cfg(feature = "std")]
type VecDeque<T> = std::collections::vec_deque::VecDeque<T>;

#[cfg(not(feature = "std"))]
pub type Box<T> = alloc::boxed::Box<T>;
#[cfg(feature = "std")]
pub type Box<T> = std::boxed::Box<T>;

#[cfg(not(feature = "std"))]
type Rc<T> = alloc::rc::Rc<T>;
#[cfg(feature = "std")]
type Rc<T> = std::rc::Rc<T>;

pub use conv::{
    FromSample, ToSample, Duplex,
    FromSampleSlice, ToSampleSlice, DuplexSampleSlice,
    FromSampleSliceMut, ToSampleSliceMut, DuplexSampleSliceMut,
    FromBoxedSampleSlice, ToBoxedSampleSlice, DuplexBoxedSampleSlice,
    FromFrameSlice, ToFrameSlice, DuplexFrameSlice,
    FromFrameSliceMut, ToFrameSliceMut, DuplexFrameSliceMut,
    FromBoxedFrameSlice, ToBoxedFrameSlice, DuplexBoxedFrameSlice,
    DuplexSlice, DuplexSliceMut, DuplexBoxedSlice,
};
pub use frame::Frame;
pub use signal::Signal;
pub use types::{I24, U24, I48, U48};

pub mod slice;
pub mod conv;
pub mod frame;
pub mod signal;
pub mod rate;
pub mod types;

#[cfg(not(feature = "std"))]
fn floor(x: f64) -> f64 {
    unsafe { core::intrinsics::floorf64(x) }
}
#[cfg(feature = "std")]
fn floor(x: f64) -> f64 {
    x.floor()
}

#[cfg(not(feature = "std"))]
fn sin(x: f64) -> f64 {
    unsafe { core::intrinsics::sinf64(x) }
}
#[cfg(feature = "std")]
fn sin(x: f64) -> f64 {
    x.sin()
}

#[cfg(not(feature = "std"))]
fn sqrt_f32(x: f32) -> f32 {
    unsafe { core::intrinsics::sqrtf32(x) }
}
#[cfg(feature = "std")]
fn sqrt_f32(x: f32) -> f32 {
    x.sqrt()
}

#[cfg(not(feature = "std"))]
fn sqrt_f64(x: f64) -> f64 {
    unsafe { core::intrinsics::sqrtf64(x) }
}
#[cfg(feature = "std")]
fn sqrt_f64(x: f64) -> f64 {
    x.sqrt()
}

/// A trait for working generically across different **Sample** format types.
///
/// Provides methods for converting to and from any type that implements the
/// [`FromSample`](./trait.FromSample.html) trait and provides methods for performing signal
/// amplitude addition and multiplication.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::{I24, Sample};
///
/// fn main() {
///     assert_eq!((-1.0).to_sample::<u8>(), 0);
///     assert_eq!(0.0.to_sample::<u8>(), 128);
///     assert_eq!(0i32.to_sample::<u32>(), 2_147_483_648);
///     assert_eq!(I24::new(0).unwrap(), Sample::from_sample(0.0));
///     assert_eq!(0.0, Sample::equilibrium());
/// }
/// ```
pub trait Sample: Copy + Clone + PartialOrd + PartialEq {

    /// When summing two samples of a signal together, it is necessary for both samples to be
    /// represented in some signed format. This associated `Addition` type represents the format to
    /// which `Self` should be converted for optimal `Addition` performance.
    ///
    /// For example, u32's optimal `Addition` type would be i32, u8's would be i8, f32's would be
    /// f32, etc.
    ///
    /// Specifying this as an associated type allows us to automatically determine the optimal,
    /// lossless Addition format type for summing any two unique `Sample` types together.
    ///
    /// As a user of the `sample` crate, you will never need to be concerned with this type unless
    /// you are defining your own unique `Sample` type(s).
    type Signed: SignedSample + Duplex<Self>;

    /// When multiplying two samples of a signal together, it is necessary for both samples to be
    /// represented in some signed, floating-point format. This associated `Multiplication` type
    /// represents the format to which `Self` should be converted for optimal `Multiplication`
    /// performance.
    ///
    /// For example, u32's optimal `Multiplication` type would be f32, u64's would be f64, i8's
    /// would be f32, etc.
    ///
    /// Specifying this as an associated type allows us to automatically determine the optimal,
    /// lossless Multiplication format type for multiplying any two unique `Sample` types together.
    ///
    /// As a user of the `sample` crate, you will never need to be concerned with this type unless
    /// you are defining your own unique `Sample` type(s).
    type Float: FloatSample + Duplex<Self>;

    /// The equilibrium value for the wave that this `Sample` type represents. This is normally the
    /// value that is equal distance from both the min and max ranges of the sample.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Sample;
    ///
    /// fn main() {
    ///     assert_eq!(0.0, f32::equilibrium());
    ///     assert_eq!(0, i32::equilibrium());
    ///     assert_eq!(128, u8::equilibrium());
    ///     assert_eq!(32_768_u16, Sample::equilibrium());
    /// }
    /// ```
    ///
    /// **Note:** This will likely be changed to an "associated const" if the feature lands.
    fn equilibrium() -> Self;

    /// The multiplicative identity of the signal.
    ///
    /// In other words: A value which when used to scale/multiply the amplitude or frequency of a
    /// signal, returns the same signal.
    ///
    /// This is useful as a default, non-affecting amplitude or frequency multiplier.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::{Sample, U48};
    ///
    /// fn main() {
    ///     assert_eq!(1.0, f32::identity());
    ///     assert_eq!(1.0, i8::identity());
    ///     assert_eq!(1.0, u8::identity());
    ///     assert_eq!(1.0, U48::identity());
    /// }
    /// ```
    #[inline]
    fn identity() -> Self::Float {
        <Self::Float as FloatSample>::identity()
    }

    /// Convert `self` to any type that implements `FromSample<Self>`.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Sample;
    ///
    /// fn main() {
    ///     assert_eq!(0.0.to_sample::<i32>(), 0);
    ///     assert_eq!(0.0.to_sample::<u8>(), 128);
    ///     assert_eq!((-1.0).to_sample::<u8>(), 0);
    /// }
    /// ```
    #[inline]
    fn to_sample<S>(self) -> S
        where Self: ToSample<S>,
    {
        self.to_sample_()
    }

    /// Create a `Self` from any type that implements `ToSample<Self>`.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::{Sample, I24};
    ///
    /// fn main() {
    ///     assert_eq!(f32::from_sample(128_u8), 0.0);
    ///     assert_eq!(i8::from_sample(-1.0), -128);
    ///     assert_eq!(I24::from_sample(0.0), I24::new(0).unwrap());
    /// }
    /// ```
    #[inline]
    fn from_sample<S>(s: S) -> Self
        where Self: FromSample<S>,
    {
        FromSample::from_sample_(s)
    }

    /// Converts `self` to the equivalent `Sample` in the associated `Signed` format.
    ///
    /// This is a simple wrapper around `Sample::to_sample` which may provide extra convenience in
    /// some cases, particularly for assisting type inference.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Sample;
    ///
    /// fn main() {
    ///     assert_eq!(128_u8.to_signed_sample(), 0i8);
    /// }
    /// ```
    fn to_signed_sample(self) -> Self::Signed {
        self.to_sample()
    }

    /// Converts `self` to the equivalent `Sample` in the associated `Float` format.
    ///
    /// This is a simple wrapper around `Sample::to_sample` which may provide extra convenience in
    /// some cases, particularly for assisting type inference.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Sample;
    ///
    /// fn main() {
    ///     assert_eq!(128_u8.to_float_sample(), 0.0);
    /// }
    /// ```
    fn to_float_sample(self) -> Self::Float {
        self.to_sample()
    }

    /// Adds (or "offsets") the amplitude of the `Sample` by the given signed amplitude.
    ///
    /// `Self` will be converted to `Self::Signed`, the addition will occur and then the result
    /// will be converted back to `Self`. These conversions allow us to correctly handle the
    /// addition of unsigned signal formats.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Sample;
    ///
    /// fn main() {
    ///     assert_eq!(0.25.add_amp(0.5), 0.75);
    ///     assert_eq!(192u8.add_amp(-128), 64);
    /// }
    /// ```
    #[inline]
    fn add_amp(self, amp: Self::Signed) -> Self {
        let self_s = self.to_signed_sample();
        (self_s + amp).to_sample()
    }

    /// Multiplies (or "scales") the amplitude of the `Sample` by the given float amplitude.
    ///
    /// - `amp` > 1.0 amplifies the sample.
    /// - `amp` < 1.0 attenuates the sample.
    /// - `amp` == 1.0 yields the same sample.
    /// - `amp` == 0.0 yields the `Sample::equilibrium`.
    ///
    /// `Self` will be converted to `Self::Float`, the multiplication will occur and then the
    /// result will be converted back to `Self`. These conversions allow us to correctly handle the
    /// multiplication of integral signal formats.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Sample;
    ///
    /// fn main() {
    ///     assert_eq!(64_i8.mul_amp(0.5), 32);
    ///     assert_eq!(0.5.mul_amp(-2.0), -1.0);
    ///     assert_eq!(64_u8.mul_amp(0.0), 128);
    /// }
    /// ```
    #[inline]
    fn mul_amp(self, amp: Self::Float) -> Self {
        let self_f = self.to_float_sample();
        (self_f * amp).to_sample()
    }

}

/// A macro used to simplify the implementation of `Sample`.
macro_rules! impl_sample {
    ($($T:ty:
       Signed: $Addition:ty,
       Float: $Modulation:ty,
       equilibrium: $equilibrium:expr),*) =>
    {
        $(
            impl Sample for $T {
                type Signed = $Addition;
                type Float = $Modulation;
                #[inline]
                fn equilibrium() -> Self {
                    $equilibrium
                }
            }
        )*
    }
}

// Expands to `Sample` implementations for all of the following types.
impl_sample!{
    i8:  Signed: i8,  Float: f32, equilibrium: 0,
    i16: Signed: i16, Float: f32, equilibrium: 0,
    I24: Signed: I24, Float: f32, equilibrium: types::i24::EQUILIBRIUM,
    i32: Signed: i32, Float: f32, equilibrium: 0,
    I48: Signed: I48, Float: f64, equilibrium: types::i48::EQUILIBRIUM,
    i64: Signed: i64, Float: f64, equilibrium: 0,
    u8:  Signed: i8,  Float: f32, equilibrium: 128,
    u16: Signed: i16, Float: f32, equilibrium: 32_768,
    U24: Signed: i32, Float: f32, equilibrium: types::u24::EQUILIBRIUM,
    u32: Signed: i32, Float: f32, equilibrium: 2_147_483_648,
    U48: Signed: i64, Float: f64, equilibrium: types::u48::EQUILIBRIUM,
    u64: Signed: i64, Float: f64, equilibrium: 9_223_372_036_854_775_808,
    f32: Signed: f32, Float: f32, equilibrium: 0.0,
    f64: Signed: f64, Float: f64, equilibrium: 0.0
}


/// Integral and floating-point **Sample** format types whose equilibrium is at 0.
///
/// **Sample**s often need to be converted to some mutual **SignedSample** type for signal
/// addition.
pub trait SignedSample: Sample<Signed=Self>
    + core::ops::Add<Output=Self>
    + core::ops::Sub<Output=Self>
    + core::ops::Neg<Output=Self> {}
macro_rules! impl_signed_sample { ($($T:ty)*) => { $( impl SignedSample for $T {} )* } }
impl_signed_sample!(i8 i16 I24 i32 I48 i64 f32 f64);

/// Sample format types represented as floating point numbers.
///
/// **Sample**s often need to be converted to some mutual **FloatSample** type for signal scaling
/// and modulation.
pub trait FloatSample: Sample<Signed=Self, Float=Self>
    + SignedSample
    + core::ops::Mul<Output=Self>
    + core::ops::Div<Output=Self>
    + Duplex<f32>
    + Duplex<f64>
{
    /// Represents the multiplicative identity of the floating point signal.
    fn identity() -> Self;
    /// Calculate the square root of `Self`. A convenience generic wrapper around `.sqrt()`.
    fn sample_sqrt(self) -> Self;
}

impl FloatSample for f32 {
    #[inline]
    fn identity() -> Self { 1.0 }
    #[inline]
    fn sample_sqrt(self) -> Self { sqrt_f32(self) }
}

impl FloatSample for f64 {
    #[inline]
    fn identity() -> Self { 1.0 }
    #[inline]
    fn sample_sqrt(self) -> Self { sqrt_f64(self) }
}