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
|
use rodio::{Decoder, OutputStream, OutputStreamHandle, Sink, Source};
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::thread;
use crate::state::TimerPhase;
// OutputStream is !Send, so we keep it alive in a dedicated thread.
// Only OutputStreamHandle and Sink (both Send) cross thread boundaries.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AmbientSound {
Rain,
Cafe,
WhiteNoise,
}
impl AmbientSound {
pub fn filename(&self) -> &'static str {
match self {
AmbientSound::Rain => "rain.ogg",
AmbientSound::Cafe => "cafe.ogg",
AmbientSound::WhiteNoise => "white_noise.ogg",
}
}
pub fn name(&self) -> &'static str {
match self {
AmbientSound::Rain => "rain",
AmbientSound::Cafe => "cafe",
AmbientSound::WhiteNoise => "white_noise",
}
}
pub fn from_str(s: &str) -> Option<Self> {
match s {
"rain" => Some(AmbientSound::Rain),
"cafe" => Some(AmbientSound::Cafe),
"white_noise" => Some(AmbientSound::WhiteNoise),
_ => None,
}
}
}
pub struct AudioEngine {
stream_handle: OutputStreamHandle,
sink: Option<Sink>,
current_sound: Option<AmbientSound>,
volume: f32,
ducked: bool,
duck_volume: f32,
audio_dir: PathBuf,
}
impl AudioEngine {
fn new_with_handle(stream_handle: OutputStreamHandle, audio_dir: PathBuf) -> Self {
Self {
stream_handle,
sink: None,
current_sound: None,
volume: 0.5,
ducked: false,
duck_volume: 0.2,
audio_dir,
}
}
pub fn play(&mut self, sound: AmbientSound) -> Result<(), String> {
self.stop();
let filename = sound.filename();
let path = self.audio_dir.join(filename);
let file = File::open(&path).map_err(|e| format!("Cannot open {filename}: {e}"))?;
let source = Decoder::new(BufReader::new(file))
.map_err(|e| format!("Decode error: {e}"))?;
let sink = Sink::try_new(&self.stream_handle)
.map_err(|e| format!("Sink error: {e}"))?;
sink.append(source.repeat_infinite());
sink.set_volume(if self.ducked { self.duck_volume } else { self.volume });
sink.play();
self.current_sound = Some(sound);
self.sink = Some(sink);
Ok(())
}
pub fn stop(&mut self) {
if let Some(sink) = self.sink.take() {
sink.stop();
}
self.current_sound = None;
}
pub fn set_volume(&mut self, volume: f32) {
self.volume = volume.clamp(0.0, 1.0);
if let Some(ref sink) = self.sink {
if !self.ducked {
sink.set_volume(self.volume);
}
}
}
pub fn duck(&mut self) {
self.ducked = true;
if let Some(ref sink) = self.sink {
sink.set_volume(self.duck_volume);
}
}
pub fn unduck(&mut self) {
self.ducked = false;
if let Some(ref sink) = self.sink {
sink.set_volume(self.volume);
}
}
pub fn is_playing(&self) -> bool {
self.sink.is_some()
}
pub fn current_sound(&self) -> Option<AmbientSound> {
self.current_sound
}
pub fn volume(&self) -> f32 {
self.volume
}
}
pub fn should_duck_for_phase(phase: TimerPhase) -> bool {
!matches!(phase, TimerPhase::Work)
}
/// Managed state: Arc<Mutex<Option<AudioEngine>>>.
/// None means audio init failed (graceful degradation).
pub struct AudioState(pub Arc<Mutex<Option<AudioEngine>>>);
/// Initialise the audio subsystem.
///
/// Spawns a dedicated thread to keep `OutputStream` alive (it is `!Send`).
/// Returns `AudioState` whose inner `Option` is `None` if no audio device exists.
pub fn init_audio(audio_dir: PathBuf) -> AudioState {
let state: Arc<Mutex<Option<AudioEngine>>> = Arc::new(Mutex::new(None));
let state_clone = Arc::clone(&state);
thread::spawn(move || {
match OutputStream::try_default() {
Ok((_stream, handle)) => {
let engine = AudioEngine::new_with_handle(handle, audio_dir);
{
let mut guard = state_clone.lock().unwrap();
*guard = Some(engine);
}
// Park forever — _stream must stay alive to keep audio device open.
loop {
thread::park();
}
}
Err(e) => {
eprintln!("[audio] No audio output device: {e}");
// state remains None
}
}
});
// Give the audio thread a moment to initialise before returning.
// Commands will work fine regardless due to Option<AudioEngine> guard.
thread::sleep(std::time::Duration::from_millis(100));
AudioState(state)
}
#[cfg(test)]
mod tests {
use super::should_duck_for_phase;
use crate::state::TimerPhase;
#[test]
fn work_phase_does_not_duck() {
assert!(!should_duck_for_phase(TimerPhase::Work));
}
#[test]
fn break_phases_duck() {
assert!(should_duck_for_phase(TimerPhase::ShortBreak));
assert!(should_duck_for_phase(TimerPhase::LongBreak));
}
}
|