Skip to main content

unbanished_audio/
device.rs

1//! A pool of concurrent voices, after the original `Audio::Device` (Runtime DLL): 64 channels
2//! (`0x28` bytes each, flag bit 0 = in use, bit 1 = ended). `Device::Play` takes the first free
3//! channel and returns null when all are busy; `PlayPlatform` starts one XAudio2 source voice at
4//! `offset % duration`, with the given volume and a frequency ratio of `1.05946314^pitch` (pitch in
5//! semitones), looping when the sound buffer's loop flag is set. `Device::Update` frees ended
6//! channels and calls their end callbacks; `Device::Stop` stops, frees and calls back.
7//!
8//! The port plays every channel at once through rodio's mixer natively and through one Web Audio
9//! graph (a gain node per channel into a master gain) in the browser. The end callback becomes the
10//! list of channels `update` returns.
11//!
12//! Original: Runtime `0x1800e0ad0`, Runtime `0x1800e0ff0`, Runtime `0x1800e0d70`, Runtime
13//! `0x1800e0a50`.
14
15use std::sync::Arc;
16use std::time::Duration;
17
18use crate::Pcm;
19
20/// `Audio::Device` channel count (loops in `FindFreeChannel`, `Play`, `Update`).
21pub const CHANNELS: usize = 64;
22
23/// `DAT_180164810`: one semitone (the twelfth root of two).
24const SEMITONE: f32 = 1.059_463_1;
25
26/// The playback speed for a pitch in semitones: one semitone is the twelfth root of two, as
27/// XAudio2's frequency ratio.
28///
29/// Original: `FUN_180129df0(1.05946314, pitch)`.
30pub fn pitch_ratio(semitones: f32) -> f32 {
31    SEMITONE.powf(semitones)
32}
33
34/// A decoded sound buffer (`Audio::SoundBuffer`) that any number of channels can play at once;
35/// the samples are shared, not copied, per channel.
36#[derive(Clone)]
37pub struct Sound {
38    pcm: Arc<Pcm>,
39    // SoundBuffer +0x20
40    /// Whether the sound loops.
41    pub looping: bool,
42    #[cfg(target_arch = "wasm32")]
43    web: std::rc::Rc<std::cell::RefCell<Option<web_sys::AudioBuffer>>>,
44}
45
46impl Sound {
47    /// A sound from decoded samples and its loop flag.
48    pub fn new(pcm: Pcm, looping: bool) -> Sound {
49        Sound {
50            pcm: Arc::new(pcm),
51            looping,
52            #[cfg(target_arch = "wasm32")]
53            web: Default::default(),
54        }
55    }
56
57    /// Load and decode a sound by resource reference (see [`crate::load_sound`]).
58    pub fn load(
59        archive: &unbanished_formats::pkg::Archive,
60        reference: &str,
61    ) -> Result<Sound, String> {
62        let (pcm, looping) = crate::load_sound(archive, reference)?;
63        Ok(Sound::new(pcm, looping))
64    }
65
66    /// The decoded samples.
67    pub fn pcm(&self) -> &Pcm {
68        &self.pcm
69    }
70
71    /// The length in frames (samples per channel).
72    pub fn frames(&self) -> usize {
73        self.pcm.samples.len() / self.pcm.channels.max(1) as usize
74    }
75
76    /// The length.
77    pub fn duration(&self) -> Duration {
78        Duration::from_secs_f64(self.frames() as f64 / self.pcm.sample_rate.max(1) as f64)
79    }
80
81    /// `PlayPlatform`'s start point: the requested time wrapped into the sound.
82    pub fn wrap(&self, offset: Duration) -> Duration {
83        let d = self.duration().as_secs_f64();
84        if d <= 0.0 {
85            return Duration::ZERO;
86        }
87        Duration::from_secs_f64(offset.as_secs_f64() % d)
88    }
89}
90
91/// A playing channel. Handles carry a generation, so one kept after its channel was freed and
92/// reused refers to nothing (calls on it do nothing).
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94pub struct Channel {
95    index: u8,
96    generation: u32,
97}
98
99impl Channel {
100    /// The channel's number, 0 to 63.
101    pub fn index(self) -> usize {
102        self.index as usize
103    }
104
105    #[cfg(test)]
106    pub(crate) fn test(n: u32) -> Channel {
107        Channel {
108            index: (n % 64) as u8,
109            generation: n,
110        }
111    }
112}
113
114/// Channel bookkeeping without any output: first-free allocation and generations.
115#[derive(Debug)]
116pub struct Slots<T> {
117    slots: Vec<Option<(u32, T)>>,
118    generation: u32,
119}
120
121impl<T> Default for Slots<T> {
122    fn default() -> Self {
123        Slots {
124            slots: (0..CHANNELS).map(|_| None).collect(),
125            generation: 0,
126        }
127    }
128}
129
130impl<T> Slots<T> {
131    /// `FindFreeChannel`: the lowest free index, or `None` when all 64 are in use.
132    pub fn insert(&mut self, value: T) -> Option<Channel> {
133        let index = self.slots.iter().position(Option::is_none)?;
134        self.generation = self.generation.wrapping_add(1);
135        self.slots[index] = Some((self.generation, value));
136        Some(Channel {
137            index: index as u8,
138            generation: self.generation,
139        })
140    }
141
142    /// The value of a channel, or `None` when the handle is stale.
143    pub fn get(&self, c: Channel) -> Option<&T> {
144        match self.slots.get(c.index())? {
145            Some((g, v)) if *g == c.generation => Some(v),
146            _ => None,
147        }
148    }
149
150    /// The value of a channel, to change it, or `None` when the handle is stale.
151    pub fn get_mut(&mut self, c: Channel) -> Option<&mut T> {
152        match self.slots.get_mut(c.index())? {
153            Some((g, v)) if *g == c.generation => Some(v),
154            _ => None,
155        }
156    }
157
158    /// Free a channel and return its value.
159    pub fn remove(&mut self, c: Channel) -> Option<T> {
160        self.get(c)?;
161        self.slots[c.index()].take().map(|(_, v)| v)
162    }
163
164    /// The channels in use, with their values.
165    pub fn iter(&self) -> impl Iterator<Item = (Channel, &T)> {
166        self.slots.iter().enumerate().filter_map(|(i, s)| {
167            s.as_ref().map(|(g, v)| {
168                (
169                    Channel {
170                        index: i as u8,
171                        generation: *g,
172                    },
173                    v,
174                )
175            })
176        })
177    }
178
179    /// The number of channels in use.
180    pub fn len(&self) -> usize {
181        self.slots.iter().filter(|s| s.is_some()).count()
182    }
183
184    /// Whether no channel is in use.
185    pub fn is_empty(&self) -> bool {
186        self.len() == 0
187    }
188}
189
190/// How a channel starts (`Device::Play`'s time and floats).
191#[derive(Debug, Clone, Copy)]
192pub struct PlayParams {
193    /// Start time, wrapped into the sound.
194    pub offset: Duration,
195    /// The volume, from 0 to 1.
196    pub volume: f32,
197    /// Semitones.
198    pub pitch: f32,
199    /// Defaults to the sound's own loop flag.
200    pub looping: Option<bool>,
201}
202
203impl Default for PlayParams {
204    fn default() -> Self {
205        PlayParams {
206            offset: Duration::ZERO,
207            volume: 1.0,
208            pitch: 0.0,
209            looping: None,
210        }
211    }
212}
213
214#[cfg(not(target_arch = "wasm32"))]
215pub use native::Device;
216#[cfg(target_arch = "wasm32")]
217pub use web::Device;
218
219#[cfg(not(target_arch = "wasm32"))]
220mod native;
221
222#[cfg(target_arch = "wasm32")]
223mod web;
224
225#[cfg(test)]
226mod tests;