Skip to main content

unbanished_audio/device/
native.rs

1//! The native audio device: rodio sources that play the channels.
2
3use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
4use std::sync::Arc;
5use std::time::Duration;
6
7use super::{pitch_ratio, Channel, PlayParams, Slots, Sound};
8
9/// A rodio source over a shared buffer. Position and looping are shared with the channel,
10/// so they can be read and changed while it plays.
11pub(crate) struct SharedSource {
12    pub(crate) sound: Sound,
13    /// Next sample index (interleaved).
14    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
69/// The multi-channel output (rodio).
70pub struct Device {
71    stream: Option<rodio::OutputStream>,
72    voices: Slots<Voice>,
73    master: f32,
74    /// Kept at volume 0 for good ([`Device::silence`], or `UNBANISHED_MUTE`).
75    silent: bool,
76}
77
78/// Whether `UNBANISHED_MUTE` is set: tests and tools set it so that no run is heard, whatever
79/// volume the game asks for.
80fn 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    /// `Device::Play`: start `sound` on the first free channel. `Ok(None)` when all 64 are
107    /// busy (the original returns null); `Err` when there is no audio output.
108    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    /// `Device::Stop`.
135    pub fn stop(&mut self, c: Channel) {
136        if let Some(v) = self.voices.remove(c) {
137            v.sink.stop();
138        }
139    }
140
141    /// `Scene::StopAll`.
142    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    /// `Device::Update`: free the channels that finished, returning them (the end
150    /// callbacks).
151    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    /// Whether the channel is still allocated and has not finished.
165    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    /// Whether the channel is allocated and has not finished, paused or not.
172    pub fn is_active(&self, c: Channel) -> bool {
173        self.voices.get(c).is_some_and(|v| !v.sink.empty())
174    }
175
176    /// The number of channels in use.
177    pub fn active(&self) -> usize {
178        self.voices.len()
179    }
180
181    /// Pause a channel. The other channels go on.
182    pub fn pause(&mut self, c: Channel) {
183        if let Some(v) = self.voices.get(c) {
184            v.sink.pause();
185        }
186    }
187
188    /// Resume a paused channel.
189    pub fn resume(&mut self, c: Channel) {
190        if let Some(v) = self.voices.get(c) {
191            v.sink.play();
192        }
193    }
194
195    /// Whether the channel is paused.
196    pub fn is_paused(&self, c: Channel) -> bool {
197        self.voices.get(c).is_some_and(|v| v.sink.is_paused())
198    }
199
200    /// Position in the sound (wrapped for looping channels).
201    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    /// Move a channel to a position in its sound.
212    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    /// `Device::SetChannelVolume`.
222    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    /// Change a channel's pitch, in semitones.
231    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    /// Change whether a channel loops.
238    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    /// Scales every channel (always 0 with `UNBANISHED_MUTE` set).
245    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    /// Keep this device at volume 0 from now on, whatever volume is asked for later (tests).
253    pub fn silence(&mut self) {
254        self.silent = true;
255        self.set_master_volume(0.0);
256    }
257
258    /// Browsers start audio suspended until a user gesture; nothing to do natively.
259    pub fn unlock(&mut self) {}
260}