1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use std::{
    sync::Mutex,
    sync::Arc,
};
use cpal::traits::*;
use crossbeam::channel;
pub mod decoders;
pub mod traits;
pub use traits::Source;
pub use decoders::{Decoder, FlacDecoder, Mp3Decoder, VorbisDecoder};

#[derive(Debug, Clone, Copy)]
enum SampleFormat {
    I16(i16),
    U16(u16),
    F32(f32),
    None,
}

/// Type abstraction to get a sample as one type, save it and get it as any other
/// possible sample type.
#[derive(Debug, Clone, Copy)]
pub struct Sample(SampleFormat);
impl From<i16> for Sample {
    fn from (val: i16) -> Self {
        Sample(SampleFormat::I16(val))
    }
}
impl From<u16> for Sample {
    fn from (val: u16) -> Self {
        Sample(SampleFormat::U16(val))
    }
}
impl From<f32> for Sample {
    fn from (val: f32) -> Self {
        Sample(SampleFormat::F32(val))
    }
}
impl From<i32> for Sample {
    fn from (val: i32) -> Self {
        Sample(SampleFormat::F32((val as f32 / std::i32::MAX as f32) * 200.0))
    }
}
impl Sample {
    /// Convert the inner sample to an i16.
    fn get_i16(&self) -> Result<i16, ()> {
        match self.0 {
            SampleFormat::I16(v) => Ok(v),
            SampleFormat::U16(v) => Ok((v as i32 - std::i16::MAX as i32) as i16),
            SampleFormat::F32(v) => Ok((v * std::i16::MAX as f32) as i16),
            SampleFormat::None => Err(())
        }
    }
    /// Convert the inner sample to an u16.
    fn get_u16(&self) -> Result<u16, ()> {
        match self.0 {
            SampleFormat::I16(v) => Ok((v as i32 + 32768) as u16),
            SampleFormat::U16(v) => Ok(v),
            SampleFormat::F32(v) => Ok((v * std::u16::MAX as f32) as u16),
            SampleFormat::None => Err(()),
        }
    }
    /// Convert the inner sample to an f32.
    fn get_f32(&self) -> Result<f32, ()> {
        match self.0 {
            SampleFormat::I16(v) => Ok(v as f32 / std::i16::MAX as f32),
            SampleFormat::U16(v) => Ok(v as f32 / std::u16::MAX as f32),
            SampleFormat::F32(v) => Ok(v),
            SampleFormat::None => Err(()),
        }
    }
    fn end () -> Self {
        Sample(SampleFormat::None)
    }
}

/// Plays back samples from a type that implements Source.
///
/// # Example
/// ```
/// use rmus::{Source, VorbisDecoder, Sink};
/// fn main () {
///     let sink = Sink::new(VorbisDecoder::new("example.ogg").unwrap());
/// }
/// ```
pub struct Sink {
    total_length: u32,
    control: Mutex<channel::Sender<(u8, f32)>>,
    end: Mutex<channel::Receiver<bool>>,
    back_recv: Mutex<channel::Receiver<u8>>,
    //thread_channels: (Box<channel::Receiver<(u8, f32)>>, Box<channel::Sender<bool>>, Box<channel::Sender<u8>>),
}

impl Sink {
    /// This creates a new "Sink" and starts playing back the samples its source creates
    pub fn new<T: 'static + Source + Send + Sync> (mut source: T) -> Arc<Self> {
        let (end_send, end_recv) = channel::unbounded();
        let (back_send, back_recv) = channel::unbounded();
        let (control_send, control_recv) = channel::unbounded();
        let sound = Self {
            total_length: source.total_length(),
            control: Mutex::new(control_send),
            end: Mutex::new(end_recv),
            back_recv: Mutex::new(back_recv),
            //thread_channels: (Box::new(control_recv), Box::new(end_send), Box::new(back_send)),
        };
        std::thread::spawn(move || {
        let host = cpal::default_host();
        let device = host.default_output_device().unwrap();
        let format = cpal::Format {
            channels: source.channels() as u16,
            sample_rate: cpal::SampleRate(source.sample_rate()),
            data_type: device.default_output_format().unwrap().data_type,
        };
        let event_loop = Arc::new(host.event_loop());
        event_loop.build_output_stream(&device, &format).unwrap();
        let mut vol = 100;
        let mut paused = true;
        let mut position_samples: u32 = 0;
        let mut position_secs: u32 = 0;
        event_loop.run(move |stream_id, stream_result| {
            match control_recv.try_recv() {
                Ok(v) => match v {
                    (0, _) => {
                        if paused {
                            paused = false;
                        } else {
                            paused = true;
                        }
                    }
                    (1, v) => {
                        let sample_rate = source.sample_rate();
                        let cur_pos: i64 = (position_samples + (sample_rate * position_secs)).into();
                        let new_pos = cur_pos + (sample_rate as f32 * v) as i64;
                        dbg!(cur_pos, new_pos);
                        if new_pos <= 0 {
                            source.goto(0);
                            position_samples = 0;
                            position_secs = 0;
                        } else {
                            source.goto(new_pos as u64);
                            position_secs += (v / sample_rate as f32) as u32;
                            position_samples += (v % sample_rate as f32) as u32;
                        }
                    }
                    (2, v) => {
                        vol += v as u32;
                    },
                    (3, v) => {
                        vol = v as u32;
                    },
                    (4, _) => {
                        back_send.send(vol as u8).unwrap();
                    },
                    (5, _) => {
                        if paused {
                            back_send.send(101).unwrap();
                        } else {
                            back_send.send(102).unwrap();
                        }
                    },
                    (6, _) => {
                        return;
                    },
                    _ => {}
                },
                _ => {}
            }
            let stream_data = match stream_result {
                Ok(data) => data,
                Err(err) => {
                    eprintln!("error on stream {:?}: {}", stream_id, err);
                    return;
                }
            };
            match stream_data {
                cpal::StreamData::Output {
                    buffer: cpal::UnknownTypeOutputBuffer::F32(mut buffer),
                } => {
                    for sample in buffer.chunks_mut(format.channels as usize) {
                        for channel in (0..format.channels as usize).rev() {
                            if position_samples as u32 == format.sample_rate.0 {
                                position_secs += 1;
                                position_samples = 0;
                            } else {
                                position_samples += 1;
                            }
                            sample[channel] = if paused == true {
                                0.0
                            } else {
                                match source.next_sample().get_f32() {
                                    Ok(v) => (v as f32 * vol as f32 / 100.0),
                                    Err(_) => {
                                        if position_secs <= 5 {
                                            0.0
                                        } else {
                                            end_send.send(true).unwrap();
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                cpal::StreamData::Output {
                    buffer: cpal::UnknownTypeOutputBuffer::I16(mut buffer),
                } => {
                    for sample in buffer.chunks_mut(format.channels as usize) {
                        for channel in (0..format.channels as usize).rev() {
                            if position_samples as u32 == format.sample_rate.0 {
                                position_secs += 1;
                                position_samples = 0;
                            } else {
                                position_samples += 1;
                            }
                            sample[channel] = if paused == true {
                                0
                            } else {
                                match source.next_sample().get_i16() {
                                    Ok(v) => (v as f32 * vol as f32 / 100.0) as i16,
                                    Err(_) => {
                                        if position_secs <= 5 {
                                            0
                                        } else {
                                            end_send.send(true).unwrap();
                                            return;
                                        }
                                    }
                                }
                            }
                        };
                    }
                }
                cpal::StreamData::Output {
                    buffer: cpal::UnknownTypeOutputBuffer::U16(mut buffer),
                } => {
                    for sample in buffer.chunks_mut(format.channels as usize) {
                        for channel in (0..format.channels as usize).rev() {
                            if position_samples as u32 == format.sample_rate.0 {
                                position_secs += 1;
                                position_samples = 0;
                            } else {
                                position_samples += 1;
                            }
                            sample[channel] = if paused == true {
                                0
                            } else {
                                match source.next_sample().get_u16() {
                                    Ok(v) => (v as f32 * vol as f32 / 100.0) as u16,
                                    Err(_) => {
                                        if position_secs <= 5 {
                                            0
                                        } else {
                                            end_send.send(true).unwrap();
                                            return;
                                        }
                                    }
                                }
                            }
                        };
                    }
                }
                _ => {}
            }
        });
        });
        return Arc::new(sound);
    }
    pub fn toggle_playback(&self) {
        self.control.lock().unwrap()
            .send((0, 1.0))
            .unwrap();
    }
    /// Skips a certain time span in seconds. Can be negative to skip backwards.
    pub fn skip(&self, pos: f32) {
        self.control.lock().unwrap()
            .send((1, pos))
            .unwrap();
    }
    /// Gets the total length in tenths of seconds.
    pub fn get_length(&self) -> u32 {
        self.total_length
    }
    /// Sets the volume relative to the current value.
    pub fn set_rel_vol(&self, vol: i8) {
        self.control.lock().unwrap().send((2, vol as f32)).unwrap();
    }
    pub fn set_vol (&self, vol: u8) {
        self.control.lock().unwrap().send((3, vol as f32)).unwrap();
    }
    pub fn is_finished(&self) -> bool {
        match self.end.lock().unwrap().try_recv() {
            Ok(v) => v,
            Err(_) => false,
        }
    }
    pub fn sleep_until_end(&self) {
        while self.end.lock().unwrap().recv().unwrap() == false {};
    }
    /// Gets the volume from the event loop of the Sink.
    pub fn get_vol(&self) -> u8 {
        self.control.lock().unwrap().send((4, 0.0)).unwrap();
        self.back_recv.lock().unwrap().recv().unwrap()
    }
    /// Checks whether the Sink's playback is paused.
    pub fn paused (&self) -> bool {
        self.control.lock().unwrap().send((5, 0.0)).unwrap();
        if self.back_recv.lock().unwrap().recv().unwrap() == 101 {
            true
        } else {
            false
        }
    }
    pub fn destroy(&self) {
        self.control.lock().unwrap().send((6, 0.0)).unwrap();
    }
}