lasprs 0.8.0

Library for Acoustic Signal Processing (Rust edition, with optional Python bindings via pyo3)
Documentation
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
//! Data acquisition model. Provides abstract layers around DAQ devices.
use super::*;
use crate::{
    config::*,
    rt::PPM,
    siggen::{self, Siggen, SiggenCommand},
};
use anyhow::{anyhow, bail, Error, Result};
use api::StreamApiDescr;
use array_init::from_iter;
use core::time;
use cpal::Sample;
use crossbeam::{
    channel::{unbounded, Receiver, Sender, TrySendError},
    thread,
};
use std::thread::{JoinHandle, Thread};
use std::{
    sync::{atomic::AtomicBool, Arc, Mutex, Weak},
    time::Duration,
};
use streamcmd::StreamCommand;
use streamdata::*;
use streammetadata::*;
use streammsg::*;

#[cfg(feature = "cpal-api")]
use super::api::{api_cpal::CpalApi, Stream};

/// Keep track of whether the stream has been created. To ensure singleton behaviour.
static STREAMMGR_CREATED: AtomicBool = AtomicBool::new(false);

/// Store a queue in a shared pointer, to share sending
/// and receiving part of the queue.
pub type SharedInQueue = Sender<InStreamMsg>;

/// Vector of queues for stream messages
pub type InQueues = Vec<SharedInQueue>;

struct StreamInfo<T> {
    streamtype: StreamType,
    stream: Box<dyn Stream>,
    threadhandle: JoinHandle<T>,
    commtx: Sender<StreamCommand>,
    commrx: Receiver<Result<()>>,
}

/// Configure and manage input / output streams. This method is supposed to be a
/// SINGLETON. Runtime checks are performed to see whether this is true.
///
/// A stream manager provides the interaction layer for interacting with audio /
/// data streams.
///
/// * See [Recording] for an example of starting a recording on an input stream.
/// * See [Siggen] for an example of playing a signal to an output stream.
///
#[cfg_attr(feature = "python-bindings", pyclass(unsendable))]
pub struct StreamMgr {
    /// Input PPM detector, if running
    PPMmon: Weak<PPM>,

    /// Monitor PPM detector, if running
    PPMinp: Weak<PPM>,

    // List of available devices
    devs: Vec<DeviceInfo>,

    // Input stream can be both input and duplex
    input_stream: Option<StreamInfo<InQueues>>,

    // Output only stream
    output_stream: Option<StreamInfo<(InQueues, Siggen)>>,

    #[cfg(feature = "cpal-api")]
    cpal_api: CpalApi,

    /// The storage of queues. When no streams are running, they
    /// are here. When stream is running, they will become available
    /// in the JoinHandle of the thread.
    instreamqueues: Option<InQueues>,

    monitorqueues: Option<InQueues>,

    // Signal generator. Stored here on the bench in case no stream is running.
    // It is picked when it is configured correctly for the starting output stream
    // If it is not configured correctly, when a stream that outputs data is started
    // ,it is removed here.
    siggen: Option<crate::siggen::Siggen>,
}

#[cfg(feature = "python-bindings")]
#[cfg_attr(feature = "python-bindings", pymethods)]
impl StreamMgr {
    #[new]
    /// See (StreamMgr::new())
    fn new_py() -> StreamMgr {
        StreamMgr::new()
    }

    #[pyo3(name = "startDefaultInputStream")]
    fn startDefaultInputStream_py(&mut self) -> PyResult<()> {
        Ok(self.startDefaultInputStream()?)
    }
    #[pyo3(name = "startDefaultOutputStream")]
    fn startDefaultOutputStream_py(&mut self) -> PyResult<()> {
        Ok(self.startDefaultOutputStream()?)
    }
    #[pyo3(name = "startStream")]
    fn startStream_py(&mut self, st: StreamType, d: &DaqConfig) -> PyResult<()> {
        Ok(self.startStream(st, d)?)
    }
    #[pyo3(name = "stopStream")]
    fn stopStream_py(&mut self, st: StreamType) -> PyResult<()> {
        Ok(self.stopStream(st)?)
    }
    #[pyo3(name = "getDeviceInfo")]
    fn getDeviceInfo_py(&mut self) -> PyResult<Vec<DeviceInfo>> {
        Ok(self.getDeviceInfo())
    }
    #[pyo3(name = "getStatus")]
    fn getStatus_py(&self, st: StreamType) -> StreamStatus {
        self.getStatus(st)
    }
    #[pyo3(name = "setSiggen")]
    fn setSiggen_py(&mut self, siggen: Siggen) -> PyResult<()> {
        self.setSiggen(siggen)?;
        Ok(())
    }
    #[pyo3(name = "getStreamMetaData")]
    fn getStreamMetaData_py(&self, st: StreamType) -> Option<StreamMetaData> {
        // Unfortunately (but not really, only cosmetically), the underlying
        // value (not the Arc) has to be cloned.
        self.getStreamMetaData(st).map(|b| (*b).clone())
    }
    #[pyo3(name = "siggenCommand")]
    fn siggenCommand_py(&mut self, cmd: SiggenCommand) -> PyResult<()> {
        self.siggenCommand(cmd)?;
        Ok(())
    }
}

impl Default for StreamMgr {
    fn default() -> Self {
        Self::new()
    }
}

impl StreamMgr {
    /// Create new stream manager. A stream manager is supposed to be a
    /// singleton. Note that we let Rust's ownership model handle that there is
    /// only a single [StreamMgr].
    ///
    /// # Panics
    ///
    /// When a StreamMgr object is already alive.
    ///
    pub fn new() -> StreamMgr {
        if STREAMMGR_CREATED.load(std::sync::atomic::Ordering::Relaxed) {
            panic!("BUG: Stream manager is supposed to be a singleton");
        }
        STREAMMGR_CREATED.store(true, std::sync::atomic::Ordering::Relaxed);

        let mut smgr = StreamMgr {
            devs: vec![],
            input_stream: None,
            output_stream: None,
            siggen: Some(Siggen::newSilence(1., 1)),

            #[cfg(feature = "cpal-api")]
            cpal_api: CpalApi::new(),

            monitorqueues: Some(vec![]),
            instreamqueues: Some(vec![]),
            PPMmon: Weak::new(),
            PPMinp: Weak::new(),
        };
        smgr.devs = smgr.scanDeviceInfo();
        smgr
    }

    /// Returns the metadata for a given stream, when the stream type (see
    /// [StreamType]) is alive, i.e. (StreamMgr::getStatus) gives a 'Running'.
    ///
    pub fn getStreamMetaData(&self, t: StreamType) -> Option<Arc<StreamMetaData>> {
        match t {
            StreamType::Input | StreamType::Duplex => {
                if let Some(s) = &self.input_stream {
                    return Some(s.stream.metadata());
                }
            }
            StreamType::Output => {
                if let Some(s) = &self.output_stream {
                    return Some(s.stream.metadata());
                }
            }
        }
        None
    }

    /// Get stream status for given stream type.
    pub fn getStatus(&self, t: StreamType) -> StreamStatus {
        match t {
            StreamType::Input | StreamType::Duplex => {
                if let Some(s) = &self.input_stream {
                    s.stream.status()
                } else {
                    StreamStatus::NotRunning {}
                }
            }
            StreamType::Output => {
                if let Some(s) = &self.output_stream {
                    s.stream.status()
                } else {
                    StreamStatus::NotRunning {}
                }
            }
        }
    }
    /// Set a new signal generator. Returns an error if it is unapplicable.
    /// It is unapplicable if the number of channels of output does not match the
    /// number of output channels in a running stream.
    pub fn setSiggen(&mut self, siggen: Siggen) -> Result<()> {
        // Current signal generator. Where to place it?
        if let Some(os) = &self.output_stream {
            assert!(self.siggen.is_none());
            os.commtx.send(StreamCommand::NewSiggen(siggen)).unwrap();
            os.commrx.recv().unwrap()
        } else if let Some(istream) = &self.input_stream {
            if let StreamType::Duplex = istream.streamtype {
                assert!(self.siggen.is_none());
                istream
                    .commtx
                    .send(StreamCommand::NewSiggen(siggen))
                    .unwrap();
                istream.commrx.recv().unwrap()
            } else {
                self.siggen = Some(siggen);
                Ok(())
            }
        } else {
            self.siggen = Some(siggen);
            Ok(())
        }
    }

    /// Obtain a list of devices that are available for each available API
    pub fn getDeviceInfo(&mut self) -> Vec<DeviceInfo> {
        self.devs.clone()
    }

    fn scanDeviceInfo(&self) -> Vec<DeviceInfo> {
        let mut devinfo = vec![];
        #[cfg(feature = "cpal-api")]
        {
            let cpal_devs = self.cpal_api.getDeviceInfo();
            if let Ok(devs) = cpal_devs {
                devinfo.extend(devs);
            }
        }
        devinfo
    }

    /// Add a new queue to the lists of queues. On the queue, input data is
    /// added.
    ///
    /// If the stream is unable to write data on the queue (which might
    /// happen when the handler is dropped), the queue is removed from the list
    /// of queues that get data from the stream.
    pub fn addInQueue(&mut self, tx: Sender<InStreamMsg>) {
        if let Some(is) = &self.input_stream {
            is.commtx.send(StreamCommand::AddInQueue(tx)).unwrap();
            return;
        }
        if let Some(queuelist) = &mut self.instreamqueues {
            queuelist.push(tx);
            return;
        }
        panic!("Do not know where to store queue!");
    }
    /// Add a new monitor queue to the lists of queues. On the queue, monitor of
    /// output data is added.
    ///
    /// If the stream is unable to write data on the queue (which might happen
    /// when the handler is dropped), the queue is removed from the list of
    /// queues that get data from the signal generator.
    pub fn addMonitorQueue(&mut self, tx: SharedInQueue) {
        if let Some(os) = &self.output_stream {
            os.commtx.send(StreamCommand::AddMonitorQueue(tx)).unwrap();
            return;
        }
        if let Some(is) = &self.input_stream {
            if matches!(is.streamtype, StreamType::Duplex) {
                is.commtx.send(StreamCommand::AddMonitorQueue(tx)).unwrap();
                return;
            }
        }
        if let Some(queues) = &mut self.monitorqueues {
            queues.push(tx);
            return;
        }
        panic!("Do not know where to store monitor queue!");
    }

    fn startInputStreamThread(
        &mut self,
        meta: Arc<StreamMetaData>,
        rx: Receiver<InStreamMsg>,
    ) -> (
        JoinHandle<InQueues>,
        Sender<StreamCommand>,
        Receiver<Result<()>>,
    ) {
        // Bi-directional communication between input stream thread and stream manager
        let (commtx_ret, commrx) = unbounded();
        let (commtx, commrx_ret) = unbounded();

        // Unwrap here, as the queues should be free to grab
        let mut iqueues = self
            .instreamqueues
            .take()
            .expect("No input streams queues!");

        let threadhandle = std::thread::spawn(move || {
            'infy: loop {
                if let Ok(comm_msg) = commrx.try_recv() {
                    match comm_msg {
                        // New queue added
                        StreamCommand::AddInQueue(queue) => {
                            match queue.send(InStreamMsg::StreamStarted(meta.clone())) {
                                Ok(()) => {
                                    iqueues.push(queue);
                                    commtx.send(Ok(())).unwrap();
                                }
                                Err(e) => {
                                    commtx
                                        .send(Err(anyhow!(
                                            "Cannot push to queue: {e}. Object destructed?"
                                        )))
                                        .unwrap();
                                }
                            }
                        }

                        // Stop this thread. Returns the queue
                        StreamCommand::StopThread => {
                            sendMsgToAllQueuesRemoveUnused(
                                &mut iqueues,
                                InStreamMsg::StreamStopped,
                            );
                            commtx.send(Ok(())).unwrap();
                            break 'infy;
                        }
                        StreamCommand::NewSiggen(..) => {
                            panic!("Error: signal generator send to input-only stream.");
                        }
                        StreamCommand::SiggenCommand(..) => {
                            panic!("Error: signal generator command send to input-only stream.");
                        }
                        StreamCommand::AddMonitorQueue(..) => {
                            panic!("Error: add monitor queue command send to input-only stream.");
                        }
                    }
                }
                if let Ok(msg) = rx.recv_timeout(time::Duration::from_millis(10)) {
                    sendMsgToAllQueuesRemoveUnused(&mut iqueues, msg);
                }
            }
            iqueues
        });
        (threadhandle, commtx_ret, commrx_ret)
    }

    // Match device info struct on given daq config.
    fn find_device(&self, cfg: &DaqConfig) -> Result<&DeviceInfo> {
        if let Some(matching_dev) = self
            .devs
            .iter()
            .find(|&d| d.device_name == cfg.device_name && d.api == cfg.api)
        {
            return Ok(matching_dev);
        }
        bail!("Could not find device with name {}.", cfg.device_name);
    }

    /// Start signal generator thread
    ///
    /// # Args
    ///
    /// - `meta` - Stream metadata
    /// - `tx` - The channel where the generated signal needs to be send to.
    ///
    /// # Returns
    ///
    /// - Signal generator join handle
    /// - Channel part where messages can be send to, to control the signal
    ///   generator (change source, set gains etc)
    /// - Result receiver for messages from sending part.
    ///
    fn startSiggenThread(
        &mut self,
        meta: Arc<StreamMetaData>,
        tx: Sender<RawStreamData>,
        mut mon_queues: Vec<SharedInQueue>,
    ) -> (
        JoinHandle<(InQueues, Siggen)>,
        Sender<StreamCommand>,
        Receiver<Result<()>>,
    ) {
        let (commtx_res, commrx) = unbounded();
        let (commtx, commrx_res) = unbounded();

        // Number of channels to output for
        let nchannels = meta.nchannels();

        // Obtain signal generator. Set to silence when no signal generator is
        // installed.
        let mut siggen = self.siggen.take().expect("signal generator not available");

        siggen.setAllMute(true);
        if siggen.nchannels() != nchannels {
            // Updating number of channels
            siggen.setNChannels(nchannels);
        }
        siggen.reset(meta.samplerate);

        let threadhandle = std::thread::spawn(move || {
            // What is a good sleep time? We have made sure that there are
            // two buffers available for the output stream. We choose to wake up twice per frame.
            let sleep_time_us = Duration::from_micros(
                (0.5 * 1e6 * meta.framesPerBlock as Flt / meta.samplerate) as u64,
            );

            let mut floatbuf: Vec<Flt> = vec![0.; nchannels * meta.framesPerBlock];
            let mut ctr = 0;
            'infy: loop {
                if let Ok(comm_msg) = commrx.recv_timeout(sleep_time_us) {
                    match comm_msg {
                        // New queue added
                        StreamCommand::AddInQueue(_) => {
                            panic!("Invalid message send to output thread: AddInQueue");
                        }

                        // Stop this thread. Returns the queue
                        StreamCommand::StopThread => {
                            commtx.send(Ok(())).unwrap();
                            // Send all monitor queues the fact that the stream stops
                            mon_queues.retain(|q| q.send(InStreamMsg::StreamStopped).is_ok());
                            break 'infy;
                        }
                        StreamCommand::NewSiggen(new_siggen) => {
                            // println!("NEW SIGNAL GENERATOR ARRIVED!");
                            siggen = new_siggen;
                            siggen.reset(meta.samplerate);
                            if siggen.nchannels() != nchannels {
                                // println!("Updating channels");
                                siggen.setNChannels(nchannels);
                            }
                            commtx.send(Ok(())).unwrap();
                        }
                        StreamCommand::SiggenCommand(cmd) => {
                            // Apply command to signal generator.
                            let res = siggen.applyCommand(cmd);
                            commtx.send(res).unwrap();
                        }
                        StreamCommand::AddMonitorQueue(tx) => {
                            if let Ok(()) = tx.send(InStreamMsg::StreamStarted(meta.clone())) {
                                mon_queues.push(tx);
                            }
                        }
                    }
                }
                if tx.is_empty() {
                    // Obtain signal from signal generator
                    siggen.genSignal(&mut floatbuf);

                    // Convert signal generator data to raw data and push to the stream thread
                    let msg = match meta.rawDatatype {
                        DataType::I8 => {
                            let v = Vec::<i8>::from_iter(floatbuf.iter().map(|f| f.to_sample()));
                            RawStreamData::Datai8(v)
                        }
                        DataType::I16 => {
                            let v = Vec::<i16>::from_iter(floatbuf.iter().map(|f| f.to_sample()));
                            RawStreamData::Datai16(v)
                        }
                        DataType::I32 => {
                            let v = Vec::<i32>::from_iter(floatbuf.iter().map(|f| f.to_sample()));
                            RawStreamData::Datai32(v)
                        }
                        DataType::F32 => {
                            let v = Vec::<f32>::from_iter(floatbuf.iter().map(|f| f.to_sample()));
                            RawStreamData::Dataf32(v)
                        }
                        DataType::F64 => {
                            let v = Vec::<f64>::from_iter(floatbuf.iter().map(|f| f.to_sample()));
                            RawStreamData::Dataf64(v)
                        }
                    };
                    if let Err(_e) = tx.send(msg) {
                        // An error occured while trying to send the raw data to
                        // the stream. This might be because the stream has
                        // stopped or has an error.

                        // There is nothing we can do here, but we should not stop the thread.
                    }
                    if !mon_queues.is_empty() {
                        let floatdat = Array2::from_shape_fn(
                            (meta.framesPerBlock, meta.nchannels()).f(),
                            |(frame, channel)| floatbuf[frame * meta.nchannels() + channel],
                        );
                        let msg = InStreamMsg::InStreamData(Arc::new(
                            InStreamData::newFromConverted(ctr, meta.clone(), floatdat),
                        ));
                        mon_queues.retain(|q| q.send(msg.clone()).is_ok());
                    }

                    // Increment block counter
                    ctr += 1;
                }
            }
            (mon_queues, siggen)
        });
        (threadhandle, commtx_res, commrx_res)
    }

    /// Start a stream of certain type, using given configuration
    pub fn startStream(&mut self, stype: StreamType, cfg: &DaqConfig) -> Result<()> {
        match stype {
            StreamType::Input | StreamType::Duplex => {
                self.startInputOrDuplexStream(stype, cfg)?;
            }
            StreamType::Output => {
                self.startOutputStream(cfg)?;
            }
        }
        Ok(())
    }

    /// Start a stream for output only, using only the output channel
    /// configuration as given in the `cfg`.
    fn startOutputStream(&mut self, cfg: &DaqConfig) -> Result<()> {
        let (tx, rx): (Sender<RawStreamData>, Receiver<RawStreamData>) = unbounded();
        let stream = match cfg.api {
            StreamApiDescr::Cpal => {
                let devinfo = self.find_device(cfg)?;
                cfg_if::cfg_if! {
                    if #[cfg(feature="cpal-api")] {
                            self.cpal_api.startOutputStream(devinfo, cfg, rx)?
                    } else {
                        bail!("API {} not available", cfg.api)
                    }
                }
            }
            _ => bail!("API {} not implemented!", cfg.api),
        };
        let meta = stream.metadata();
        let monqueues = self
            .monitorqueues
            .take()
            .expect("Monitor queues not in store!");
        let (threadhandle, commtx, commrx) = self.startSiggenThread(meta, tx, monqueues);

        self.output_stream = Some(StreamInfo {
            streamtype: StreamType::Input,
            stream,
            threadhandle,
            commtx,
            commrx,
        });

        Ok(())
    }

    // Start an input or duplex stream
    fn startInputOrDuplexStream(&mut self, stype: StreamType, cfg: &DaqConfig) -> Result<()> {
        if self.input_stream.is_some() {
            bail!("An input stream is already running. Please first stop existing input stream.")
        }
        if cfg.numberEnabledInChannels() == 0 {
            bail!("At least one input channel should be enabled for an input stream")
        }
        if stype == StreamType::Duplex {
            if cfg.numberEnabledOutChannels() == 0 {
                bail!("At least one output channel should be enabled for a duplex stream")
            }
            if self.output_stream.is_some() {
                bail!("An output stream is already running. Duplex mode stream cannot be started. Please first stop existing output stream.");
            }
        }
        let (tx, rx): (Sender<InStreamMsg>, Receiver<InStreamMsg>) = unbounded();

        let stream = match cfg.api {
            StreamApiDescr::Cpal => {
                if stype == StreamType::Duplex {
                    bail!("Duplex mode not supported for CPAL api");
                }
                let devinfo = self.find_device(cfg)?;
                cfg_if::cfg_if! {
                    if #[cfg(feature="cpal-api")] {
                        self.cpal_api.startInputStream(stype, devinfo, cfg, tx)?
                    } else {
                        bail!("API {} not available", cfg.api)
                    }
                }
            }
            _ => bail!("API {} not implemented!", cfg.api),
        };

        // Input queues should be available, otherwise panic bug.
        let iqueues = self.instreamqueues.as_mut().unwrap();

        let meta = stream.metadata();

        sendMsgToAllQueuesRemoveUnused(iqueues, InStreamMsg::StreamStarted(meta.clone()));

        let (threadhandle, commtx, commrx) = self.startInputStreamThread(meta, rx);

        self.input_stream = Some(StreamInfo {
            streamtype: stype,
            stream,
            threadhandle,
            commtx,
            commrx,
        });

        Ok(())
    }

    /// Start a default input stream, using default settings on everything. This is only possible
    /// when the CPAL_api is available
    pub fn startDefaultInputStream(&mut self) -> Result<()> {
        if self.input_stream.is_some() {
            bail!("Input stream is already running. Please first stop existing input stream.")
        }

        let (tx, rx): (Sender<InStreamMsg>, Receiver<InStreamMsg>) = unbounded();

        // Only a default input stream when CPAL feature is enabled
        cfg_if::cfg_if! {
        if #[cfg(feature="cpal-api")] {
        let stream = self.cpal_api.startDefaultInputStream(tx)?;
                // Inform all listeners of new stream data

        let iqueues = self.instreamqueues.as_mut().unwrap();
        let meta = stream.metadata();
        sendMsgToAllQueuesRemoveUnused(iqueues, InStreamMsg::StreamStarted(meta.clone()));

        let (threadhandle, commtx, commrx) = self.startInputStreamThread(meta, rx);

        self.input_stream = Some(StreamInfo {
            streamtype: StreamType::Input,
            stream,
            threadhandle,
            commtx,
            commrx,
        });
        Ok(())

        }
        else {
        bail!("Unable to start default input stream: no CPAL api available")
        }
        }
    }

    /// Start a default output stream. Only possible when CPAL Api is available.
    pub fn startDefaultOutputStream(&mut self) -> Result<()> {
        if let Some(istream) = &self.input_stream {
            if istream.streamtype == StreamType::Duplex {
                bail!("Duplex stream is already running");
            }
        }
        if self.output_stream.is_some() {
            bail!("An output stream is already running. Duplex mode stream cannot be started. Please first stop existing output stream.");
        }

        cfg_if::cfg_if! {
        if #[cfg(feature="cpal-api")] {

        let (tx, rx)= unbounded();
        let stream = self.cpal_api.startDefaultOutputStream(rx)?;
        let meta = stream.metadata();
        let monqueues = self.monitorqueues.take().expect("monitor queues not in place");
        let (threadhandle, commtx, commrx) = self.startSiggenThread(meta, tx, monqueues);

        self.output_stream = Some(StreamInfo {
            streamtype: StreamType::Input,
            stream,
            threadhandle,
            commtx,
            commrx,
        });
        Ok(())

        }  // end if cpal api available
        else {
        bail!("Unable to start default input stream: no CPAL api available")
        }

        } // end of cfg_if
    }

    /// Stop existing input stream.
    pub fn stopInputStream(&mut self) -> Result<()> {
        if let Some(StreamInfo {
            streamtype: _, // Ignored here
            stream: _,
            threadhandle,
            commtx,
            commrx,
        }) = self.input_stream.take()
        {
            // println!("Stopping existing stream..");
            // Send thread to stop
            commtx.send(StreamCommand::StopThread).unwrap();

            // Store stream queues back into StreamMgr
            self.instreamqueues = Some(threadhandle.join().expect("Stream thread panicked!"));

            
            commrx.recv().unwrap()
        } else {
            bail!("Stream is not running.")
        }
    }
    /// Stop existing output stream
    pub fn stopOutputStream(&mut self) -> Result<()> {
        if let Some(StreamInfo {
            streamtype: _, // Ignored here
            stream: _,
            threadhandle,
            commtx,
            commrx,
        }) = self.output_stream.take()
        {
            commtx.send(StreamCommand::StopThread).unwrap();
            // eprintln!("Wainting for threadhandle to join...");
            let (monqueues, siggen) = threadhandle.join().expect("Output thread panicked!");
            assert!(self.siggen.is_none());
            assert!(self.monitorqueues.is_none());
            self.siggen.replace(siggen);
            self.monitorqueues.replace(monqueues);
            commrx.recv().unwrap()
        } else {
            bail!("Stream is not running.");
        }
    }
    /// Stop existing running stream.
    ///
    /// Args
    ///
    /// * st: The stream type.
    pub fn stopStream(&mut self, st: StreamType) -> Result<()> {
        match st {
            StreamType::Input | StreamType::Duplex => self.stopInputStream(),
            StreamType::Output => self.stopOutputStream(),
        }
    }

    /// Apply a signal generator command to control the output stream's signal
    /// generator. see [SiggenCommand] for types of commands. Muting, setting
    /// gain etc. A result code is given back and should be checked for errors.
    pub fn siggenCommand(&mut self, cmd: SiggenCommand) -> Result<()> {
        if let Some(stream) = self.output_stream.as_ref() {
            stream
                .commtx
                .send(StreamCommand::SiggenCommand(cmd))
                .unwrap();
            stream.commrx.recv().unwrap()
        } else if let Some(stream) = self.input_stream.as_ref() {
            // When its duplex, it should have a signal generator
            if matches!(stream.streamtype, StreamType::Duplex) {
                stream
                    .commtx
                    .send(StreamCommand::SiggenCommand(cmd))
                    .unwrap();
                stream.commrx.recv().unwrap()
            } else {
                return self
                    .siggen
                    .as_mut()
                    .expect("siggen should be in rest pos")
                    .applyCommand(cmd);
            }
        } else {
            return self
                .siggen
                .as_mut()
                .expect("siggen should be in rest pos")
                .applyCommand(cmd);
        }
    }

    /// Get an already running PPM for the input stream. This method should not
    /// be called directly by the user. Instead, the user should call
    /// [PPM::newInput] instead.
    pub fn getPPMInput(&self) -> Option<Arc<PPM>> {
        self.PPMinp.upgrade()
    }
    /// Called to update the weakref to the input PPM
    pub fn setPPMInput(&mut self, ppmMon: &Arc<PPM>) {
        if self.PPMinp.upgrade().is_some() {
            panic!("Input PPM is already running!")
        }
        self.PPMinp = Arc::downgrade(ppmMon);
    }

    /// Get an already running PPM for the monitor stream. This method should not
    /// be called directly by the user. Instead, the user should call
    /// [PPM::newMonitor] instead.
    pub fn getPPMMon(&self) -> Option<Arc<PPM>> {
        self.PPMmon.upgrade()
    }
    /// Called to update the weakref to the monitor PPM
    pub fn setPPMMon(&mut self, ppmMon: &Arc<PPM>) {
        if self.PPMmon.upgrade().is_some() {
            panic!("Monitor PPM is already running!")
        }
        self.PPMmon = Arc::downgrade(ppmMon);
    }
} // impl StreamMgr
impl Drop for StreamMgr {
    fn drop(&mut self) {
        // Kill input stream if there is one
        if self.input_stream.is_some() {
            self.stopStream(StreamType::Input).unwrap();
        }
        if self.output_stream.is_some() {
            // println!("Stopstream in Drop");
            self.stopStream(StreamType::Output).unwrap();
            // println!("Stopstream in Drop done");
        }

        // Decref the singleton
        STREAMMGR_CREATED.store(false, std::sync::atomic::Ordering::Relaxed);
    }
}

/// Send to all queues, remove queues that are disconnected when found out
// on the way.
fn sendMsgToAllQueuesRemoveUnused(iqueues: &mut InQueues, msg: InStreamMsg) {
    // Loop over queues. Remove queues that error when we try to send
    // to them
    iqueues.retain(|q| match q.try_send(msg.clone()) {
        Ok(_) => true,
        Err(_e) => false,
    });
}