1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
#![warn(missing_docs)]
#![doc(issue_tracker_base_url = "https://gitlab.101100.ca/ben1jen/playback-rs/-/issues")]
#![doc = include_str!("../docs.md")]
use std::collections::VecDeque;
use std::sync::mpsc::{self, Receiver};
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::time::Duration;
use color_eyre::eyre::{Report, Result};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{Sample, SampleFormat};
use log::{error, info};
use samplerate::{ConverterType, Samplerate};
use symphonia::core::audio::SampleBuffer;
use symphonia::core::codecs::DecoderOptions;
use symphonia::core::errors::Error as SymphoniaError;
use symphonia::core::formats::FormatOptions;
use symphonia::core::io::{MediaSource, MediaSourceStream, MediaSourceStreamOptions};
use symphonia::core::meta::MetadataOptions;
use symphonia::default;
pub use symphonia::core::probe::Hint;
#[derive(Debug)]
struct DecodingSong {
channel: Mutex<Receiver<Option<Vec<f32>>>>,
done: bool,
buffer: VecDeque<f32>,
len: usize,
}
impl DecodingSong {
fn new(song: &Song, sample_rate: u32, channel_count: usize) -> Result<DecodingSong> {
const DECODE_BLOCK_SIZE: usize = 1029 * 48000 / 44100 * 2;
let samples = {
let sample_count = song.samples[0].len();
let mut samples = vec![0.0; channel_count * sample_count];
for chan in 0..channel_count {
if chan < 2 || chan < song.samples.len() {
for sample in 0..sample_count {
samples[sample * channel_count as usize + chan] =
song.samples[chan % song.samples.len()][sample]
}
};
}
samples
};
let len = samples.len() * sample_rate as usize / song.sample_rate as usize;
let (tx, rx) = mpsc::channel();
let source_sample_rate = song.sample_rate;
thread::spawn(move || {
let converter = Samplerate::new(
ConverterType::SincFastest,
source_sample_rate,
sample_rate,
channel_count,
)
.unwrap();
let last = samples.len() / DECODE_BLOCK_SIZE;
for i in 0..=last {
let pos = i * DECODE_BLOCK_SIZE;
let samples = &samples[pos..((pos + DECODE_BLOCK_SIZE).min(samples.len()))];
let processed_samples = if i == last {
converter.process_last(samples)
} else {
converter.process(samples)
}
.unwrap();
if tx.send(Some(processed_samples)).is_err() {
break;
}
}
});
Ok(DecodingSong {
channel: Mutex::new(rx),
done: false,
buffer: VecDeque::new(),
len,
})
}
fn read_samples(&mut self, count: usize) -> (Vec<f32>, bool) {
let channel = self.channel.lock().unwrap();
if !self.done {
while self.buffer.len() < count {
if let Some(buf) = channel.recv().unwrap() {
self.buffer.append(&mut VecDeque::from(buf));
} else {
self.done = true;
break;
}
}
}
let mut vec = Vec::new();
let mut done = false;
for _i in 0..count {
if let Some(sample) = self.buffer.pop_front() {
vec.push(sample);
} else {
done = true;
break;
}
}
(vec, done)
}
fn len(&self) -> usize {
self.len
}
}
type PlaybackState = (DecodingSong, usize);
#[derive(Clone)]
struct PlayerState {
playback: Arc<RwLock<Option<PlaybackState>>>,
next_samples: Arc<RwLock<Option<DecodingSong>>>,
playing: Arc<RwLock<bool>>,
sample_rate: u32,
channel_count: usize,
}
impl PlayerState {
fn new(channel_count: u32, sample_rate: u32) -> Result<PlayerState> {
Ok(PlayerState {
playback: Arc::new(RwLock::new(None)),
next_samples: Arc::new(RwLock::new(None)),
playing: Arc::new(RwLock::new(true)),
channel_count: channel_count as usize,
sample_rate,
})
}
fn write_samples<T: Sample>(&self, data: &mut [T]) {
for sample in data.iter_mut() {
*sample = Sample::from(&0.0);
}
if *self.playing.read().unwrap() {
let mut playback = self.playback.write().unwrap();
if playback.is_none() {
if let Some(new_samples) = self.next_samples.write().unwrap().take() {
*playback = Some((new_samples, 0));
}
}
let mut done = false;
if let Some((decoding_song, pos)) = playback.as_mut() {
let mut neg_offset = 0;
let (samples, is_final) = decoding_song.read_samples(data.len());
done = is_final;
for (i, sample) in data.iter_mut().enumerate() {
if i >= samples.len() {
if let Some(new_samples) = self.next_samples.write().unwrap().take() {
*decoding_song = new_samples;
neg_offset = i;
*pos = 0;
} else {
break;
}
}
*sample = Sample::from(&samples[i]);
}
*pos += data.len() - neg_offset;
}
if done {
*playback = None;
}
}
}
fn decode_song(&self, song: &Song) -> Result<DecodingSong> {
DecodingSong::new(song, self.sample_rate, self.channel_count)
}
fn stop(&self) {
*self.next_samples.write().unwrap() = None;
*self.playback.write().unwrap() = None;
}
fn skip(&self) {
*self.playback.write().unwrap() = None;
}
fn play_song(&self, song: &Song) -> Result<()> {
let samples = self.decode_song(song)?;
*self.next_samples.write().unwrap() = Some(samples);
Ok(())
}
fn set_playing(&self, playing: bool) {
*self.playing.write().unwrap() = playing;
}
fn get_position(&self) -> Option<(usize, usize)> {
self.playback
.read()
.unwrap()
.as_ref()
.map(|(samples, pos)| (*pos, samples.len()))
}
fn seek(&self, position: usize) -> bool {
if let Some((_samples, pos)) = self.playback.write().unwrap().as_mut() {
*pos = position;
true
} else {
false
}
}
fn force_remove_next_song(&self) {
let (mut playback, mut next_song) = (
self.playback.write().unwrap(),
self.next_samples.write().unwrap(),
);
if next_song.is_some() {
*next_song = None;
} else {
*playback = None;
}
}
}
pub struct Player {
_stream: Box<dyn StreamTrait>,
player_state: PlayerState,
}
impl Player {
pub fn new() -> Result<Player> {
let device = {
let mut selected_host = cpal::default_host();
for host in cpal::available_hosts() {
if host.name().to_lowercase().contains("jack") {
selected_host = cpal::host_from_id(host)?;
}
}
info!("Selected Host: {:?}", selected_host.id());
let mut selected_device = selected_host
.default_output_device()
.ok_or_else(|| Report::msg("No output device found."))?;
for device in selected_host.output_devices()? {
if let Ok(name) = device.name().map(|s| s.to_lowercase()) {
if name.contains("pipewire") || name.contains("pulse") || name.contains("jack")
{
selected_device = device;
}
}
}
info!(
"Selected Device: {}",
selected_device
.name()
.unwrap_or_else(|_| "Unknown".to_string())
);
selected_device
};
let supported_config = device
.supported_output_configs()?
.next()
.ok_or_else(|| Report::msg("No supported output config."))?
.with_max_sample_rate();
let sample_format = supported_config.sample_format();
let sample_rate = supported_config.sample_rate().0;
let channel_count = supported_config.channels();
let config = supported_config.into();
let err_fn = |err| error!("A playback error has occured! {}", err);
let player_state = PlayerState::new(channel_count as u32, sample_rate)?;
info!("SR, CC: {}, {}", sample_rate, channel_count);
let stream = {
let player_state = player_state.clone();
match sample_format {
SampleFormat::F32 => device.build_output_stream(
&config,
move |data, _| player_state.write_samples::<f32>(data),
err_fn,
)?,
SampleFormat::I16 => device.build_output_stream(
&config,
move |data, _| player_state.write_samples::<i16>(data),
err_fn,
)?,
SampleFormat::U16 => device.build_output_stream(
&config,
move |data, _| player_state.write_samples::<u16>(data),
err_fn,
)?,
}
};
Ok(Player {
_stream: Box::new(stream),
player_state,
})
}
pub fn play_song_next(&self, song: &Song) -> Result<()> {
self.player_state.play_song(song)
}
pub fn play_song_now(&self, song: &Song) -> Result<()> {
self.player_state.stop();
self.player_state.play_song(song)?;
Ok(())
}
pub fn force_replace_next_song(&self, song: &Song) -> Result<()> {
self.player_state.force_remove_next_song();
self.player_state.play_song(song)?;
Ok(())
}
pub fn force_remove_next_song(&self) -> Result<()> {
self.player_state.force_remove_next_song();
Ok(())
}
pub fn stop(&self) {
self.player_state.stop();
}
pub fn skip(&self) {
self.player_state.skip();
}
fn get_duration_per_sample(&self) -> Duration {
Duration::from_nanos(
1000000000
/ (self.player_state.sample_rate as u64 * self.player_state.channel_count as u64),
)
}
pub fn get_playback_position(&self) -> Option<(Duration, Duration)> {
self.player_state.get_position().map(|(current, total)| {
let duration_per_sample = self.get_duration_per_sample();
(
duration_per_sample * current as u32,
duration_per_sample * total as u32,
)
})
}
pub fn seek(&self, time: Duration) -> bool {
let duration_per_sample = self.get_duration_per_sample();
let samples = (time.as_nanos() / duration_per_sample.as_nanos()) as usize;
self.player_state.seek(samples)
}
pub fn set_playing(&self, playing: bool) {
self.player_state.set_playing(playing);
}
pub fn is_playing(&self) -> bool {
*self.player_state.playing.read().unwrap()
}
pub fn has_next_song(&self) -> bool {
self.player_state
.next_samples
.read()
.expect("Next song mutex poisoned.")
.is_some()
}
pub fn has_current_song(&self) -> bool {
self.player_state
.playback
.read()
.expect("Current song mutex poisoned.")
.is_some() || self
.player_state
.next_samples
.read()
.expect("Next song mutex poisoned.")
.is_some()
}
}
#[derive(Debug, Clone)]
pub struct Song {
samples: Vec<Vec<f32>>,
sample_rate: u32,
channel_count: u32,
}
impl Song {
pub fn new(reader: Box<dyn MediaSource>, hint: &Hint) -> Result<Song> {
let media_source_stream =
MediaSourceStream::new(reader, MediaSourceStreamOptions::default());
let mut probe_result = default::get_probe().format(
hint,
media_source_stream,
&FormatOptions {
enable_gapless: true,
..FormatOptions::default()
},
&MetadataOptions::default(),
)?;
let mut decoder = default::get_codecs().make(
&probe_result
.format
.default_track()
.ok_or_else(|| Report::msg("No default track in media file."))?
.codec_params,
&DecoderOptions::default(),
)?;
let mut song: Option<Song> = None;
loop {
match probe_result.format.next_packet() {
Ok(packet) => {
let decoded = decoder.decode(&packet)?;
let spec = *decoded.spec();
let song = if let Some(old_song) = &mut song {
if spec.rate != old_song.sample_rate
|| spec.channels.count() as u32 != old_song.channel_count
{
return Err(Report::msg("Sample rate or channel count of decoded does not match previous sample rate."));
}
old_song
} else {
song = Some(Song {
samples: vec![Vec::new(); spec.channels.count()],
sample_rate: spec.rate,
channel_count: spec.channels.count() as u32,
});
song.as_mut().unwrap()
};
let mut samples = SampleBuffer::new(decoded.frames() as u64, spec);
samples.copy_interleaved_ref(decoded);
for frame in samples.samples().chunks(spec.channels.count()) {
for (chan, sample) in frame.iter().enumerate() {
song.samples[chan].push(*sample)
}
}
}
Err(SymphoniaError::IoError(_)) => break,
Err(e) => return Err(e.into()),
}
}
song.ok_or_else(|| Report::msg("No song data decoded."))
}
pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Song> {
let mut hint = Hint::new();
if let Some(extension) = path.as_ref().extension().and_then(|s| s.to_str()) {
hint.with_extension(extension);
}
Self::new(Box::new(std::fs::File::open(path)?), &hint)
}
}