Skip to main content

sample/
signal.rs

1//! Use the **Signal** trait for working with **Iterator**s that yield **Frame**s. To complement
2//! the **Iterator** trait, **Signal** provides methods for adding, scaling, offsetting,
3//! multiplying, clipping and generating frame iterators and more.
4//!
5//! You may also find a series of **Signal** source functions, including:
6//!
7//! - [equilibrium](./fn.equilibrium.html) for generating "silent" frames.
8//! - [phase](./fn.phase.html) for a stepping phase, useful for oscillators.
9//! - [sine](./fn.sine.html) for generating a sine waveform.
10//! - [saw](./fn.saw.html) for generating a sawtooth waveform.
11//! - [square](./fn.square.html) for generating a square waveform.
12//! - [noise](./fn.noise.html) for generating a noise waveform.
13//! - [noise_simplex](./fn.noise_simplex.html) for generating a 1D simplex noise waveform.
14//! - [gen](./fn.gen.html) for generating frames of type F from some `Fn() -> F`.
15//! - [gen_mut](./fn.gen_mut.html) for generating frames of type F from some `FnMut() -> F`.
16//! - [from_iter](./fn.from_iter.html) for converting an iterator yielding frames to a signal.
17//! - [from_interleaved_samples_iter](./fn.from_interleaved_samples_iter.html) for converting an
18//! iterator yielding interleaved samples to a signal.
19//!
20//! Working with **Signal**s allows for easy, readable creation of rich and complex DSP graphs with
21//! a simple and familiar API.
22
23use {BTreeMap, Duplex, Frame, Sample, Rc, VecDeque, Box};
24use core;
25use core::cell::RefCell;
26use envelope;
27use interpolate::{Converter, Interpolator};
28use ring_buffer;
29use rms;
30
31
32/// Types that yield `Frame`s as a multi-channel PCM signal.
33///
34/// For example, `Signal` allows us to add two signals, modulate a signal's amplitude by another
35/// signal, scale a signals amplitude and much more.
36pub trait Signal {
37    /// The `Frame` type returned by the `Signal`.
38    type Frame: Frame;
39
40    /// Yield the next `Frame` in the `Signal`.
41    ///
42    /// # Example
43    ///
44    /// ```rust
45    /// extern crate sample;
46    ///
47    /// use sample::{signal, Signal};
48    ///
49    /// fn main() {
50    ///     let frames = [[0.2], [-0.6], [0.4]];
51    ///     let mut signal = signal::from_iter(frames.iter().cloned());
52    ///     assert_eq!(signal.next(), [0.2]);
53    ///     assert_eq!(signal.next(), [-0.6]);
54    ///     assert_eq!(signal.next(), [0.4]);
55    /// }
56    /// ```
57    fn next(&mut self) -> Self::Frame;
58
59    /// Whether or not the signal is exhausted of meaningful frames.
60    ///
61    /// By default, this returns `false` and assumes that the `Signal` is infinite.
62    ///
63    /// As an example, `signal::FromIterator` becomes exhausted once the inner `Iterator` has been
64    /// exhausted. `Sine` on the other hand will always return `false` as it will produce
65    /// meaningful values infinitely.
66    ///
67    /// It should be rare for users to need to call this method directly, unless they are
68    /// implementing their own custom `Signal`s. Instead, idiomatic code will tend toward the
69    /// `Signal::until_exhasted` method which produces an `Iterator` that yields `Frame`s until
70    /// `Signal::is_exhausted` returns `true`.
71    ///
72    /// Adaptors that source frames from more than one signal (`AddAmp`, `MulHz`, etc) will return
73    /// `true` if *any* of the source signals return `true`. In this sense exhaustiveness is
74    /// contagious. This can be likened to the way that `Iterator::zip` begins returning `None`
75    /// when either `A` or `B` begins returning `None`.
76    ///
77    /// ```rust
78    /// extern crate sample;
79    ///
80    /// use sample::{signal, Signal};
81    ///
82    /// fn main() {
83    ///     // Infinite signals always return `false`.
84    ///     let sine_signal = signal::rate(44_100.0).const_hz(400.0).sine();
85    ///     assert_eq!(sine_signal.is_exhausted(), false);
86    ///
87    ///     // Signals over iterators return `true` when the inner iterator is exhausted.
88    ///     let frames = [[0.2], [-0.6], [0.4]];
89    ///     let mut iter_signal = signal::from_iter(frames.iter().cloned());
90    ///     assert_eq!(iter_signal.is_exhausted(), false);
91    ///     iter_signal.by_ref().take(3).count();
92    ///     assert_eq!(iter_signal.is_exhausted(), true);
93    ///
94    ///     // Adaptors return `true` when the first signal becomes exhausted.
95    ///     let a = [[1], [2]];
96    ///     let b = [[1], [2], [3], [4]];
97    ///     let a_signal = signal::from_iter(a.iter().cloned());
98    ///     let b_signal = signal::from_iter(b.iter().cloned());
99    ///     let mut added = a_signal.add_amp(b_signal);
100    ///     assert_eq!(added.is_exhausted(), false);
101    ///     added.by_ref().take(2).count();
102    ///     assert_eq!(added.is_exhausted(), true);
103    /// }
104    /// ```
105    #[inline]
106    fn is_exhausted(&self) -> bool {
107        false
108    }
109
110    /// A signal that maps one set of frames to another.
111    ///
112    /// # Example
113    ///
114    /// ```rust
115    /// extern crate sample;
116    ///
117    /// use sample::{signal, Signal};
118    ///
119    /// fn main() {
120    ///     let frames = signal::gen(|| [0.5]);
121    ///     let mut mapper = frames.map(|f| [f[0], 0.25]);
122    ///     assert_eq!(mapper.next(), [0.5, 0.25]);
123    ///     assert_eq!(mapper.next(), [0.5, 0.25]);
124    ///     assert_eq!(mapper.next(), [0.5, 0.25]);
125    /// }
126    /// ```
127    ///
128    /// This can also be useful for monitoring the peak values of a signal.
129    ///
130    /// ```
131    /// extern crate sample;
132    ///
133    /// use sample::{peak, signal, Frame, Signal};
134    ///
135    /// fn main() {
136    ///     let sine_wave = signal::rate(4.0).const_hz(1.0).sine();
137    ///     let mut peak = sine_wave
138    ///         .map(peak::full_wave)
139    ///         .map(|f| [f[0].round()]);
140    ///     assert_eq!(
141    ///         peak.take(4).collect::<Vec<_>>(),
142    ///         vec![[0.0], [1.0], [0.0], [1.0]]
143    ///     );
144    /// }
145    /// ```
146    fn map<M, F>(self, map: M) -> Map<Self, M, F>
147    where
148        Self: Sized,
149        M: FnMut(Self::Frame) -> F,
150        F: Frame,
151    {
152        Map {
153            signal: self,
154            map: map,
155            frame: core::marker::PhantomData,
156        }
157    }
158
159    /// A signal that maps one set of frames to another.
160    ///
161    /// # Example
162    ///
163    /// ```rust
164    /// extern crate sample;
165    ///
166    /// use sample::{signal, Signal};
167    ///
168    /// fn main() {
169    ///     let frames = signal::gen(|| [0.5]);
170    ///     let more_frames = signal::gen(|| [0.25]);
171    ///     let mut mapper = frames.zip_map(more_frames, |f, o| [f[0], o[0]]);
172    ///     assert_eq!(mapper.next(), [0.5, 0.25]);
173    ///     assert_eq!(mapper.next(), [0.5, 0.25]);
174    ///     assert_eq!(mapper.next(), [0.5, 0.25]);
175    /// }
176    /// ```
177    fn zip_map<O, M, F>(self, other: O, map: M) -> ZipMap<Self, O, M, F>
178    where
179        Self: Sized,
180        M: FnMut(Self::Frame, O::Frame) -> F,
181        O: Signal,
182        F: Frame,
183    {
184        ZipMap {
185            this: self,
186            map: map,
187            other: other,
188            frame: core::marker::PhantomData,
189        }
190    }
191
192    /// Provides an iterator that yields the sum of the frames yielded by both `other` and `self`
193    /// in lock-step.
194    ///
195    /// # Example
196    ///
197    /// ```rust
198    /// extern crate sample;
199    ///
200    /// use sample::{signal, Signal};
201    ///
202    /// fn main() {
203    ///     let a = [[0.2], [-0.6], [0.4]];
204    ///     let b = [[0.2], [0.1], [-0.8]];
205    ///     let a_signal = signal::from_iter(a.iter().cloned());
206    ///     let b_signal = signal::from_iter(b.iter().cloned());
207    ///     let added: Vec<_> = a_signal.add_amp(b_signal).take(3).collect();
208    ///     assert_eq!(added, vec![[0.4], [-0.5], [-0.4]]);
209    /// }
210    /// ```
211    #[inline]
212    fn add_amp<S>(self, other: S) -> AddAmp<Self, S>
213    where
214        Self: Sized,
215        S: Signal,
216        S::Frame: Frame<
217            Sample = <<Self::Frame as Frame>::Sample as Sample>::Signed,
218            NumChannels = <Self::Frame as Frame>::NumChannels,
219        >,
220    {
221        AddAmp { a: self, b: other }
222    }
223
224    /// Provides an iterator that yields the product of the frames yielded by both `other` and
225    /// `self` in lock-step.
226    ///
227    /// # Example
228    ///
229    /// ```rust
230    /// extern crate sample;
231    ///
232    /// use sample::{signal, Signal};
233    ///
234    /// fn main() {
235    ///     let a = [[0.25], [-0.8], [-0.5]];
236    ///     let b = [[0.2], [0.5], [0.8]];
237    ///     let a_signal = signal::from_iter(a.iter().cloned());
238    ///     let b_signal = signal::from_iter(b.iter().cloned());
239    ///     let added: Vec<_> = a_signal.mul_amp(b_signal).take(3).collect();
240    ///     assert_eq!(added, vec![[0.05], [-0.4], [-0.4]]);
241    /// }
242    /// ```
243    #[inline]
244    fn mul_amp<S>(self, other: S) -> MulAmp<Self, S>
245    where
246        Self: Sized,
247        S: Signal,
248        S::Frame: Frame<
249            Sample = <<Self::Frame as Frame>::Sample as Sample>::Float,
250            NumChannels = <Self::Frame as Frame>::NumChannels,
251        >,
252    {
253        MulAmp { a: self, b: other }
254    }
255
256    /// Provides an iterator that offsets the amplitude of every channel in each frame of the
257    /// signal by some sample value and yields the resulting frames.
258    ///
259    /// # Example
260    ///
261    /// ```rust
262    /// extern crate sample;
263    ///
264    /// use sample::{signal, Signal};
265    ///
266    /// fn main() {
267    ///     let frames = [[0.25, 0.4], [-0.2, -0.5]];
268    ///     let signal = signal::from_iter(frames.iter().cloned());
269    ///     let offset: Vec<_> = signal.offset_amp(0.5).take(2).collect();
270    ///     assert_eq!(offset, vec![[0.75, 0.9], [0.3, 0.0]]);
271    /// }
272    /// ```
273    #[inline]
274    fn offset_amp(
275        self,
276        offset: <<Self::Frame as Frame>::Sample as Sample>::Signed,
277    ) -> OffsetAmp<Self>
278    where
279        Self: Sized,
280    {
281        OffsetAmp {
282            signal: self,
283            offset: offset,
284        }
285    }
286
287    /// Produces an `Iterator` that scales the amplitude of the sample of each channel in every
288    /// `Frame` yielded by `self` by the given amplitude.
289    ///
290    /// # Example
291    ///
292    /// ```rust
293    /// extern crate sample;
294    ///
295    /// use sample::{signal, Signal};
296    ///
297    /// fn main() {
298    ///     let frames = [[0.2], [-0.5], [-0.4], [0.3]];
299    ///     let signal = signal::from_iter(frames.iter().cloned());
300    ///     let scaled: Vec<_> = signal.scale_amp(2.0).take(4).collect();
301    ///     assert_eq!(scaled, vec![[0.4], [-1.0], [-0.8], [0.6]]);
302    /// }
303    /// ```
304    #[inline]
305    fn scale_amp(self, amp: <<Self::Frame as Frame>::Sample as Sample>::Float) -> ScaleAmp<Self>
306    where
307        Self: Sized,
308    {
309        ScaleAmp {
310            signal: self,
311            amp: amp,
312        }
313    }
314
315    /// Produces a new `Signal` that offsets the amplitude of every `Frame` in `self` by the
316    /// respective amplitudes in each channel of the given `amp_frame`.
317    ///
318    /// # Example
319    ///
320    /// ```rust
321    /// extern crate sample;
322    ///
323    /// use sample::{signal, Signal};
324    ///
325    /// fn main() {
326    ///     let frames = [[0.5, 0.3], [-0.25, 0.9]];
327    ///     let signal = signal::from_iter(frames.iter().cloned());
328    ///     let offset: Vec<_> = signal.offset_amp_per_channel([0.25, -0.5]).take(2).collect();
329    ///     assert_eq!(offset, vec![[0.75, -0.2], [0.0, 0.4]]);
330    /// }
331    /// ```
332    #[inline]
333    fn offset_amp_per_channel<F>(self, amp_frame: F) -> OffsetAmpPerChannel<Self, F>
334    where
335        Self: Sized,
336        F: Frame<
337            Sample = <<Self::Frame as Frame>::Sample as Sample>::Signed,
338            NumChannels = <Self::Frame as Frame>::NumChannels,
339        >,
340    {
341        OffsetAmpPerChannel {
342            signal: self,
343            amp_frame: amp_frame,
344        }
345    }
346
347    /// Produces a new `Signal` that scales the amplitude of every `Frame` in `self` by the
348    /// respective amplitudes in each channel of the given `amp_frame`.
349    ///
350    /// # Example
351    ///
352    /// ```rust
353    /// extern crate sample;
354    ///
355    /// use sample::{signal, Signal};
356    ///
357    /// fn main() {
358    ///     let frames = [[0.2, -0.5], [-0.4, 0.3]];
359    ///     let signal = signal::from_iter(frames.iter().cloned());
360    ///     let scaled: Vec<_> = signal.scale_amp_per_channel([0.5, 2.0]).take(2).collect();
361    ///     assert_eq!(scaled, vec![[0.1, -1.0], [-0.2, 0.6]]);
362    /// }
363    /// ```
364    #[inline]
365    fn scale_amp_per_channel<F>(self, amp_frame: F) -> ScaleAmpPerChannel<Self, F>
366    where
367        Self: Sized,
368        F: Frame<
369            Sample = <<Self::Frame as Frame>::Sample as Sample>::Float,
370            NumChannels = <Self::Frame as Frame>::NumChannels,
371        >,
372    {
373        ScaleAmpPerChannel {
374            signal: self,
375            amp_frame: amp_frame,
376        }
377    }
378
379    /// Multiplies the rate at which frames of `self` are yielded by the given `signal`.
380    ///
381    /// This happens by wrapping `self` in a `rate::Converter` and calling `set_playback_hz_scale`
382    /// with each value yielded by `signal`
383    ///
384    /// # Example
385    ///
386    /// ```rust
387    /// extern crate sample;
388    ///
389    /// use sample::{signal, Signal};
390    /// use sample::interpolate::Linear;
391    ///
392    /// fn main() {
393    ///     let foo = [[0.0], [1.0], [0.0], [-1.0]];
394    ///     let mul = [[1.0], [1.0], [0.5], [0.5], [0.5], [0.5]];
395    ///     let mut source = signal::from_iter(foo.iter().cloned());
396    ///     let interp = Linear::from_source(&mut source);
397    ///     let hz_signal = signal::from_iter(mul.iter().cloned());
398    ///     let frames: Vec<_> = source.mul_hz(interp, hz_signal).take(6).collect();
399    ///     assert_eq!(&frames[..], &[[0.0], [1.0], [0.0], [-0.5], [-1.0], [-0.5]][..]);
400    /// }
401    /// ```
402    fn mul_hz<M, I>(self, interpolator: I, mul_per_frame: M) -> MulHz<Self, M, I>
403    where
404        Self: Sized,
405        M: Signal<Frame = [f64; 1]>,
406        I: Interpolator,
407    {
408        MulHz {
409            signal: Converter::scale_playback_hz(self, interpolator, 1.0),
410            mul_per_frame: mul_per_frame,
411        }
412    }
413
414    /// Converts the rate at which frames of the `Signal` are yielded using interpolation.
415    ///
416    /// # Example
417    ///
418    /// ```rust
419    /// extern crate sample;
420    ///
421    /// use sample::{signal, Signal};
422    /// use sample::interpolate::Linear;
423    ///
424    /// fn main() {
425    ///     let foo = [[0.0], [1.0], [0.0], [-1.0]];
426    ///     let mut source = signal::from_iter(foo.iter().cloned());
427    ///     let interp = Linear::from_source(&mut source);
428    ///     let frames: Vec<_> = source.from_hz_to_hz(interp, 1.0, 2.0).take(8).collect();
429    ///     assert_eq!(&frames[..], &[[0.0], [0.5], [1.0], [0.5], [0.0], [-0.5], [-1.0], [-0.5]][..]);
430    /// }
431    /// ```
432    fn from_hz_to_hz<I>(self, interpolator: I, source_hz: f64, target_hz: f64) -> Converter<Self, I>
433    where
434        Self: Sized,
435        I: Interpolator,
436    {
437        Converter::from_hz_to_hz(self, interpolator, source_hz, target_hz)
438    }
439
440    /// Multiplies the rate at which frames of the `Signal` are yielded by the given value.
441    ///
442    /// # Example
443    ///
444    /// ```rust
445    /// extern crate sample;
446    ///
447    /// use sample::{signal, Signal};
448    /// use sample::interpolate::Linear;
449    ///
450    /// fn main() {
451    ///     let foo = [[0.0], [1.0], [0.0], [-1.0]];
452    ///     let mut source = signal::from_iter(foo.iter().cloned());
453    ///     let interp = Linear::from_source(&mut source);
454    ///     let frames: Vec<_> = source.scale_hz(interp, 0.5).take(8).collect();
455    ///     assert_eq!(&frames[..], &[[0.0], [0.5], [1.0], [0.5], [0.0], [-0.5], [-1.0], [-0.5]][..]);
456    /// }
457    /// ```
458    fn scale_hz<I>(self, interpolator: I, multi: f64) -> Converter<Self, I>
459    where
460        Self: Sized,
461        I: Interpolator,
462    {
463        Converter::scale_playback_hz(self, interpolator, multi)
464    }
465
466    /// Delays the `Signal` by the given number of frames.
467    ///
468    /// The delay is performed by yielding `Frame::equilibrium()` `n_frames` times before
469    /// continuing to yield frames from `signal`.
470    ///
471    /// # Example
472    ///
473    /// ```rust
474    /// extern crate sample;
475    ///
476    /// use sample::{signal, Signal};
477    ///
478    /// fn main() {
479    ///     let frames = [[0.2], [0.4]];
480    ///     let signal = signal::from_iter(frames.iter().cloned());
481    ///     let delayed: Vec<_> = signal.delay(2).take(4).collect();
482    ///     assert_eq!(delayed, vec![[0.0], [0.0], [0.2], [0.4]]);
483    /// }
484    /// ```
485    fn delay(self, n_frames: usize) -> Delay<Self>
486    where
487        Self: Sized,
488    {
489        Delay {
490            signal: self,
491            n_frames: n_frames,
492        }
493    }
494
495    /// Converts a `Signal` into a type that yields the interleaved `Sample`s.
496    ///
497    /// # Example
498    ///
499    /// ```rust
500    /// extern crate sample;
501    ///
502    /// use sample::{signal, Signal};
503    ///
504    /// fn main() {
505    ///     let frames = [[0.1, 0.2], [0.3, 0.4]];
506    ///     let signal = signal::from_iter(frames.iter().cloned());
507    ///     let samples = signal.into_interleaved_samples();
508    ///     let samples: Vec<_> = samples.into_iter().take(4).collect();
509    ///     assert_eq!(samples, vec![0.1, 0.2, 0.3, 0.4]);
510    /// }
511    /// ```
512    fn into_interleaved_samples(mut self) -> IntoInterleavedSamples<Self>
513    where
514        Self: Sized,
515    {
516        let first = self.next().channels();
517        IntoInterleavedSamples {
518            signal: self,
519            current_frame: first,
520        }
521    }
522
523    /// Clips the amplitude of each channel in each `Frame` yielded by `self` to the given
524    /// threshold amplitude.
525    ///
526    /// # Example
527    ///
528    /// ```rust
529    /// extern crate sample;
530    ///
531    /// use sample::{signal, Signal};
532    ///
533    /// fn main() {
534    ///     let frames = [[1.2, 0.8], [-0.7, -1.4]];
535    ///     let signal = signal::from_iter(frames.iter().cloned());
536    ///     let clipped: Vec<_> = signal.clip_amp(0.9).take(2).collect();
537    ///     assert_eq!(clipped, vec![[0.9, 0.8], [-0.7, -0.9]]);
538    /// }
539    /// ```
540    fn clip_amp(self, thresh: <<Self::Frame as Frame>::Sample as Sample>::Signed) -> ClipAmp<Self>
541    where
542        Self: Sized,
543    {
544        ClipAmp {
545            signal: self,
546            thresh: thresh,
547        }
548    }
549
550    /// Create a new `Signal` that calls the enclosing function on each iteration.
551    ///
552    /// # Example
553    ///
554    /// ```rust
555    /// extern crate sample;
556    ///
557    /// use sample::{signal, Signal};
558    ///
559    /// fn main() {
560    ///     let mut f = [0.0];
561    ///     let mut signal = signal::gen_mut(move || {
562    ///         f[0] += 0.1;
563    ///         f
564    ///     });
565    ///     let func = |x: &[f64; 1]| {
566    ///         assert_eq!(*x, [0.1]);
567    ///     };
568    ///     let mut inspected = signal.inspect(func);
569    ///     let out = inspected.next();
570    ///     assert_eq!(out, [0.1]);
571    /// }
572    /// ```
573    fn inspect<F>(self, inspect: F) -> Inspect<Self, F>
574    where
575        Self: Sized,
576        F: FnMut(&Self::Frame),
577    {
578        Inspect {
579            signal: self,
580            inspect: inspect,
581        }
582    }
583
584    /// Forks `Self` into two signals that produce the same frames.
585    ///
586    /// The given `ring_buffer` must be empty to ensure correct behaviour.
587    ///
588    /// Each time a frame is requested from the signal on one branch, that frame will be pushed to
589    /// the given `ring_buffer` of pending frames to be collected by the other branch and a flag
590    /// will be set to indicate that there are pending frames.
591    ///
592    /// **Fork** can be used to share the queue between the two branches by reference
593    /// `fork.by_ref()` or via a reference counted pointer `fork.by_rc()`.
594    ///
595    /// **Fork** is a slightly more efficient alternative to **Bus** when only two branches are
596    /// required.
597    ///
598    /// **Note:** It is up to the user to ensure that there are never more than
599    /// `ring_buffer.max_len()` pending frames - otherwise the oldest frames will be overridden and
600    /// glitching may occur on the lagging branch.
601    ///
602    /// **Panic!**s if the given `ring_buffer` is not empty in order to guarantee correct
603    /// behaviour.
604    ///
605    /// ```
606    /// extern crate sample;
607    ///
608    /// use sample::{ring_buffer, signal, Signal};
609    ///
610    /// fn main() {
611    ///     let signal = signal::rate(44_100.0).const_hz(440.0).sine();
612    ///     let ring_buffer = ring_buffer::Bounded::<[[f64; 1]; 64]>::array();
613    ///     let mut fork = signal.fork(ring_buffer);
614    ///
615    ///     // Forks can be split into their branches via reference.
616    ///     {
617    ///         let (mut a, mut b) = fork.by_ref();
618    ///         assert_eq!(a.next(), b.next());
619    ///         assert_eq!(a.by_ref().take(64).collect::<Vec<_>>(),
620    ///                    b.by_ref().take(64).collect::<Vec<_>>());
621    ///     }
622    ///
623    ///     // Forks can also be split via reference counted pointer.
624    ///     let (mut a, mut b) = fork.by_rc();
625    ///     assert_eq!(a.next(), b.next());
626    ///     assert_eq!(a.by_ref().take(64).collect::<Vec<_>>(),
627    ///                b.by_ref().take(64).collect::<Vec<_>>());
628    ///
629    ///     // The lagging branch will be missing frames if we exceed `ring_buffer.max_len()`
630    ///     // pending frames.
631    ///     assert!(a.by_ref().take(67).collect::<Vec<_>>() !=
632    ///             b.by_ref().take(67).collect::<Vec<_>>())
633    /// }
634    /// ```
635    fn fork<S>(self, ring_buffer: ring_buffer::Bounded<S>) -> Fork<Self, S>
636    where
637        Self: Sized,
638        S: ring_buffer::SliceMut<Element=Self::Frame>,
639    {
640        assert!(ring_buffer.is_empty());
641        let shared = ForkShared {
642            signal: self,
643            ring_buffer: ring_buffer,
644            pending: Fork::<Self, S>::B,
645        };
646        Fork { shared: RefCell::new(shared) }
647    }
648
649    /// Moves the `Signal` into a `Bus` from which its output may be divided into multiple other
650    /// `Signal`s in the form of `Output`s.
651    ///
652    /// This method allows to create more complex directed acyclic graph structures that
653    /// incorporate concepts like sends, side-chaining, etc, rather than being restricted to tree
654    /// structures where signals can only ever be joined but never divided.
655    ///
656    /// Note: When using multiple `Output`s in this fashion, you will need to be sure to pull the
657    /// frames from each `Output` in sync (whether per frame or per buffer). This is because when
658    /// output A requests `Frame`s before output B, those frames must remain available for output
659    /// B and in turn must be stored in an intermediary ring buffer.
660    ///
661    /// # Example
662    ///
663    /// ```rust
664    /// extern crate sample;
665    ///
666    /// use sample::{signal, Signal};
667    ///
668    /// fn main() {
669    ///     let frames = [[0.1], [0.2], [0.3], [0.4], [0.5], [0.6]];
670    ///     let signal = signal::from_iter(frames.iter().cloned());
671    ///     let bus = signal.bus();
672    ///     let mut a = bus.send();
673    ///     let mut b = bus.send();
674    ///     assert_eq!(a.by_ref().take(3).collect::<Vec<_>>(), vec![[0.1], [0.2], [0.3]]);
675    ///     assert_eq!(b.by_ref().take(3).collect::<Vec<_>>(), vec![[0.1], [0.2], [0.3]]);
676    ///
677    ///     let c = bus.send();
678    ///     assert_eq!(c.take(3).collect::<Vec<_>>(), vec![[0.4], [0.5], [0.6]]);
679    ///     assert_eq!(b.take(3).collect::<Vec<_>>(), vec![[0.4], [0.5], [0.6]]);
680    ///     assert_eq!(a.take(3).collect::<Vec<_>>(), vec![[0.4], [0.5], [0.6]]);
681    /// }
682    /// ```
683    fn bus(self) -> Bus<Self>
684    where
685        Self: Sized,
686    {
687        Bus::new(self, BTreeMap::new())
688    }
689
690    /// Converts the `Signal` into an `Iterator` that will yield the given number for `Frame`s
691    /// before returning `None`.
692    ///
693    /// # Example
694    ///
695    /// ```rust
696    /// extern crate sample;
697    ///
698    /// use sample::{signal, Signal};
699    ///
700    /// fn main() {
701    ///     let frames = [[0.1], [0.2], [0.3], [0.4]];
702    ///     let mut signal = signal::from_iter(frames.iter().cloned()).take(2);
703    ///     assert_eq!(signal.next(), Some([0.1]));
704    ///     assert_eq!(signal.next(), Some([0.2]));
705    ///     assert_eq!(signal.next(), None);
706    /// }
707    /// ```
708    fn take(self, n: usize) -> Take<Self>
709    where
710        Self: Sized,
711    {
712        Take { signal: self, n: n }
713    }
714
715    /// Converts the `Signal` into an `Iterator` yielding frames until the `signal.is_exhausted()`
716    /// returns `true`.
717    ///
718    /// # Example
719    ///
720    /// ```
721    /// extern crate sample;
722    ///
723    /// use sample::{signal, Signal};
724    ///
725    /// fn main() {
726    ///     let frames = [[1], [2]];
727    ///     let signal = signal::from_iter(frames.iter().cloned());
728    ///     assert_eq!(signal.until_exhausted().count(), 2);
729    /// }
730    /// ```
731    fn until_exhausted(self) -> UntilExhausted<Self>
732    where
733        Self: Sized,
734    {
735        UntilExhausted {
736            signal: self,
737        }
738    }
739
740    /// Buffers the signal using the given ring buffer.
741    ///
742    /// When `next` is called on the returned signal, it will first check if the ring buffer is
743    /// empty. If so, it will completely fill the ring buffer with the inner signal before yielding
744    /// the next value. If the ring buffer still contains un-yielded values, the next frame will be
745    /// popped from the front of the ring buffer and immediately returned.
746    ///
747    /// ```
748    /// extern crate sample;
749    ///
750    /// use sample::ring_buffer;
751    /// use sample::{signal, Signal};
752    ///
753    /// fn main() {
754    ///     let frames = [[0.1], [0.2], [0.3], [0.4]];
755    ///     let signal = signal::from_iter(frames.iter().cloned());
756    ///     let ring_buffer = ring_buffer::Bounded::<[[f32; 1]; 2]>::array();
757    ///     let mut buffered_signal = signal.buffered(ring_buffer);
758    ///     assert_eq!(buffered_signal.next(), [0.1]);
759    ///     assert_eq!(buffered_signal.next(), [0.2]);
760    ///     assert_eq!(buffered_signal.next(), [0.3]);
761    ///     assert_eq!(buffered_signal.next(), [0.4]);
762    ///     assert_eq!(buffered_signal.next(), [0.0]);
763    /// }
764    /// ```
765    ///
766    /// If the given ring buffer already contains frames, those will be yielded first.
767    ///
768    /// ```
769    /// extern crate sample;
770    /// use sample::ring_buffer;
771    /// use sample::{signal, Signal};
772    ///
773    /// fn main() {
774    ///     let frames = [[0.1], [0.2], [0.3], [0.4]];
775    ///     let signal = signal::from_iter(frames.iter().cloned());
776    ///     let ring_buffer = ring_buffer::Bounded::from_full([[0.8], [0.9]]);
777    ///     let mut buffered_signal = signal.buffered(ring_buffer);
778    ///     assert_eq!(buffered_signal.next(), [0.8]);
779    ///     assert_eq!(buffered_signal.next(), [0.9]);
780    ///     assert_eq!(buffered_signal.next(), [0.1]);
781    ///     assert_eq!(buffered_signal.next(), [0.2]);
782    ///     assert_eq!(buffered_signal.next(), [0.3]);
783    ///     assert_eq!(buffered_signal.next(), [0.4]);
784    ///     assert_eq!(buffered_signal.next(), [0.0]);
785    /// }
786    /// ```
787    fn buffered<S>(self, ring_buffer: ring_buffer::Bounded<S>) -> Buffered<Self, S>
788    where
789        Self: Sized,
790        S: ring_buffer::Slice<Element = Self::Frame> + ring_buffer::SliceMut,
791    {
792        Buffered {
793            signal: self,
794            ring_buffer: ring_buffer,
795        }
796    }
797
798    /// An adaptor that yields the RMS of the signal.
799    ///
800    /// The window size of the RMS detector is equal to the given ring buffer length.
801    ///
802    /// # Example
803    ///
804    /// ```
805    /// extern crate sample;
806    ///
807    /// use sample::ring_buffer;
808    /// use sample::{signal, Signal};
809    ///
810    /// fn main() {
811    ///     let frames = [[0.9], [-0.8], [0.6], [-0.9]];
812    ///     let signal = signal::from_iter(frames.iter().cloned());
813    ///     let ring_buffer = ring_buffer::Fixed::from([[0.0]; 2]);
814    ///     let mut rms_signal = signal.rms(ring_buffer);
815    ///     assert_eq!(
816    ///         [rms_signal.next(), rms_signal.next(), rms_signal.next()],
817    ///         [[0.6363961030678927], [0.8514693182963201], [0.7071067811865476]]
818    ///     );
819    /// }
820    /// ```
821    fn rms<S>(self, ring_buffer: ring_buffer::Fixed<S>) -> Rms<Self, S>
822    where
823        Self: Sized,
824        S: ring_buffer::Slice<Element = <Self::Frame as Frame>::Float> + ring_buffer::SliceMut,
825    {
826        Rms {
827            signal: self,
828            rms: rms::Rms::new(ring_buffer),
829        }
830    }
831
832    /// An adaptor that detects and yields the envelope of the signal.
833    ///
834    /// # Example
835    ///
836    /// ```
837    /// extern crate sample;
838    ///
839    /// use sample::{envelope, signal, Signal};
840    ///
841    /// fn main() {
842    ///     let signal = signal::rate(4.0).const_hz(1.0).sine();
843    ///     let attack = 1.0;
844    ///     let release = 1.0;
845    ///     let detector = envelope::Detector::peak(attack, release);
846    ///     let mut envelope = signal.detect_envelope(detector);
847    ///     assert_eq!(
848    ///         envelope.take(4).collect::<Vec<_>>(),
849    ///         vec![[0.0], [0.6321205496788025], [0.23254416035257117], [0.7176687675647109]]
850    ///     );
851    /// }
852    /// ```
853    fn detect_envelope<D>(
854        self,
855        detector: envelope::Detector<Self::Frame, D>,
856    ) -> DetectEnvelope<Self, D>
857    where
858        Self: Sized,
859        D: envelope::Detect<Self::Frame>,
860    {
861        DetectEnvelope {
862            signal: self,
863            detector: detector,
864        }
865    }
866
867    /// Borrows a Signal rather than consuming it.
868    ///
869    /// This is useful to allow applying signal adaptors while still retaining ownership of the
870    /// original signal.
871    ///
872    /// # Example
873    ///
874    /// ```rust
875    /// extern crate sample;
876    ///
877    /// use sample::{signal, Signal};
878    ///
879    /// fn main() {
880    ///     let frames = [[0], [1], [2], [3], [4]];
881    ///     let mut signal = signal::from_iter(frames.iter().cloned());
882    ///     assert_eq!(signal.next(), [0]);
883    ///     assert_eq!(signal.by_ref().take(2).collect::<Vec<_>>(), vec![[1], [2]]);
884    ///     assert_eq!(signal.next(), [3]);
885    ///     assert_eq!(signal.next(), [4]);
886    /// }
887    /// ```
888    fn by_ref(&mut self) -> &mut Self
889    where
890        Self: Sized,
891    {
892        self
893    }
894}
895
896
897/// Consumes the given `Iterator`, converts it to a `Signal`, applies the given function to the
898/// `Signal` and returns an `Iterator` that will become exhausted when the consumed `Iterator`
899/// does.
900///
901/// This is particularly useful when you want to apply `Signal` methods to an `Iterator` yielding
902/// `Frame`s and return an `Iterator` as a result.
903///
904/// # Example
905///
906/// ```
907/// extern crate sample;
908///
909/// use sample::{signal, Signal};
910///
911/// fn main() {
912///     let frames = vec![[0], [1], [2], [3]];
913///     let offset_frames = signal::lift(frames, |signal| signal.offset_amp(2));
914///     assert_eq!(offset_frames.collect::<Vec<_>>(), vec![[2], [3], [4], [5]]);
915/// }
916/// ```
917pub fn lift<I, F, S>(iter: I, f: F) -> UntilExhausted<S>
918where
919    I: IntoIterator,
920    I::Item: Frame,
921    F: FnOnce(FromIterator<I::IntoIter>) -> S,
922    S: Signal<Frame = I::Item>,
923{
924    let iter = iter.into_iter();
925    let signal = from_iter(iter);
926    let new_signal = f(signal);
927    new_signal.until_exhausted()
928}
929
930
931///// Signal Types
932
933
934/// An iterator that endlessly yields `Frame`s of type `F` at equilibrium.
935#[derive(Clone)]
936pub struct Equilibrium<F> {
937    frame: core::marker::PhantomData<F>,
938}
939
940/// A signal that generates frames using the given function.
941#[derive(Clone)]
942pub struct Gen<G, F> {
943    gen: G,
944    frame: core::marker::PhantomData<F>,
945}
946
947/// A signal that generates frames using the given function which may mutate some state.
948#[derive(Clone)]
949pub struct GenMut<G, F> {
950    gen_mut: G,
951    frame: core::marker::PhantomData<F>,
952}
953
954/// A signal that maps from one signal to another
955#[derive(Clone)]
956pub struct Map<S, M, F> {
957    signal: S,
958    map: M,
959    frame: core::marker::PhantomData<F>,
960}
961
962/// A signal that iterates two signals in parallel and combines them with a function.
963///
964/// `ZipMap::is_exhausted` returns `true` if *either* of the two signals returns `true`.
965#[derive(Clone)]
966pub struct ZipMap<S, O, M, F> {
967    this: S,
968    other: O,
969    map: M,
970    frame: core::marker::PhantomData<F>,
971}
972
973/// A type that wraps an Iterator and provides a `Signal` implementation for it.
974#[derive(Clone)]
975pub struct FromIterator<I>
976where
977    I: Iterator,
978{
979    iter: I,
980    next: Option<I::Item>,
981}
982
983/// An iterator that converts an iterator of `Sample`s to an iterator of `Frame`s.
984#[derive(Clone)]
985pub struct FromInterleavedSamplesIterator<I, F>
986where
987    I: Iterator,
988    I::Item: Sample,
989    F: Frame<Sample = I::Item>,
990{
991    samples: I,
992    next: Option<F>,
993}
994
995/// The rate at which phrase a **Signal** is sampled.
996#[derive(Copy, Clone, Debug, PartialEq)]
997pub struct Rate {
998    hz: f64,
999}
1000
1001/// A constant phase step size.
1002#[derive(Clone)]
1003pub struct ConstHz {
1004    step: f64,
1005}
1006
1007/// An iterator that yields the step size for a phase.
1008#[derive(Clone)]
1009pub struct Hz<S> {
1010    hz: S,
1011    rate: Rate,
1012}
1013
1014
1015/// An iterator that yields a phase, useful for waveforms like Sine or Saw.
1016#[derive(Clone)]
1017pub struct Phase<S> {
1018    step: S,
1019    next: f64,
1020}
1021
1022/// A sine wave signal generator.
1023#[derive(Clone)]
1024pub struct Sine<S> {
1025    phase: Phase<S>,
1026}
1027
1028/// A saw wave signal generator.
1029#[derive(Clone)]
1030pub struct Saw<S> {
1031    phase: Phase<S>,
1032}
1033
1034/// A square wave signal generator.
1035#[derive(Clone)]
1036pub struct Square<S> {
1037    phase: Phase<S>,
1038}
1039
1040/// A noise signal generator.
1041#[derive(Clone)]
1042pub struct Noise {
1043    seed: u64,
1044}
1045
1046/// A 1D simplex-noise generator.
1047#[derive(Clone)]
1048pub struct NoiseSimplex<S> {
1049    phase: Phase<S>,
1050}
1051
1052/// An iterator that yields the sum of the frames yielded by both `other` and `self` in lock-step.
1053#[derive(Clone)]
1054pub struct AddAmp<A, B> {
1055    a: A,
1056    b: B,
1057}
1058
1059/// An iterator that yields the product of the frames yielded by both `other` and `self` in
1060/// lock-step.
1061#[derive(Clone)]
1062pub struct MulAmp<A, B> {
1063    a: A,
1064    b: B,
1065}
1066
1067/// Provides an iterator that offsets the amplitude of every channel in each frame of the
1068/// signal by some sample value and yields the resulting frames.
1069#[derive(Clone)]
1070pub struct OffsetAmp<S>
1071where
1072    S: Signal,
1073{
1074    signal: S,
1075    offset: <<S::Frame as Frame>::Sample as Sample>::Signed,
1076}
1077
1078/// An `Iterator` that scales the amplitude of the sample of each channel in every `Frame` yielded
1079/// by `self` by the given amplitude.
1080#[derive(Clone)]
1081pub struct ScaleAmp<S>
1082where
1083    S: Signal,
1084{
1085    signal: S,
1086    amp: <<S::Frame as Frame>::Sample as Sample>::Float,
1087}
1088
1089/// An `Iterator` that scales the amplitude of every `Frame` in `self` by the respective amplitudes
1090/// in each channel of the given `amp` `Frame`.
1091#[derive(Clone)]
1092pub struct OffsetAmpPerChannel<S, F> {
1093    signal: S,
1094    amp_frame: F,
1095}
1096
1097/// An `Iterator` that scales the amplitude of every `Frame` in `self` by the respective amplitudes
1098/// in each channel of the given `amp` `Frame`.
1099#[derive(Clone)]
1100pub struct ScaleAmpPerChannel<S, F> {
1101    signal: S,
1102    amp_frame: F,
1103}
1104
1105/// Multiplies the rate at which frames of `self` are yielded by the given `signal`.
1106///
1107/// This happens by wrapping `self` in a `rate::Converter` and calling `set_playback_hz_scale`
1108/// with the value yielded by `signal`
1109#[derive(Clone)]
1110pub struct MulHz<S, M, I>
1111where
1112    S: Signal,
1113    I: Interpolator,
1114{
1115    signal: Converter<S, I>,
1116    mul_per_frame: M,
1117}
1118
1119/// Delays the `signal` by the given number of frames.
1120///
1121/// The delay is performed by yielding `Frame::equilibrium()` `n_frames` times before
1122/// continuing to yield frames from `signal`.
1123#[derive(Clone)]
1124pub struct Delay<S> {
1125    signal: S,
1126    n_frames: usize,
1127}
1128
1129/// A signal that calls its enclosing function and returns the original value. The signal may
1130/// mutate state.
1131#[derive(Clone)]
1132pub struct Inspect<S, F> {
1133    signal: S,
1134    inspect: F,
1135}
1136
1137/// Converts a `Signal` to a type that yields the individual interleaved samples.
1138pub struct IntoInterleavedSamples<S>
1139where
1140    S: Signal,
1141{
1142    signal: S,
1143    current_frame: <S::Frame as Frame>::Channels,
1144}
1145
1146/// Converts the `IntoInterleavedSamples` into an `Iterator` that always returns `Some`.
1147pub struct IntoInterleavedSamplesIterator<S>
1148where
1149    S: Signal,
1150{
1151    samples: IntoInterleavedSamples<S>,
1152}
1153
1154/// Yields frames from the signal until the `signal.is_exhausted()` returns `true`.
1155#[derive(Clone)]
1156pub struct UntilExhausted<S>
1157where
1158    S: Signal,
1159{
1160    signal: S,
1161}
1162
1163/// Clips samples in each frame yielded by `signal` to the given threshhold amplitude.
1164#[derive(Clone)]
1165pub struct ClipAmp<S>
1166where
1167    S: Signal,
1168{
1169    signal: S,
1170    thresh: <<S::Frame as Frame>::Sample as Sample>::Signed,
1171}
1172
1173/// Represents a forked `Signal` that has not yet been split into its two branches.
1174///
1175/// A `Fork` can be split into its two branches via either of the following methods:
1176///
1177/// - `fork.by_rc()`: consumes self and shares the fork via `Rc<RefCell>`.
1178/// - `fork.by_ref()`: borrows self and shares the fork via `&RefCell`.
1179#[derive(Clone)]
1180pub struct Fork<S, D> {
1181    shared: RefCell<ForkShared<S, D>>,
1182}
1183
1184#[derive(Clone)]
1185struct ForkShared<S, D> {
1186    signal: S,
1187    ring_buffer: ring_buffer::Bounded<D>,
1188    pending: bool,
1189}
1190
1191impl<S, D> Fork<S, D> {
1192    const A: bool = true;
1193    const B: bool = false;
1194
1195    /// Consumes the `Fork` and returns two branches that share the signal and inner ring buffer
1196    /// via a reference countered pointer (`Rc`).
1197    ///
1198    /// Note: This requires dynamical allocation as `Rc<RefCell<Self>>` is used to share the signal
1199    /// and ring buffer. A user may avoid this dynamic allocation by using the `Fork::by_ref`
1200    /// method instead, however this comes with the ergonomic cost of bounding the lifetime of the
1201    /// branches to the lifetime of the fork.
1202    /// `Fork::by_ref`
1203    pub fn by_rc(self) -> (BranchRcA<S, D>, BranchRcB<S, D>) {
1204        let Fork { shared } = self;
1205        let shared_fork = Rc::new(shared);
1206        let a = BranchRcA { shared_fork: shared_fork.clone() };
1207        let b = BranchRcB { shared_fork: shared_fork };
1208        (a, b)
1209    }
1210
1211    /// Mutably borrows the `Fork` and returns two branches that share the signal and inner ring
1212    /// buffer via reference.
1213    ///
1214    /// This is more efficient than `Fork::by_rc` as it does not require `Rc`, however it may be
1215    /// less ergonomic in some cases as the returned branches are bound to the lifetime of `Fork`.
1216    pub fn by_ref(&mut self) -> (BranchRefA<S, D>, BranchRefB<S, D>) {
1217        let Fork { ref shared } = *self;
1218        let a = BranchRefA { shared_fork: shared };
1219        let b = BranchRefB { shared_fork: shared };
1220        (a, b)
1221    }
1222}
1223
1224// A macro to simplify the boilerplate shared between the two branch types returned by `Fork`.
1225macro_rules! define_branch {
1226    ($TRc:ident, $TRef:ident, $SELF:ident, $OTHER:ident) => {
1227        /// One of the two `Branch` signals returned by `Fork::by_rc`.
1228        pub struct $TRc<S, D> {
1229            shared_fork: Rc<RefCell<ForkShared<S, D>>>,
1230        }
1231
1232        /// One of the two `Branch` signals returned by `Fork::by_ref`.
1233        pub struct $TRef<'a, S: 'a, D: 'a> {
1234            shared_fork: &'a RefCell<ForkShared<S, D>>,
1235        }
1236
1237        impl<S, D> Signal for $TRc<S, D>
1238        where
1239            S: Signal,
1240            D: ring_buffer::SliceMut<Element=S::Frame>,
1241        {
1242            type Frame = S::Frame;
1243            fn next(&mut self) -> Self::Frame {
1244                let mut fork = self.shared_fork.borrow_mut();
1245                if fork.pending == Fork::<S, D>::$SELF {
1246                    if let Some(frame) = fork.ring_buffer.pop() {
1247                        return frame;
1248                    }
1249                    fork.pending = Fork::<S, D>::$OTHER;
1250                }
1251                let frame = fork.signal.next();
1252                fork.ring_buffer.push(frame);
1253                frame
1254            }
1255        }
1256
1257        impl<'a, S, D> Signal for $TRef<'a, S, D>
1258        where
1259            S: 'a + Signal,
1260            D: 'a + ring_buffer::SliceMut<Element=S::Frame>,
1261        {
1262            type Frame = S::Frame;
1263            fn next(&mut self) -> Self::Frame {
1264                let mut fork = self.shared_fork.borrow_mut();
1265                if fork.pending == Fork::<S, D>::$SELF {
1266                    if let Some(frame) = fork.ring_buffer.pop() {
1267                        return frame;
1268                    }
1269                    fork.pending = Fork::<S, D>::$OTHER;
1270                }
1271                let frame = fork.signal.next();
1272                fork.ring_buffer.push(frame);
1273                frame
1274            }
1275        }
1276
1277        impl<S, D> $TRc<S, D>
1278        where
1279            D: ring_buffer::Slice,
1280            D::Element: Copy,
1281        {
1282            /// The number of frames that are pending collection by this branch.
1283            pub fn pending_frames(&self) -> usize {
1284                let fork = self.shared_fork.borrow();
1285                if fork.pending == Fork::<S, D>::$SELF {
1286                    fork.ring_buffer.len()
1287                } else {
1288                    0
1289                }
1290            }
1291        }
1292
1293        impl<'a, S, D> $TRef<'a, S, D>
1294        where
1295            D: ring_buffer::Slice,
1296            D::Element: Copy,
1297        {
1298            /// The number of frames that are pending collection by this branch.
1299            pub fn pending_frames(&self) -> usize {
1300                let fork = self.shared_fork.borrow();
1301                if fork.pending == Fork::<S, D>::$SELF {
1302                    fork.ring_buffer.len()
1303                } else {
1304                    0
1305                }
1306            }
1307        }
1308    };
1309}
1310
1311define_branch!(BranchRcA, BranchRefA, A, B);
1312define_branch!(BranchRcB, BranchRefB, B, A);
1313
1314
1315/// A type which allows for `send`ing a single `Signal` to multiple outputs.
1316///
1317/// This type manages
1318pub struct Bus<S>
1319where
1320    S: Signal,
1321{
1322    node: Rc<core::cell::RefCell<SharedNode<S>>>,
1323}
1324
1325/// The data shared between each `Output`.
1326struct SharedNode<S>
1327where
1328    S: Signal,
1329{
1330    signal: S,
1331    // The buffer of frames that have not yet been consumed by all outputs.
1332    buffer: VecDeque<S::Frame>,
1333    // The number of frames in `buffer` that have already been read for each output.
1334    frames_read: BTreeMap<usize, usize>,
1335    // The next output key.
1336    next_key: usize,
1337}
1338
1339/// An output node to which some signal `S` is `Output`ing its frames.
1340///
1341/// It may be more accurate to say that the `Output` "pull"s frames from the signal.
1342pub struct Output<S>
1343where
1344    S: Signal,
1345{
1346    key: usize,
1347    node: Rc<core::cell::RefCell<SharedNode<S>>>,
1348}
1349
1350/// An iterator that yields `n` number of `Frame`s from the inner `signal`.
1351#[derive(Clone)]
1352pub struct Take<S>
1353where
1354    S: Signal,
1355{
1356    signal: S,
1357    n: usize,
1358}
1359
1360/// Buffers the signal using the given ring buffer.
1361///
1362/// When `next` is called, `Buffered` will first check if the ring buffer is empty. If so, it will
1363/// completely fill the ring buffer with `signal` before yielding the next frame.
1364///
1365/// If `next` is called and the ring buffer still contains un-yielded values, the next frame will
1366/// be popped from the front of the ring buffer and immediately returned.
1367#[derive(Clone)]
1368pub struct Buffered<S, D> {
1369    signal: S,
1370    ring_buffer: ring_buffer::Bounded<D>,
1371}
1372
1373/// An iterator that pops elements from the inner bounded ring buffer and yields them.
1374///
1375/// Returns `None` once the inner ring buffer is exhausted.
1376pub struct BufferedFrames<'a, D: 'a> {
1377    ring_buffer: &'a mut ring_buffer::Bounded<D>,
1378}
1379
1380/// An adaptor that yields the RMS of the signal.
1381///
1382/// The window size of the RMS detector is equal to the given ring buffer length.
1383#[derive(Clone)]
1384pub struct Rms<S, D>
1385where
1386    S: Signal,
1387    D: ring_buffer::Slice<Element = <S::Frame as Frame>::Float>,
1388{
1389    signal: S,
1390    rms: rms::Rms<S::Frame, D>,
1391}
1392
1393/// An adaptor that detects and yields the envelope of the signal.
1394#[derive(Clone)]
1395pub struct DetectEnvelope<S, D>
1396where
1397    S: Signal,
1398    D: envelope::Detect<S::Frame>,
1399{
1400    signal: S,
1401    detector: envelope::Detector<S::Frame, D>,
1402}
1403
1404
1405///// Signal Constructors
1406
1407
1408/// Provides an iterator that endlessly yields `Frame`s of type `F` at equilibrium.
1409///
1410/// # Example
1411///
1412/// ```rust
1413/// extern crate sample;
1414///
1415/// use sample::Signal;
1416///
1417/// fn main() {
1418///     let equilibrium: Vec<[f32; 1]> = sample::signal::equilibrium().take(4).collect();
1419///     assert_eq!(equilibrium, vec![[0.0], [0.0], [0.0], [0.0]]);
1420///
1421///     let equilibrium: Vec<[u8; 2]> = sample::signal::equilibrium().take(3).collect();
1422///     assert_eq!(equilibrium, vec![[128, 128], [128, 128], [128, 128]]);
1423/// }
1424/// ```
1425pub fn equilibrium<F>() -> Equilibrium<F>
1426where
1427    F: Frame,
1428{
1429    Equilibrium { frame: core::marker::PhantomData }
1430}
1431
1432
1433/// A signal that generates frames using the given function.
1434///
1435/// The resulting signal is assumed to be infinite and `is_exhausted` will always return `false`.
1436/// To create an exhaustive signal first create an `Iterator` and then use `from_iter`.
1437///
1438/// # Example
1439///
1440/// ```rust
1441/// extern crate sample;
1442///
1443/// use sample::{signal, Signal};
1444///
1445/// fn main() {
1446///     let mut frames = signal::gen(|| [0.5]);
1447///     assert_eq!(frames.next(), [0.5]);
1448///     assert_eq!(frames.next(), [0.5]);
1449///     assert_eq!(frames.next(), [0.5]);
1450/// }
1451/// ```
1452pub fn gen<G, F>(gen: G) -> Gen<G, F>
1453where
1454    G: Fn() -> F,
1455    F: Frame,
1456{
1457    Gen {
1458        gen: gen,
1459        frame: core::marker::PhantomData,
1460    }
1461}
1462
1463
1464/// A signal that generates frames using the given function which may mutate some state.
1465///
1466/// The resulting signal is assumed to be infinite and `is_exhausted` will always return `false`.
1467/// To create an exhaustive signal first create an `Iterator` and then use `from_iter`.
1468///
1469/// # Example
1470///
1471/// ```rust
1472/// extern crate sample;
1473///
1474/// use sample::{signal, Signal};
1475///
1476/// fn main() {
1477///     let mut f = [0.0];
1478///     let mut signal = signal::gen_mut(|| {
1479///         let r = f;
1480///         f[0] += 0.1;
1481///         r
1482///     });
1483///     assert_eq!(signal.next(), [0.0]);
1484///     assert_eq!(signal.next(), [0.1]);
1485///     assert_eq!(signal.next(), [0.2]);
1486/// }
1487/// ```
1488pub fn gen_mut<G, F>(gen_mut: G) -> GenMut<G, F>
1489where
1490    G: FnMut() -> F,
1491    F: Frame,
1492{
1493    GenMut {
1494        gen_mut: gen_mut,
1495        frame: core::marker::PhantomData,
1496    }
1497}
1498
1499
1500/// Create a new `Signal` from the given `Frame`-yielding `Iterator`.
1501///
1502/// When the `Iterator` is exhausted, the new `Signal` will yield `F::equilibrium`.
1503///
1504/// Note that `Iterator::next` will be called immediately so that `FromIterator` can store the next
1505/// pending frame and efficiently test for exhaustiveness.
1506///
1507/// # Example
1508///
1509/// ```rust
1510/// extern crate sample;
1511///
1512/// use sample::{signal, Signal};
1513///
1514/// fn main() {
1515///     let frames = [[1], [-3], [5], [6]];
1516///     let mut signal = signal::from_iter(frames.iter().cloned());
1517///     assert_eq!(signal.next(), [1]);
1518///     assert_eq!(signal.next(), [-3]);
1519///     assert_eq!(signal.next(), [5]);
1520///     assert_eq!(signal.next(), [6]);
1521///     assert_eq!(signal.next(), [0]);
1522/// }
1523/// ```
1524pub fn from_iter<I>(frames: I) -> FromIterator<I::IntoIter>
1525where
1526    I: IntoIterator,
1527    I::Item: Frame,
1528{
1529    let mut iter = frames.into_iter();
1530    let next = iter.next();
1531    FromIterator {
1532        iter: iter,
1533        next: next,
1534    }
1535}
1536
1537
1538/// Create a new `Signal` from the given `Frame`-yielding `Iterator`.
1539///
1540/// When the `Iterator` is exhausted, the new `Signal` will yield `F::equilibrium`.
1541///
1542/// # Example
1543///
1544/// ```rust
1545/// extern crate sample;
1546///
1547/// use sample::{signal, Signal};
1548///
1549/// fn main() {
1550///     let foo = [0, 1, 2, 3];
1551///     let mut signal = signal::from_interleaved_samples_iter::<_, [i32; 2]>(foo.iter().cloned());
1552///     assert_eq!(signal.next(), [0, 1]);
1553///     assert_eq!(signal.next(), [2, 3]);
1554///     assert_eq!(signal.next(), [0, 0]);
1555///
1556///     let bar = [0, 1, 2];
1557///     let mut signal = signal::from_interleaved_samples_iter::<_, [i32; 2]>(bar.iter().cloned());
1558///     assert_eq!(signal.next(), [0, 1]);
1559///     assert_eq!(signal.next(), [0, 0]);
1560/// }
1561/// ```
1562pub fn from_interleaved_samples_iter<I, F>(
1563    samples: I,
1564) -> FromInterleavedSamplesIterator<I::IntoIter, F>
1565where
1566    I: IntoIterator,
1567    I::Item: Sample,
1568    F: Frame<Sample = I::Item>,
1569{
1570    let mut samples = samples.into_iter();
1571    let next = Frame::from_samples(&mut samples);
1572    FromInterleavedSamplesIterator {
1573        samples: samples,
1574        next: next,
1575    }
1576}
1577
1578
1579/// Creates a `Phase` that continuously steps forward by the given `step` size yielder.
1580///
1581/// # Example
1582///
1583/// ```rust
1584/// extern crate sample;
1585///
1586/// use sample::{signal, Signal};
1587///
1588/// fn main() {
1589///     let step = signal::rate(4.0).const_hz(1.0);
1590///     // Note that this is the same as `step.phase()`, a composable alternative.
1591///     let mut phase = signal::phase(step);
1592///     assert_eq!(phase.next(), [0.0]);
1593///     assert_eq!(phase.next(), [0.25]);
1594///     assert_eq!(phase.next(), [0.5]);
1595///     assert_eq!(phase.next(), [0.75]);
1596///     assert_eq!(phase.next(), [0.0]);
1597///     assert_eq!(phase.next(), [0.25]);
1598/// }
1599/// ```
1600pub fn phase<S>(step: S) -> Phase<S>
1601where
1602    S: Step,
1603{
1604    Phase {
1605        step: step,
1606        next: 0.0,
1607    }
1608}
1609
1610
1611/// Creates a frame `Rate` (aka sample rate) representing the rate at which a signal may be
1612/// sampled.
1613///
1614/// This is necessary for composing `Hz` or `ConstHz`, both of which may be used to step forward
1615/// the `Phase` for some kind of oscillator (i.e. `Sine`, `Saw`, `Square` or `NoiseSimplex`).
1616pub fn rate(hz: f64) -> Rate {
1617    Rate { hz: hz }
1618}
1619
1620
1621/// Produces a `Signal` that yields a sine wave oscillating at the given hz.
1622///
1623/// # Example
1624///
1625/// ```rust
1626/// extern crate sample;
1627///
1628/// use sample::{signal, Signal};
1629///
1630/// fn main() {
1631///     // Generates a sine wave signal at 1hz to be sampled 4 times per second.
1632///     let mut signal = signal::rate(4.0).const_hz(1.0).sine();
1633///     assert_eq!(signal.next(), [0.0]);
1634///     assert_eq!(signal.next(), [1.0]);
1635///     signal.next();
1636///     assert_eq!(signal.next(), [-1.0]);
1637/// }
1638/// ```
1639pub fn sine<S>(phase: Phase<S>) -> Sine<S> {
1640    Sine { phase: phase }
1641}
1642
1643/// Produces a `Signal` that yields a saw wave oscillating at the given hz.
1644///
1645/// # Example
1646///
1647/// ```rust
1648/// extern crate sample;
1649///
1650/// use sample::{signal, Signal};
1651///
1652/// fn main() {
1653///     // Generates a saw wave signal at 1hz to be sampled 4 times per second.
1654///     let mut signal = signal::rate(4.0).const_hz(1.0).saw();
1655///     assert_eq!(signal.next(), [1.0]);
1656///     assert_eq!(signal.next(), [0.5]);
1657///     assert_eq!(signal.next(), [0.0]);
1658///     assert_eq!(signal.next(), [-0.5]);
1659/// }
1660/// ```
1661pub fn saw<S>(phase: Phase<S>) -> Saw<S> {
1662    Saw { phase: phase }
1663}
1664
1665/// Produces a `Signal` that yields a square wave oscillating at the given hz.
1666///
1667/// # Example
1668///
1669/// ```rust
1670/// extern crate sample;
1671///
1672/// use sample::{signal, Signal};
1673///
1674/// fn main() {
1675///     // Generates a square wave signal at 1hz to be sampled 4 times per second.
1676///     let mut signal = signal::rate(4.0).const_hz(1.0).square();
1677///     assert_eq!(signal.next(), [1.0]);
1678///     assert_eq!(signal.next(), [1.0]);
1679///     assert_eq!(signal.next(), [-1.0]);
1680///     assert_eq!(signal.next(), [-1.0]);
1681/// }
1682/// ```
1683pub fn square<S>(phase: Phase<S>) -> Square<S> {
1684    Square { phase: phase }
1685}
1686
1687/// Produces a `Signal` that yields random values between -1.0..1.0.
1688///
1689/// # Example
1690///
1691/// ```rust
1692/// extern crate sample;
1693///
1694/// use sample::{signal, Signal};
1695///
1696/// fn main() {
1697///     let mut noise = sample::signal::noise(0);
1698///     for n in noise.take(1_000_000) {
1699///         assert!(-1.0 <= n[0] && n[0] < 1.0);
1700///     }
1701/// }
1702/// ```
1703pub fn noise(seed: u64) -> Noise {
1704    Noise { seed: seed }
1705}
1706
1707/// Produces a 1-dimensional simplex noise `Signal`.
1708///
1709/// This is sometimes known as the "drunken walk" or "noise walk".
1710///
1711/// # Example
1712///
1713/// ```rust
1714/// extern crate sample;
1715///
1716/// use sample::{signal, Signal};
1717///
1718/// fn main() {
1719///     // Creates a simplex noise signal oscillating at 440hz sampled 44_100 times per second.
1720///     let mut signal = signal::rate(44_100.0).const_hz(440.0).noise_simplex();
1721///     for n in signal.take(1_000_000) {
1722///         assert!(-1.0 <= n[0] && n[0] < 1.0);
1723///     }
1724/// }
1725/// ```
1726pub fn noise_simplex<S>(phase: Phase<S>) -> NoiseSimplex<S> {
1727    NoiseSimplex { phase: phase }
1728}
1729
1730
1731//// Trait Implementations for Signal Types.
1732
1733
1734impl<'a, S> Signal for &'a mut S
1735where
1736    S: Signal + ?Sized,
1737{
1738    type Frame = S::Frame;
1739    #[inline]
1740    fn next(&mut self) -> Self::Frame {
1741        (**self).next()
1742    }
1743
1744    #[inline]
1745    fn is_exhausted(&self) -> bool {
1746        (**self).is_exhausted()
1747    }
1748}
1749
1750
1751impl<S> Signal for Box<S>
1752where
1753    S: Signal + ?Sized,
1754{
1755    type Frame = S::Frame;
1756    #[inline]
1757    fn next(&mut self) -> Self::Frame {
1758        (**self).next()
1759    }
1760
1761    #[inline]
1762    fn is_exhausted(&self) -> bool {
1763        (**self).is_exhausted()
1764    }
1765}
1766
1767
1768impl<I> Signal for FromIterator<I>
1769where
1770    I: Iterator,
1771    I::Item: Frame,
1772{
1773    type Frame = I::Item;
1774    #[inline]
1775    fn next(&mut self) -> Self::Frame {
1776        match self.next.take() {
1777            Some(frame) => {
1778                self.next = self.iter.next();
1779                frame
1780            },
1781            None => Frame::equilibrium(),
1782        }
1783    }
1784
1785    #[inline]
1786    fn is_exhausted(&self) -> bool {
1787        self.next.is_none()
1788    }
1789}
1790
1791
1792impl<I, F> Signal for FromInterleavedSamplesIterator<I, F>
1793where
1794    I: Iterator,
1795    I::Item: Sample,
1796    F: Frame<Sample = I::Item>,
1797{
1798    type Frame = F;
1799    #[inline]
1800    fn next(&mut self) -> Self::Frame {
1801        match self.next.take() {
1802            Some(frame) => {
1803                self.next = F::from_samples(&mut self.samples);
1804                frame
1805            },
1806            None => F::equilibrium(),
1807        }
1808    }
1809
1810    #[inline]
1811    fn is_exhausted(&self) -> bool {
1812        self.next.is_none()
1813    }
1814}
1815
1816
1817impl<F> Signal for Equilibrium<F>
1818where
1819    F: Frame,
1820{
1821    type Frame = F;
1822    #[inline]
1823    fn next(&mut self) -> Self::Frame {
1824        F::equilibrium()
1825    }
1826}
1827
1828
1829impl<G, F> Signal for Gen<G, F>
1830where
1831    G: Fn() -> F,
1832    F: Frame,
1833{
1834    type Frame = F;
1835    #[inline]
1836    fn next(&mut self) -> Self::Frame {
1837        (self.gen)()
1838    }
1839}
1840
1841
1842impl<G, F> Signal for GenMut<G, F>
1843where
1844    G: FnMut() -> F,
1845    F: Frame,
1846{
1847    type Frame = F;
1848    #[inline]
1849    fn next(&mut self) -> Self::Frame {
1850        (self.gen_mut)()
1851    }
1852}
1853
1854
1855impl<S, M, F> Signal for Map<S, M, F>
1856where
1857    S: Signal,
1858    M: FnMut(S::Frame) -> F,
1859    F: Frame,
1860{
1861    type Frame = F;
1862    #[inline]
1863    fn next(&mut self) -> Self::Frame {
1864        (self.map)(self.signal.next())
1865    }
1866
1867    fn is_exhausted(&self) -> bool {
1868        self.signal.is_exhausted()
1869    }
1870}
1871
1872
1873impl<S, O, M, F> Signal for ZipMap<S, O, M, F>
1874where
1875    S: Signal,
1876    O: Signal,
1877    M: FnMut(S::Frame, O::Frame) -> F,
1878    F: Frame,
1879{
1880    type Frame = F;
1881    #[inline]
1882    fn next(&mut self) -> Self::Frame {
1883        (self.map)(self.this.next(), self.other.next())
1884    }
1885
1886    fn is_exhausted(&self) -> bool {
1887        self.this.is_exhausted() || self.other.is_exhausted()
1888    }
1889}
1890
1891
1892impl<S> Signal for Hz<S>
1893where
1894    S: Signal<Frame = [f64; 1]>,
1895{
1896    type Frame = [f64; 1];
1897    #[inline]
1898    fn next(&mut self) -> Self::Frame {
1899        [self.step()]
1900    }
1901
1902    #[inline]
1903    fn is_exhausted(&self) -> bool {
1904        self.hz.is_exhausted()
1905    }
1906}
1907
1908
1909impl Signal for ConstHz {
1910    type Frame = [f64; 1];
1911    #[inline]
1912    fn next(&mut self) -> Self::Frame {
1913        [self.step()]
1914    }
1915}
1916
1917
1918impl<S> Signal for Phase<S>
1919where
1920    S: Step,
1921{
1922    type Frame = [f64; 1];
1923    #[inline]
1924    fn next(&mut self) -> Self::Frame {
1925        [self.next_phase()]
1926    }
1927}
1928
1929
1930impl<S> Signal for Sine<S>
1931where
1932    S: Step,
1933{
1934    type Frame = [f64; 1];
1935    #[inline]
1936    fn next(&mut self) -> Self::Frame {
1937        const PI_2: f64 = core::f64::consts::PI * 2.0;
1938        let phase = self.phase.next_phase();
1939        [super::ops::f64::sin(PI_2 * phase)]
1940    }
1941}
1942
1943
1944impl<S> Signal for Saw<S>
1945where
1946    S: Step,
1947{
1948    type Frame = [f64; 1];
1949    #[inline]
1950    fn next(&mut self) -> Self::Frame {
1951        let phase = self.phase.next_phase();
1952        [phase * -2.0 + 1.0]
1953    }
1954}
1955
1956
1957impl<S> Signal for Square<S>
1958where
1959    S: Step,
1960{
1961    type Frame = [f64; 1];
1962    #[inline]
1963    fn next(&mut self) -> Self::Frame {
1964        let phase = self.phase.next_phase();
1965        [if phase < 0.5 { 1.0 } else { -1.0 }]
1966    }
1967}
1968
1969
1970impl Rate {
1971    /// Create a `ConstHz` signal which consistently yields `hz / rate`.
1972    pub fn const_hz(self, hz: f64) -> ConstHz {
1973        ConstHz { step: hz / self.hz }
1974    }
1975
1976    /// Create a `Hz` signal which yields phase step sizes controlled by an input
1977    /// signal `hz`.
1978    /// 
1979    /// # Example
1980    /// 
1981    /// ``` rust
1982    /// extern crate sample;
1983    /// 
1984    /// use sample::{signal, Signal};
1985    /// 
1986    /// fn main() {
1987    ///     let step = signal::rate(4.0).hz(signal::gen(|| [1.0]));
1988    ///     let mut phase = signal::phase(step);
1989    ///     assert_eq!(phase.next(), [0.0]);
1990    ///     assert_eq!(phase.next(), [0.25]);
1991    ///     assert_eq!(phase.next(), [0.5]);
1992    ///     assert_eq!(phase.next(), [0.75]);
1993    ///     assert_eq!(phase.next(), [0.0]);
1994    ///     assert_eq!(phase.next(), [0.25]);
1995    /// }
1996    /// ```
1997    pub fn hz<S>(self, hz: S) -> Hz<S>
1998    where
1999        S: Signal<Frame = [f64; 1]>,
2000    {
2001        Hz {
2002            hz: hz,
2003            rate: self,
2004        }
2005    }
2006}
2007
2008impl<S> Hz<S>
2009where
2010    S: Signal<Frame = [f64; 1]>,
2011{
2012    /// Construct a `Phase` iterator that, for every `hz` yielded by `self`, yields a phase that is
2013    /// stepped by `hz / self.rate.hz`.
2014    #[inline]
2015    pub fn phase(self) -> Phase<Self> {
2016        phase(self)
2017    }
2018
2019    /// A composable alternative to the `signal::sine` function.
2020    #[inline]
2021    pub fn sine(self) -> Sine<Self> {
2022        self.phase().sine()
2023    }
2024
2025    /// A composable alternative to the `signal::saw` function.
2026    #[inline]
2027    pub fn saw(self) -> Saw<Self> {
2028        self.phase().saw()
2029    }
2030
2031    /// A composable alternative to the `signal::square` function.
2032    #[inline]
2033    pub fn square(self) -> Square<Self> {
2034        self.phase().square()
2035    }
2036
2037    /// A composable alternative to the `signal::noise_simplex` function.
2038    #[inline]
2039    pub fn noise_simplex(self) -> NoiseSimplex<Self> {
2040        self.phase().noise_simplex()
2041    }
2042}
2043
2044impl ConstHz {
2045    /// Construct a `Phase` iterator that is incremented via the constant step size, `self.step`.
2046    #[inline]
2047    pub fn phase(self) -> Phase<Self> {
2048        phase(self)
2049    }
2050
2051    /// A composable alternative to the `signal::sine` function.
2052    #[inline]
2053    pub fn sine(self) -> Sine<Self> {
2054        self.phase().sine()
2055    }
2056
2057    /// A composable alternative to the `signal::saw` function.
2058    #[inline]
2059    pub fn saw(self) -> Saw<Self> {
2060        self.phase().saw()
2061    }
2062
2063    /// A composable alternative to the `signal::square` function.
2064    #[inline]
2065    pub fn square(self) -> Square<Self> {
2066        self.phase().square()
2067    }
2068
2069    /// A composable alternative to the `signal::noise_simplex` function.
2070    #[inline]
2071    pub fn noise_simplex(self) -> NoiseSimplex<Self> {
2072        self.phase().noise_simplex()
2073    }
2074}
2075
2076/// Types that may be used to give a phase step size based on some `hz / sample rate`.
2077///
2078/// This allows the `Phase` to be generic over either `ConstHz` and `Hz<I>`.
2079///
2080/// Generally, users need not be concerned with this trait unless writing code that must remain
2081/// generic over phase stepping types like oscillators.
2082pub trait Step {
2083    /// Yield the phase step size (normally `hz / sampling rate`).
2084    ///
2085    /// The `Phase` calls this and uses the returned value to step forward its internal `phase`.
2086    fn step(&mut self) -> f64;
2087}
2088
2089impl Step for ConstHz {
2090    #[inline]
2091    fn step(&mut self) -> f64 {
2092        self.step
2093    }
2094}
2095
2096impl<S> Step for Hz<S>
2097where
2098    S: Signal<Frame = [f64; 1]>,
2099{
2100    #[inline]
2101    fn step(&mut self) -> f64 {
2102        let hz = self.hz.next()[0];
2103        hz / self.rate.hz
2104    }
2105}
2106
2107
2108impl<S> Phase<S>
2109where
2110    S: Step,
2111{
2112    /// Before yielding the current phase, the internal phase is stepped forward and wrapped via
2113    /// the given value.
2114    #[inline]
2115    pub fn next_phase_wrapped_to(&mut self, rem: f64) -> f64 {
2116        let phase = self.next;
2117        self.next = (self.next + self.step.step()) % rem;
2118        phase
2119    }
2120
2121    /// Calls `next_phase_wrapped_to`, with a wrapping value of `1.0`.
2122    #[inline]
2123    pub fn next_phase(&mut self) -> f64 {
2124        self.next_phase_wrapped_to(1.0)
2125    }
2126
2127    /// A composable version of the `signal::sine` function.
2128    #[inline]
2129    pub fn sine(self) -> Sine<S> {
2130        sine(self)
2131    }
2132
2133    /// A composable version of the `signal::saw` function.
2134    #[inline]
2135    pub fn saw(self) -> Saw<S> {
2136        saw(self)
2137    }
2138
2139    /// A composable version of the `signal::square` function.
2140    #[inline]
2141    pub fn square(self) -> Square<S> {
2142        square(self)
2143    }
2144
2145    /// A composable version of the `signal::noise_simplex` function.
2146    #[inline]
2147    pub fn noise_simplex(self) -> NoiseSimplex<S> {
2148        noise_simplex(self)
2149    }
2150}
2151
2152
2153impl Noise {
2154    #[inline]
2155    pub fn next_sample(&mut self) -> f64 {
2156        // A simple one-dimensional noise generator.
2157        //
2158        // Credit for the pseudo code from which this was translated goes to Hugo Elias and his
2159        // excellent primer on perlin noise at
2160        // http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
2161        fn noise_1(seed: u64) -> f64 {
2162            const PRIME_1: u64 = 15_731;
2163            const PRIME_2: u64 = 789_221;
2164            const PRIME_3: u64 = 1_376_312_589;
2165            let x = (seed << 13) ^ seed;
2166            1.0 -
2167                (x.wrapping_mul(x.wrapping_mul(x).wrapping_mul(PRIME_1).wrapping_add(
2168                    PRIME_2,
2169                )).wrapping_add(PRIME_3) & 0x7fffffff) as f64 / 1_073_741_824.0
2170        }
2171
2172        let noise = noise_1(self.seed);
2173        self.seed += 1;
2174        noise
2175    }
2176}
2177
2178impl Signal for Noise {
2179    type Frame = [f64; 1];
2180    #[inline]
2181    fn next(&mut self) -> Self::Frame {
2182        [self.next_sample()]
2183    }
2184}
2185
2186
2187impl<S> NoiseSimplex<S>
2188where
2189    S: Step,
2190{
2191    #[inline]
2192    pub fn next_sample(&mut self) -> f64 {
2193        // The constant remainder used to wrap the phase back to 0.0.
2194        //
2195        // This is the first power of two that is over double the human hearing range. This should
2196        // allow for simplex noise to be generated at a frequency matching the extent of the human
2197        // hearing range while never repeating more than once per second; the repetition would
2198        // likely be indistinguishable at such a high frequency, and in this should be practical
2199        // for audio simplex noise.
2200        const TWO_POW_SIXTEEN: f64 = 65_536.0;
2201        let phase = self.phase.next_phase_wrapped_to(TWO_POW_SIXTEEN);
2202
2203        // 1D Perlin simplex noise.
2204        //
2205        // Takes a floating point x coordinate and yields a noise value in the range of -1..1, with
2206        // value of 0.0 on all integer coordinates.
2207        //
2208        // This function and the enclosing functions have been adapted from SRombauts' MIT licensed
2209        // C++ implementation at the following link: https://github.com/SRombauts/SimplexNoise
2210        fn simplex_noise_1d(x: f64) -> f64 {
2211
2212            // Permutation table. This is a random jumble of all numbers 0...255.
2213            const PERM: [u8; 256] = [
2214                151,
2215                160,
2216                137,
2217                91,
2218                90,
2219                15,
2220                131,
2221                13,
2222                201,
2223                95,
2224                96,
2225                53,
2226                194,
2227                233,
2228                7,
2229                225,
2230                140,
2231                36,
2232                103,
2233                30,
2234                69,
2235                142,
2236                8,
2237                99,
2238                37,
2239                240,
2240                21,
2241                10,
2242                23,
2243                190,
2244                6,
2245                148,
2246                247,
2247                120,
2248                234,
2249                75,
2250                0,
2251                26,
2252                197,
2253                62,
2254                94,
2255                252,
2256                219,
2257                203,
2258                117,
2259                35,
2260                11,
2261                32,
2262                57,
2263                177,
2264                33,
2265                88,
2266                237,
2267                149,
2268                56,
2269                87,
2270                174,
2271                20,
2272                125,
2273                136,
2274                171,
2275                168,
2276                68,
2277                175,
2278                74,
2279                165,
2280                71,
2281                134,
2282                139,
2283                48,
2284                27,
2285                166,
2286                77,
2287                146,
2288                158,
2289                231,
2290                83,
2291                111,
2292                229,
2293                122,
2294                60,
2295                211,
2296                133,
2297                230,
2298                220,
2299                105,
2300                92,
2301                41,
2302                55,
2303                46,
2304                245,
2305                40,
2306                244,
2307                102,
2308                143,
2309                54,
2310                65,
2311                25,
2312                63,
2313                161,
2314                1,
2315                216,
2316                80,
2317                73,
2318                209,
2319                76,
2320                132,
2321                187,
2322                208,
2323                89,
2324                18,
2325                169,
2326                200,
2327                196,
2328                135,
2329                130,
2330                116,
2331                188,
2332                159,
2333                86,
2334                164,
2335                100,
2336                109,
2337                198,
2338                173,
2339                186,
2340                3,
2341                64,
2342                52,
2343                217,
2344                226,
2345                250,
2346                124,
2347                123,
2348                5,
2349                202,
2350                38,
2351                147,
2352                118,
2353                126,
2354                255,
2355                82,
2356                85,
2357                212,
2358                207,
2359                206,
2360                59,
2361                227,
2362                47,
2363                16,
2364                58,
2365                17,
2366                182,
2367                189,
2368                28,
2369                42,
2370                223,
2371                183,
2372                170,
2373                213,
2374                119,
2375                248,
2376                152,
2377                2,
2378                44,
2379                154,
2380                163,
2381                70,
2382                221,
2383                153,
2384                101,
2385                155,
2386                167,
2387                43,
2388                172,
2389                9,
2390                129,
2391                22,
2392                39,
2393                253,
2394                19,
2395                98,
2396                108,
2397                110,
2398                79,
2399                113,
2400                224,
2401                232,
2402                178,
2403                185,
2404                112,
2405                104,
2406                218,
2407                246,
2408                97,
2409                228,
2410                251,
2411                34,
2412                242,
2413                193,
2414                238,
2415                210,
2416                144,
2417                12,
2418                191,
2419                179,
2420                162,
2421                241,
2422                81,
2423                51,
2424                145,
2425                235,
2426                249,
2427                14,
2428                239,
2429                107,
2430                49,
2431                192,
2432                214,
2433                31,
2434                181,
2435                199,
2436                106,
2437                157,
2438                184,
2439                84,
2440                204,
2441                176,
2442                115,
2443                121,
2444                50,
2445                45,
2446                127,
2447                4,
2448                150,
2449                254,
2450                138,
2451                236,
2452                205,
2453                93,
2454                222,
2455                114,
2456                67,
2457                29,
2458                24,
2459                72,
2460                243,
2461                141,
2462                128,
2463                195,
2464                78,
2465                66,
2466                215,
2467                61,
2468                156,
2469                180,
2470            ];
2471
2472            // Hashes the given integer with the above permutation table.
2473            fn hash(i: i64) -> u8 {
2474                PERM[(i as u8) as usize]
2475            }
2476
2477            // Computes the gradients-dot-residual vectors (1D).
2478            fn grad(hash: i64, x: f64) -> f64 {
2479                // Convert low 4 bits of hash code.
2480                let h = hash & 0x0F;
2481                // Gradien value 1.0, 2.0, ..., 8.0.
2482                let mut grad = 1.0 + (h & 7) as f64;
2483                // Set a random sign for the gradient.
2484                if (h & 8) != 0 {
2485                    grad = -grad;
2486                }
2487                // Multiply the gradient with the distance.
2488                grad * x
2489            }
2490
2491            // Corners coordinates (nearest integer values).
2492            let i0 = super::ops::f64::floor(x) as i64;
2493            let i1 = i0 + 1;
2494
2495            // Distances to corners (between 0 and 1);
2496            let x0 = x - i0 as f64;
2497            let x1 = x0 - 1.0;
2498
2499            // Calculate the contribution from the first corner.
2500            let mut t0 = 1.0 - x0 * x0;
2501            t0 *= t0;
2502            let n0 = t0 * t0 * grad(hash(i0) as i64, x0);
2503
2504            // Calculate the contribution rom the second corner.
2505            let mut t1 = 1.0 - x1 * x1;
2506            t1 *= t1;
2507            let n1 = t1 * t1 * grad(hash(i1) as i64, x1);
2508
2509            // The max value of this noise is 2.53125. 0.395 scales to fit exactly within -1..1.
2510            0.395 * (n0 + n1)
2511        }
2512
2513        simplex_noise_1d(phase)
2514    }
2515}
2516
2517impl<S> Signal for NoiseSimplex<S>
2518where
2519    S: Step,
2520{
2521    type Frame = [f64; 1];
2522    #[inline]
2523    fn next(&mut self) -> Self::Frame {
2524        [self.next_sample()]
2525    }
2526}
2527
2528
2529impl<A, B> Signal for AddAmp<A, B>
2530where
2531    A: Signal,
2532    B: Signal,
2533    B::Frame: Frame<Sample=<<A::Frame as Frame>::Sample as Sample>::Signed,
2534                    NumChannels=<A::Frame as Frame>::NumChannels>,
2535{
2536    type Frame = A::Frame;
2537    #[inline]
2538    fn next(&mut self) -> Self::Frame {
2539        self.a.next().add_amp(self.b.next())
2540    }
2541
2542    #[inline]
2543    fn is_exhausted(&self) -> bool {
2544        self.a.is_exhausted() || self.b.is_exhausted()
2545    }
2546}
2547
2548
2549impl<A, B> Signal for MulAmp<A, B>
2550where
2551    A: Signal,
2552    B: Signal,
2553    B::Frame: Frame<Sample=<<A::Frame as Frame>::Sample as Sample>::Float,
2554                    NumChannels=<A::Frame as Frame>::NumChannels>,
2555{
2556    type Frame = A::Frame;
2557    #[inline]
2558    fn next(&mut self) -> Self::Frame {
2559        self.a.next().mul_amp(self.b.next())
2560    }
2561
2562    #[inline]
2563    fn is_exhausted(&self) -> bool {
2564        self.a.is_exhausted() || self.b.is_exhausted()
2565    }
2566}
2567
2568
2569impl<S> Signal for ScaleAmp<S>
2570where
2571    S: Signal,
2572{
2573    type Frame = S::Frame;
2574    #[inline]
2575    fn next(&mut self) -> Self::Frame {
2576        self.signal.next().scale_amp(self.amp)
2577    }
2578
2579    #[inline]
2580    fn is_exhausted(&self) -> bool {
2581        self.signal.is_exhausted()
2582    }
2583}
2584
2585
2586impl<S, F> Signal for ScaleAmpPerChannel<S, F>
2587where
2588    S: Signal,
2589    F: Frame<Sample=<<S::Frame as Frame>::Sample as Sample>::Float,
2590             NumChannels=<S::Frame as Frame>::NumChannels>,
2591{
2592    type Frame = S::Frame;
2593    #[inline]
2594    fn next(&mut self) -> Self::Frame {
2595        self.signal.next().mul_amp(self.amp_frame)
2596    }
2597
2598    #[inline]
2599    fn is_exhausted(&self) -> bool {
2600        self.signal.is_exhausted()
2601    }
2602}
2603
2604
2605impl<S> Signal for OffsetAmp<S>
2606where
2607    S: Signal,
2608{
2609    type Frame = S::Frame;
2610    #[inline]
2611    fn next(&mut self) -> Self::Frame {
2612        self.signal.next().offset_amp(self.offset)
2613    }
2614
2615    #[inline]
2616    fn is_exhausted(&self) -> bool {
2617        self.signal.is_exhausted()
2618    }
2619}
2620
2621
2622impl<S, F> Signal for OffsetAmpPerChannel<S, F>
2623where
2624    S: Signal,
2625    F: Frame<Sample=<<S::Frame as Frame>::Sample as Sample>::Signed,
2626             NumChannels=<S::Frame as Frame>::NumChannels>,
2627{
2628    type Frame = S::Frame;
2629    #[inline]
2630    fn next(&mut self) -> Self::Frame {
2631        self.signal.next().add_amp(self.amp_frame)
2632    }
2633
2634    #[inline]
2635    fn is_exhausted(&self) -> bool {
2636        self.signal.is_exhausted()
2637    }
2638}
2639
2640
2641impl<S, M, I> Signal for MulHz<S, M, I>
2642where
2643    S: Signal,
2644    <S::Frame as Frame>::Sample: Duplex<f64>,
2645    M: Signal<Frame = [f64; 1]>,
2646    I: Interpolator<Frame = S::Frame>,
2647{
2648    type Frame = S::Frame;
2649    #[inline]
2650    fn next(&mut self) -> Self::Frame {
2651        let mul = self.mul_per_frame.next()[0];
2652        self.signal.set_playback_hz_scale(mul);
2653        self.signal.next()
2654    }
2655
2656    #[inline]
2657    fn is_exhausted(&self) -> bool {
2658        self.signal.is_exhausted() || self.mul_per_frame.is_exhausted()
2659    }
2660}
2661
2662
2663impl<S> Signal for Delay<S>
2664where
2665    S: Signal,
2666{
2667    type Frame = S::Frame;
2668    #[inline]
2669    fn next(&mut self) -> Self::Frame {
2670        if self.n_frames > 0 {
2671            self.n_frames -= 1;
2672            Self::Frame::equilibrium()
2673        } else {
2674            self.signal.next()
2675        }
2676    }
2677
2678    #[inline]
2679    fn is_exhausted(&self) -> bool {
2680        self.n_frames == 0 && self.signal.is_exhausted()
2681    }
2682}
2683
2684
2685impl<S, F> Signal for Inspect<S, F>
2686where
2687    S: Signal,
2688    F: FnMut(&S::Frame),
2689{
2690    type Frame = S::Frame;
2691    #[inline]
2692    fn next(&mut self) -> Self::Frame {
2693        let out = self.signal.next();
2694        (self.inspect)(&out);
2695        out
2696    }
2697
2698    #[inline]
2699    fn is_exhausted(&self) -> bool {
2700        self.signal.is_exhausted()
2701    }
2702}
2703
2704
2705impl<S> IntoInterleavedSamples<S>
2706where
2707    S: Signal,
2708{
2709    /// Yield the next interleaved sample from the inner `Signal`.
2710    #[inline]
2711    pub fn next_sample(&mut self) -> <S::Frame as Frame>::Sample {
2712        loop {
2713            match self.current_frame.next() {
2714                Some(channel) => return channel,
2715                None => self.current_frame = self.signal.next().channels(),
2716            }
2717        }
2718    }
2719
2720    /// Convert the `ToInterleavedSamples` into an `Iterator`.
2721    #[inline]
2722    pub fn into_iter(self) -> IntoInterleavedSamplesIterator<S> {
2723        IntoInterleavedSamplesIterator { samples: self }
2724    }
2725}
2726
2727impl<S> Iterator for IntoInterleavedSamplesIterator<S>
2728where
2729    S: Signal,
2730{
2731    type Item = <S::Frame as Frame>::Sample;
2732    #[inline]
2733    fn next(&mut self) -> Option<Self::Item> {
2734        Some(self.samples.next_sample())
2735    }
2736}
2737
2738impl<S> Iterator for UntilExhausted<S>
2739where
2740    S: Signal,
2741{
2742    type Item = S::Frame;
2743    #[inline]
2744    fn next(&mut self) -> Option<Self::Item> {
2745        if self.signal.is_exhausted() {
2746            return None;
2747        }
2748        Some(self.signal.next())
2749    }
2750}
2751
2752impl<S> Clone for IntoInterleavedSamples<S>
2753where
2754    S: Signal + Clone,
2755    <S::Frame as Frame>::Channels: Clone,
2756{
2757    #[inline]
2758    fn clone(&self) -> Self {
2759        IntoInterleavedSamples {
2760            signal: self.signal.clone(),
2761            current_frame: self.current_frame.clone(),
2762        }
2763    }
2764}
2765
2766impl<S> Clone for IntoInterleavedSamplesIterator<S>
2767where
2768    S: Signal,
2769    IntoInterleavedSamples<S>: Clone,
2770{
2771    #[inline]
2772    fn clone(&self) -> Self {
2773        IntoInterleavedSamplesIterator { samples: self.samples.clone() }
2774    }
2775}
2776
2777
2778impl<S> Signal for ClipAmp<S>
2779where
2780    S: Signal,
2781{
2782    type Frame = S::Frame;
2783    #[inline]
2784    fn next(&mut self) -> Self::Frame {
2785        let f = self.signal.next();
2786        f.map(|s| {
2787            let s: <<S::Frame as Frame>::Sample as Sample>::Signed = s.to_sample();
2788            if s > self.thresh {
2789                self.thresh
2790            } else if s < -self.thresh {
2791                -self.thresh
2792            } else {
2793                s
2794            }.to_sample()
2795        })
2796    }
2797
2798    #[inline]
2799    fn is_exhausted(&self) -> bool {
2800        self.signal.is_exhausted()
2801    }
2802}
2803
2804
2805impl<S> Bus<S>
2806where
2807    S: Signal,
2808{
2809    fn new(signal: S, frames_read: BTreeMap<usize, usize>) -> Self {
2810        Bus {
2811            node: Rc::new(core::cell::RefCell::new(SharedNode {
2812                signal: signal,
2813                buffer: VecDeque::new(),
2814                frames_read: frames_read,
2815                next_key: 0,
2816            })),
2817        }
2818    }
2819
2820    /// Produce a new Output node to which the signal `S` will output its frames.
2821    #[inline]
2822    pub fn send(&self) -> Output<S> {
2823        let mut node = self.node.borrow_mut();
2824
2825        // Get the key and increment for the next output.
2826        let key = node.next_key;
2827        node.next_key = node.next_key.wrapping_add(1);
2828
2829        // Insert the number of frames read by the new output.
2830        let num_frames = node.buffer.len();
2831        node.frames_read.insert(key, num_frames);
2832
2833        Output {
2834            key: key,
2835            node: self.node.clone(),
2836        }
2837    }
2838}
2839
2840impl<S> SharedNode<S>
2841where
2842    S: Signal,
2843{
2844    // Requests the next frame for the `Output` at the given key.
2845    //
2846    // If there are no frames pending for the output, a new frame will be requested from the
2847    // signal and appended to the ring buffer to be received by the other outputs.
2848    fn next_frame(&mut self, key: usize) -> S::Frame {
2849        let num_frames = self.buffer.len();
2850        let frames_read = self.frames_read.remove(&key).expect(
2851            "no frames_read for Output",
2852        );
2853
2854        let frame = if frames_read < num_frames {
2855            self.buffer[frames_read]
2856        } else {
2857            let frame = self.signal.next();
2858            self.buffer.push_back(frame);
2859            frame
2860        };
2861
2862        // If the number of frames read by this output is the lowest, then we can pop the frame
2863        // from the front.
2864        let least_frames_read = !self.frames_read.values().any(|&other_frames_read| {
2865            other_frames_read <= frames_read
2866        });
2867
2868        // If this output had read the least number of frames, pop the front frame and decrement
2869        // the frames read counters for each of the other outputs.
2870        let new_frames_read = if least_frames_read {
2871            self.buffer.pop_front();
2872            for other_frames_read in self.frames_read.values_mut() {
2873                *other_frames_read -= 1;
2874            }
2875            frames_read
2876        } else {
2877            frames_read + 1
2878        };
2879
2880        self.frames_read.insert(key, new_frames_read);
2881
2882        frame
2883    }
2884
2885    #[inline]
2886    fn pending_frames(&self, key: usize) -> usize {
2887        self.buffer.len() - self.frames_read[&key]
2888    }
2889
2890    // Drop the given output from the `Bus`.
2891    //
2892    // Called by the `Output::drop` implementation.
2893    fn drop_output(&mut self, key: usize) {
2894        self.frames_read.remove(&key);
2895        let least_frames_read = self.frames_read.values().fold(self.buffer.len(), |a, &b| {
2896            core::cmp::min(a, b)
2897        });
2898        if least_frames_read > 0 {
2899            for frames_read in self.frames_read.values_mut() {
2900                *frames_read -= least_frames_read;
2901            }
2902            for _ in 0..least_frames_read {
2903                self.buffer.pop_front();
2904            }
2905        }
2906    }
2907}
2908
2909impl<S> Output<S>
2910where
2911    S: Signal,
2912{
2913    /// The number of frames that have been requested from the `Signal` `S` by some other `Output`
2914    /// that have not yet been requested by this `Output`.
2915    ///
2916    /// This is useful when using an `Output` to "monitor" some signal, allowing the user to drain
2917    /// only frames that have already been requested by some other `Output`.
2918    ///
2919    /// # Example
2920    ///
2921    /// ```
2922    /// extern crate sample;
2923    ///
2924    /// use sample::{signal, Signal};
2925    ///
2926    /// fn main() {
2927    ///     let frames = [[0.1], [0.2], [0.3]];
2928    ///     let bus = signal::from_iter(frames.iter().cloned()).bus();
2929    ///     let signal = bus.send();
2930    ///     let mut monitor = bus.send();
2931    ///     assert_eq!(signal.take(3).collect::<Vec<_>>(), vec![[0.1], [0.2], [0.3]]);
2932    ///     assert_eq!(monitor.pending_frames(), 3);
2933    ///     assert_eq!(monitor.next(), [0.1]);
2934    ///     assert_eq!(monitor.pending_frames(), 2);
2935    /// }
2936    /// ```
2937    #[inline]
2938    pub fn pending_frames(&self) -> usize {
2939        self.node.borrow().pending_frames(self.key)
2940    }
2941}
2942
2943impl<S> Signal for Output<S>
2944where
2945    S: Signal,
2946{
2947    type Frame = S::Frame;
2948    #[inline]
2949    fn next(&mut self) -> Self::Frame {
2950        self.node.borrow_mut().next_frame(self.key)
2951    }
2952
2953    #[inline]
2954    fn is_exhausted(&self) -> bool {
2955        let node = self.node.borrow();
2956        node.pending_frames(self.key) == 0 && node.signal.is_exhausted()
2957    }
2958}
2959
2960impl<S> Drop for Output<S>
2961where
2962    S: Signal,
2963{
2964    fn drop(&mut self) {
2965        self.node.borrow_mut().drop_output(self.key)
2966    }
2967}
2968
2969
2970impl<S> Iterator for Take<S>
2971where
2972    S: Signal,
2973{
2974    type Item = S::Frame;
2975    #[inline]
2976    fn next(&mut self) -> Option<Self::Item> {
2977        if self.n == 0 {
2978            return None;
2979        }
2980        self.n -= 1;
2981        Some(self.signal.next())
2982    }
2983    fn size_hint(&self) -> (usize, Option<usize>) {
2984        (self.n, Some(self.n))
2985    }
2986}
2987
2988impl<S> ExactSizeIterator for Take<S>
2989where
2990    S: Signal,
2991{
2992    #[inline]
2993    fn len(&self) -> usize {
2994        self.n
2995    }
2996}
2997
2998impl<S, D> Buffered<S, D>
2999where
3000    S: Signal,
3001    D: ring_buffer::Slice<Element = S::Frame> + ring_buffer::SliceMut,
3002{
3003    /// Produces an iterator yielding the next batch of buffered frames.
3004    ///
3005    /// The returned iterator returns `None` once the inner ring buffer becomes exhausted.
3006    ///
3007    /// If the inner ring buffer is empty when this method is called, the ring buffer will first be
3008    /// filled using `Buffered`'s inner `signal` before `BufferedFrames` is returned.
3009    ///
3010    /// ```
3011    /// extern crate sample;
3012    ///
3013    /// use sample::signal::{self, Signal};
3014    /// use sample::ring_buffer;
3015    ///
3016    /// fn main() {
3017    ///     let frames = [[0.1], [0.2], [0.3], [0.4]];
3018    ///     let signal = signal::from_iter(frames.iter().cloned());
3019    ///     let ring_buffer = ring_buffer::Bounded::<[[f32; 1]; 2]>::array();
3020    ///     let mut buffered_signal = signal.buffered(ring_buffer);
3021    ///     assert_eq!(buffered_signal.next_frames().collect::<Vec<_>>(), vec![[0.1], [0.2]]);
3022    ///     assert_eq!(buffered_signal.next_frames().collect::<Vec<_>>(), vec![[0.3], [0.4]]);
3023    ///     assert_eq!(buffered_signal.next_frames().collect::<Vec<_>>(), vec![[0.0], [0.0]]);
3024    /// }
3025    /// ```
3026    pub fn next_frames(&mut self) -> BufferedFrames<D> {
3027        let Buffered {
3028            ref mut signal,
3029            ref mut ring_buffer,
3030        } = *self;
3031        if ring_buffer.len() == 0 {
3032            for _ in 0..ring_buffer.max_len() {
3033                ring_buffer.push(signal.next());
3034            }
3035        }
3036        BufferedFrames { ring_buffer: ring_buffer }
3037    }
3038
3039    /// Consumes the `Buffered` signal and returns its inner signal `S` and bounded ring buffer.
3040    pub fn into_parts(self) -> (S, ring_buffer::Bounded<D>) {
3041        let Buffered {
3042            signal,
3043            ring_buffer,
3044        } = self;
3045        (signal, ring_buffer)
3046    }
3047}
3048
3049impl<S, D> Signal for Buffered<S, D>
3050where
3051    S: Signal,
3052    D: ring_buffer::Slice<Element=S::Frame> + ring_buffer::SliceMut,
3053{
3054    type Frame = S::Frame;
3055    fn next(&mut self) -> Self::Frame {
3056        let Buffered { ref mut signal, ref mut ring_buffer } = *self;
3057        loop {
3058            match ring_buffer.pop() {
3059                Some(frame) => return frame,
3060                None => for _ in 0..ring_buffer.max_len() {
3061                    ring_buffer.push(signal.next());
3062                },
3063            }
3064        }
3065    }
3066
3067    fn is_exhausted(&self) -> bool {
3068        self.ring_buffer.len() == 0 && self.signal.is_exhausted()
3069    }
3070}
3071
3072impl<'a, D> Iterator for BufferedFrames<'a, D>
3073where
3074    D: ring_buffer::SliceMut,
3075    D::Element: Copy,
3076{
3077    type Item = D::Element;
3078    fn next(&mut self) -> Option<Self::Item> {
3079        self.ring_buffer.pop()
3080    }
3081}
3082
3083impl<S, D> Rms<S, D>
3084where
3085    S: Signal,
3086    D: ring_buffer::Slice<Element = <S::Frame as Frame>::Float> + ring_buffer::SliceMut,
3087{
3088/// The same as `Signal::next` but does not calculate the final square root required to
3089/// determine the RMS.
3090    pub fn next_squared(&mut self) -> <Self as Signal>::Frame {
3091        self.rms.next_squared(self.signal.next())
3092    }
3093
3094/// Consumes the `Rms` signal and returns its inner signal `S` and `Rms` detector.
3095    pub fn into_parts(self) -> (S, rms::Rms<S::Frame, D>) {
3096        let Rms {
3097            signal,
3098            rms,
3099        } = self;
3100        (signal, rms)
3101    }
3102}
3103
3104impl<S, D> Signal for Rms<S, D>
3105where
3106    S: Signal,
3107    D: ring_buffer::Slice<Element = <S::Frame as Frame>::Float>
3108        + ring_buffer::SliceMut,
3109{
3110    type Frame = <S::Frame as Frame>::Float;
3111    fn next(&mut self) -> Self::Frame {
3112        self.rms.next(self.signal.next())
3113    }
3114
3115    fn is_exhausted(&self) -> bool {
3116        self.signal.is_exhausted()
3117    }
3118}
3119
3120impl<S, D> DetectEnvelope<S, D>
3121where
3122    S: Signal,
3123    D: envelope::Detect<S::Frame>,
3124{
3125    /// Set the **Detector**'s attack time as a number of frames.
3126    pub fn set_attack_frames(&mut self, frames: f32) {
3127        self.detector.set_attack_frames(frames);
3128    }
3129
3130    /// Set the **Detector**'s release time as a number of frames.
3131    pub fn set_release_frames(&mut self, frames: f32) {
3132        self.detector.set_release_frames(frames);
3133    }
3134
3135    /// Consumes `Self` and returns the inner signal `S` and `Detector`.
3136    pub fn into_parts(self) -> (S, envelope::Detector<S::Frame, D>) {
3137        let DetectEnvelope { signal, detector } = self;
3138        (signal, detector)
3139    }
3140}
3141
3142impl<S, D> Signal for DetectEnvelope<S, D>
3143where
3144    S: Signal,
3145    D: envelope::Detect<S::Frame>,
3146{
3147    type Frame = D::Output;
3148    fn next(&mut self) -> Self::Frame {
3149        self.detector.next(self.signal.next())
3150    }
3151
3152    fn is_exhausted(&self) -> bool {
3153        self.signal.is_exhausted()
3154    }
3155}