geng_rodio/source/
pausable.rs

1use std::time::Duration;
2
3use crate::{Sample, Source};
4
5/// Internal function that builds a `Pausable` object.
6pub fn pausable<I>(source: I, paused: bool) -> Pausable<I>
7where
8    I: Source,
9    I::Item: Sample,
10{
11    let paused_channels = if paused {
12        Some(source.channels())
13    } else {
14        None
15    };
16    Pausable {
17        input: source,
18        paused_channels,
19        remaining_paused_samples: 0,
20    }
21}
22
23#[derive(Clone, Debug)]
24pub struct Pausable<I> {
25    input: I,
26    paused_channels: Option<u16>,
27    remaining_paused_samples: u16,
28}
29
30impl<I> Pausable<I>
31where
32    I: Source,
33    I::Item: Sample,
34{
35    /// Sets whether the filter applies.
36    ///
37    /// If set to true, the inner sound stops playing and no samples are processed from it.
38    #[inline]
39    pub fn set_paused(&mut self, paused: bool) {
40        match (self.paused_channels, paused) {
41            (None, true) => self.paused_channels = Some(self.input.channels()),
42            (Some(_), false) => self.paused_channels = None,
43            _ => (),
44        }
45    }
46
47    /// Returns a reference to the inner source.
48    #[inline]
49    pub fn inner(&self) -> &I {
50        &self.input
51    }
52
53    /// Returns a mutable reference to the inner source.
54    #[inline]
55    pub fn inner_mut(&mut self) -> &mut I {
56        &mut self.input
57    }
58
59    /// Returns the inner source.
60    #[inline]
61    pub fn into_inner(self) -> I {
62        self.input
63    }
64}
65
66impl<I> Iterator for Pausable<I>
67where
68    I: Source,
69    I::Item: Sample,
70{
71    type Item = I::Item;
72
73    #[inline]
74    fn next(&mut self) -> Option<I::Item> {
75        if self.remaining_paused_samples > 0 {
76            self.remaining_paused_samples -= 1;
77            return Some(I::Item::zero_value());
78        }
79
80        if let Some(paused_channels) = self.paused_channels {
81            self.remaining_paused_samples = paused_channels - 1;
82            return Some(I::Item::zero_value());
83        }
84
85        self.input.next()
86    }
87
88    #[inline]
89    fn size_hint(&self) -> (usize, Option<usize>) {
90        self.input.size_hint()
91    }
92}
93
94impl<I> Source for Pausable<I>
95where
96    I: Source,
97    I::Item: Sample,
98{
99    #[inline]
100    fn current_frame_len(&self) -> Option<usize> {
101        self.input.current_frame_len()
102    }
103
104    #[inline]
105    fn channels(&self) -> u16 {
106        self.input.channels()
107    }
108
109    #[inline]
110    fn sample_rate(&self) -> u32 {
111        self.input.sample_rate()
112    }
113
114    #[inline]
115    fn total_duration(&self) -> Option<Duration> {
116        self.input.total_duration()
117    }
118}