-
Notifications
You must be signed in to change notification settings - Fork 89
/
stream.rs
1443 lines (1346 loc) · 52.5 KB
/
stream.rs
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module aims to provide a user-friendly rust-esque wrapper around the portaudio Stream
//! types.
//!
//! The primary type of interest is [**Stream**](./struct.Stream).
use ffi;
use libc;
use num::FromPrimitive;
use std::os::raw;
use std::{self, ptr};
use super::error::Error;
use super::types::{DeviceIndex, DeviceKind, SampleFormat, SampleFormatFlags, Time};
use super::Sample;
pub use self::callback_flags::CallbackFlags;
pub use self::flags::Flags;
/// There are two **Mode**s with which a **Stream** can be set: [**Blocking**](./struct.Blocking)
/// and [**NonBlocking**](./struct.NonBlocking).
pub trait Mode {}
/// Types used to open a **Stream** via the
/// [**PortAudio::open_blocking_stream**](../struct.PortAudio.html#method.open_blocking_stream) and
/// [**PortAudio::open_non_blocking_stream**](../struct.PortAudio.html#method.open_blocking_stream)
/// methods.
pub trait Settings {
/// The **Flow** of the **Stream** (**Input**, **Output** or **Duplex**).
type Flow;
/// Construct the **Stream**'s **Flow** alongside the rest of its settings.
fn into_flow_and_settings(self) -> (Self::Flow, f64, u32, Flags);
}
/// There are three possible **Flow**s available for a **Stream**: [**Input**](./struct.Input),
/// [**Out**](./struct.Output) and [**Duplex**](./struct.Duplex).
pub trait Flow {
/// The type of buffer(s) necessary for transferring audio in a Blocking stream.
type Buffer;
/// The arguments passed to the non-blocking stream callback.
type CallbackArgs;
/// Timing information for the buffer passed to the stream callback.
type CallbackTimeInfo;
/// Construct a new **Self::Buffer**.
fn new_buffer(&self, frames_per_buffer: u32) -> Self::Buffer;
/// Necessary for dynamically acquiring bi-directional params for Pa_OpenStream.
fn params_both_directions(
&self,
) -> (
Option<ffi::PaStreamParameters>,
Option<ffi::PaStreamParameters>,
);
/// Constructs the **Flow**'s associated **CallbackArgs** from the non-blocking C API stream
/// parameters.
fn new_callback_args(
input: *const raw::c_void,
output: *mut raw::c_void,
frame_count: raw::c_ulong,
time_info: *const ffi::PaStreamCallbackTimeInfo,
flags: ffi::PaStreamCallbackFlags,
in_channels: i32,
out_channels: i32,
) -> Self::CallbackArgs;
}
/// **Streams** that can be read by the user.
pub trait Reader: Flow {
/// The sample format for the readable buffer.
type Sample;
/// Borrow the readable **Buffer**.
fn readable_buffer(blocking: &Blocking<Self::Buffer>) -> &Buffer;
/// The number of channels in the readable **Buffer**.
fn channel_count(&self) -> i32;
}
/// **Streams** that can be written to by the user for output to some DAC.
pub trait Writer: Flow {
/// The sample format for the writable buffer.
type Sample;
/// Mutably borrow the the writable **Buffer**.
fn writable_buffer(blocking: &mut Blocking<Self::Buffer>) -> &mut Buffer;
/// The number of channels in the writable **Buffer**.
fn channel_count(&self) -> i32;
}
/// An alias for the boxed Callback function type.
type CallbackFn = dyn FnMut(
*const raw::c_void,
*mut raw::c_void,
raw::c_ulong,
*const ffi::PaStreamCallbackTimeInfo,
ffi::PaStreamCallbackFlags,
) -> ffi::PaStreamCallbackResult;
/// A wrapper around a user-given **CallbackFn** that can be sent to PortAudio.
struct CallbackFnWrapper {
f: Box<CallbackFn>,
}
/// Timing information for the buffer passed to the input stream callback.
///
/// Time values are expressed in seconds and are synchronised with the time base used by
/// `Stream::time` method for the associated stream.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct InputCallbackTimeInfo {
/// The time when the stream callback was invoked.
pub current: Time,
/// The time when the first sample of the input buffer was captured at the ADC input.
pub buffer_adc: Time,
}
/// Timing information for the buffer passed to the output stream callback.
///
/// Time values are expressed in seconds and are synchronised with the time base used by
/// `Stream::time` method for the associated stream.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct OutputCallbackTimeInfo {
/// The time when the stream callback was invoked.
pub current: Time,
/// The time when the first sample of the output buffer will output the DAC.
pub buffer_dac: Time,
}
/// Timing information for the buffers passed to the stream callback.
///
/// Time values are expressed in seconds and are synchronised with the time base used by
/// `Stream::time` method for the associated stream.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct DuplexCallbackTimeInfo {
/// The time when the stream callback was invoked.
pub current: Time,
/// The time when the first sample of the input buffer was captured at the ADC input.
pub in_buffer_adc: Time,
/// The time when the first sample of the output buffer will output the DAC.
pub out_buffer_dac: Time,
}
/// Arguments given to a **NonBlocking** **Input** **Stream**'s **CallbackFn**.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct InputCallbackArgs<'a, I: 'a> {
/// The buffer of interleaved samples read from the **Input** **Stream**'s ADC.
pub buffer: &'a [I],
/// The number of frames of audio data stored within the `buffer`.
pub frames: usize,
/// Flags indicating the current state of the stream and whether or not any special edge cases
/// have occurred.
pub flags: CallbackFlags,
/// Timing information relevant to the callback.
pub time: InputCallbackTimeInfo,
}
/// Arguments given to a **NonBlocking** **Input** **Stream**'s **CallbackFn**.
#[derive(Debug, PartialEq)]
pub struct OutputCallbackArgs<'a, O: 'a> {
/// The **Output** **Stream**'s buffer, to which we will write our interleaved audio data.
pub buffer: &'a mut [O],
/// The number of frames of audio data stored within the `buffer`.
pub frames: usize,
/// Flags indicating the current state of the stream and whether or not any special edge cases
/// have occurred.
pub flags: CallbackFlags,
/// Timing information relevant to the callback.
pub time: OutputCallbackTimeInfo,
}
/// Arguments given to a **NonBlocking** **Input** **Stream**'s **CallbackFn**.
#[derive(Debug, PartialEq)]
pub struct DuplexCallbackArgs<'a, I: 'a, O: 'a> {
/// The buffer of interleaved samples read from the **Stream**'s ADC.
pub in_buffer: &'a [I],
/// The **Stream**'s output buffer, to which we will write interleaved audio data.
pub out_buffer: &'a mut [O],
/// The number of frames of audio data stored within the `buffer`.
pub frames: usize,
/// Flags indicating the current state of the stream and whether or not any special edge cases
/// have occurred.
pub flags: CallbackFlags,
/// Timing information relevant to the callback.
pub time: DuplexCallbackTimeInfo,
}
/// A **Stream** **Mode** representing a blocking stream.
///
/// Unlike the **NonBlocking** stream, PortAudio requires that we manually manage the audio data
/// buffer for the **Blocking** stream.
pub struct Blocking<B> {
buffer: B,
}
/// A **Stream** **Mode** representing a non-blocking stream.
pub struct NonBlocking {
callback: Box<CallbackFnWrapper>,
}
/// A type-safe PortAudio PaStream wrapper.
///
/// **F** is the stream's directional [**Flow**][1]:
///
/// - [**Input**][2] - Receives data from an input device's ADC.
/// - [**Output**][3] - Sends data to an output device's DAC.
/// - [**Duplex**][4] - Receives and Sends data on two devices synchronously.
///
/// A **Stream** of a particular [**Flow**][1] type can be opened by passing the **Flow**'s
/// associated **Settings** type to either of the [**PortAudio::open_blocking_stream**][12] or
/// [**PortAudio::open_non_blocking_stream**][13] methods.
///
/// - [**InputSettings**][14] -> [**Input**][2]
/// - [**OutputSettings**][15] -> [**Output**][3]
/// - [**DuplexSettings**][16] -> [**Duplex**][4]
///
/// **M** is the stream's [**Mode**][5]:
///
/// - [**Blocking**][6] - The stream will be run on the caller's thread. For [**Blocking**][6]
/// streams, a user can read from [**Input**][2] and [**Duplex**][4] streams using the
/// [**Stream::read_available**][8] and [**Stream::read**][9] methods and write to [**Output**][3]
/// and [**Duplex**][4] streams using the [**Stream::write_available**][10] and
/// [**Stream::write**][11] methods. A [**Blocking**][6] **Stream** can be opened using the
/// [**PortAudio::open_blocking_stream][12]** method.
/// - [**NonBlocking**][7] - The stream will be run on a separate thread. [**NonBlocking][7]
/// streams are read and written to via the callback arguments that are associated with the
/// **Stream**'s [**Flow**][1] type:
/// - **Input** -> [**InputCallbackArgs**](./struct.InputCallbackArgs.html)
/// - **Output** -> [**OutputCallbackArgs**](./struct.OutputCallbackArgs.html)
/// - **Duplex** -> [**DuplexCallbackArgs**](./struct.DuplexCallbackArgs.html)
/// A [**NonBlocking**][7] **Stream** can be opened using the
/// [**PortAudio::open_non_blocking_stream][13]** method.
///
/// A **Stream** may only live as long as the **PortAudio** instance from which it was spawned and
/// no longer.
///
/// The original PortAudio documentation for the **PaStream** type can be found [here][17].
///
/// [1]: ./trait.Flow.html
/// [2]: ./struct.Input.html
/// [3]: ./struct.Output.html
/// [4]: ./struct.Duplex.html
/// [5]: ./trait.Mode.html
/// [6]: ./struct.Blocking.html
/// [7]: ./struct.NonBlocking.html
/// [8]: ./struct.Stream.html#method.read_available
/// [9]: ./struct.Stream.html#method.read
/// [10]: ./struct.Stream.html#method.write_available
/// [11]: ./struct.Stream.html#method.write
/// [12]: ../struct.PortAudio.html#method.open_blocking_stream
/// [13]: ../struct.PortAudio.html#method.open_non_blocking_stream
/// [14]: ./struct.InputSettings.html
/// [15]: ./struct.OutputSettings.html
/// [16]: ./struct.DuplexSettings.html
/// [17]: http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a19874734f89958fccf86785490d53b4c
#[allow(dead_code)]
pub struct Stream<M, F> {
pa_stream: *mut ffi::PaStream,
mode: M,
flow: F,
port_audio_life: std::sync::Arc<super::Life>,
}
/// Parameters for one direction (input or output) of a stream.
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Parameters<S> {
/// Index of the device to be used, or a variant indicating to use the host-specific API.
pub device: DeviceKind,
/// The number of channels for this device
pub channel_count: i32,
/// The suggested latency for this device
pub suggested_latency: Time,
/// Indicates the format of the audio buffer.
///
/// If `true`, audio data is passed as a single buffer with all channels interleaved.
///
/// If `false`, audio data is passed as an array of pointers to separate buffers, one buffer
/// for each channel.
pub is_interleaved: bool,
/// Sample format of the audio data provided to/by the device.
sample_format: std::marker::PhantomData<S>,
}
/// Settings used to construct an **Input** **Stream**.
#[derive(Copy, Clone, Debug)]
pub struct InputSettings<I> {
/// The set of Parameters necessary for constructing the **Stream**.
pub params: Parameters<I>,
/// The number of audio frames read per second.
pub sample_rate: f64,
/// The number of audio frames that are read per buffer.
pub frames_per_buffer: u32,
/// Any special **Stream** behaviour we require given as a set of flags.
pub flags: Flags,
}
/// Settings used to construct an **Out** **Stream**.
#[derive(Copy, Clone, Debug)]
pub struct OutputSettings<O> {
/// The set of Parameters necessary for constructing the **Stream**.
pub params: Parameters<O>,
/// The number of audio frames written per second.
pub sample_rate: f64,
/// The number of audio frames requested per buffer.
pub frames_per_buffer: u32,
/// Any special **Stream** behaviour we require given as a set of flags.
pub flags: Flags,
}
/// Settings used to construct a **Duplex** **Stream**.
#[derive(Copy, Clone, Debug)]
pub struct DuplexSettings<I, O> {
/// The set of Parameters necessary for constructing the input **Stream**.
pub in_params: Parameters<I>,
/// The set of Parameters necessary for constructing the output **Stream**.
pub out_params: Parameters<O>,
/// The number of audio frames written per second.
pub sample_rate: f64,
/// The number of audio frames requested per buffer.
pub frames_per_buffer: u32,
/// Any special **Stream** behaviour we require given as a set of flags.
pub flags: Flags,
}
/// A type of **Flow** that describes an input-only **Stream**.
pub struct Input<I> {
params: Parameters<I>,
}
/// A type of **Flow** that describes an output-only **Stream**.
pub struct Output<O> {
params: Parameters<O>,
}
/// A type of **Flow** that describes a bi-directional (input *and* output) **Stream**.
pub struct Duplex<I, O> {
in_params: Parameters<I>,
out_params: Parameters<O>,
}
unsafe impl Send for NonBlocking {}
unsafe impl<M, F> Send for Stream<M, F>
where
M: Send,
F: Send,
{
}
impl<S> Parameters<S> {
/// Construct a new **Parameters**.
pub fn new(
device: DeviceIndex,
channel_count: i32,
is_interleaved: bool,
suggested_latency: Time,
) -> Self {
Self::new_internal(
device.into(),
channel_count,
is_interleaved,
suggested_latency,
)
}
/// The same as **Parameters::new**, but the device(s) to be used are specified in the host
/// api specific stream info structure.
///
/// **NOTE:** This has not yet been tested.
pub fn host_api_specific_device(
channel_count: i32,
is_interleaved: bool,
suggested_latency: Time,
) -> Self {
let kind = DeviceKind::UseHostApiSpecificDeviceSpecification;
Self::new_internal(kind, channel_count, is_interleaved, suggested_latency)
}
fn new_internal(
device_kind: DeviceKind,
channel_count: i32,
is_interleaved: bool,
suggested_latency: Time,
) -> Self {
Parameters {
device: device_kind,
channel_count: channel_count,
is_interleaved: is_interleaved,
suggested_latency: suggested_latency,
sample_format: std::marker::PhantomData,
}
}
}
/// Simplify implementation of one-way-Stream Settings types.
macro_rules! impl_half_duplex_settings {
($name:ident) => {
impl<S> $name<S> {
/// Construct the settings from the given `params`, `sample_rate` and
/// `frames_per_buffer` with an empty set of **StreamFlags**.
pub fn new(params: Parameters<S>, sample_rate: f64, frames_per_buffer: u32) -> Self {
Self::with_flags(params, sample_rate, frames_per_buffer, Flags::empty())
}
/// Construct the settings with the given **Parameters**, `sample_rate`,
/// `frames_per_buffer` and **StreamFlags**.
pub fn with_flags(
params: Parameters<S>,
sample_rate: f64,
frames_per_buffer: u32,
flags: Flags,
) -> Self {
$name {
params: params,
sample_rate: sample_rate,
frames_per_buffer: frames_per_buffer,
flags: flags,
}
}
}
};
}
impl_half_duplex_settings!(OutputSettings);
impl_half_duplex_settings!(InputSettings);
impl<I, O> DuplexSettings<I, O> {
/// Construct the settings from the given `params`, `sample_rate` and
/// `frames_per_buffer` with an empty set of **StreamFlags**.
pub fn new(
in_params: Parameters<I>,
out_params: Parameters<O>,
sample_rate: f64,
frames_per_buffer: u32,
) -> Self {
Self::with_flags(
in_params,
out_params,
sample_rate,
frames_per_buffer,
Flags::empty(),
)
}
/// Construct the settings with the given **Parameters**, `sample_rate`,
/// `frames_per_buffer` and **StreamFlags**.
pub fn with_flags(
in_params: Parameters<I>,
out_params: Parameters<O>,
sample_rate: f64,
frames_per_buffer: u32,
flags: Flags,
) -> Self {
DuplexSettings {
in_params: in_params,
out_params: out_params,
sample_rate: sample_rate,
frames_per_buffer: frames_per_buffer,
flags: flags,
}
}
}
impl<I> Flow for Input<I>
where
I: Sample + 'static,
{
type Buffer = Buffer;
type CallbackArgs = InputCallbackArgs<'static, I>;
type CallbackTimeInfo = InputCallbackTimeInfo;
fn new_buffer(&self, frames_per_buffer: u32) -> Self::Buffer {
let channel_count = self.params.channel_count;
Buffer::new::<I>(frames_per_buffer, channel_count)
}
fn params_both_directions(
&self,
) -> (
Option<ffi::PaStreamParameters>,
Option<ffi::PaStreamParameters>,
) {
(Some(self.params.into()), None)
}
fn new_callback_args(
input: *const raw::c_void,
_output: *mut raw::c_void,
frame_count: raw::c_ulong,
time_info: *const ffi::PaStreamCallbackTimeInfo,
flags: ffi::PaStreamCallbackFlags,
in_channels: i32,
_out_channels: i32,
) -> Self::CallbackArgs {
let flags = CallbackFlags::from_bits(flags).unwrap_or_else(|| CallbackFlags::empty());
let time = unsafe {
InputCallbackTimeInfo {
current: (*time_info).currentTime,
buffer_adc: (*time_info).inputBufferAdcTime,
}
};
// TODO: At the moment, we assume the buffer is interleaved. We need to check whether or
// not buffer is interleaved here. This should probably an extra type parameter (along-side
// the Sample type param).
let buffer: &[I] = {
let buffer_len = in_channels as usize * frame_count as usize;
let buffer_ptr = input as *const I;
unsafe { std::slice::from_raw_parts(buffer_ptr, buffer_len) }
};
InputCallbackArgs {
buffer: buffer,
frames: frame_count as usize,
flags: flags,
time: time,
}
}
}
impl<O> Flow for Output<O>
where
O: Sample + 'static,
{
type Buffer = Buffer;
type CallbackArgs = OutputCallbackArgs<'static, O>;
type CallbackTimeInfo = OutputCallbackTimeInfo;
fn params_both_directions(
&self,
) -> (
Option<ffi::PaStreamParameters>,
Option<ffi::PaStreamParameters>,
) {
(None, Some(self.params.into()))
}
fn new_buffer(&self, frames_per_buffer: u32) -> Self::Buffer {
let channel_count = self.params.channel_count;
Buffer::new::<O>(frames_per_buffer, channel_count)
}
fn new_callback_args(
_input: *const raw::c_void,
output: *mut raw::c_void,
frame_count: raw::c_ulong,
time_info: *const ffi::PaStreamCallbackTimeInfo,
flags: ffi::PaStreamCallbackFlags,
_in_channels: i32,
out_channels: i32,
) -> Self::CallbackArgs {
let flags = CallbackFlags::from_bits(flags).unwrap_or_else(|| CallbackFlags::empty());
let time = unsafe {
OutputCallbackTimeInfo {
current: (*time_info).currentTime,
buffer_dac: (*time_info).outputBufferDacTime,
}
};
// TODO: At the moment, we assume the buffer is interleaved. We need to check whether or
// not buffer is interleaved here. This should probably an extra type parameter (along-side
// the Sample type param).
let buffer: &mut [O] = {
let buffer_len = out_channels as usize * frame_count as usize;
let buffer_ptr = output as *mut O;
unsafe { std::slice::from_raw_parts_mut(buffer_ptr, buffer_len) }
};
OutputCallbackArgs {
buffer: buffer,
frames: frame_count as usize,
flags: flags,
time: time,
}
}
}
impl<I, O> Flow for Duplex<I, O>
where
I: Sample + 'static,
O: Sample + 'static,
{
type Buffer = (Buffer, Buffer);
type CallbackArgs = DuplexCallbackArgs<'static, I, O>;
type CallbackTimeInfo = DuplexCallbackTimeInfo;
fn params_both_directions(
&self,
) -> (
Option<ffi::PaStreamParameters>,
Option<ffi::PaStreamParameters>,
) {
(Some(self.in_params.into()), Some(self.out_params.into()))
}
fn new_buffer(&self, frames_per_buffer: u32) -> Self::Buffer {
let in_channel_count = self.in_params.channel_count;
let in_buffer = Buffer::new::<I>(frames_per_buffer, in_channel_count);
let out_channel_count = self.out_params.channel_count;
let out_buffer = Buffer::new::<O>(frames_per_buffer, out_channel_count);
(in_buffer, out_buffer)
}
fn new_callback_args(
input: *const raw::c_void,
output: *mut raw::c_void,
frame_count: raw::c_ulong,
time_info: *const ffi::PaStreamCallbackTimeInfo,
flags: ffi::PaStreamCallbackFlags,
in_channels: i32,
out_channels: i32,
) -> Self::CallbackArgs {
let flags = CallbackFlags::from_bits(flags).unwrap_or_else(|| CallbackFlags::empty());
let time = unsafe {
DuplexCallbackTimeInfo {
current: (*time_info).currentTime,
in_buffer_adc: (*time_info).inputBufferAdcTime,
out_buffer_dac: (*time_info).outputBufferDacTime,
}
};
// TODO: At the moment, we assume these buffers are interleaved. We need to check whether
// or not buffer is interleaved here. This should probably an extra type parameter
// (along-side the Sample type param).
let in_buffer: &[I] = {
let buffer_len = in_channels as usize * frame_count as usize;
let buffer_ptr = input as *const I;
unsafe { std::slice::from_raw_parts(buffer_ptr, buffer_len) }
};
let out_buffer: &mut [O] = {
let buffer_len = out_channels as usize * frame_count as usize;
let buffer_ptr = output as *mut O;
unsafe { std::slice::from_raw_parts_mut(buffer_ptr, buffer_len) }
};
DuplexCallbackArgs {
in_buffer: in_buffer,
out_buffer: out_buffer,
frames: frame_count as usize,
flags: flags,
time: time,
}
}
}
impl<I> Reader for Input<I>
where
I: Sample + 'static,
{
type Sample = I;
fn readable_buffer(blocking: &Blocking<<Input<I> as Flow>::Buffer>) -> &Buffer {
&blocking.buffer
}
fn channel_count(&self) -> i32 {
self.params.channel_count
}
}
impl<I, O> Reader for Duplex<I, O>
where
I: Sample + 'static,
O: Sample + 'static,
{
type Sample = I;
fn readable_buffer(blocking: &Blocking<<Duplex<I, O> as Flow>::Buffer>) -> &Buffer {
&blocking.buffer.0
}
fn channel_count(&self) -> i32 {
self.in_params.channel_count
}
}
impl<O> Writer for Output<O>
where
O: Sample + 'static,
{
type Sample = O;
fn writable_buffer(blocking: &mut Blocking<<Output<O> as Flow>::Buffer>) -> &mut Buffer {
&mut blocking.buffer
}
fn channel_count(&self) -> i32 {
self.params.channel_count
}
}
impl<I, O> Writer for Duplex<I, O>
where
I: Sample + 'static,
O: Sample + 'static,
{
type Sample = O;
fn writable_buffer(blocking: &mut Blocking<<Duplex<I, O> as Flow>::Buffer>) -> &mut Buffer {
&mut blocking.buffer.1
}
fn channel_count(&self) -> i32 {
self.out_params.channel_count
}
}
/// The buffer used to transfer audio data between the input and output streams.
pub struct Buffer {
data: *mut libc::c_void,
}
pub mod flags {
//! A type safe wrapper around PortAudio's stream flags.
use ffi;
bitflags! {
/// Flags used to control the behaviour of a stream. They are passed as parameters to
/// Stream::open or Stream::open_default. Multiple flags may be used together.
///
/// See the [bitflags repo](https://github.com/rust-lang/bitflags/blob/master/src/lib.rs)
/// for examples of composing flags together.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Flags: ::std::os::raw::c_ulong {
/// No flags.
const NO_FLAG = ffi::PA_NO_FLAG;
/// Disable default clipping of out of range samples.
const CLIP_OFF = ffi::PA_CLIP_OFF;
/// Disable default dithering.
const DITHER_OFF = ffi::PA_DITHER_OFF;
/// Flag requests that where possible a full duplex stream will not discard overflowed
/// input samples without calling the stream callback.
const NEVER_DROP_INPUT = ffi::PA_NEVER_DROP_INPUT;
/// Call the stream callback to fill initial output buffers, rather than the default
/// behavior of priming the buffers with zeros (silence)
const PA_PRIME_OUTPUT_BUFFERS_USING_STREAM_CALLBACK = ffi::PA_PRIME_OUTPUT_BUFFERS_USING_STREAM_CALLBACK;
/// A mask specifying the platform specific bits.
const PA_PLATFORM_SPECIFIC_FLAGS = ffi::PA_PLATFORM_SPECIFIC_FLAGS;
}
}
impl ::std::fmt::Display for Flags {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(
f,
"{:?}",
match self.bits() {
ffi::PA_NO_FLAG => "NO_FLAG",
ffi::PA_CLIP_OFF => "CLIP_OFF",
ffi::PA_DITHER_OFF => "DITHER_OFF",
ffi::PA_NEVER_DROP_INPUT => "NEVER_DROP_INPUT",
ffi::PA_PRIME_OUTPUT_BUFFERS_USING_STREAM_CALLBACK => {
"PRIME_OUTPUT_BUFFERS_USING_STREAM_CALLBACK"
}
ffi::PA_PLATFORM_SPECIFIC_FLAGS => "PLATFORM_SPECIFIC_FLAGS",
_ => "<Unknown StreamFlags>",
}
)
}
}
}
/// Describes stream availability and the number for frames available for reading/writing if there
/// is any.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Available {
/// The number of frames available for reading.
Frames(::std::os::raw::c_long),
/// The input stream has overflowed.
InputOverflowed,
/// The output stream has underflowed.
OutputUnderflowed,
}
pub mod callback_flags {
//! A type safe wrapper around PortAudio's stream callback flags.
use ffi;
bitflags! {
/// Flag bit constants for the status flags passed to the stream's callback function.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CallbackFlags: ::std::os::raw::c_ulong {
/// No flags.
const NO_FLAG = ffi::PA_NO_FLAG;
/// In a stream opened with paFramesPerBufferUnspecified, indicates that input data is
/// all silence (zeros) because no real data is available. In a stream opened without
/// `FramesPerBufferUnspecified`, it indicates that one or more zero samples have been
/// inserted into the input buffer to compensate for an input underflow.
const INPUT_UNDERFLOW = ffi::INPUT_UNDERFLOW;
/// In a stream opened with paFramesPerBufferUnspecified, indicates that data prior to
/// the first sample of the input buffer was discarded due to an overflow, possibly
/// because the stream callback is using too much CPU time. Otherwise indicates that
/// data prior to one or more samples in the input buffer was discarded.
const INPUT_OVERFLOW = ffi::INPUT_OVERFLOW;
/// Indicates that output data (or a gap) was inserted, possibly because the stream
/// callback is using too much CPU time.
const OUTPUT_UNDERFLOW = ffi::OUTPUT_UNDERFLOW;
/// Indicates that output data will be discarded because no room is available.
const OUTPUT_OVERFLOW = ffi::OUTPUT_OVERFLOW;
/// Some of all of the output data will be used to prime the stream, input data may be
/// zero.
const PRIMING_OUTPUT = ffi::PRIMING_OUTPUT;
}
}
impl ::std::fmt::Display for CallbackFlags {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(
f,
"{:?}",
match self.bits() {
ffi::PA_NO_FLAG => "NO_FLAG",
ffi::INPUT_UNDERFLOW => "INPUT_UNDERFLOW",
ffi::INPUT_OVERFLOW => "INPUT_OVERFLOW",
ffi::OUTPUT_UNDERFLOW => "OUTPUT_UNDERFLOW",
ffi::OUTPUT_OVERFLOW => "OUTPUT_OVERFLOW",
ffi::PRIMING_OUTPUT => "PRIMING_INPUT",
_ => "<Unknown StreamCallbackFlags>",
}
)
}
}
}
/// Timing information for the buffers passed to the stream callback.
///
/// Time values are expressed in seconds and are synchronised with the time base used by
/// `Stream::time` method for the associated stream.
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct CallbackTimeInfo {
/// The time when the first sample of the input buffer was captured by the
pub input_buffer_adc_time: Time,
/// The time when the tream callback was invoked.
pub current_time: Time,
pub output_buffer_dac_time: Time,
}
/// A structure containing unchanging information about an open stream.
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
#[repr(C)]
pub struct Info {
/// Struct version
pub struct_version: i32,
/// The input latency for this open stream
pub input_latency: Time,
/// The output latency for this open stream
pub output_latency: Time,
/// The sample rate for this open stream
pub sample_rate: f64,
}
impl From<ffi::PaStreamInfo> for Info {
fn from(info: ffi::PaStreamInfo) -> Info {
Info {
struct_version: info.structVersion,
input_latency: info.inputLatency,
output_latency: info.outputLatency,
sample_rate: info.sampleRate,
}
}
}
impl<B> Mode for Blocking<B> {}
impl Mode for NonBlocking {}
impl<S: Sample> Parameters<S> {
/// Converts the given `C_PaStreamParameters` into their respective **Parameters**.
///
/// Returns `None` if the `sample_format` differs to that of the **S** **Sample** parameter.
///
/// Returns `None` if the `device` index is neither a valid index or a
/// `UseHostApiSpecificDeviceSpecification` flag.
pub fn from_c_params(c_params: ffi::PaStreamParameters) -> Option<Self> {
let sample_format_flags: SampleFormatFlags = c_params.sampleFormat.into();
let is_interleaved = !sample_format_flags.contains(SampleFormatFlags::NON_INTERLEAVED);
let c_sample_format = SampleFormat::from_flags(c_params.sampleFormat.into());
if S::sample_format() != c_sample_format {
return None;
}
let device = match c_params.device {
n if n >= 0 => DeviceIndex(n as u32).into(),
-1 => DeviceKind::UseHostApiSpecificDeviceSpecification,
_ => return None,
};
Some(Parameters {
device: device,
channel_count: c_params.channelCount,
suggested_latency: c_params.suggestedLatency,
is_interleaved: is_interleaved,
sample_format: std::marker::PhantomData,
})
}
}
impl<S: Sample> From<Parameters<S>> for ffi::PaStreamParameters {
/// Converts the **Parameters** into its matching `C_PaStreamParameters`.
fn from(params: Parameters<S>) -> Self {
let Parameters {
device,
channel_count,
suggested_latency,
is_interleaved,
..
} = params;
let sample_format = S::sample_format();
let mut sample_format_flags = sample_format.flags();
if !is_interleaved {
sample_format_flags.insert(SampleFormatFlags::NON_INTERLEAVED);
}
ffi::PaStreamParameters {
device: device.into(),
channelCount: channel_count as raw::c_int,
sampleFormat: sample_format_flags.bits(),
suggestedLatency: suggested_latency,
hostApiSpecificStreamInfo: ptr::null_mut(),
}
}
}
impl<I> Settings for InputSettings<I> {
type Flow = Input<I>;
fn into_flow_and_settings(self) -> (Self::Flow, f64, u32, Flags) {
let InputSettings {
params,
sample_rate,
frames_per_buffer,
flags,
} = self;
let flow = Input { params: params };
(flow, sample_rate, frames_per_buffer, flags)
}
}
impl<O> Settings for OutputSettings<O> {
type Flow = Output<O>;
fn into_flow_and_settings(self) -> (Self::Flow, f64, u32, Flags) {
let OutputSettings {
params,
sample_rate,
frames_per_buffer,
flags,
} = self;
let flow = Output { params: params };
(flow, sample_rate, frames_per_buffer, flags)
}
}
impl<I, O> Settings for DuplexSettings<I, O> {
type Flow = Duplex<I, O>;
fn into_flow_and_settings(self) -> (Self::Flow, f64, u32, Flags) {
let DuplexSettings {
in_params,
out_params,
sample_rate,
frames_per_buffer,
flags,
} = self;
let flow = Duplex {
in_params: in_params,
out_params: out_params,
};
(flow, sample_rate, frames_per_buffer, flags)
}
}
impl Buffer {
/// Construct a new **Buffer** for transferring audio on a stream with the given format.
fn new<S>(frames_per_buffer: u32, channel_count: i32) -> Buffer {
let sample_format_bytes = ::std::mem::size_of::<S>() as libc::size_t;
let n_frames = frames_per_buffer as libc::size_t;
let n_channels = channel_count as libc::size_t;
let malloc_size = sample_format_bytes * n_frames * n_channels;
Buffer {
data: unsafe { libc::malloc(malloc_size) as *mut libc::c_void },
}
}
/// Convert the **Buffer**'s data field into a slice with the given format.
unsafe fn slice<'a, S>(&'a self, frames: u32, channels: i32) -> &'a [S] {
let len = (frames * channels as u32) as usize;
// TODO: At the moment, we assume this buffer is interleaved. We need to check whether
// or not buffer is interleaved here. This should probably an extra type parameter
// (along-side the Sample type param).
std::slice::from_raw_parts(self.data as *const S, len)
}
/// Convert the **Buffer**'s data field into a mutable slice with the given format.
unsafe fn slice_mut<'a, S>(&'a mut self, frames: u32, channels: i32) -> &'a mut [S] {
let len = (frames * channels as u32) as usize;
// TODO: At the moment, we assume this buffer is interleaved. We need to check whether
// or not buffer is interleaved here. This should probably an extra type parameter
// (along-side the Sample type param).
std::slice::from_raw_parts_mut(self.data as *mut S, len)
}
}
impl Drop for Buffer {
fn drop(&mut self) {
unsafe { libc::free(self.data) }
}
}
fn open_blocking_stream(
in_params: Option<ffi::PaStreamParameters>,
out_params: Option<ffi::PaStreamParameters>,
sample_rate: f64,
frames_per_buffer: u32,
flags: Flags,
) -> Result<*mut raw::c_void, Error> {
// The pointer to which PortAudio will attach the stream.
let mut c_stream_ptr: *mut raw::c_void = ptr::null_mut();
let in_c_params = in_params.map(|p| p.into());
let out_c_params = out_params.map(|p| p.into());
let in_c_params_ptr = in_c_params
.as_ref()
.map(|p| p as *const _)
.unwrap_or(ptr::null());
let out_c_params_ptr = out_c_params
.as_ref()
.map(|p| p as *const _)
.unwrap_or(ptr::null());
let c_flags = flags.bits();