1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use Sample;
use Source;

/// Filter that allows another thread to pause the stream.
#[derive(Clone, Debug)]
pub struct Stoppable<I>
    where I: Source,
          I::Item: Sample
{
    input: I,

    // The paused value which may be manipulated by another thread.
    remote_stopped: Arc<AtomicBool>,

    // The frequency with which remote_stopped is checked.
    update_frequency: u32,

    // How many samples remain until it is time to check remote_stopped.
    samples_until_update: u32,
}

impl<I> Stoppable<I>
    where I: Source,
          I::Item: Sample
{
    pub fn new(source: I, remote_stopped: Arc<AtomicBool>, update_ms: u32) -> Stoppable<I> {
        // TODO: handle the fact that the samples rate can change
        let update_frequency = (update_ms * source.get_samples_rate()) / 1000;
        Stoppable {
            input: source,
            remote_stopped: remote_stopped,
            update_frequency: update_frequency,
            samples_until_update: update_frequency,
        }
    }
}

impl<I> Iterator for Stoppable<I>
    where I: Source,
          I::Item: Sample
{
    type Item = I::Item;

    #[inline]
    fn next(&mut self) -> Option<I::Item> {
        if self.samples_until_update == 0 {
            if self.remote_stopped.load(Ordering::Relaxed) {
                return None;
            } else {
                self.samples_until_update = self.update_frequency;
            }
        } else {
            self.samples_until_update -= 1;
        }

        self.input.next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.input.size_hint()
    }
}

impl<I> Source for Stoppable<I>
    where I: Source,
          I::Item: Sample
{
    #[inline]
    fn get_current_frame_len(&self) -> Option<usize> {
        self.input.get_current_frame_len()
    }

    #[inline]
    fn get_channels(&self) -> u16 {
        self.input.get_channels()
    }

    #[inline]
    fn get_samples_rate(&self) -> u32 {
        self.input.get_samples_rate()
    }

    #[inline]
    fn get_total_duration(&self) -> Option<Duration> {
        self.input.get_total_duration()
    }
}