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
|
use crate::notification;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
#[allow(dead_code)]
pub enum AudioCommand {
Play(PathBuf),
Pause,
Resume,
Stop,
SetVolume(f32),
}
pub struct AudioEngine {
command_tx: Sender<AudioCommand>,
is_playing: Arc<AtomicBool>,
pub current_track: Arc<Mutex<Option<std::path::PathBuf>>>,
track_ended: Arc<AtomicBool>,
volume: Arc<Mutex<f32>>,
}
#[allow(clippy::new_without_default)]
impl AudioEngine {
pub fn new() -> Self {
let (tx, rx) = mpsc::channel();
let is_playing = Arc::new(AtomicBool::new(false));
let is_playing_clone = Arc::clone(&is_playing);
let current_track = Arc::new(Mutex::new(None));
let current_track_clone = Arc::clone(¤t_track);
let track_ended = Arc::new(AtomicBool::new(false));
let track_ended_clone = Arc::clone(&track_ended);
let volume = Arc::new(Mutex::new(1.0f32));
let volume_clone = Arc::clone(&volume);
thread::spawn(move || {
audio_thread(
rx,
is_playing_clone,
current_track_clone,
volume_clone,
track_ended_clone,
);
});
AudioEngine {
command_tx: tx,
is_playing,
current_track,
track_ended,
volume,
}
}
pub fn play(&self, path: PathBuf) {
self.track_ended.store(false, Ordering::SeqCst);
if let Ok(mut track) = self.current_track.lock() {
*track = Some(path.clone());
}
let _ = self.command_tx.send(AudioCommand::Play(path));
}
pub fn pause(&self) {
let _ = self.command_tx.send(AudioCommand::Pause);
}
pub fn resume(&self) {
let _ = self.command_tx.send(AudioCommand::Resume);
}
pub fn stop(&self) {
let _ = self.command_tx.send(AudioCommand::Stop);
}
pub fn set_volume(&self, volume: f32) {
let _ = self.command_tx.send(AudioCommand::SetVolume(volume));
}
pub fn get_volume(&self) -> u8 {
self.volume
.lock()
.map(|v| (*v * 100.0) as u8)
.unwrap_or(100)
}
pub fn is_playing(&self) -> bool {
self.is_playing.load(Ordering::SeqCst)
}
pub fn current_track(&self) -> Option<std::path::PathBuf> {
self.current_track.lock().ok().and_then(|g| g.clone())
}
pub fn poll_track_ended(&self) -> bool {
self.track_ended.swap(false, Ordering::SeqCst)
}
}
struct AudioData {
format: Box<dyn symphonia::core::formats::FormatReader>,
decoder: Box<dyn symphonia::core::codecs::Decoder>,
sample_rate: u32,
channels: u16,
sample_buffer: Vec<f32>,
buffer_pos: usize,
resample_ratio: Option<f64>,
}
fn resample_linear(input: &[f32], ratio: f64, channels: usize) -> Vec<f32> {
if ratio == 1.0 {
return input.to_vec();
}
let input_frames = input.len() / channels;
let output_frames = (input_frames as f64 * ratio).ceil() as usize;
let mut output = Vec::with_capacity(output_frames * channels);
for i in 0..output_frames {
let input_pos = i as f64 / ratio;
let idx = input_pos.floor() as usize;
let frac = input_pos.fract() as f32;
for ch in 0..channels {
let cur = if idx * channels + ch < input.len() {
input[idx * channels + ch]
} else {
0.0
};
let next = if (idx + 1) * channels + ch < input.len() {
input[(idx + 1) * channels + ch]
} else {
cur
};
output.push(cur + frac * (next - cur));
}
}
output
}
fn audio_thread(
rx: Receiver<AudioCommand>,
is_playing: Arc<AtomicBool>,
current_track: Arc<Mutex<Option<std::path::PathBuf>>>,
volume: Arc<Mutex<f32>>,
track_ended: Arc<AtomicBool>,
) {
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
let host = cpal::default_host();
let device = match host.default_output_device() {
Some(d) => d,
None => {
eprintln!("No output device available");
return;
}
};
let config = match device.default_output_config() {
Ok(c) => c,
Err(e) => {
eprintln!("Failed to get output config: {}", e);
return;
}
};
let device_sample_rate = config.sample_rate();
let channels = config.channels();
eprintln!(
"Default output: {} Hz, {} channels",
device_sample_rate, channels
);
let mut current_stream: Option<cpal::Stream> = None;
let audio_data: Arc<Mutex<Option<AudioData>>> = Arc::new(Mutex::new(None));
while let Ok(cmd) = rx.recv() {
match cmd {
AudioCommand::Play(path) => {
is_playing.store(true, Ordering::SeqCst);
if let Ok(mut track) = current_track.lock() {
*track = Some(path.clone());
}
// Drop the current stream before creating a new one
current_stream = None;
match open_audio_file(&path) {
Ok(mut data) => {
eprintln!("File: {} Hz, {} channels", data.sample_rate, data.channels);
if data.sample_rate != device_sample_rate {
eprintln!(
"Resampling from {} Hz to {} Hz",
data.sample_rate, device_sample_rate
);
data.resample_ratio =
Some(device_sample_rate as f64 / data.sample_rate as f64);
}
// Pre-decode some samples before starting playback to prevent buffer underrun
let channels = data.channels as usize;
for _ in 0..50 {
match data.format.next_packet() {
Ok(packet) => {
match data.decoder.decode(&packet) {
Ok(decoded) => {
let spec = *decoded.spec();
let mut sample_buf =
symphonia::core::audio::SampleBuffer::<f32>::new(
decoded.capacity() as u64, spec
);
sample_buf.copy_interleaved_ref(decoded);
let samples = sample_buf.samples();
let resampled = if let Some(ratio) = data.resample_ratio {
resample_linear(samples, ratio, channels)
} else {
samples.to_vec()
};
data.sample_buffer.extend(resampled);
}
Err(_) => break,
}
}
Err(_) => break,
}
}
data.buffer_pos = 0;
let stream_config: cpal::StreamConfig =
device.default_output_config().unwrap().into();
let audio_data_clone = Arc::clone(&audio_data);
let vol = Arc::clone(&volume);
let ended = Arc::clone(&track_ended);
let is_playing_clone = Arc::clone(&is_playing);
if let Ok(mut d) = audio_data.lock() {
*d = Some(data);
}
match device.build_output_stream(
&stream_config,
move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
let vol = vol.lock().map(|v| *v).unwrap_or(1.0);
if let Ok(mut audio_data) = audio_data_clone.lock() {
let mut should_clear = false;
if let Some(ref mut state) = *audio_data {
let channels = state.channels as usize;
let mut offset = 0usize;
// Keep decoding until we fill the buffer or run out of data
while offset < data.len() {
// First, copy any buffered samples
if state.buffer_pos < state.sample_buffer.len() {
let remaining =
&state.sample_buffer[state.buffer_pos..];
let to_copy =
remaining.len().min(data.len() - offset);
data[offset..offset + to_copy]
.copy_from_slice(&remaining[..to_copy]);
state.buffer_pos += to_copy;
offset += to_copy;
// If we've consumed all buffered samples, clear the buffer
if state.buffer_pos >= state.sample_buffer.len() {
state.sample_buffer.clear();
state.buffer_pos = 0;
}
continue; // Try to fill more of the buffer
}
// Decode more data
match state.format.next_packet() {
Ok(packet) => {
match state.decoder.decode(&packet) {
Ok(decoded) => {
let spec = *decoded.spec();
let mut sample_buf =
symphonia::core::audio::SampleBuffer::<
f32,
>::new(
decoded.capacity() as u64, spec
);
sample_buf
.copy_interleaved_ref(decoded);
let samples = sample_buf.samples();
// Resample if needed
let resampled = if let Some(ratio) =
state.resample_ratio
{
resample_linear(
samples, ratio, channels,
)
} else {
samples.to_vec()
};
// Copy what we can to output
let to_copy = resampled
.len()
.min(data.len() - offset);
data[offset..offset + to_copy]
.copy_from_slice(
&resampled[..to_copy],
);
offset += to_copy;
// Buffer the rest
if to_copy < resampled.len() {
state.sample_buffer.clear();
state
.sample_buffer
.extend_from_slice(
&resampled[to_copy..],
);
state.buffer_pos = 0;
}
}
Err(_) => break,
}
}
Err(_) => break,
}
}
// Apply volume
for sample in data.iter_mut().take(offset) {
*sample *= vol;
}
// Fill remaining with silence
for sample in data.iter_mut().skip(offset) {
*sample = 0.0;
}
// If no more data and offset is 0, track ended
if offset == 0 && state.sample_buffer.is_empty() {
ended.store(true, Ordering::SeqCst);
is_playing_clone.store(false, Ordering::SeqCst);
should_clear = true;
}
} else {
for sample in data.iter_mut() {
*sample = 0.0;
}
}
if should_clear {
*audio_data = None;
}
}
},
|err| {
eprintln!("Stream error: {}", err);
},
None,
) {
Ok(stream) => {
if let Err(e) = stream.play() {
eprintln!("Failed to start stream: {}", e);
notification::notify_error("Failed to start audio stream");
is_playing.store(false, Ordering::SeqCst);
} else {
current_stream = Some(stream);
}
}
Err(e) => {
eprintln!("Failed to create stream: {}", e);
notification::notify_error("Failed to create audio stream");
is_playing.store(false, Ordering::SeqCst);
}
}
}
Err(e) => {
eprintln!("Failed to open audio: {}", e);
notification::notify_error("Failed to open audio file");
is_playing.store(false, Ordering::SeqCst);
}
}
}
AudioCommand::Pause => {
if let Some(ref stream) = current_stream {
if let Err(e) = stream.pause() {
eprintln!("Failed to pause stream: {}", e);
}
is_playing.store(false, Ordering::SeqCst);
}
}
AudioCommand::Resume => {
if let Some(ref stream) = current_stream {
if let Err(e) = stream.play() {
eprintln!("Failed to resume stream: {}", e);
} else {
is_playing.store(true, Ordering::SeqCst);
}
}
}
AudioCommand::Stop => {
current_stream = None;
if let Ok(mut d) = audio_data.lock() {
*d = None;
}
is_playing.store(false, Ordering::SeqCst);
if let Ok(mut track) = current_track.lock() {
*track = None;
}
}
AudioCommand::SetVolume(vol) => {
if let Ok(mut volume_ref) = volume.lock() {
*volume_ref = vol;
}
}
}
}
}
fn open_audio_file(path: &PathBuf) -> Result<AudioData, Box<dyn std::error::Error>> {
use symphonia::core::audio::Channels;
use symphonia::core::io::MediaSourceStream;
let file = std::fs::File::open(path)?;
let mss = MediaSourceStream::new(Box::new(file), Default::default());
let hint = symphonia::core::probe::Hint::new();
let probed = symphonia::default::get_probe().format(
&hint,
mss,
&Default::default(),
&Default::default(),
)?;
let format = probed.format;
let track = format
.tracks()
.iter()
.find(|t| t.codec_params.sample_rate.is_some())
.ok_or("No suitable track found")?;
let sample_rate = track.codec_params.sample_rate.unwrap_or(44100);
let channels = track
.codec_params
.channels
.unwrap_or(Channels::FRONT_LEFT | Channels::FRONT_RIGHT)
.count() as u16;
let decoder =
symphonia::default::get_codecs().make(&track.codec_params, &Default::default())?;
Ok(AudioData {
format,
decoder,
sample_rate,
channels,
sample_buffer: Vec::new(),
buffer_pos: 0,
resample_ratio: None,
})
}
|