lasprs 0.14.2

Library for Acoustic Signal Processing (Rust edition, with optional Python bindings via pyo3)
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! Provides stream messages that come from a running stream
use crate::config::*;
use crate::siggen::Siggen;
use anyhow::{Result, bail};
use dasp_sample::{FromSample, Sample};
use itertools::Itertools;
use ndarray::ArcArray2;
use num::{Bounded, FromPrimitive, Num};

use super::*;
use super::*;
use parking_lot::RwLock;
use reinterpret::{reinterpret_mut_slice, reinterpret_slice, reinterpret_vec};
use std::any::{Any, TypeId};
use std::sync::{Arc, OnceLock};
use strum_macros::Display;

const UNWRAP_RAW_DATA_ERROR: &str = "No raw data available";

/// Raw stream data coming from a stream or going to a stream, in interleaved
/// form
#[derive(Clone, Debug)]
pub enum RawStreamData {
    /// 8-bits integers
    Datai8(Vec<i8>),
    /// 16-bits integers
    Datai16(Vec<i16>),
    /// 24-bits integers, stored as 32-bit integers within the range if -2^23 to
    /// 2^23 - 1
    Datai24(Vec<dasp_sample::I24>),
    /// 32-bits integers
    Datai32(Vec<i32>),
    /// 32-bits floats
    Dataf32(Vec<f32>),
    /// 64-bits floats
    Dataf64(Vec<f64>),
}

impl RawStreamData {
    /// Create raw stream data from slice of data, or vec of data. Copies over
    /// the data. Allocates a new buffer if a slice is provided.
    ///
    /// # Args
    ///
    /// - `input`: A Vec, slice, or any that will be stored inside.
    pub fn new<T, U>(input: T) -> RawStreamData
    where
        T: Into<Vec<U>> + 'static,
        U: Sample + Clone + 'static + Any,
    {
        let input = input.into();
        // Apparently, this code does not work with a match. I have searched
        // around and have not found the reason for this. So this is a bit of
        // stupid boilerplate.
        const i8type_id: TypeId = TypeId::of::<i8>();
        const i16type_id: TypeId = TypeId::of::<i16>();
        const i24type_id: TypeId = TypeId::of::<dasp_sample::I24>();
        const i32type_id: TypeId = TypeId::of::<i32>();
        const f32type_id: TypeId = TypeId::of::<f32>();
        const f64type_id: TypeId = TypeId::of::<f64>();

        // The type to create for
        let input_type_id: TypeId = TypeId::of::<U>();

        if i8type_id == input_type_id {
            let v: Vec<i8> = unsafe { reinterpret_vec(input) };
            RawStreamData::Datai8(v)
        } else if i16type_id == input_type_id {
            let v: Vec<i16> = unsafe { reinterpret_vec(input) };
            RawStreamData::Datai16(v)
        } else if i24type_id == input_type_id {
            let v: Vec<dasp_sample::I24> = unsafe { reinterpret_vec(input) };
            RawStreamData::Datai24(v)
        } else if i32type_id == input_type_id {
            let v: Vec<i32> = unsafe { reinterpret_vec(input) };
            RawStreamData::Datai32(v)
        } else if f32type_id == input_type_id {
            let v: Vec<f32> = unsafe { reinterpret_vec(input) };
            RawStreamData::Dataf32(v)
        } else if f64type_id == input_type_id {
            let v: Vec<f64> = unsafe { reinterpret_vec(input) };
            RawStreamData::Dataf64(v)
        } else {
            panic!(
                "Not implemented sample type! Type: {input_type_id:?},\
                i8 = {i8type_id:?}, i16 = {i16type_id:?}, i32 = {i32type_id:?},\
                f32 = {f32type_id:?}, f64 = {f64type_id:?}."
            )
        }
    }

    /// Return the number of samples in the stream data. This is the number of
    /// channels times the number of frames.
    pub fn nsamples(&self) -> usize {
        match self {
            RawStreamData::Datai8(v) => v.len(),
            RawStreamData::Datai16(v) => v.len(),
            RawStreamData::Datai24(v) => v.len(),
            RawStreamData::Datai32(v) => v.len(),
            RawStreamData::Dataf32(v) => v.len(),
            RawStreamData::Dataf64(v) => v.len(),
        }
    }

    /// Return a reference to the slice of data.
    ///
    /// # Panics
    ///
    /// - If the tye requested does not match the type stored.
    pub fn get_ref<T>(&self) -> &[T]
    where
        T: Sample + 'static,
    {
        let type_requested = TypeId::of::<T>();
        macro_rules! ret_ref {
            ($c:expr_2021,$t:ty) => {{
                let type_this = TypeId::of::<$t>();
                assert_eq!(type_requested, type_this, "Wrong type requested");
                unsafe { reinterpret_slice::<$t, T>(&$c) }
            }};
        }
        use RawStreamData::*;
        match &self {
            Datai8(v) => {
                ret_ref!(v, i8)
            }
            Datai16(v) => {
                ret_ref!(v, i16)
            }
            Datai24(v) => {
                ret_ref!(v, dasp_sample::I24)
            }
            Datai32(v) => {
                ret_ref!(v, i32)
            }
            Dataf32(v) => {
                ret_ref!(v, f32)
            }
            Dataf64(v) => {
                ret_ref!(v, f64)
            }
        }
    }
    /// Return a reference to the slice of data.
    ///
    /// # Panics
    ///
    /// - If the tye requested does not match the type stored.
    pub fn get_mut<T>(&mut self) -> &mut [T]
    where
        T: Sample + 'static,
    {
        let type_requested = TypeId::of::<T>();
        macro_rules! return_ref {
            ($c:expr_2021,$t:ty) => {{
                let type_this = TypeId::of::<$t>();
                assert_eq!(type_requested, type_this, "Wrong type requested");
                unsafe { reinterpret_mut_slice::<$t, T>($c) }
            }};
        }
        use RawStreamData::*;
        match self {
            Datai8(v) => {
                return_ref!(v, i8)
            }
            Datai16(v) => {
                return_ref!(v, i16)
            }
            Datai24(v) => {
                return_ref!(v, dasp_sample::I24)
            }
            Datai32(v) => {
                return_ref!(v, i32)
            }
            Dataf32(v) => {
                return_ref!(v, f32)
            }
            Dataf64(v) => {
                return_ref!(v, f64)
            }
        }
    }
}
/// Stream data (audio / other) coming from a stream or to be send to a stream
#[derive(Debug)]
pub struct InStreamData {
    /// Package counter. Should always increase monotonically.
    pub ctr: usize,

    /// Stream metadata. All info required for properly interpreting the raw data.
    pub meta: Arc<StreamMetaData>,

    /// This is typically what is stored when recording
    raw: Option<Arc<RawStreamData>>,

    // Converted to floating point format. Used for further real time
    // processing. Stored in an rw-lock. The first thread that acesses this data
    // will perform the conversion. All threads after that will get the data.
    converted_with_sensitivity: OnceLock<ArcArray<Flt, Ix2>>,

    // Converted to floating point format WITHOUT sensitivity applied. Stored in
    // an rw-lock. The first thread that acesses this data will perform the
    // conversion. All threads after that will get the data for free.
    converted_without_sensitivity: OnceLock<ArcArray<Flt, Ix2>>,
}

impl InStreamData {
    #[inline]
    /// Return reference to underlying raw data storage
    pub fn getRaw(&self) -> Option<Arc<RawStreamData>> {
        self.raw.clone()
    }
    #[inline]
    /// Convenience function to return the number of channels in this instreamdata.
    pub fn nchannels(&self) -> usize {
        self.meta.nchannels()
    }

    /// Check if converted data is already available
    pub fn isConverted(&self) -> bool {
        self.converted_without_sensitivity.get().is_some()
            || self.converted_with_sensitivity.get().is_some()
    }

    /// Iterate over raw data of a certain channel. Type should be specificied
    /// by generic parameter `T`.
    ///
    /// # Panics
    ///
    ///  - If type T does not correspond with type of raw data type
    ///  - If the stream data does not have any raw data (only converted /
    ///    floats)
    pub fn iter_channel_raw<'a, T>(&'a self, ch: usize) -> impl Iterator<Item = &'a T> + 'a
    where
        T: Sample + Copy + 'static,
    {
        let type_requested: TypeId = TypeId::of::<T>();
        macro_rules! create_iter {
            ($c:expr,$t:ty) => {{
                // Check that the type matches the type stored
                let cur_type: TypeId = TypeId::of::<$t>();
                assert!(
                    type_requested == cur_type,
                    "BUG: Type mismatch on channel data iterator"
                );
                let v: &'a [T] = unsafe { reinterpret_slice($c) };
                v.iter().skip(ch).step_by(self.meta.nchannels())
            }};
        }

        let raw = self.raw.as_ref().expect(UNWRAP_RAW_DATA_ERROR);
        match raw.as_ref() {
            RawStreamData::Datai8(c) => {
                create_iter!(c, i8)
            }
            RawStreamData::Datai16(c) => {
                create_iter!(c, i16)
            }
            RawStreamData::Datai24(c) => {
                create_iter!(c, i32)
            }
            RawStreamData::Datai32(c) => {
                create_iter!(c, i32)
            }
            RawStreamData::Dataf32(c) => {
                create_iter!(c, f32)
            }
            RawStreamData::Dataf64(c) => {
                create_iter!(c, f64)
            }
        }
    }
    /// Iterate over all channels, deinterleaved. So first all samples from the
    /// first channel, etc...
    pub fn iter_deinterleaved_raw_allchannels<'a, T>(
        &'a self,
    ) -> Box<dyn Iterator<Item = &'a T> + 'a>
    where
        T: Sample + Copy + 'static,
    {
        Box::new((0..self.meta.nchannels()).flat_map(|chi| self.iter_channel_raw(chi)))
    }
    fn iter_channel_converted<T>(
        &self,
        ch: usize,
        apply_sens: bool,
    ) -> impl Iterator<Item = Flt> + '_
    where
        T: Sample + Copy + 'static,
        Flt: FromSample<T>,
    {
        let sens = if apply_sens {
            self.meta.channelInfo[ch].sensitivity
        } else {
            1.0
        };

        self.iter_channel_raw(ch)
            .copied()
            .map(move |v: T| Flt::from_sample(v) / sens)
    }

    /// Iterate over data. where data is converted to floating point, and
    /// corrected for sensivity values. Returns all data, in order of channel.
    ///
    /// # Arguments
    /// * `apply_sens` - Whether to apply sensitivity correction.
    pub fn iter_deinterleaved_converted<'a, T>(
        &'a self,
        apply_sens: bool,
    ) -> Box<dyn Iterator<Item = Flt> + 'a>
    where
        T: Sample + Copy + 'static,
        Flt: FromSample<T>,
    {
        Box::new(
            (0..self.meta.nchannels())
                .flat_map(move |chi| self.iter_channel_converted(chi, apply_sens)),
        )
    }

    /// Create new stream data object.
    pub fn newFromRaw(
        ctr: usize,
        meta: Arc<StreamMetaData>,
        raw: Arc<RawStreamData>,
    ) -> InStreamData {
        InStreamData {
            ctr,
            meta,
            raw: Some(raw),
            converted_with_sensitivity: OnceLock::new(),
            converted_without_sensitivity: OnceLock::new(),
        }
    }

    /// Create InstreamData data that only contains the converted data (floating
    /// point) format, not the underlying raw format.
    pub fn newFromConverted(
        ctr: usize,
        meta: Arc<StreamMetaData>,
        data: Array2<Flt>,
        sens_applied: bool,
    ) -> InStreamData {
        let data: ArcArray2<Flt> = data.into();
        let converted_without_sensitivity = OnceLock::new();
        let converted_with_sensitivity = OnceLock::new();
        if sens_applied {
            converted_with_sensitivity
                .set(data)
                .expect("Cannot set data");
        } else {
            converted_without_sensitivity
                .set(data)
                .expect("Cannot set data");
        }
        InStreamData {
            ctr,
            meta,
            raw: None,
            converted_with_sensitivity,
            converted_without_sensitivity,
        }
    }

    /// Returns the number of frames in this InstreamData
    pub fn nframes(&self) -> usize {
        if self.isConverted() {
            return self
                .converted_without_sensitivity
                .get()
                .expect("isConverted not converted?")
                .nrows();
        }
        let nch = self.meta.nchannels();
        match self.raw.as_ref().expect(UNWRAP_RAW_DATA_ERROR).as_ref() {
            RawStreamData::Datai8(c) => c.len() / nch,
            RawStreamData::Datai16(c) => c.len() / nch,
            RawStreamData::Datai24(c) => c.len() / nch,
            RawStreamData::Datai32(c) => c.len() / nch,
            RawStreamData::Dataf32(c) => c.len() / nch,
            RawStreamData::Dataf64(c) => c.len() / nch,
        }
    }
    /// Get the data in floating point format. If already converted, uses the
    /// cached float data.
    ///
    /// # Arguments
    /// * `apply_sens` - Whether to apply sensitivity correction
    pub fn getFloatData(&self, apply_sens: bool) -> ArcArray2<Flt> {
        let errmsg = "Data cannot be converted to floating point";
        if apply_sens {
            self.converted_with_sensitivity
                .get_or_init(|| {
                    let sens = self.meta.sensitivities();
                    let converted_without_sens = self.getFloatData(false);
                    let mut converted_data = converted_without_sens.into_owned();
                    for (i, mut col) in converted_data.columns_mut().into_iter().enumerate() {
                        col /= sens[i];
                    }
                    let converted_data: ArcArray2<Flt> = converted_data.into();
                    converted_data
                })
                .clone()
        } else {
            self.converted_without_sensitivity
                .get_or_init(|| {
                    macro_rules! convert_data {
                        ($t:ty) => {
                            Dmat::from_shape_vec(
                                (self.nframes(), self.nchannels()).f(),
                                self.iter_deinterleaved_converted::<$t>(false).collect(),
                            )
                            .expect(errmsg)
                        };
                    }
                    // Perform the actual conversion
                    let converted_data =
                        match self.raw.as_ref().expect(UNWRAP_RAW_DATA_ERROR).as_ref() {
                            RawStreamData::Datai8(_) => convert_data!(i8),
                            RawStreamData::Datai16(_) => convert_data!(i16),
                            RawStreamData::Datai24(_) => convert_data!(i32),
                            RawStreamData::Datai32(_) => convert_data!(i32),
                            RawStreamData::Dataf32(_) => convert_data!(f32),
                            RawStreamData::Dataf64(_) => convert_data!(f64),
                        };
                    let converted_data: ArcArray2<Flt> = converted_data.into();
                    converted_data
                })
                .clone()
        }
    }
}

#[cfg(test)]
mod test {
    use dasp_sample::Sample;
    use num::traits::sign;

    use super::*;
    use crate::siggen::Siggen;

    #[test]
    fn test_streamdata() {
        const fs: Flt = 20.;
        // Number of samples per channel
        const Nframes: usize = 20;
        const Nch: usize = 2;
        let mut signal = [0.; Nch * Nframes];
        let mut siggen = Siggen::newSine(Nch, fs, 1.0).unwrap();

        siggen.setMute(&[false, true]);
        siggen.genSignal(&mut signal);

        let raw: Vec<i16> = Vec::from_iter(signal.iter().map(|o| o.to_sample::<i16>()));

        let ms1 = raw
            .iter()
            .step_by(2)
            .map(|s1| *s1 as f64 * *s1 as f64)
            .sum::<f64>()
            / Nframes as f64;

        let i16maxsq = (i16::MAX as f64).powf(2.);
        // println!("ms1: {} {}", ms1, i16maxsq/2.);
        // println!("{:?}", raw.iter().cloned().step_by(2).collect::<Vec<i16>>());
        // println!("{:?}", i16::EQUILIBRIUM);
        assert!(f64::abs(ms1 - i16maxsq / 2.) / i16maxsq < 1e-3);
    }
}