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
//! Provides stream messages that come from a running stream
use crate::config::*;
use crate::siggen::Siggen;
use anyhow::{bail, Result};
use cpal::{FromSample, Sample};
use itertools::Itertools;
use num::cast::AsPrimitive;
use num::{Bounded, FromPrimitive, Num};
use super::*;
use super::*;
use parking_lot::RwLock;
use reinterpret::{reinterpret_slice, reinterpret_vec};
use std::any::TypeId;
use std::sync::Arc;
use std::u128::MAX;
use strum_macros::Display;
/// Raw stream data coming from a stream or going to a stream.
#[derive(Clone, Debug)]
pub enum RawStreamData {
/// 8-bits integers
Datai8(Vec<i8>),
/// 16-bits integers
Datai16(Vec<i16>),
/// 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.
fn new<T, U>(input: T) -> RawStreamData
where
T: Into<Vec<U>> + 'static,
U: num::ToPrimitive + Clone + 'static,
{
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.
let i8type: TypeId = TypeId::of::<i8>();
let i16type: TypeId = TypeId::of::<i16>();
let i32type: TypeId = TypeId::of::<i32>();
let f32type: TypeId = TypeId::of::<f32>();
let f64type: TypeId = TypeId::of::<f64>();
// The type to create for
let thetype: TypeId = TypeId::of::<U>();
if i8type == thetype {
let v: Vec<i8> = unsafe { reinterpret_vec(input) };
RawStreamData::Datai8(v)
} else if i16type == thetype {
let v: Vec<i16> = unsafe { reinterpret_vec(input) };
RawStreamData::Datai16(v)
} else if i32type == thetype {
let v: Vec<i32> = unsafe { reinterpret_vec(input) };
RawStreamData::Datai32(v)
} else if f32type == thetype {
let v: Vec<f32> = unsafe { reinterpret_vec(input) };
RawStreamData::Dataf32(v)
} else if f64type == thetype {
let v: Vec<f64> = unsafe { reinterpret_vec(input) };
RawStreamData::Dataf64(v)
} else {
panic!("Not implemented sample type! Type: {thetype:?}, i8 = {i8type:?}, i16 = {i16type:?}, i32 = {i32type:?}, f32 = {f32type:?}, f64 = {f64type:?}.")
}
}
/// Return a reference to the slice of data.
///
/// # Panics
///
/// - If the tye requested does not match the type stored.
pub fn getRef<T>(&self) -> &[T]
where
T: Sample + 'static,
{
let type_requested = TypeId::of::<T>();
macro_rules! ret_ref {
($c:expr,$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)
}
Datai32(v) => {
ret_ref!(v, i32)
}
Dataf32(v) => {
ret_ref!(v, f32)
}
Dataf64(v) => {
ret_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: 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: RwLock<Option<Arc<Dmat>>>,
}
impl InStreamData {
#[inline]
/// Return reference to underlying raw data storage
pub fn getRaw(&self) -> &RawStreamData {
&self.raw
}
#[inline]
/// Convenience function to return the number of channels in this instreamdata.
pub fn nchannels(&self) -> usize {
self.meta.nchannels()
}
/// Iterate over raw data of a certain channel. Tye should be specificied
/// and if not set correctly, this results in undefined behavior
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())
}};
}
match &self.raw {
RawStreamData::Datai8(c) => {
create_iter!(c, i8)
}
RawStreamData::Datai16(c) => {
create_iter!(c, i16)
}
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) -> impl Iterator<Item = Flt> + '_
where
T: Sample + Copy + 'static,
Flt: FromSample<T>,
{
self.iter_channel_raw(ch)
.copied()
.map(move |v: T| Flt::from_sample(v) / self.meta.channelInfo[ch].sensitivity)
}
/// Iterate over data. where data is converted to floating point, and
/// corrected for sensivity values. Returns all data, in order of channel.
pub fn iter_deinterleaved_converted<'a, T>(&'a self) -> 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)),
)
}
/// Create new stream data object.
pub fn new<T, U>(ctr: usize, meta: Arc<StreamMetaData>, raw: T) -> InStreamData
where
T: Into<Vec<U>> + 'static,
U: Sample + num::ToPrimitive + Clone + 'static,
{
InStreamData {
ctr,
meta,
raw: RawStreamData::new(raw),
converted: RwLock::new(None),
}
}
/// Returns the number of frames in this InstreamData
pub fn nframes(&self) -> usize {
let nch = self.meta.nchannels();
match &self.raw {
RawStreamData::Datai8(c) => {
c.len() / nch
}
RawStreamData::Datai16(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.
pub fn getFloatData(&self) -> Arc<Dmat> {
if let Some(dat) = self.converted.read().as_ref() {
return dat.clone();
}
// In case we reach here, the data has not yet be converted to floating
// point, so we do this.
let mut write_lock = self.converted.write();
// It might be that another thread was 'first', and already performed
// the conversion. In that case, we still do an early return, and we
// just openend the lock twice for writing. Not a problem.
if let Some(dat) = write_lock.as_ref() {
return dat.clone();
}
let errmsg = "Data cannot be converted to floating point";
macro_rules! convert_data {
($t:ty) => {
Dmat::from_shape_vec(
(self.nframes(), self.nchannels()).f(),
self.iter_deinterleaved_converted::<$t>().collect(),
)
.expect(errmsg)
};
}
// Perform the actual conversion
let converted_data = match &self.raw {
RawStreamData::Datai8(_) => convert_data!(i8),
RawStreamData::Datai16(_) => convert_data!(i16),
RawStreamData::Datai32(_) => convert_data!(i32),
RawStreamData::Dataf32(_) => convert_data!(f32),
RawStreamData::Dataf64(_) => convert_data!(f64),
};
let converted_data = Arc::new(converted_data);
// Replace the option with the Some
write_lock.replace(converted_data.clone());
converted_data
}
}
#[cfg(test)]
mod test {
use cpal::Sample;
use num::traits::sign;
use super::*;
use crate::siggen::Siggen;
#[test]
fn test() {
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(fs, Nch, 1.).unwrap();
siggen.reset(fs);
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);
}
}