unbanished_audio/device/
native.rs1use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
4use std::sync::Arc;
5use std::time::Duration;
6
7use super::{pitch_ratio, Channel, PlayParams, Slots, Sound};
8
9pub(crate) struct SharedSource {
12 pub(crate) sound: Sound,
13 pub(crate) cursor: Arc<AtomicUsize>,
15 pub(crate) looping: Arc<AtomicBool>,
16}
17
18impl Iterator for SharedSource {
19 type Item = f32;
20
21 fn next(&mut self) -> Option<f32> {
22 let samples = &self.sound.pcm.samples;
23 let mut i = self.cursor.load(Ordering::Relaxed);
24 if i >= samples.len() {
25 if !self.looping.load(Ordering::Relaxed) || samples.is_empty() {
26 return None;
27 }
28 i = 0;
29 }
30 self.cursor.store(i + 1, Ordering::Relaxed);
31 Some(samples[i])
32 }
33}
34
35impl rodio::Source for SharedSource {
36 fn current_span_len(&self) -> Option<usize> {
37 None
38 }
39
40 fn channels(&self) -> rodio::ChannelCount {
41 self.sound.pcm.channels.max(1)
42 }
43
44 fn sample_rate(&self) -> rodio::SampleRate {
45 self.sound.pcm.sample_rate.max(1)
46 }
47
48 fn total_duration(&self) -> Option<Duration> {
49 (!self.looping.load(Ordering::Relaxed)).then(|| self.sound.duration())
50 }
51
52 fn try_seek(&mut self, pos: Duration) -> Result<(), rodio::source::SeekError> {
53 let channels = self.sound.pcm.channels.max(1) as usize;
54 let frame = (pos.as_secs_f64() * self.sound.pcm.sample_rate as f64) as usize;
55 let i = (frame.min(self.sound.frames())) * channels;
56 self.cursor.store(i, Ordering::Relaxed);
57 Ok(())
58 }
59}
60
61struct Voice {
62 sink: rodio::Sink,
63 sound: Sound,
64 cursor: Arc<AtomicUsize>,
65 looping: Arc<AtomicBool>,
66 volume: f32,
67}
68
69pub struct Device {
71 stream: Option<rodio::OutputStream>,
72 voices: Slots<Voice>,
73 master: f32,
74 silent: bool,
76}
77
78fn muted() -> bool {
81 std::env::var_os("UNBANISHED_MUTE").is_some_and(|v| !v.is_empty() && v != "0")
82}
83
84impl Default for Device {
85 fn default() -> Self {
86 Device {
87 stream: None,
88 voices: Slots::default(),
89 master: if muted() { 0.0 } else { 1.0 },
90 silent: muted(),
91 }
92 }
93}
94
95impl Device {
96 fn mixer(&mut self) -> Result<&rodio::mixer::Mixer, String> {
97 if self.stream.is_none() {
98 let mut stream =
99 rodio::OutputStreamBuilder::open_default_stream().map_err(|e| e.to_string())?;
100 stream.log_on_drop(false);
101 self.stream = Some(stream);
102 }
103 Ok(self.stream.as_ref().unwrap().mixer())
104 }
105
106 pub fn play(&mut self, sound: &Sound, params: PlayParams) -> Result<Option<Channel>, String> {
109 if self.voices.len() >= super::CHANNELS {
110 return Ok(None);
111 }
112 let sink = rodio::Sink::connect_new(self.mixer()?);
113 let looping = Arc::new(AtomicBool::new(params.looping.unwrap_or(sound.looping)));
114 let channels = sound.pcm.channels.max(1) as usize;
115 let start = sound.wrap(params.offset);
116 let frame = (start.as_secs_f64() * sound.pcm.sample_rate as f64) as usize;
117 let cursor = Arc::new(AtomicUsize::new(frame.min(sound.frames()) * channels));
118 sink.set_volume((params.volume * self.master).max(0.0));
119 sink.set_speed(pitch_ratio(params.pitch));
120 sink.append(SharedSource {
121 sound: sound.clone(),
122 cursor: cursor.clone(),
123 looping: looping.clone(),
124 });
125 Ok(self.voices.insert(Voice {
126 sink,
127 sound: sound.clone(),
128 cursor,
129 looping,
130 volume: params.volume,
131 }))
132 }
133
134 pub fn stop(&mut self, c: Channel) {
136 if let Some(v) = self.voices.remove(c) {
137 v.sink.stop();
138 }
139 }
140
141 pub fn stop_all(&mut self) {
143 let all: Vec<_> = self.voices.iter().map(|(c, _)| c).collect();
144 for c in all {
145 self.stop(c);
146 }
147 }
148
149 pub fn update(&mut self) -> Vec<Channel> {
152 let ended: Vec<_> = self
153 .voices
154 .iter()
155 .filter(|(_, v)| v.sink.empty())
156 .map(|(c, _)| c)
157 .collect();
158 for &c in &ended {
159 self.voices.remove(c);
160 }
161 ended
162 }
163
164 pub fn is_playing(&self, c: Channel) -> bool {
166 self.voices
167 .get(c)
168 .is_some_and(|v| !v.sink.empty() && !v.sink.is_paused())
169 }
170
171 pub fn is_active(&self, c: Channel) -> bool {
173 self.voices.get(c).is_some_and(|v| !v.sink.empty())
174 }
175
176 pub fn active(&self) -> usize {
178 self.voices.len()
179 }
180
181 pub fn pause(&mut self, c: Channel) {
183 if let Some(v) = self.voices.get(c) {
184 v.sink.pause();
185 }
186 }
187
188 pub fn resume(&mut self, c: Channel) {
190 if let Some(v) = self.voices.get(c) {
191 v.sink.play();
192 }
193 }
194
195 pub fn is_paused(&self, c: Channel) -> bool {
197 self.voices.get(c).is_some_and(|v| v.sink.is_paused())
198 }
199
200 pub fn position(&self, c: Channel) -> Duration {
202 let Some(v) = self.voices.get(c) else {
203 return Duration::ZERO;
204 };
205 let channels = v.sound.pcm.channels.max(1) as usize;
206 let frame = v.cursor.load(Ordering::Relaxed) / channels;
207 Duration::from_secs_f64(frame as f64 / v.sound.pcm.sample_rate.max(1) as f64)
208 .min(v.sound.duration())
209 }
210
211 pub fn seek(&mut self, c: Channel, position: Duration) -> Result<(), String> {
213 if let Some(v) = self.voices.get(c) {
214 v.sink
215 .try_seek(position.min(v.sound.duration()))
216 .map_err(|e| e.to_string())?;
217 }
218 Ok(())
219 }
220
221 pub fn set_volume(&mut self, c: Channel, volume: f32) {
223 let master = self.master;
224 if let Some(v) = self.voices.get_mut(c) {
225 v.volume = volume.max(0.0);
226 v.sink.set_volume(v.volume * master);
227 }
228 }
229
230 pub fn set_pitch(&mut self, c: Channel, semitones: f32) {
232 if let Some(v) = self.voices.get(c) {
233 v.sink.set_speed(pitch_ratio(semitones));
234 }
235 }
236
237 pub fn set_looping(&mut self, c: Channel, looping: bool) {
239 if let Some(v) = self.voices.get(c) {
240 v.looping.store(looping, Ordering::Relaxed);
241 }
242 }
243
244 pub fn set_master_volume(&mut self, volume: f32) {
246 self.master = if self.silent { 0.0 } else { volume.max(0.0) };
247 for (_, v) in self.voices.iter() {
248 v.sink.set_volume(v.volume * self.master);
249 }
250 }
251
252 pub fn silence(&mut self) {
254 self.silent = true;
255 self.set_master_volume(0.0);
256 }
257
258 pub fn unlock(&mut self) {}
260}