lasprs 0.14.1

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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
#![allow(dead_code)]
use super::{DaqApiMethods, Stream, StreamMetaData};
use crate::config::{self, *};
use crate::daq::{self, *};
use crate::daq::{DaqApiDescriptor, streamdata::*};
use crate::tools::find_unused_buf;
use cpal::{
    BufferSize, Device, Host, Sample, SampleFormat, SampleRate, SupportedBufferSize,
    SupportedStreamConfig,
    traits::{DeviceTrait, HostTrait, StreamTrait},
};
use crossbeam::channel::{Receiver, Sender};
use itertools::Itertools;
use num::ToPrimitive;
use parking_lot::RwLock;
use reinterpret::reinterpret_slice;
use snafu::prelude::*;
use std::collections::VecDeque;
use std::collections::btree_map::OccupiedEntry;
use std::fmt::Debug;
use std::sync::Arc;

type Result<T> = std::result::Result<T, StreamMgrError>;

/// Convert CPAL sampleformat datatype
impl From<DataType> for cpal::SampleFormat {
    fn from(dt: DataType) -> cpal::SampleFormat {
        match dt {
            DataType::F64 => SampleFormat::F64,
            DataType::F32 => SampleFormat::F32,
            DataType::I8 => SampleFormat::I8,
            DataType::I16 => SampleFormat::I16,
            DataType::I32 => SampleFormat::I32,
            DataType::I24 => SampleFormat::I24,
        }
    }
}
// Convert datatype to CPAL sample format
impl TryFrom<cpal::SampleFormat> for DataType {
    type Error = ();
    fn try_from(sf: cpal::SampleFormat) -> std::result::Result<DataType, ()> {
        match sf {
            SampleFormat::F64 => Ok(DataType::F64),
            SampleFormat::F32 => Ok(DataType::F32),
            SampleFormat::I8 => Ok(DataType::I8),
            SampleFormat::I16 => Ok(DataType::I16),
            SampleFormat::I32 => Ok(DataType::I32),
            SampleFormat::I24 => Ok(DataType::I24),
            // These types are not supported by us
            SampleFormat::I64 => Err(()),
            SampleFormat::U8 => Err(()),
            SampleFormat::U16 => Err(()),
            SampleFormat::U24 => Err(()),
            SampleFormat::U32 => Err(()),
            SampleFormat::U64 => Err(()),
            SampleFormat::DsdU8 => Err(()),
            SampleFormat::DsdU16 => Err(()),
            SampleFormat::DsdU32 => Err(()),
            _ => Err(()),
        }
    }
}

/// Cpal api
pub struct CpalApi {
    host: cpal::Host,
}
impl Debug for CpalApi {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CpalApi").finish()
    }
}
pub struct CpalStream {
    stream: cpal::Stream,
    metadata: Arc<StreamMetaData>,
    noutchannels: usize,
    status: Arc<RwLock<StreamStatus>>,
}
impl Debug for CpalStream {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CpalStream")
            .field("metadata", &self.metadata)
            .field("noutchannels", &self.noutchannels)
            .field("status", &self.status)
            .finish()
    }
}
impl Stream for CpalStream {
    fn inMetaData(&self) -> Option<Arc<StreamMetaData>> {
        Some(self.metadata.clone())
    }
    fn status(&self, _dir: StreamDirection) -> StreamStatus {
        self.status.read().clone()
    }
    fn outMetaData(&self) -> Option<Arc<StreamMetaData>> {
        Some(self.metadata.clone())
    }
}

impl DaqApiMethods for CpalApi {
    fn getDeviceInfo(&self) -> Result<Vec<DeviceInfo>> {
        let samplerates_set1 = [
            1000, 2000, 4000, 8000, 12000, 16000, 24000, 48000, 96000, 192000, 384000,
        ];
        let samplerates_set2 = [11025, 22050, 44100, 88200];

        // Sort while still integer form
        let mut samplerates_set =
            Vec::from_iter(samplerates_set1.iter().chain(samplerates_set2.iter()));
        samplerates_set.sort();

        // Convert to floating point
        let samplerates_set = Vec::from_iter(samplerates_set.iter().map(|i| **i as Flt));

        let mut devs = vec![];
        for dev in self.host.devices()? {
            let mut iChannelCount = 0;
            let mut oChannelCount = 0;

            let mut avSampleRates = samplerates_set.clone();
            let mut avFramesPerBlock = vec![256_usize, 512, 1024, 2048, 4096, 8192];

            let mut sample_formats = vec![];
            // Search for sample formats
            if let Ok(icfg) = dev.supported_input_configs() {
                for icfg in icfg {
                    let thissf = icfg.sample_format();
                    if thissf.is_uint() {
                        // Ignore unsigned integer formats
                        continue;
                    }
                    sample_formats.push(icfg.sample_format());
                    avSampleRates.retain(|sr| {
                        *sr >= (icfg.min_sample_rate() as Flt)
                            && *sr <= (icfg.max_sample_rate() as Flt)
                    });
                    if let SupportedBufferSize::Range { min, max } = icfg.buffer_size() {
                        avFramesPerBlock.retain(|i| i >= &(*min as usize));
                        avFramesPerBlock.retain(|i| i <= &(*max as usize));
                    }
                    iChannelCount = icfg.channels() as u8;
                    // avFramesPerBlock.retain(|i| i >= icfg.buffer_size().)
                }
            }
            if let Ok(ocfg) = dev.supported_output_configs() {
                for ocfg in ocfg {
                    let thissf = ocfg.sample_format();
                    if thissf.is_uint() {
                        continue;
                    }
                    sample_formats.push(thissf);
                    avSampleRates.retain(|sr| *sr >= (ocfg.min_sample_rate() as Flt));
                    avSampleRates.retain(|sr| *sr <= (ocfg.max_sample_rate() as Flt));
                    if let SupportedBufferSize::Range { min, max } = ocfg.buffer_size() {
                        avFramesPerBlock.retain(|i| i >= &(*min as usize));
                        avFramesPerBlock.retain(|i| i <= &(*max as usize));
                    }
                    oChannelCount = ocfg.channels() as u8;
                }
            }

            // Bugfix here. We first had dedup(), but this only removes
            // consecutive duplicates. Iterating with the unique() filter
            // removes all duplicates.
            let dtypes: Vec<DataType> = sample_formats
                .iter()
                .unique()
                // Convert sample formats to data types, filtering out any that
                // fail
                .filter_map(|i| (*i).try_into().ok())
                .collect();

            if sample_formats.is_empty() || dtypes.is_empty() {
                // Skip device if it does not have any sample formats or data types.
                continue;
            }

            assert!(!dtypes.is_empty());
            let prefDataType = match dtypes.iter().position(|d| d == &DataType::F32) {
                Some(idx) => dtypes[idx],
                // Choose highest value. dtypes is already asserted to contain
                // at least one element.
                None => dtypes[dtypes.len() - 1],
            };

            // Default audio sample rate
            let prefSampleRate = 48000.;

            // Do not add device if it does not have any channels at all.
            if iChannelCount == oChannelCount && oChannelCount == 0 {
                continue;
            }
            if avSampleRates.is_empty() {
                continue;
            }
            devs.push(DeviceInfo {
                api: DaqApiDescriptor::Cpal,
                device_name: dev.description()?.name().into(),
                avDataTypes: dtypes,
                prefDataType,

                avSampleRates,
                prefSampleRate,
                avFramesPerBlock,
                prefFramesPerBlock: 2048,

                iChannelCount,
                oChannelCount,
                avInputRanges: vec![(-1., 1.)],
                avOutputRanges: vec![(-1., 1.)],
                hasInputIEPE: false,
                hasDuplexMode: false,
                hasInputACCouplingSwitch: false,
                hasInputTrigger: false,
                hasInternalOutputMonitor: false,
                duplexModeForced: false,
                physicalIOQty: Qty::Number,
            });
        }

        Ok(devs)
    }

    /// Start a stream for a device with a given configuration.
    fn startInputOrDuplexStream(
        &self,
        stype: StreamType,
        devinfo: &DeviceInfo,
        conf: &DaqConfig,
        sender: Sender<InStreamMsg>,
        _receiver: Option<Receiver<Arc<RawStreamData>>>,
    ) -> Result<Box<dyn Stream>> {
        ensure!(
            stype != StreamType::Duplex,
            DAQConfigSnafu {
                msg: "Duplex mode not supported for CPAL api"
            }
        );
        for cpaldev in self.host.devices()? {
            if cpaldev.description()?.name() == conf.device_name {
                // See if we can create a supported stream config.
                let supported_config = (match stype {
                    StreamType::Duplex => DAQConfigSnafu {
                        msg: "Duplex mode not supported for CPAL api",
                    }
                    .fail(),
                    StreamType::Input => CpalApi::create_cpal_config(
                        stype,
                        devinfo,
                        conf,
                        &cpaldev,
                        cpaldev.supported_input_configs()?,
                    ),
                    StreamType::Output => CpalApi::create_cpal_config(
                        stype,
                        devinfo,
                        conf,
                        &cpaldev,
                        cpaldev.supported_output_configs()?,
                    ),
                })?;
                let framesPerBlock = conf.framesPerBlock(devinfo);

                let sf = supported_config.sample_format();
                let mut config: cpal::StreamConfig = supported_config.config();
                config.buffer_size = BufferSize::Fixed(framesPerBlock as u32);

                let meta = StreamMetaData::new(
                    &conf.enabledInChannels(),
                    conf.dtype,
                    (supported_config.sample_rate() as Flt)
                        .try_into()
                        .context(DAQConfigValidationSnafu {})?,
                    framesPerBlock,
                    Qty::Number,
                );
                let meta = Arc::new(meta);

                let (stream, status) = CpalApi::build_input_stream(
                    meta.clone(),
                    sf,
                    &config,
                    &cpaldev,
                    sender,
                    conf.enabledInchannelsList(),
                    framesPerBlock,
                )?;

                stream.play()?;
                *status.write() = StreamStatus::newRunning();

                return Ok(Box::new(CpalStream {
                    stream,
                    metadata: meta,
                    noutchannels: 0,
                    status,
                }));
            }
        }
        DeviceNotAvailableSnafu {
            device_name: &devinfo.device_name,
        }
        .fail()
    }

    fn startOutputStream(
        &self,
        dev: &DeviceInfo,
        cfg: &DaqConfig,
        receiver: Receiver<Arc<RawStreamData>>,
    ) -> Result<Box<dyn Stream>> {
        let (device, cpalconfig, sampleformat, framesPerBlock) =
            self.getCPALOutputConfig(dev, cfg)?;

        let (stream, status) = Self::build_output_stream(
            sampleformat,
            &cpalconfig,
            &device,
            receiver,
            &cfg.outchannel_config,
            framesPerBlock,
        )?;

        stream.play()?;
        *status.write() = StreamStatus::newRunning();

        // // Specify data tape
        let dtype = DataType::try_from(sampleformat).map_err(|_| {
            DataTypeNotSupportedSnafu {
                dtype: format!("{sampleformat:?}"),
            }
            .build()
        })?;

        let md = StreamMetaData::new(
            &cfg.enabledOutChannels(),
            dtype,
            (cpalconfig.sample_rate as Flt)
                .try_into()
                .context(DAQConfigValidationSnafu {})?,
            framesPerBlock,
            Qty::Number,
        );
        let md = Arc::new(md);
        let str = Box::new(CpalStream {
            stream,
            metadata: md,
            noutchannels: cpalconfig.channels as usize,
            status,
        });
        Ok(str)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}
impl CpalApi {
    pub fn new() -> CpalApi {
        // let av_host = cpal::available_hosts();
        // for host in av_host {
        //     match host {
        //         cpal::HostId::Alsa => todo!(),
        //     }
        // }
        CpalApi {
            host: cpal::default_host(),
        }
    }
    // Create the error function closure, that capture the send channel on which error messages from the stream are sent
    fn create_errfcn(
        send_ch: Option<Sender<InStreamMsg>>,
        status: Arc<RwLock<StreamStatus>>,
        device_name: String,
        is_input: bool,
    ) -> impl FnMut(cpal::Error) {
        move |err: cpal::Error| {
            let serr = match err.kind() {
                cpal::ErrorKind::DeviceNotAvailable => StreamError::DeviceNotAvailable {
                    device_name: device_name.clone(),
                },
                cpal::ErrorKind::StreamInvalidated => StreamError::SystemError {
                    msg: "stream invalidated".into(),
                },
                cpal::ErrorKind::Xrun => {
                    if is_input {
                        StreamError::InputOverrun {}
                    } else {
                        StreamError::OutputUnderrun {}
                    }
                }
                _ => StreamError::SystemError {
                    msg: err.to_string(),
                },
            };
            if let Some(sender) = &send_ch {
                sender.send(InStreamMsg::StreamError(serr.clone())).unwrap();
            }
            *status.write() = StreamStatus::Error { e: serr };
        }
    }

    fn create_incallback<T>(
        meta: Arc<StreamMetaData>,
        config: &cpal::StreamConfig,
        sender: Sender<InStreamMsg>,
        framesPerBlock: usize,
        en_inchannels: Vec<usize>,
    ) -> impl FnMut(&[T], &cpal::InputCallbackInfo) + use<T>
    where
        T: 'static + Sample + ToPrimitive,
    {
        let tot_inch = config.channels as usize;

        let mut q = VecDeque::<T>::with_capacity(2 * tot_inch * framesPerBlock);

        // let meta = StreamMetaData::new()
        let mut ctr = 0;
        let mut bufs: VecDeque<Arc<RawStreamData>> = VecDeque::with_capacity(10);

        // The actual callback that is returned
        move |input: &[T], _: &cpal::InputCallbackInfo| {
            // Copy elements over in ring buffer
            q.extend(input);

            while q.len() > tot_inch * framesPerBlock {
                let mut buf = find_unused_buf(&mut bufs).unwrap_or_else(|| {
                    let buf: Vec<T> =
                        vec![Sample::EQUILIBRIUM; en_inchannels.len() * framesPerBlock];
                    Arc::new(RawStreamData::new(buf))
                });
                let out = Arc::get_mut(&mut buf)
                    .expect("Buf should be mutable")
                    .get_mut();

                // Loop over enabled channels
                for (i, ch) in en_inchannels.iter().enumerate() {
                    let in_iterator = q.iter().skip(*ch).step_by(tot_inch);
                    let out_iterator = out.iter_mut().skip(i).step_by(en_inchannels.len());

                    // Copy over elements, *DEINTERLEAVED*
                    out_iterator.zip(in_iterator).for_each(|(o, i)| {
                        *o = *i;
                    });
                }
                // let mut buf = find_unused_buf(&mut bufs).unwrap_or_else(|| Arc::new())

                // Drain copied elements from ring buffer
                q.drain(0..framesPerBlock * tot_inch);

                // Store back ref to buffer
                bufs.push_front(buf.clone());
                // Send over data
                let streamdata = Arc::new(InStreamData::newFromRaw(ctr, meta.clone(), buf));

                sender.send(InStreamMsg::InStreamData(streamdata)).unwrap();
                ctr += 1;
            }
        }
    }

    /// Create an input stream for a CPAL device.
    ///
    /// # Arguments
    ///
    /// * sf: Sample format
    fn build_input_stream(
        meta: Arc<StreamMetaData>,
        sf: cpal::SampleFormat,
        config: &cpal::StreamConfig,
        device: &cpal::Device,
        sender: Sender<InStreamMsg>,
        en_inchannels: Vec<usize>,
        framesPerBlock: usize,
    ) -> Result<(cpal::Stream, Arc<RwLock<StreamStatus>>)> {
        let status = Arc::new(RwLock::new(StreamStatus::NotRunning {}));

        let device_name = device
            .description()
            .map(|d| d.name().to_string())
            .unwrap_or_else(|_| "unknown device".to_string());
        let errfcn =
            CpalApi::create_errfcn(Some(sender.clone()), status.clone(), device_name, true);

        macro_rules! build_stream {
            ($($cpaltype:pat => $rtype:ty),*) => {
                match sf {
                    $(
                        $cpaltype => {
                        let icb = CpalApi::create_incallback::<$rtype>(
                            meta,
                            &config, sender, framesPerBlock, en_inchannels);
                            device.build_input_stream(
                            *config,
                            icb,
                            errfcn,
                            None)?
                }),*,
                        _ => {return DAQConfigSnafu {msg: format!("Unsupported sample format: {}", sf)}.fail();}
                }
            };
        }
        let stream: cpal::Stream = build_stream!(
        SampleFormat::I8 => i8,
        SampleFormat::I16 => i16,
        SampleFormat::I32 => i32,
        SampleFormat::F32 => f32
        );
        Ok((stream, status))
    }

    fn create_outcallback<T>(
        config: &cpal::StreamConfig,
        streamstatus: Arc<RwLock<StreamStatus>>,
        receiver: Receiver<Arc<RawStreamData>>,
        ch_config: &[DaqChannel],
        framesPerBlock: usize,
    ) -> impl FnMut(&mut [T], &cpal::OutputCallbackInfo) + use<T>
    where
        T: 'static + Sample + Debug,
    {
        let number_total_out_channels: usize = config.channels as usize;
        let number_enabled_out_channels = ch_config.iter().filter(|ch| ch.enabled).count();

        let disabled_ch = DaqChannel::default();
        let disabled_repeater = std::iter::repeat(&disabled_ch);
        let enabled_outch = ch_config.iter().chain(disabled_repeater);

        // Vector of enabled output channells, with length of number_total_out_channels
        let enabled_outch: Vec<bool> = (0..number_total_out_channels)
            .zip(enabled_outch)
            .map(|(_, b)| b.enabled)
            .collect();
        assert_eq!(enabled_outch.len(), number_total_out_channels);

        let mut callback_ctr: usize = 0;
        let mut q = VecDeque::<T>::with_capacity(2 * number_total_out_channels * framesPerBlock);

        move |outdata, _info: &_| {
            let nsamples_asked =
                (outdata.len() / number_total_out_channels) * number_enabled_out_channels;
            let status = streamstatus.read();
            callback_ctr += 1;

            let mut setToEquilibrium = || {
                outdata.iter_mut().for_each(|v| {
                    *v = Sample::EQUILIBRIUM;
                })
            };
            match *status {
                StreamStatus::NotRunning {} | StreamStatus::Error { .. } => {
                    setToEquilibrium();
                    return;
                }
                _ => {}
            }

            if q.len() < nsamples_asked {
                // Obtain new samples from the generator
                for dat in receiver.try_iter() {
                    let slice = dat.get_ref::<T>();
                    if let StreamStatus::Running { .. } = *status {
                        q.extend(slice);
                    }
                }
            }

            if q.len() >= nsamples_asked {
                // All right, we have enough samples to send out! They are
                // drained from the queue
                let out_chunks = outdata.iter_mut().chunks(number_total_out_channels);
                let siggen_chunks = q
                    .drain(..nsamples_asked)
                    .chunks(number_enabled_out_channels);
                for (och, ich) in out_chunks.into_iter().zip(&siggen_chunks) {
                    let mut sig_frame_iter = ich.into_iter();
                    och.into_iter().zip(&enabled_outch).for_each(|(o, en)| {
                        if *en {
                            *o = sig_frame_iter.next().unwrap();
                        } else {
                            *o = Sample::EQUILIBRIUM;
                        }
                    });
                }

                // outdata
                //     .iter_mut()
                //     .zip(q.drain(..nsamples_asked))
                //     .for_each(|(o, i)| {
                //         *o = i;
                //     });
            } else if callback_ctr <= 2 {
                // For the first two blocks, we allow dat the data is not yet
                // ready, without complaining on underruns
                setToEquilibrium();
            } else {
                // Output buffer underrun
                *streamstatus.write() = StreamStatus::Error {
                    e: StreamError::OutputUnderrun {},
                };
                setToEquilibrium();
            }
        }
    }

    fn build_output_stream(
        sf: cpal::SampleFormat,
        config: &cpal::StreamConfig,
        device: &cpal::Device,
        receiver: Receiver<Arc<RawStreamData>>,
        ch_config: &[DaqChannel],
        framesPerBlock: usize,
    ) -> Result<(cpal::Stream, Arc<RwLock<StreamStatus>>)> {
        let status = Arc::new(RwLock::new(StreamStatus::NotRunning {}));

        let device_name = device
            .description()
            .map(|d| d.name().to_string())
            .unwrap_or_else(|_| "unknown device".to_string());
        let err_cb = CpalApi::create_errfcn(None, status.clone(), device_name, false);
        macro_rules! build_stream {
            ($($cpaltype:pat => $rtype:ty),*) => {
                match sf {
                    $(
                        $cpaltype => {
        let outcallback = CpalApi::create_outcallback::<$rtype>(config, status.clone(), receiver, ch_config, framesPerBlock);
                            device.build_output_stream(
                            *config,
                            outcallback,
                            err_cb,
                            None)?
                }),*,
                        _ => {
                           return DAQConfigSnafu{msg: format!("Unsupported sample format '{}'", sf)}.fail();}
                }
            };
        }
        let stream: cpal::Stream = build_stream!(
        SampleFormat::I8 => i8,
        SampleFormat::I16 => i16,
        SampleFormat::I32 => i32,
        SampleFormat::F32 => f32
        );

        Ok((stream, status))
    }

    /// Create CPAL specific configuration, from our specified daq config and device info
    fn create_cpal_config<T>(
        st: StreamType,
        devinfo: &DeviceInfo,
        conf: &DaqConfig,
        _dev: &cpal::Device,
        conf_iterator: T,
    ) -> Result<cpal::SupportedStreamConfig>
    where
        T: Iterator<Item = cpal::SupportedStreamConfigRange>,
    {
        let nchannels = match st {
            StreamType::Input => devinfo.iChannelCount,
            StreamType::Output => devinfo.oChannelCount,
            _ => unreachable!(),
        };
        for cpalconf in conf_iterator {
            if cpalconf.sample_format() == conf.dtype.into() {
                // Specified sample format is available
                if cpalconf.channels() == (nchannels as u16) {
                    let requested_sr = conf.sampleRate(devinfo);
                    if (cpalconf.min_sample_rate() as Flt) <= requested_sr
                        && (cpalconf.max_sample_rate() as Flt) >= requested_sr
                    {
                        // Sample rate falls within range.
                        let requested_fpb = conf.framesPerBlock(devinfo) as u32;
                        // Last check: check if buffer size is allowed
                        if let SupportedBufferSize::Range { min, max } = cpalconf.buffer_size()
                            && (*min > requested_fpb || *max < requested_fpb)
                        {
                            return BufferSizeNotSupportedSnafu {
                                min: *min,
                                max: *max,
                                requested: requested_fpb,
                            }
                            .fail();
                        }

                        return Ok(cpalconf.with_sample_rate(requested_sr as u32));
                    }
                }
            }
        }
        APISpecificSnafu {
            msg: "specified DAQ configuration is not available for device",
        }
        .fail()
    }

    /// Start a default input stream.
    ///
    ///
    pub fn startDefaultInputStream(&self, sender: Sender<InStreamMsg>) -> Result<Box<dyn Stream>> {
        match self.host.default_input_device() {
            Some(device) => {
                if let Ok(config) = device.default_input_config() {
                    let framesPerBlock: usize = 4096;
                    let final_config = cpal::StreamConfig {
                        channels: config.channels(),
                        sample_rate: config.sample_rate(),
                        buffer_size: cpal::BufferSize::Fixed(framesPerBlock as u32),
                    };
                    let en_inchannels = Vec::from_iter((0..config.channels()).map(|i| i as usize));

                    let sf = config.sample_format();
                    // Specify data tape
                    let dtype = DataType::try_from(sf).map_err(|_| {
                        DataTypeNotSupportedSnafu {
                            dtype: format! {"{sf}"},
                        }
                        .build()
                    })?;

                    // Daq: default channel config
                    let daqchannels =
                        Vec::from_iter((0..final_config.channels).map(|i| {
                            DaqChannel::defaultAudio(format!("Unnamed input channel {i}"))
                        }));
                    // Create stream metadata
                    let metadata = StreamMetaData::new(
                        &daqchannels,
                        dtype,
                        (config.sample_rate() as Flt)
                            .try_into()
                            .context(DAQConfigValidationSnafu {})?,
                        framesPerBlock,
                        Qty::Number,
                    );
                    let metadata = Arc::new(metadata);

                    let (stream, status) = CpalApi::build_input_stream(
                        metadata.clone(),
                        sf,
                        &final_config,
                        &device,
                        sender,
                        en_inchannels,
                        framesPerBlock,
                    )?;
                    stream.play()?;
                    *status.write() = StreamStatus::newRunning();

                    Ok(Box::new(CpalStream {
                        stream,
                        metadata,
                        noutchannels: 0,
                        status,
                    }))
                } else {
                    NoDefaultDeviceFoundSnafu {}.fail()
                }
            }
            _ => NoDefaultDeviceFoundSnafu {}.fail(),
        }
    }

    fn getDefaultOutputConfig(&self) -> Result<(Device, cpal::StreamConfig, SampleFormat, usize)> {
        if let Some(dev) = self.host.default_output_device() {
            let cfg = dev.default_output_config()?;
            // let framesPerBlock: usize = 256;
            // let framesPerBlock: usize = 8192;
            let framesPerBlock: usize = cfg.sample_rate() as usize;
            // let framesPerBlock: usize = 256;
            let final_config = cpal::StreamConfig {
                channels: cfg.channels(),
                sample_rate: cfg.sample_rate(),
                buffer_size: cpal::BufferSize::Fixed(framesPerBlock as u32),
            };
            return Ok((dev, final_config, cfg.sample_format(), framesPerBlock));
        }
        DeviceNotAvailableSnafu {
            device_name: "default output device".to_string(),
        }
        .fail()
    }

    pub fn startDefaultOutputStream(
        &self,
        receiver: Receiver<Arc<RawStreamData>>,
    ) -> Result<Box<dyn Stream>> {
        let (device, config, sampleformat, framesPerBlock) = self.getDefaultOutputConfig()?;

        // Daq: default channel config
        let daqchannels = Vec::from_iter(
            (0..config.channels)
                .map(|i| DaqChannel::defaultAudio(format!("Unnamed output channel {i}"))),
        );
        let (stream, status) = CpalApi::build_output_stream(
            sampleformat,
            &config,
            &device,
            receiver,
            &daqchannels,
            framesPerBlock,
        )?;

        stream.play()?;
        *status.write() = StreamStatus::newRunning();

        // // Specify data tape
        let dtype = DataType::try_from(sampleformat).map_err(|_| {
            DataTypeNotSupportedSnafu {
                dtype: format! {"{sampleformat}"},
            }
            .build()
        })?;

        // // Create stream metadata
        let md = StreamMetaData::new(
            &daqchannels,
            dtype,
            (config.sample_rate as Flt)
                .try_into()
                .context(DAQConfigValidationSnafu {})?,
            framesPerBlock,
            Qty::Number,
        );
        let md = Arc::new(md);
        let str = Box::new(CpalStream {
            stream,
            metadata: md,
            noutchannels: daqchannels.len(),
            status,
        });
        Ok(str)
    }

    fn getCPALOutputConfig(
        &self,
        dev: &DeviceInfo,
        daqconfig: &DaqConfig,
    ) -> Result<(Device, cpal::StreamConfig, SampleFormat, usize)> {
        let samplerate = dev.avSampleRates[daqconfig.sampleRateIndex] as u32;
        let framesPerBlock = dev.avFramesPerBlock[daqconfig.framesPerBlockIndex];

        let highest_ch: Result<usize> =
            daqconfig
                .highestEnabledOutChannel()
                .with_context(|| DAQConfigSnafu {
                    msg: "Not enough enabled output channels",
                });
        let highest_ch = highest_ch? as u16;

        for cpaldev in self.host.devices()? {
            if cpaldev.description()?.name() == dev.device_name {
                // Check, device name matches required device name
                for cpalcfg in cpaldev.supported_output_configs()? {
                    let sf = cpalcfg.sample_format();
                    if sf == daqconfig.dtype.into() {
                        let max_sr = cpalcfg.max_sample_rate();
                        let min_sr = cpalcfg.min_sample_rate();
                        if samplerate <= max_sr && samplerate >= min_sr {
                            let cfg = cpalcfg.with_sample_rate(samplerate);

                            let mut cfg = cfg.config();
                            cfg.channels = highest_ch + 1;

                            // Overwrite buffer size to required buffer size
                            cfg.buffer_size = cpal::BufferSize::Fixed(framesPerBlock as u32);

                            // Return tuple of device, config, sample format and
                            // frames per block
                            return Ok((cpaldev, cfg, sf, framesPerBlock));
                        }
                    }
                }
            }
        }
        DeviceNotAvailableSnafu {
            device_name: &dev.device_name,
        }
        .fail()
    }
}

impl From<cpal::Error> for StreamMgrError {
    fn from(value: cpal::Error) -> Self {
        match value.kind() {
            cpal::ErrorKind::UnsupportedConfig | cpal::ErrorKind::InvalidInput => {
                StreamMgrError::DAQConfigError {
                    msg: value.to_string(),
                }
            }
            cpal::ErrorKind::HostUnavailable => StreamMgrError::ApiNotAvailable {
                apiname: "CPAL".into(),
            },
            _ => StreamMgrError::BackendSpecificError {
                msg: value.to_string(),
            },
        }
    }
}