ferravex_render/audio/
mod.rs

1//! Shared runtime audio. Rust owns clips, voices and mixing; hosts consume PCM.
2use crate::prelude::{Vec3, vec3};
3pub use ferravex_play::audio::*;
4use std::cell::{Cell, RefCell};
5use std::rc::Rc;
6pub mod batch;
7#[cfg(not(target_arch = "wasm32"))]
8mod capture;
9mod game;
10mod score;
11pub use score::AdaptiveScore;
12#[cfg(not(target_arch = "wasm32"))]
13mod native;
14pub use game::GameAudio;
15pub const SAMPLE_RATE: u32 = 48000;
16pub const MAX_PULL_FRAMES: usize = 4096;
17struct Audio {
18    identity: Rc<()>,
19    mixer: Mixer,
20    bank: Option<SoundBank>,
21    fraction: f64,
22}
23thread_local! {
24    static AUDIO:RefCell<Option<Audio>>=const {RefCell::new(None)};
25    static MUTED:Cell<bool>=const {Cell::new(false)};
26    static GAIN:Cell<f32>=const {Cell::new(0.7)};
27    static BROWSER_RUNNING:Cell<bool>=const {Cell::new(false)};
28    static PCM:RefCell<Vec<[f32;2]>>=const {RefCell::new(Vec::new())};
29    static OFFLINE:Cell<bool>=const {Cell::new(false)};
30}
31fn initialize() {
32    AUDIO.with(|cell| {
33        let mut state = cell.borrow_mut();
34        if state.is_none() {
35            *state = Some(Audio {
36                identity: Rc::new(()),
37                mixer: Mixer::new(SAMPLE_RATE, 64).unwrap(),
38                bank: None,
39                fraction: 0.,
40            });
41        }
42    });
43}
44pub(crate) fn reset() {
45    AUDIO.with(|a| *a.borrow_mut() = None);
46    BROWSER_RUNNING.with(|v| v.set(false));
47}
48pub fn muted() -> bool {
49    MUTED.with(Cell::get)
50}
51pub fn set_muted(value: bool) {
52    if value && !muted() {
53        suspend();
54    }
55    MUTED.with(|v| v.set(value));
56}
57pub fn suspend() {
58    AUDIO.with(|a| {
59        if let Some(a) = a.borrow_mut().as_mut() {
60            a.mixer.suspend();
61        }
62    });
63}
64pub(crate) fn focus_lost() {
65    if !OFFLINE.with(Cell::get) {
66        suspend();
67    }
68}
69pub fn master_gain() -> f32 {
70    GAIN.with(Cell::get)
71}
72pub fn bus_gains() -> [f32; 4] {
73    AUDIO.with(|a| {
74        a.borrow().as_ref().map_or([1.; 4], |a| {
75            [Bus::Effects, Bus::Ambience, Bus::Music, Bus::Ui].map(|bus| a.mixer.bus_gain(bus))
76        })
77    })
78}
79pub fn set_master_gain(value: f32) -> bool {
80    if !value.is_finite() || !(0. ..=1.).contains(&value) {
81        return false;
82    }
83    GAIN.with(|v| v.set(value));
84    true
85}
86pub fn set_bus_gain(bus: Bus, value: f32) -> bool {
87    initialize();
88    AUDIO.with(|a| {
89        a.borrow_mut()
90            .as_mut()
91            .unwrap()
92            .mixer
93            .set_bus_gain(bus, value)
94    })
95}
96pub fn listener(position: Vec3, right: Vec3) -> bool {
97    if !position.is_finite() || !right.is_finite() || right.length_squared() < 1e-8 {
98        return false;
99    }
100    initialize();
101    AUDIO.with(|a| {
102        let mut a = a.borrow_mut();
103        let m = &mut a.as_mut().unwrap().mixer;
104        m.listener = position.to_array();
105        m.right = right.normalize().to_array();
106    });
107    true
108}
109/// Generate the built-in bank outside a frame/audio callback when desired.
110pub fn preload_cues() {
111    initialize();
112    AUDIO.with(|a| {
113        let mut a = a.borrow_mut();
114        a.as_mut()
115            .unwrap()
116            .bank
117            .get_or_insert_with(|| SoundBank::procedural(24000).unwrap());
118    });
119}
120pub fn play_sound(sound: &Sound, params: VoiceParams) -> Option<VoiceHandle> {
121    initialize();
122    AUDIO.with(|a| a.borrow_mut().as_mut().unwrap().mixer.start(sound, params))
123}
124pub fn stop_all() {
125    AUDIO.with(|a| {
126        if let Some(a) = a.borrow_mut().as_mut() {
127            a.mixer.stop_all();
128        }
129    });
130}
131pub fn play(cue: Cue, params: VoiceParams) -> Option<VoiceHandle> {
132    initialize();
133    AUDIO.with(|cell| {
134        let mut state = cell.borrow_mut();
135        let Audio { mixer, bank, .. } = state.as_mut().unwrap();
136        let bank = bank.get_or_insert_with(|| SoundBank::procedural(24000).unwrap());
137        mixer.start(bank.get(cue), params)
138    })
139}
140pub fn set_params(voice: VoiceHandle, params: VoiceParams) -> bool {
141    AUDIO.with(|a| {
142        a.borrow_mut()
143            .as_mut()
144            .is_some_and(|a| a.mixer.set_params(voice, params))
145    })
146}
147pub fn playing(voice: VoiceHandle) -> bool {
148    AUDIO.with(|a| {
149        a.borrow()
150            .as_ref()
151            .is_some_and(|a| a.mixer.params(voice).is_some())
152    })
153}
154pub fn stop(voice: VoiceHandle, fade_frames: u32) -> bool {
155    AUDIO.with(|a| {
156        a.borrow_mut()
157            .as_mut()
158            .is_some_and(|a| a.mixer.stop(voice, fade_frames))
159    })
160}
161pub fn stats() -> MixStats {
162    AUDIO.with(|a| {
163        a.borrow()
164            .as_ref()
165            .map_or(MixStats::default(), |a| a.mixer.stats())
166    })
167}
168fn audible() -> bool {
169    !muted() && (OFFLINE.with(Cell::get) || crate::read(|s| s.input.focused && !s.controls_open))
170}
171/// For a host output callback, limited to 4096 frames and a valid device rate.
172/// This runs on the game/Wasm thread; devices never borrow this mixer directly.
173pub fn render(out: &mut [[f32; 2]], rate: u32) -> bool {
174    if out.len() > MAX_PULL_FRAMES || !(8000..=96000).contains(&rate) {
175        out.fill([0.; 2]);
176        return false;
177    }
178    let gain = if audible() { GAIN.with(Cell::get) } else { 0. };
179    AUDIO.with(|a| {
180        let mut a = a.borrow_mut();
181        let Some(a) = a.as_mut() else {
182            out.fill([0.; 2]);
183            return true;
184        };
185        a.mixer.set_sample_rate(rate);
186        a.mixer.set_master_gain(gain);
187        a.mixer.render(out);
188        true
189    })
190}
191fn skip(dt: f32) {
192    if !dt.is_finite() {
193        return;
194    }
195    AUDIO.with(|a| {
196        if let Some(a) = a.borrow_mut().as_mut() {
197            let frames =
198                f64::from(dt.clamp(0., 0.1)) * f64::from(a.mixer.sample_rate()) + a.fraction;
199            a.fraction = frames.fract();
200            a.mixer.skip(frames as u32);
201        }
202    });
203}
204#[cfg(not(target_arch = "wasm32"))]
205struct Output {
206    device: Option<native::Output>,
207    offline: bool,
208    enabled: bool,
209    paused: bool,
210    retry_in: f32,
211    fraction: f64,
212    capture: Option<capture::Capture>,
213}
214#[cfg(not(target_arch = "wasm32"))]
215thread_local! {static OUTPUT:RefCell<Option<Output>>=const {RefCell::new(None)};}
216#[cfg(not(target_arch = "wasm32"))]
217pub(crate) fn boot_native(offline: bool) {
218    OFFLINE.with(|v| v.set(offline));
219    OUTPUT.with(|output| {
220        let capture =
221            std::env::var_os("FERRAVEX_AUDIO_CAPTURE").and_then(
222                |path| match capture::Capture::new(std::path::Path::new(&path)) {
223                    Ok(capture) => Some(capture),
224                    Err(error) => {
225                        eprintln!("Ferravex audio capture unavailable: {error}");
226                        None
227                    }
228                },
229            );
230        let enabled = !offline && std::env::var("FERRAVEX_AUDIO").ok().as_deref() != Some("off");
231        let device = if enabled {
232            Some(native::Output::new(
233                std::env::var("FERRAVEX_AUDIO_DEVICE").unwrap_or_else(|_| "default".into()),
234            ))
235        } else {
236            None
237        };
238        *output.borrow_mut() = Some(Output {
239            #[cfg(not(target_arch = "wasm32"))]
240            device,
241            offline,
242            enabled,
243            paused: false,
244            retry_in: 2.,
245            fraction: 0.,
246            capture,
247        });
248    });
249}
250#[cfg(not(target_arch = "wasm32"))]
251pub(crate) fn shutdown_native() {
252    OFFLINE.with(|v| v.set(false));
253    OUTPUT.with(|o| *o.borrow_mut() = None);
254}
255#[cfg(not(target_arch = "wasm32"))]
256pub(crate) fn suspend_native() {
257    #[cfg(not(target_arch = "wasm32"))]
258    OUTPUT.with(|o| {
259        if let Some(o) = o.borrow_mut().as_mut() {
260            o.device = None;
261            o.paused = true;
262        }
263    });
264}
265#[cfg(not(target_arch = "wasm32"))]
266pub(crate) fn resume_native() {
267    #[cfg(not(target_arch = "wasm32"))]
268    OUTPUT.with(|o| {
269        if let Some(o) = o.borrow_mut().as_mut() {
270            o.paused = false;
271        }
272        if let Some(o) = o.borrow_mut().as_mut()
273            && o.enabled
274            && o.device.is_none()
275        {
276            o.device = Some(native::Output::new(
277                std::env::var("FERRAVEX_AUDIO_DEVICE").unwrap_or_else(|_| "default".into()),
278            ));
279        }
280    });
281}
282#[derive(Clone, Copy, Debug, PartialEq, Eq)]
283pub struct OutputStats {
284    pub ready: bool,
285    pub error: i32,
286    pub written_frames: usize,
287    pub xruns: usize,
288}
289#[cfg(not(target_arch = "wasm32"))]
290pub fn output_stats() -> OutputStats {
291    OUTPUT.with(|o| {
292        #[cfg(not(target_arch = "wasm32"))]
293        if let Some(device) = o.borrow().as_ref().and_then(|o| o.device.as_ref()) {
294            let status = device.status();
295            return OutputStats {
296                ready: status == 1,
297                error: status.min(0),
298                written_frames: device.written_frames(),
299                xruns: device.xruns(),
300            };
301        }
302        OutputStats {
303            ready: false,
304            error: 0,
305            written_frames: 0,
306            xruns: 0,
307        }
308    })
309}
310#[cfg(target_arch = "wasm32")]
311pub fn output_stats() -> OutputStats {
312    OutputStats {
313        ready: BROWSER_RUNNING.with(Cell::get),
314        error: 0,
315        written_frames: stats().rendered_frames as usize,
316        xruns: 0,
317    }
318}
319pub(crate) fn end_frame(dt: f32) {
320    #[cfg(target_arch = "wasm32")]
321    if !BROWSER_RUNNING.with(Cell::get) {
322        skip(dt);
323    }
324    #[cfg(not(target_arch = "wasm32"))]
325    OUTPUT.with(|cell| {
326        let mut output = cell.borrow_mut();
327        let Some(output) = output.as_mut() else {
328            skip(dt);
329            return;
330        };
331        if output.offline {
332            let frames = f64::from(dt.clamp(0., 0.1)) * f64::from(SAMPLE_RATE) + output.fraction;
333            output.fraction = frames.fract();
334            let mut left = frames as usize;
335            let mut block = [[0.; 2]; 512];
336            while left > 0 {
337                let len = left.min(block.len());
338                render(&mut block[..len], SAMPLE_RATE);
339                if let Some(capture) = &mut output.capture {
340                    capture.write(&block[..len]);
341                }
342                left -= len;
343            }
344            return;
345        }
346        if output.paused {
347            skip(dt);
348            return;
349        }
350        output.retry_in = (output.retry_in - dt.max(0.)).max(0.);
351        if output.device.as_ref().is_some_and(|d| d.status() < 0) {
352            output.device = None;
353        }
354        if output.device.is_none() && output.retry_in <= 0. && output.enabled {
355            output.device = Some(native::Output::new(
356                std::env::var("FERRAVEX_AUDIO_DEVICE").unwrap_or_else(|_| "default".into()),
357            ));
358            output.retry_in = 2.;
359        }
360        #[cfg(not(target_arch = "wasm32"))]
361        if let Some(device) = &output.device
362            && device.status() == 1
363        {
364            device.pump(|block| {
365                render(block, SAMPLE_RATE);
366                if let Some(capture) = &mut output.capture {
367                    capture.write(block);
368                }
369            });
370            return;
371        }
372        skip(dt);
373    });
374}
375#[cfg(target_arch = "wasm32")]
376mod wasm {
377    use super::*;
378    #[unsafe(no_mangle)]
379    pub extern "C" fn ferravex_audio_state(running: u32) {
380        let previous = BROWSER_RUNNING.with(|v| v.replace(running != 0));
381        if previous && running == 0 {
382            suspend();
383        }
384    }
385    #[unsafe(no_mangle)]
386    pub extern "C" fn ferravex_audio_mute(mute: u32) {
387        set_muted(mute != 0);
388    }
389    #[unsafe(no_mangle)]
390    pub extern "C" fn ferravex_audio_master_gain() -> f32 {
391        master_gain()
392    }
393    #[unsafe(no_mangle)]
394    pub extern "C" fn ferravex_audio_muted() -> u32 {
395        u32::from(muted())
396    }
397    #[unsafe(no_mangle)]
398    pub extern "C" fn ferravex_audio_pcm() -> *const [f32; 2] {
399        PCM.with(|v| v.borrow().as_ptr())
400    }
401    #[unsafe(no_mangle)]
402    pub extern "C" fn ferravex_audio_render(frames: u32, rate: u32) -> u32 {
403        if frames as usize > MAX_PULL_FRAMES || !(8000..=96000).contains(&rate) {
404            return 0;
405        }
406        PCM.with(|pcm| {
407            let mut pcm = pcm.borrow_mut();
408            if pcm.capacity() < MAX_PULL_FRAMES {
409                *pcm = Vec::with_capacity(MAX_PULL_FRAMES);
410            }
411            pcm.resize(frames as usize, [0.; 2]);
412            render(&mut pcm, rate);
413        });
414        frames
415    }
416}
417#[cfg(test)]
418mod tests {
419    use super::*;
420    #[cfg(target_os = "linux")]
421    #[test]
422    #[ignore = "requires the system ALSA null PCM"]
423    fn native_sink_resume_keeps_capture_and_mixer() {
424        if std::env::var_os("FERRAVEX_AUDIO_LIFECYCLE_CHILD").is_none() {
425            let path = std::env::temp_dir()
426                .join(format!("ferravex-audio-resume-{}.wav", std::process::id()));
427            let result = std::process::Command::new(std::env::current_exe().unwrap())
428                .args([
429                    "--exact",
430                    "audio::tests::native_sink_resume_keeps_capture_and_mixer",
431                    "--ignored",
432                ])
433                .env("FERRAVEX_AUDIO_LIFECYCLE_CHILD", "1")
434                .env("FERRAVEX_AUDIO_DEVICE", "null")
435                .env("FERRAVEX_AUDIO", "on")
436                .env("FERRAVEX_AUDIO_CAPTURE", &path)
437                .output()
438                .unwrap();
439            let _ = std::fs::remove_file(path);
440            assert!(
441                result.status.success(),
442                "{}\n{}",
443                String::from_utf8_lossy(&result.stdout),
444                String::from_utf8_lossy(&result.stderr)
445            );
446            return;
447        }
448        let wait = || {
449            let end = std::time::Instant::now() + std::time::Duration::from_secs(2);
450            while !output_stats().ready && std::time::Instant::now() < end {
451                std::thread::sleep(std::time::Duration::from_millis(2));
452            }
453            assert!(output_stats().ready, "{:?}", output_stats());
454        };
455        reset();
456        set_muted(false);
457        set_master_gain(0.32);
458        boot_native(false);
459        wait();
460        play(Cue::Fire, VoiceParams::default()).unwrap();
461        end_frame(1. / 60.);
462        let path = std::path::PathBuf::from(std::env::var_os("FERRAVEX_AUDIO_CAPTURE").unwrap());
463        let before = std::fs::metadata(&path).unwrap().len();
464        assert!(before > 44);
465        suspend_native();
466        assert!(!output_stats().ready);
467        end_frame(1. / 60.);
468        assert_eq!(std::fs::metadata(&path).unwrap().len(), before);
469        resume_native();
470        wait();
471        assert_eq!(master_gain(), 0.32);
472        play(Cue::Fire, VoiceParams::default()).unwrap();
473        end_frame(1. / 60.);
474        shutdown_native();
475        let bytes = std::fs::read(path).unwrap();
476        assert!(
477            bytes.len() > before as usize,
478            "resume must append to the existing capture"
479        );
480        let clip = Clip::wav(&bytes).unwrap();
481        assert_eq!(clip.samples.len() * 4 + 44, bytes.len());
482    }
483    #[test]
484    fn runtime_mute_device_rate_and_reset_are_bounded() {
485        crate::edit(|s| *s = crate::State::default());
486        reset();
487        set_muted(false);
488        play(
489            Cue::Fire,
490            VoiceParams {
491                ramp_frames: 0,
492                ..Default::default()
493            },
494        )
495        .unwrap();
496        let mut out = [[0.; 2]; 128];
497        assert!(render(&mut out, 44100));
498        assert!(out.iter().flatten().any(|v| v.abs() > 0.001));
499        set_muted(true);
500        render(&mut out, 44100);
501        render(&mut out, 44100);
502        assert!(out.iter().flatten().all(|v| v.abs() < 1e-6));
503        assert!(!render(&mut out, 1));
504        assert!(out.iter().flatten().all(|v| *v == 0.));
505        reset();
506        set_muted(false);
507        assert_eq!(stats().active, 0);
508    }
509}