-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathlib.rs
More file actions
2597 lines (2381 loc) · 72.7 KB
/
lib.rs
File metadata and controls
2597 lines (2381 loc) · 72.7 KB
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
//! Use the [**Signal**](./trait.Signal.html) trait to abstract over infinite-iterator-like types
//! that yield **Frame**s. The **Signal** trait provides methods for adding, scaling, offsetting,
//! multiplying, clipping, generating frame iterators and more.
//!
//! You may also find a series of **Signal** source functions, including:
//!
//! - [equilibrium](./fn.equilibrium.html) for generating "silent" frames.
//! - [phase](./fn.phase.html) for a stepping phase, useful for oscillators.
//! - [sine](./fn.sine.html) for generating a sine waveform.
//! - [saw](./fn.saw.html) for generating a sawtooth waveform.
//! - [square](./fn.square.html) for generating a square waveform.
//! - [noise](./fn.noise.html) for generating a noise waveform.
//! - [noise_simplex](./fn.noise_simplex.html) for generating a 1D simplex noise waveform.
//! - [gen](./fn.gen.html) for generating frames of type F from some `Fn() -> F`.
//! - [gen_mut](./fn.gen_mut.html) for generating frames of type F from some `FnMut() -> F`.
//! - [from_iter](./fn.from_iter.html) for converting an iterator yielding frames to a signal.
//! - [from_interleaved_samples_iter](./fn.from_interleaved_samples_iter.html) for converting an
//! iterator yielding interleaved samples to a signal.
//!
//! Working with **Signal**s allows for easy, readable creation of rich and complex DSP graphs with
//! a simple and familiar API.
//!
//! ### Optional Features
//!
//! - The **boxed** feature (or **signal-boxed** feature if using `dasp`) provides a **Signal**
//! implementation for `Box<dyn Signal>`.
//! - The **bus** feature (or **signal-bus** feature if using `dasp`) provides the
//! [**SignalBus**](./bus/trait.SignalBus.html) trait.
//! - The **envelope** feature (or **signal-envelope** feature if using `dasp`) provides the
//! [**SignalEnvelope**](./envelope/trait.SignalEnvelope.html) trait.
//! - The **rms** feature (or **signal-rms** feature if using `dasp`) provides the
//! [**SignalRms**](./rms/trait.SignalRms.html) trait.
//! - The **window** feature (or **signal-window** feature if using `dasp`) provides the
//! [**window**](./window/index.html) module.
//!
//! ### no_std
//!
//! If working in a `no_std` context, you can disable the default **std** feature with
//! `--no-default-features`.
//!
//! To enable all of the above features in a `no_std` context, enable the **all-no-std** feature.
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(core_intrinsics))]
#[cfg(not(feature = "std"))]
extern crate alloc;
use core;
use core::cell::RefCell;
use dasp_frame::Frame;
use dasp_interpolate::Interpolator;
use dasp_ring_buffer as ring_buffer;
use dasp_sample::{Duplex, Sample};
use interpolate::Converter;
pub mod interpolate;
mod ops;
#[cfg(features = "boxed")]
mod boxed;
#[cfg(feature = "bus")]
pub mod bus;
#[cfg(feature = "envelope")]
pub mod envelope;
#[cfg(feature = "rms")]
pub mod rms;
#[cfg(feature = "window")]
pub mod window;
#[cfg(not(feature = "std"))]
type Rc<T> = alloc::rc::Rc<T>;
#[cfg(feature = "std")]
type Rc<T> = std::rc::Rc<T>;
/// Types that yield `Frame`s of a one-or-more-channel PCM signal.
///
/// For example, `Signal` allows us to add two signals, modulate a signal's amplitude by another
/// signal, scale a signal's amplitude and much more.
///
/// The **Signal** trait is inspired by the `Iterator` trait but is different in the sense that it
/// will always yield frames and will never return `None`. That said, implementors of `Signal` may
/// optionally indicate exhaustian via the `is_exhausted` method. This allows for converting
/// exhaustive signals back to iterators that are well behaved. Calling **next** on an exhausted
/// signal should always yield `Self::Frame::EQUILIBRIUM`.
pub trait Signal {
/// The `Frame` type returned by the `Signal`.
type Frame: Frame;
/// Yield the next `Frame` in the `Signal`.
///
/// # Example
///
/// An example of a mono (single-channel) signal.
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [0.2, -0.6, 0.4];
/// let mut signal = signal::from_iter(frames.iter().cloned());
/// assert_eq!(signal.next(), 0.2);
/// assert_eq!(signal.next(), -0.6);
/// assert_eq!(signal.next(), 0.4);
/// }
/// ```
///
/// An example of a stereo (dual-channel) signal.
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [[0.2, 0.2], [-0.6, -0.6], [0.4, 0.4]];
/// let mut signal = signal::from_iter(frames.iter().cloned());
/// assert_eq!(signal.next(), [0.2, 0.2]);
/// assert_eq!(signal.next(), [-0.6, -0.6]);
/// assert_eq!(signal.next(), [0.4, 0.4]);
/// }
/// ```
fn next(&mut self) -> Self::Frame;
/// Whether or not the signal is exhausted of meaningful frames.
///
/// By default, this returns `false` and assumes that the `Signal` is infinite.
///
/// As an example, `signal::FromIterator` becomes exhausted once the inner `Iterator` has been
/// exhausted. `Sine` on the other hand will always return `false` as it will produce
/// meaningful values infinitely.
///
/// It should be rare for users to need to call this method directly, unless they are
/// implementing their own custom `Signal`s. Instead, idiomatic code will tend toward the
/// `Signal::until_exhasted` method which produces an `Iterator` that yields `Frame`s until
/// `Signal::is_exhausted` returns `true`.
///
/// Adaptors that source frames from more than one signal (`AddAmp`, `MulHz`, etc) will return
/// `true` if *any* of the source signals return `true`. In this sense exhaustiveness is
/// contagious. This can be likened to the way that `Iterator::zip` begins returning `None`
/// when either `A` or `B` begins returning `None`.
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// // Infinite signals always return `false`.
/// use dasp_signal::Step;
/// let sine_signal = signal::rate(44_100.0).const_hz(400.0).sine();
/// assert_eq!(sine_signal.is_exhausted(), false);
///
/// // Signals over iterators return `true` when the inner iterator is exhausted.
/// let frames = [0.2, -0.6, 0.4];
/// let mut iter_signal = signal::from_iter(frames.iter().cloned());
/// assert_eq!(iter_signal.is_exhausted(), false);
/// iter_signal.by_ref().take(3).count();
/// assert_eq!(iter_signal.is_exhausted(), true);
///
/// // Adaptors return `true` when the first signal becomes exhausted.
/// let a = [1, 2];
/// let b = [1, 2, 3, 4];
/// let a_signal = signal::from_iter(a.iter().cloned());
/// let b_signal = signal::from_iter(b.iter().cloned());
/// let mut added = a_signal.add_amp(b_signal);
/// assert_eq!(added.is_exhausted(), false);
/// added.by_ref().take(2).count();
/// assert_eq!(added.is_exhausted(), true);
/// }
/// ```
#[inline]
fn is_exhausted(&self) -> bool {
false
}
/// A signal that maps one set of frames to another.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = signal::gen(|| 0.5);
/// let mut mapper = frames.map(|f| [f, 0.25]);
/// assert_eq!(mapper.next(), [0.5, 0.25]);
/// assert_eq!(mapper.next(), [0.5, 0.25]);
/// assert_eq!(mapper.next(), [0.5, 0.25]);
/// }
/// ```
///
/// This can also be useful for monitoring the peak values of a signal.
///
/// ```
/// use dasp_frame::Frame;
/// use dasp_peak as peak;
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let sine_wave = signal::rate(4.0).const_hz(1.0).sine();
/// let mut peak = sine_wave
/// .map(peak::full_wave)
/// .map(|f| f.round());
/// assert_eq!(
/// peak.take(4).collect::<Vec<_>>(),
/// vec![0.0, 1.0, 0.0, 1.0]
/// );
/// }
/// ```
fn map<M, F>(self, map: M) -> Map<Self, M, F>
where
Self: Sized,
M: FnMut(Self::Frame) -> F,
F: Frame,
{
Map {
signal: self,
map: map,
frame: core::marker::PhantomData,
}
}
/// A signal that maps one set of frames to another.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = signal::gen(|| 0.5);
/// let more_frames = signal::gen(|| 0.25);
/// let mut mapper = frames.zip_map(more_frames, |f, o| [f, o]);
/// assert_eq!(mapper.next(), [0.5, 0.25]);
/// assert_eq!(mapper.next(), [0.5, 0.25]);
/// assert_eq!(mapper.next(), [0.5, 0.25]);
/// }
/// ```
fn zip_map<O, M, F>(self, other: O, map: M) -> ZipMap<Self, O, M, F>
where
Self: Sized,
M: FnMut(Self::Frame, O::Frame) -> F,
O: Signal,
F: Frame,
{
ZipMap {
this: self,
map: map,
other: other,
frame: core::marker::PhantomData,
}
}
/// Provides an iterator that yields the sum of the frames yielded by both `other` and `self`
/// in lock-step.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let a = [0.2, -0.6, 0.4];
/// let b = [0.2, 0.1, -0.8];
/// let a_signal = signal::from_iter(a.iter().cloned());
/// let b_signal = signal::from_iter(b.iter().cloned());
/// let added: Vec<_> = a_signal.add_amp(b_signal).take(3).collect();
/// assert_eq!(added, vec![0.4, -0.5, -0.4]);
/// }
/// ```
#[inline]
fn add_amp<S>(self, other: S) -> AddAmp<Self, S>
where
Self: Sized,
S: Signal,
S::Frame: Frame<
Sample = <<Self::Frame as Frame>::Sample as Sample>::Signed,
NumChannels = <Self::Frame as Frame>::NumChannels,
>,
{
AddAmp { a: self, b: other }
}
/// Provides an iterator that yields the product of the frames yielded by both `other` and
/// `self` in lock-step.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let a = [0.25, -0.8, -0.5];
/// let b = [0.2, 0.5, 0.8];
/// let a_signal = signal::from_iter(a.iter().cloned());
/// let b_signal = signal::from_iter(b.iter().cloned());
/// let added: Vec<_> = a_signal.mul_amp(b_signal).take(3).collect();
/// assert_eq!(added, vec![0.05, -0.4, -0.4]);
/// }
/// ```
#[inline]
fn mul_amp<S>(self, other: S) -> MulAmp<Self, S>
where
Self: Sized,
S: Signal,
S::Frame: Frame<
Sample = <<Self::Frame as Frame>::Sample as Sample>::Float,
NumChannels = <Self::Frame as Frame>::NumChannels,
>,
{
MulAmp { a: self, b: other }
}
/// Provides an iterator that offsets the amplitude of every channel in each frame of the
/// signal by some sample value and yields the resulting frames.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [[0.25, 0.4], [-0.2, -0.5]];
/// let signal = signal::from_iter(frames.iter().cloned());
/// let offset: Vec<_> = signal.offset_amp(0.5).take(2).collect();
/// assert_eq!(offset, vec![[0.75, 0.9], [0.3, 0.0]]);
/// }
/// ```
#[inline]
fn offset_amp(
self,
offset: <<Self::Frame as Frame>::Sample as Sample>::Signed,
) -> OffsetAmp<Self>
where
Self: Sized,
{
OffsetAmp {
signal: self,
offset: offset,
}
}
/// Produces an `Iterator` that scales the amplitude of the sample of each channel in every
/// `Frame` yielded by `self` by the given amplitude.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [0.2, -0.5, -0.4, 0.3];
/// let signal = signal::from_iter(frames.iter().cloned());
/// let scaled: Vec<_> = signal.scale_amp(2.0).take(4).collect();
/// assert_eq!(scaled, vec![0.4, -1.0, -0.8, 0.6]);
/// }
/// ```
#[inline]
fn scale_amp(self, amp: <<Self::Frame as Frame>::Sample as Sample>::Float) -> ScaleAmp<Self>
where
Self: Sized,
{
ScaleAmp {
signal: self,
amp: amp,
}
}
/// Produces a new `Signal` that offsets the amplitude of every `Frame` in `self` by the
/// respective amplitudes in each channel of the given `amp_frame`.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [[0.5, 0.3], [-0.25, 0.9]];
/// let signal = signal::from_iter(frames.iter().cloned());
/// let offset: Vec<_> = signal.offset_amp_per_channel([0.25, -0.5]).take(2).collect();
/// assert_eq!(offset, vec![[0.75, -0.2], [0.0, 0.4]]);
/// }
/// ```
#[inline]
fn offset_amp_per_channel<F>(self, amp_frame: F) -> OffsetAmpPerChannel<Self, F>
where
Self: Sized,
F: Frame<
Sample = <<Self::Frame as Frame>::Sample as Sample>::Signed,
NumChannels = <Self::Frame as Frame>::NumChannels,
>,
{
OffsetAmpPerChannel {
signal: self,
amp_frame: amp_frame,
}
}
/// Produces a new `Signal` that scales the amplitude of every `Frame` in `self` by the
/// respective amplitudes in each channel of the given `amp_frame`.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [[0.2, -0.5], [-0.4, 0.3]];
/// let signal = signal::from_iter(frames.iter().cloned());
/// let scaled: Vec<_> = signal.scale_amp_per_channel([0.5, 2.0]).take(2).collect();
/// assert_eq!(scaled, vec![[0.1, -1.0], [-0.2, 0.6]]);
/// }
/// ```
#[inline]
fn scale_amp_per_channel<F>(self, amp_frame: F) -> ScaleAmpPerChannel<Self, F>
where
Self: Sized,
F: Frame<
Sample = <<Self::Frame as Frame>::Sample as Sample>::Float,
NumChannels = <Self::Frame as Frame>::NumChannels,
>,
{
ScaleAmpPerChannel {
signal: self,
amp_frame: amp_frame,
}
}
/// Multiplies the rate at which frames of `self` are yielded by the given `signal`.
///
/// This happens by wrapping `self` in a `rate::Converter` and calling `set_playback_hz_scale`
/// with each value yielded by `signal`
///
/// # Example
///
/// ```rust
/// use dasp_interpolate::linear::Linear;
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let foo = [0.0, 1.0, 0.0, -1.0];
/// let mul = [1.0, 1.0, 0.5, 0.5, 0.5, 0.5];
/// let mut source = signal::from_iter(foo.iter().cloned());
/// let a = source.next();
/// let b = source.next();
/// let interp = Linear::new(a, b);
/// let hz_signal = signal::from_iter(mul.iter().cloned());
/// let frames: Vec<_> = source.mul_hz(interp, hz_signal).take(6).collect();
/// assert_eq!(&frames[..], &[0.0, 1.0, 0.0, -0.5, -1.0, -0.5][..]);
/// }
/// ```
fn mul_hz<M, I>(self, interpolator: I, mul_per_frame: M) -> MulHz<Self, M, I>
where
Self: Sized,
M: Signal<Frame = f64>,
I: Interpolator,
{
MulHz {
signal: Converter::scale_playback_hz(self, interpolator, 1.0),
mul_per_frame: mul_per_frame,
}
}
/// Converts the rate at which frames of the `Signal` are yielded using interpolation.
///
/// # Example
///
/// ```rust
/// use dasp_interpolate::linear::Linear;
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let foo = [0.0, 1.0, 0.0, -1.0];
/// let mut source = signal::from_iter(foo.iter().cloned());
/// let a = source.next();
/// let b = source.next();
/// let interp = Linear::new(a, b);
/// let frames: Vec<_> = source.from_hz_to_hz(interp, 1.0, 2.0).take(8).collect();
/// assert_eq!(&frames[..], &[0.0, 0.5, 1.0, 0.5, 0.0, -0.5, -1.0, -0.5][..]);
/// }
/// ```
fn from_hz_to_hz<I>(self, interpolator: I, source_hz: f64, target_hz: f64) -> Converter<Self, I>
where
Self: Sized,
I: Interpolator,
{
Converter::from_hz_to_hz(self, interpolator, source_hz, target_hz)
}
/// Multiplies the rate at which frames of the `Signal` are yielded by the given value.
///
/// # Example
///
/// ```rust
/// use dasp_interpolate::linear::Linear;
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let foo = [0.0, 1.0, 0.0, -1.0];
/// let mut source = signal::from_iter(foo.iter().cloned());
/// let a = source.next();
/// let b = source.next();
/// let interp = Linear::new(a, b);
/// let frames: Vec<_> = source.scale_hz(interp, 0.5).take(8).collect();
/// assert_eq!(&frames[..], &[0.0, 0.5, 1.0, 0.5, 0.0, -0.5, -1.0, -0.5][..]);
/// }
/// ```
fn scale_hz<I>(self, interpolator: I, multi: f64) -> Converter<Self, I>
where
Self: Sized,
I: Interpolator,
{
Converter::scale_playback_hz(self, interpolator, multi)
}
/// Delays the `Signal` by the given number of frames.
///
/// The delay is performed by yielding `Frame::EQUILIBRIUM` `n_frames` times before
/// continuing to yield frames from `signal`.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [0.2, 0.4];
/// let signal = signal::from_iter(frames.iter().cloned());
/// let delayed: Vec<_> = signal.delay(2).take(4).collect();
/// assert_eq!(delayed, vec![0.0, 0.0, 0.2, 0.4]);
/// }
/// ```
fn delay(self, n_frames: usize) -> Delay<Self>
where
Self: Sized,
{
Delay {
signal: self,
n_frames: n_frames,
}
}
/// Converts a `Signal` into a type that yields the interleaved `Sample`s.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [[0.1, 0.2], [0.3, 0.4]];
/// let signal = signal::from_iter(frames.iter().cloned());
/// let samples = signal.into_interleaved_samples();
/// let samples: Vec<_> = samples.into_iter().collect();
/// assert_eq!(samples, vec![0.1, 0.2, 0.3, 0.4]);
/// }
/// ```
fn into_interleaved_samples(self) -> IntoInterleavedSamples<Self>
where
Self: Sized,
{
IntoInterleavedSamples {
signal: self,
current_frame: None,
}
}
/// Clips the amplitude of each channel in each `Frame` yielded by `self` to the given
/// threshold amplitude.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [[1.2, 0.8], [-0.7, -1.4]];
/// let signal = signal::from_iter(frames.iter().cloned());
/// let clipped: Vec<_> = signal.clip_amp(0.9).take(2).collect();
/// assert_eq!(clipped, vec![[0.9, 0.8], [-0.7, -0.9]]);
/// }
/// ```
fn clip_amp(self, thresh: <<Self::Frame as Frame>::Sample as Sample>::Signed) -> ClipAmp<Self>
where
Self: Sized,
{
ClipAmp {
signal: self,
thresh: thresh,
}
}
/// Create a new `Signal` that calls the enclosing function on each iteration.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let mut f = 0.0;
/// let mut signal = signal::gen_mut(move || {
/// f += 0.1;
/// f
/// });
/// let func = |x: &f64| {
/// assert_eq!(*x, 0.1);
/// };
/// let mut inspected = signal.inspect(func);
/// let out = inspected.next();
/// assert_eq!(out, 0.1);
/// }
/// ```
fn inspect<F>(self, inspect: F) -> Inspect<Self, F>
where
Self: Sized,
F: FnMut(&Self::Frame),
{
Inspect {
signal: self,
inspect: inspect,
}
}
/// Forks `Self` into two signals that produce the same frames.
///
/// The given `ring_buffer` must be empty to ensure correct behaviour.
///
/// Each time a frame is requested from the signal on one branch, that frame will be pushed to
/// the given `ring_buffer` of pending frames to be collected by the other branch and a flag
/// will be set to indicate that there are pending frames.
///
/// **Fork** can be used to share the queue between the two branches by reference
/// `fork.by_ref()` or via a reference counted pointer `fork.by_rc()`.
///
/// **Fork** is a slightly more efficient alternative to **Bus** when only two branches are
/// required.
///
/// **Note:** It is up to the user to ensure that there are never more than
/// `ring_buffer.max_len()` pending frames - otherwise the oldest frames will be overridden and
/// glitching may occur on the lagging branch.
///
/// **Panic!**s if the given `ring_buffer` is not empty in order to guarantee correct
/// behaviour.
///
/// ```
/// use dasp_ring_buffer as ring_buffer;
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let signal = signal::rate(44_100.0).const_hz(440.0).sine();
/// let ring_buffer = ring_buffer::Bounded::from([0f64; 64]);
/// let mut fork = signal.fork(ring_buffer);
///
/// // Forks can be split into their branches via reference.
/// {
/// let (mut a, mut b) = fork.by_ref();
/// assert_eq!(a.next(), b.next());
/// assert_eq!(a.by_ref().take(64).collect::<Vec<_>>(),
/// b.by_ref().take(64).collect::<Vec<_>>());
/// }
///
/// // Forks can also be split via reference counted pointer.
/// let (mut a, mut b) = fork.by_rc();
/// assert_eq!(a.next(), b.next());
/// assert_eq!(a.by_ref().take(64).collect::<Vec<_>>(),
/// b.by_ref().take(64).collect::<Vec<_>>());
///
/// // The lagging branch will be missing frames if we exceed `ring_buffer.max_len()`
/// // pending frames.
/// assert!(a.by_ref().take(67).collect::<Vec<_>>() !=
/// b.by_ref().take(67).collect::<Vec<_>>())
/// }
/// ```
fn fork<S>(self, ring_buffer: ring_buffer::Bounded<S>) -> Fork<Self, S>
where
Self: Sized,
S: ring_buffer::SliceMut<Element = Self::Frame>,
{
assert!(ring_buffer.is_empty());
let shared = ForkShared {
signal: self,
ring_buffer: ring_buffer,
pending: Fork::<Self, S>::B,
};
Fork {
shared: RefCell::new(shared),
}
}
/// Converts the `Signal` into an `Iterator` that will yield the given number for `Frame`s
/// before returning `None`.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [0.1, 0.2, 0.3, 0.4];
/// let mut signal = signal::from_iter(frames.iter().cloned()).take(2);
/// assert_eq!(signal.next(), Some(0.1));
/// assert_eq!(signal.next(), Some(0.2));
/// assert_eq!(signal.next(), None);
/// }
/// ```
fn take(self, n: usize) -> Take<Self>
where
Self: Sized,
{
Take { signal: self, n: n }
}
/// Converts the `Signal` into an `Iterator` yielding frames until the `signal.is_exhausted()`
/// returns `true`.
///
/// # Example
///
/// ```
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [1, 2];
/// let signal = signal::from_iter(frames.iter().cloned());
/// assert_eq!(signal.until_exhausted().count(), 2);
/// }
/// ```
fn until_exhausted(self) -> UntilExhausted<Self>
where
Self: Sized,
{
UntilExhausted { signal: self }
}
/// Buffers the signal using the given ring buffer.
///
/// When `next` is called on the returned signal, it will first check if the ring buffer is
/// empty. If so, it will completely fill the ring buffer with the inner signal before yielding
/// the next value. If the ring buffer still contains un-yielded values, the next frame will be
/// popped from the front of the ring buffer and immediately returned.
///
/// ```
/// use dasp_ring_buffer as ring_buffer;
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [0.1, 0.2, 0.3, 0.4];
/// let signal = signal::from_iter(frames.iter().cloned());
/// let ring_buffer = ring_buffer::Bounded::from([0f32; 2]);
/// let mut buffered_signal = signal.buffered(ring_buffer);
/// assert_eq!(buffered_signal.next(), 0.1);
/// assert_eq!(buffered_signal.next(), 0.2);
/// assert_eq!(buffered_signal.next(), 0.3);
/// assert_eq!(buffered_signal.next(), 0.4);
/// assert_eq!(buffered_signal.next(), 0.0);
/// }
/// ```
///
/// If the given ring buffer already contains frames, those will be yielded first.
///
/// ```
/// use dasp_ring_buffer as ring_buffer;
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [0.1, 0.2, 0.3, 0.4];
/// let signal = signal::from_iter(frames.iter().cloned());
/// let ring_buffer = ring_buffer::Bounded::from_full([0.8, 0.9]);
/// let mut buffered_signal = signal.buffered(ring_buffer);
/// assert_eq!(buffered_signal.next(), 0.8);
/// assert_eq!(buffered_signal.next(), 0.9);
/// assert_eq!(buffered_signal.next(), 0.1);
/// assert_eq!(buffered_signal.next(), 0.2);
/// assert_eq!(buffered_signal.next(), 0.3);
/// assert_eq!(buffered_signal.next(), 0.4);
/// assert_eq!(buffered_signal.next(), 0.0);
/// }
/// ```
fn buffered<S>(self, ring_buffer: ring_buffer::Bounded<S>) -> Buffered<Self, S>
where
Self: Sized,
S: ring_buffer::Slice<Element = Self::Frame> + ring_buffer::SliceMut,
{
Buffered {
signal: self,
ring_buffer: ring_buffer,
}
}
/// Borrows a Signal rather than consuming it.
///
/// This is useful to allow applying signal adaptors while still retaining ownership of the
/// original signal.
///
/// # Example
///
/// ```rust
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = [0, 1, 2, 3, 4];
/// let mut signal = signal::from_iter(frames.iter().cloned());
/// assert_eq!(signal.next(), 0);
/// assert_eq!(signal.by_ref().take(2).collect::<Vec<_>>(), vec![1, 2]);
/// assert_eq!(signal.next(), 3);
/// assert_eq!(signal.next(), 4);
/// }
/// ```
fn by_ref(&mut self) -> &mut Self
where
Self: Sized,
{
self
}
}
/// Consumes the given `Iterator`, converts it to a `Signal`, applies the given function to the
/// `Signal` and returns an `Iterator` that will become exhausted when the consumed `Iterator`
/// does.
///
/// This is particularly useful when you want to apply `Signal` methods to an `Iterator` yielding
/// `Frame`s and return an `Iterator` as a result.
///
/// # Example
///
/// ```
/// use dasp_signal::{self as signal, Signal};
///
/// fn main() {
/// let frames = vec![0, 1, 2, 3];
/// let offset_frames = signal::lift(frames, |signal| signal.offset_amp(2));
/// assert_eq!(offset_frames.collect::<Vec<_>>(), vec![2, 3, 4, 5]);
/// }
/// ```
pub fn lift<I, F, S>(iter: I, f: F) -> UntilExhausted<S>
where
I: IntoIterator,
I::Item: Frame,
F: FnOnce(FromIterator<I::IntoIter>) -> S,
S: Signal<Frame = I::Item>,
{
let iter = iter.into_iter();
let signal = from_iter(iter);
let new_signal = f(signal);
new_signal.until_exhausted()
}
///// Signal Types
/// An iterator that endlessly yields `Frame`s of type `F` at equilibrium.
#[derive(Clone)]
pub struct Equilibrium<F> {
frame: core::marker::PhantomData<F>,
}
/// A signal that generates frames using the given function.
#[derive(Clone)]
pub struct Gen<G, F> {
gen: G,
frame: core::marker::PhantomData<F>,
}
/// A signal that generates frames using the given function which may mutate some state.
#[derive(Clone)]
pub struct GenMut<G, F> {
gen_mut: G,
frame: core::marker::PhantomData<F>,
}
/// A signal that maps from one signal to another
#[derive(Clone)]
pub struct Map<S, M, F> {
signal: S,
map: M,
frame: core::marker::PhantomData<F>,
}
/// A signal that iterates two signals in parallel and combines them with a function.
///
/// `ZipMap::is_exhausted` returns `true` if *either* of the two signals returns `true`.
#[derive(Clone)]
pub struct ZipMap<S, O, M, F> {
this: S,
other: O,
map: M,
frame: core::marker::PhantomData<F>,
}
/// A type that wraps an Iterator and provides a `Signal` implementation for it.
#[derive(Clone)]
pub struct FromIterator<I>
where
I: Iterator,
{
iter: I,
next: Option<I::Item>,
}
/// An iterator that converts an iterator of `Sample`s to an iterator of `Frame`s.
#[derive(Clone)]
pub struct FromInterleavedSamplesIterator<I, F>
where
I: Iterator,
I::Item: Sample,
F: Frame<Sample = I::Item>,
{
samples: I,
next: Option<F>,
}
/// The rate at which phrase a **Signal** is sampled.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Rate {
hz: f64,
}
/// A constant phase step size.
#[derive(Clone)]
pub struct ConstHz {
step: f64,
}
/// An iterator that yields the step size for a phase.
#[derive(Clone)]
pub struct Hz<S> {
hz: S,
rate: Rate,
}
/// An iterator that yields a phase, useful for waveforms like Sine or Saw.
#[derive(Clone)]
pub struct Phase<S> {
step: S,
next: f64,
}
/// A sine wave signal generator.
#[derive(Clone)]
pub struct Sine<S> {
phase: Phase<S>,
}
/// A saw wave signal generator.
#[derive(Clone)]
pub struct Saw<S> {
phase: Phase<S>,
}
/// A square wave signal generator.
#[derive(Clone)]
pub struct Square<S> {
phase: Phase<S>,
}
/// A noise signal generator.
#[derive(Clone)]
pub struct Noise {
seed: u64,
}
/// A 1D simplex-noise generator.
#[derive(Clone)]
pub struct NoiseSimplex<S> {
phase: Phase<S>,
}
// A signal generator with offset phase.
#[derive(Clone)]
pub struct OffsetPhase<S>
where
S: Signal + Step,
{
step: S,
offset: f64,
}
/// An iterator that yields the sum of the frames yielded by both `other` and `self` in lock-step.
#[derive(Clone)]
pub struct AddAmp<A, B> {
a: A,
b: B,
}
/// An iterator that yields the product of the frames yielded by both `other` and `self` in
/// lock-step.
#[derive(Clone)]
pub struct MulAmp<A, B> {
a: A,
b: B,
}
/// Provides an iterator that offsets the amplitude of every channel in each frame of the
/// signal by some sample value and yields the resulting frames.
#[derive(Clone)]
pub struct OffsetAmp<S>
where
S: Signal,
{
signal: S,
offset: <<S::Frame as Frame>::Sample as Sample>::Signed,
}
/// An `Iterator` that scales the amplitude of the sample of each channel in every `Frame` yielded