Skip to main content

euv_core/game/audio_output/
impl.rs

1use super::*;
2
3/// Human-readable formatting for `AudioOutputError`.
4impl fmt::Display for AudioOutputError {
5    /// Formats an `AudioOutputError` diagnostic message.
6    ///
7    /// # Arguments
8    ///
9    /// - `&mut Formatter<'_>` - Output formatter.
10    ///
11    /// # Returns
12    ///
13    /// - `fmt::Result` - Formatting status.
14    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
15        match self {
16            Self::DriverUnavailable => formatter.write_str(AUDIO_ERR_DRIVER_UNAVAILABLE),
17            Self::InitializationFailed(code) => {
18                write!(formatter, "{AUDIO_ERR_COREAUDIO_INIT} (OSStatus={code})")
19            }
20            Self::StartFailed(code) => {
21                write!(formatter, "{AUDIO_ERR_COREAUDIO_START} (OSStatus={code})")
22            }
23        }
24    }
25}
26
27/// Standard `Error` implementation for `AudioOutputError`.
28impl Error for AudioOutputError {}
29
30/// Default stereo `48 kHz` audio mixer configuration.
31impl Default for AudioOutputConfig {
32    /// Creates a default stereo `48 kHz` `AudioOutputConfig`.
33    ///
34    /// # Returns
35    ///
36    /// - `Self` - Ready stereo audio configuration.
37    fn default() -> Self {
38        Self::new(
39            DEFAULT_AUDIO_SAMPLE_RATE_HZ,
40            DEFAULT_AUDIO_CHANNELS,
41            DEFAULT_AUDIO_RING_FRAMES,
42            DEFAULT_AUDIO_MAX_VOICES,
43            0.85,
44        )
45    }
46}
47
48/// Sanitization helpers for `AudioOutputConfig`.
49impl AudioOutputConfig {
50    /// Returns a clamped copy with valid sample rate, stereo channels, ring capacity, voice cap, and finite gain.
51    ///
52    /// # Returns
53    ///
54    /// - `Self` - Sanitized configuration safe for DSP and hardware drivers.
55    #[must_use]
56    pub fn sanitized(&self) -> Self {
57        let rate: u32 = self
58            .get_sample_rate_hz()
59            .clamp(MIN_AUDIO_SAMPLE_RATE_HZ, MAX_AUDIO_SAMPLE_RATE_HZ);
60        let ring: usize = self.get_ring_frames().max(64);
61        let voices: usize = self.get_max_voices().clamp(1, 256);
62        let gain: f32 = if self.get_master_gain().is_finite() {
63            self.get_master_gain().clamp(0.0, 2.0)
64        } else {
65            0.85
66        };
67        Self::new(rate, DEFAULT_AUDIO_CHANNELS, ring, voices, gain)
68    }
69}
70
71/// Stereo interleaved `f32` ring-buffer producer and consumer operations.
72impl StereoPcmRingBuffer {
73    /// Allocates a zero-filled stereo ring buffer with `capacity_frames` stereo frames.
74    ///
75    /// # Arguments
76    ///
77    /// - `usize` - Stereo frame capacity (clamped to `>= 64`).
78    ///
79    /// # Returns
80    ///
81    /// - `Self` - Empty stereo PCM ring buffer.
82    #[must_use]
83    pub(crate) fn with_capacity(capacity_frames: usize) -> Self {
84        let frames: usize = capacity_frames.max(64);
85        Self {
86            samples: vec![0.0; frames.saturating_mul(2)],
87            capacity_frames: frames,
88            read_frame: 0,
89            write_frame: 0,
90            buffered_frames: 0,
91            overruns: 0,
92            underruns: 0,
93        }
94    }
95
96    /// Pushes one stereo `(left, right)` frame into the ring buffer, overwriting the oldest frame on overrun.
97    ///
98    /// # Arguments
99    ///
100    /// - `f32` - Left channel sample.
101    /// - `f32` - Right channel sample.
102    pub(crate) fn push_stereo_frame(&mut self, left: f32, right: f32) {
103        let capacity: usize = self.get_capacity_frames();
104        let write_idx: usize = self.get_write_frame();
105        let sample_offset: usize = write_idx.saturating_mul(2);
106        let samples_mut: &mut Vec<f32> = self.get_mut_samples();
107        if sample_offset + 1 < samples_mut.len() {
108            samples_mut[sample_offset] = left;
109            samples_mut[sample_offset + 1] = right;
110        }
111        let next_write: usize = (write_idx + 1) % capacity;
112        self.set_write_frame(next_write);
113        let buffered: usize = self.get_buffered_frames();
114        if buffered >= capacity {
115            let next_read: usize = (self.get_read_frame() + 1) % capacity;
116            self.set_read_frame(next_read);
117            let next_overruns: u64 = self.get_overruns().saturating_add(1);
118            self.set_overruns(next_overruns);
119        } else {
120            self.set_buffered_frames(buffered.saturating_add(1));
121        }
122    }
123
124    /// Pops one stereo `(left, right)` frame from the ring buffer, or returns `None` when empty.
125    ///
126    /// # Returns
127    ///
128    /// - `Option<(f32, f32)>` - Next buffered stereo frame, or `None` on empty ring.
129    pub(crate) fn pop_stereo_frame(&mut self) -> Option<(f32, f32)> {
130        let buffered: usize = self.get_buffered_frames();
131        if buffered == 0 {
132            return None;
133        }
134        let capacity: usize = self.get_capacity_frames();
135        let read_idx: usize = self.get_read_frame();
136        let sample_offset: usize = read_idx.saturating_mul(2);
137        let left: f32 = self
138            .get_samples()
139            .get(sample_offset)
140            .copied()
141            .unwrap_or(0.0);
142        let right: f32 = self
143            .get_samples()
144            .get(sample_offset + 1)
145            .copied()
146            .unwrap_or(0.0);
147        self.set_read_frame((read_idx + 1) % capacity);
148        self.set_buffered_frames(buffered.saturating_sub(1));
149        Some((left, right))
150    }
151
152    /// Clears all buffered stereo frames without reallocating backing storage.
153    pub(crate) fn clear(&mut self) {
154        self.set_read_frame(0);
155        self.set_write_frame(0);
156        self.set_buffered_frames(0);
157        self.get_mut_samples().fill(0.0);
158    }
159}
160
161/// Polyphonic voice synthesis, gain/pan mixing, and ring-buffer management for `AudioMixerCore`.
162impl AudioMixerCore {
163    /// Creates an initialized `AudioMixerCore` from `config`.
164    ///
165    /// # Arguments
166    ///
167    /// - `AudioOutputConfig` - Sanitized stereo mixer configuration.
168    ///
169    /// # Returns
170    ///
171    /// - `Self` - Ready polyphonic mixer core.
172    #[must_use]
173    pub(crate) fn from_config(config: AudioOutputConfig) -> Self {
174        let clean_config: AudioOutputConfig = config.sanitized();
175        Self {
176            config: clean_config,
177            voices: Vec::with_capacity(clean_config.get_max_voices()),
178            ring: StereoPcmRingBuffer::with_capacity(clean_config.get_ring_frames()),
179            muted: false,
180            next_birth_order: 1,
181            frames_mixed: 0,
182            commands_ingested: 0,
183            clipped_samples: 0,
184            peak_amplitude: 0.0,
185        }
186    }
187
188    /// Spawns a synthesized voice for `command`, stealing the oldest voice when polyphony is saturated.
189    ///
190    /// # Arguments
191    ///
192    /// - `AudioCommand` - Spatialized cue command drained from `AudioBus`.
193    pub(crate) fn enqueue_command(&mut self, command: AudioCommand) {
194        let next_ingested: u64 = self.get_commands_ingested().saturating_add(1);
195        self.set_commands_ingested(next_ingested);
196        let raw_volume: f32 = if command.get_volume().is_finite() {
197            command.get_volume().clamp(0.0, 2.0)
198        } else {
199            0.0
200        };
201        if raw_volume <= 0.0001 {
202            return;
203        }
204        let pitch: f32 = if command.get_pitch().is_finite() {
205            command.get_pitch().clamp(0.25, 4.0)
206        } else {
207            1.0
208        };
209        let (pan_left, pan_right): (f32, f32) = equal_power_stereo_gains(command.get_pan());
210        let (_, duration_ms): (f32, u32) = cue_synth_params(command.get_cue());
211        let sample_rate: u32 = self.get_config().get_sample_rate_hz();
212        let duration_frames: u32 =
213            ((sample_rate as u64).saturating_mul(duration_ms as u64) / 1_000).max(16) as u32;
214        let birth_order: u64 = self.get_next_birth_order();
215        self.set_next_birth_order(birth_order.saturating_add(1));
216        let seed: u32 = ((birth_order as u32).wrapping_mul(747_796_405)) ^ 0xA5A5_5A5A;
217        let voice: AudioSynthVoice = AudioSynthVoice {
218            cue: command.get_cue(),
219            left_gain: raw_volume * pan_left,
220            right_gain: raw_volume * pan_right,
221            pitch,
222            phase: 0.0,
223            elapsed_frames: 0,
224            duration_frames,
225            noise_state: seed.max(1),
226            birth_order,
227        };
228        let max_voices: usize = self.get_config().get_max_voices();
229        let voices: &mut Vec<AudioSynthVoice> = self.get_mut_voices();
230        if voices.len() >= max_voices {
231            if let Some((oldest_idx, _)) = voices.iter().enumerate().min_by_key(
232                |(_, candidate): &(usize, &AudioSynthVoice)| candidate.get_birth_order(),
233            ) {
234                voices[oldest_idx] = voice;
235            }
236        } else {
237            voices.push(voice);
238        }
239    }
240
241    /// Synthesizes one stereo `(left, right)` frame across all active voices with soft-knee limiting.
242    ///
243    /// # Returns
244    ///
245    /// - `(f32, f32)` - Bounded finite stereo PCM sample pair in `[-1.0, 1.0]`.
246    pub(crate) fn render_next_stereo_frame(&mut self) -> (f32, f32) {
247        let sample_rate_hz: f32 = self.get_config().get_sample_rate_hz() as f32;
248        let master_gain: f32 = if self.get_muted() {
249            0.0
250        } else {
251            self.get_config().get_master_gain()
252        };
253        let mut left_sum: f32 = 0.0;
254        let mut right_sum: f32 = 0.0;
255        for voice in self.get_mut_voices().iter_mut() {
256            let mono: f32 = synthesize_voice_sample(voice, sample_rate_hz);
257            left_sum += mono * voice.get_left_gain();
258            right_sum += mono * voice.get_right_gain();
259        }
260        self.get_mut_voices().retain(|voice: &AudioSynthVoice| {
261            voice.get_elapsed_frames() < voice.get_duration_frames()
262        });
263        let (left_out, left_clipped): (f32, bool) = soft_limit_pcm_sample(left_sum * master_gain);
264        let (right_out, right_clipped): (f32, bool) =
265            soft_limit_pcm_sample(right_sum * master_gain);
266        let clip_inc: u64 = (left_clipped as u64) + (right_clipped as u64);
267        if clip_inc > 0 {
268            let next_clipped: u64 = self.get_clipped_samples().saturating_add(clip_inc);
269            self.set_clipped_samples(next_clipped);
270        }
271        let frame_peak: f32 = left_out.abs().max(right_out.abs());
272        if frame_peak > self.get_peak_amplitude() {
273            self.set_peak_amplitude(frame_peak);
274        }
275        let next_frames: u64 = self.get_frames_mixed().saturating_add(1);
276        self.set_frames_mixed(next_frames);
277        (left_out, right_out)
278    }
279
280    /// Synthesizes `frames` stereo frames from active voices and appends them to the internal ring buffer.
281    ///
282    /// # Arguments
283    ///
284    /// - `usize` - Number of stereo frames to render into the ring buffer.
285    ///
286    /// # Returns
287    ///
288    /// - `usize` - Number of stereo frames mixed.
289    pub(crate) fn mix_into_ring(&mut self, frames: usize) -> usize {
290        for _ in 0..frames {
291            let (left, right): (f32, f32) = self.render_next_stereo_frame();
292            self.get_mut_ring().push_stereo_frame(left, right);
293        }
294        frames
295    }
296
297    /// Fills `interleaved_output` (`[L0, R0, L1, R1, ...]`) by draining buffered ring frames first and mixing live voices for any remainder.
298    ///
299    /// # Arguments
300    ///
301    /// - `&mut [f32]` - Interleaved stereo destination slice.
302    ///
303    /// # Returns
304    ///
305    /// - `usize` - Number of complete stereo frames written.
306    pub(crate) fn pull_interleaved_stereo(&mut self, interleaved_output: &mut [f32]) -> usize {
307        let total_frames: usize = interleaved_output.len() / 2;
308        for frame_index in 0..total_frames {
309            let (left, right): (f32, f32) =
310                if let Some(buffered) = self.get_mut_ring().pop_stereo_frame() {
311                    buffered
312                } else if !self.get_voices().is_empty() {
313                    self.render_next_stereo_frame()
314                } else {
315                    let next_underruns: u64 = self.get_ring().get_underruns().saturating_add(1);
316                    self.get_mut_ring().set_underruns(next_underruns);
317                    (0.0, 0.0)
318                };
319            let base: usize = frame_index.saturating_mul(2);
320            interleaved_output[base] = left;
321            interleaved_output[base + 1] = right;
322        }
323        if interleaved_output.len() % 2 == 1
324            && let Some(trailing) = interleaved_output.last_mut()
325        {
326            *trailing = 0.0;
327        }
328        total_frames
329    }
330}
331
332/// Safe RAII CoreAudio AUHAL teardown on drop.
333#[cfg(target_os = "macos")]
334impl Drop for CoreAudioAuhalHandle {
335    /// Stops and disposes the native CoreAudio `AudioUnit` and frees its callback context.
336    fn drop(&mut self) {
337        dispose_coreaudio_auhal(self);
338    }
339}
340
341/// Cross-platform native driver lifecycle management on `NativeAudioDriverSlot`.
342impl NativeAudioDriverSlot {
343    /// Stops and releases any active native OS audio output driver handle.
344    pub(crate) fn stop_native(&mut self) {
345        #[cfg(target_os = "macos")]
346        {
347            self.set_coreaudio(None);
348        }
349        #[cfg(not(target_os = "macos"))]
350        {
351            self.set_active(false);
352        }
353    }
354}
355
356/// Structured `Debug` formatting for `AudioOutputBackend`.
357impl fmt::Debug for AudioOutputBackend {
358    /// Formats `AudioOutputBackend` driver, state, and live mixer telemetry.
359    ///
360    /// # Arguments
361    ///
362    /// - `&mut Formatter<'_>` - Output formatter.
363    ///
364    /// # Returns
365    ///
366    /// - `fmt::Result` - Formatting status.
367    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
368        let metrics: AudioOutputMetrics = self.metrics();
369        write!(
370            formatter,
371            "AudioOutputBackend(driver={:?}, state={:?}, voices={}, frames={})",
372            metrics.get_driver_kind(),
373            metrics.get_state(),
374            metrics.get_active_voices(),
375            metrics.get_frames_mixed(),
376        )
377    }
378}
379
380/// Default pull-mode `AudioOutputBackend` ready for cross-platform deterministic mixing.
381impl Default for AudioOutputBackend {
382    /// Creates a default pull-mode `AudioOutputBackend`.
383    ///
384    /// # Returns
385    ///
386    /// - `Self` - Running stereo `48 kHz` pull mixer.
387    fn default() -> Self {
388        Self::new_pull_mixer(AudioOutputConfig::default())
389    }
390}
391
392/// Safe teardown stopping any active hardware driver on `AudioOutputBackend` drop.
393impl Drop for AudioOutputBackend {
394    /// Ensures native OS audio handles are cleanly stopped and disposed on drop.
395    fn drop(&mut self) {
396        self.stop();
397    }
398}
399
400/// Production `AudioBus` ingestion, stereo PCM ring-buffer mixing, and native CoreAudio AUHAL startup for `AudioOutputBackend`.
401impl AudioOutputBackend {
402    /// Creates a deterministic cross-platform pull-mode stereo PCM mixer backend.
403    ///
404    /// # Arguments
405    ///
406    /// - `AudioOutputConfig` - Requested audio sample rate, ring size, polyphony, and master gain.
407    ///
408    /// # Returns
409    ///
410    /// - `Self` - Running pull-mode stereo PCM mixer.
411    #[must_use]
412    pub fn new_pull_mixer(config: AudioOutputConfig) -> Self {
413        let clean: AudioOutputConfig = config.sanitized();
414        let core: Arc<Mutex<AudioMixerCore>> =
415            Arc::new(Mutex::new(AudioMixerCore::from_config(clean)));
416        Self {
417            config: clean,
418            core,
419            driver_kind: AudioDriverKind::PullMixer,
420            state: AudioOutputState::Running,
421            native_slot: NativeAudioDriverSlot::default(),
422        }
423    }
424
425    /// Initializes and starts a real native OS hardware audio driver (CoreAudio AUHAL on macOS).
426    ///
427    /// # Arguments
428    ///
429    /// - `AudioOutputConfig` - Requested stereo audio stream configuration.
430    ///
431    /// # Returns
432    ///
433    /// - `Result<Self, AudioOutputError>` - Running native hardware audio backend or explicit error.
434    pub fn start_native(config: AudioOutputConfig) -> Result<Self, AudioOutputError> {
435        let clean: AudioOutputConfig = config.sanitized();
436        #[cfg(target_os = "macos")]
437        {
438            let core: Arc<Mutex<AudioMixerCore>> =
439                Arc::new(Mutex::new(AudioMixerCore::from_config(clean)));
440            let handle: CoreAudioAuhalHandle = open_coreaudio_auhal(clean, Arc::clone(&core))?;
441            let mut slot: NativeAudioDriverSlot = NativeAudioDriverSlot::default();
442            slot.set_coreaudio(Some(handle));
443            Ok(Self {
444                config: clean,
445                core,
446                driver_kind: AudioDriverKind::CoreAudioAuhal,
447                state: AudioOutputState::Running,
448                native_slot: slot,
449            })
450        }
451        #[cfg(not(target_os = "macos"))]
452        {
453            let _: AudioOutputConfig = clean;
454            Err(AudioOutputError::DriverUnavailable)
455        }
456    }
457
458    /// Drains all pending `AudioCommand` items from `bus` into active mixer voices while syncing mute state.
459    ///
460    /// # Arguments
461    ///
462    /// - `&mut AudioBus` - Source game audio bus drained in place.
463    ///
464    /// # Returns
465    ///
466    /// - `usize` - Number of audio commands ingested from `bus`.
467    pub fn ingest_bus(&mut self, bus: &mut AudioBus) -> usize {
468        let commands: Vec<AudioCommand> = bus.drain();
469        let count: usize = commands.len();
470        let bus_muted: bool = bus.get_muted();
471        if let Ok(mut guard) = self.get_core().lock() {
472            guard.set_muted(bus_muted);
473            for command in commands {
474                guard.enqueue_command(command);
475            }
476        }
477        count
478    }
479
480    /// Enqueues a single spatialized `AudioCommand` directly into the mixer voice pool.
481    ///
482    /// # Arguments
483    ///
484    /// - `AudioCommand` - Audio command specifying cue, volume, pan, and pitch.
485    pub fn enqueue_command(&mut self, command: AudioCommand) {
486        if let Ok(mut guard) = self.get_core().lock() {
487            guard.enqueue_command(command);
488        }
489    }
490
491    /// Synthesizes `frames` stereo PCM frames into the internal ring buffer for asynchronous playback or inspection.
492    ///
493    /// # Arguments
494    ///
495    /// - `usize` - Number of stereo frames to mix into the ring buffer.
496    ///
497    /// # Returns
498    ///
499    /// - `usize` - Number of stereo frames mixed.
500    pub fn mix_into_ring(&mut self, frames: usize) -> usize {
501        if self.get_state() != AudioOutputState::Running || frames == 0 {
502            return 0;
503        }
504        if let Ok(mut guard) = self.get_core().lock() {
505            guard.mix_into_ring(frames)
506        } else {
507            0
508        }
509    }
510
511    /// Pulls interleaved stereo `f32` PCM samples (`[L0, R0, L1, R1, ...]`) bounded strictly in `[-1.0, 1.0]`.
512    ///
513    /// # Arguments
514    ///
515    /// - `&mut [f32]` - Interleaved stereo destination slice.
516    ///
517    /// # Returns
518    ///
519    /// - `usize` - Number of stereo frames written to `output`.
520    pub fn pull_interleaved_f32(&mut self, output: &mut [f32]) -> usize {
521        if self.get_state() != AudioOutputState::Running {
522            output.fill(0.0);
523            return output.len() / 2;
524        }
525        if let Ok(mut guard) = self.get_core().lock() {
526            guard.pull_interleaved_stereo(output)
527        } else {
528            output.fill(0.0);
529            output.len() / 2
530        }
531    }
532
533    /// Updates the mixer master linear output gain (clamped to `[0.0, 2.0]`).
534    ///
535    /// # Arguments
536    ///
537    /// - `f32` - Target master linear gain.
538    pub fn set_master_gain(&mut self, gain: f32) {
539        let clamped: f32 = if gain.is_finite() {
540            gain.clamp(0.0, 2.0)
541        } else {
542            0.0
543        };
544        let mut next_config: AudioOutputConfig = self.get_config();
545        next_config.set_master_gain(clamped);
546        self.set_config(next_config);
547        if let Ok(mut guard) = self.get_core().lock() {
548            guard.set_config(next_config);
549        }
550    }
551
552    /// Toggles global audio mixer muting without stopping active voice progression.
553    ///
554    /// # Arguments
555    ///
556    /// - `bool` - `true` to mute output to silence, `false` to unmute.
557    pub fn set_muted(&mut self, muted: bool) {
558        if let Ok(mut guard) = self.get_core().lock() {
559            guard.set_muted(muted);
560        }
561    }
562
563    /// Pauses output rendering without discarding queued voices or buffered frames.
564    pub fn pause(&mut self) {
565        if self.get_state() == AudioOutputState::Running {
566            self.set_state(AudioOutputState::Paused);
567        }
568    }
569
570    /// Resumes a paused pull-mode mixer backend.
571    pub fn resume(&mut self) {
572        if self.get_state() == AudioOutputState::Paused {
573            self.set_state(AudioOutputState::Running);
574        }
575    }
576
577    /// Stops any native OS audio driver, clears buffered PCM frames, and transitions to `Stopped`.
578    pub fn stop(&mut self) {
579        self.get_mut_native_slot().stop_native();
580        if let Ok(mut guard) = self.get_core().lock() {
581            guard.get_mut_voices().clear();
582            guard.get_mut_ring().clear();
583        }
584        self.set_state(AudioOutputState::Stopped);
585    }
586
587    /// Captures a live telemetry snapshot of driver status, voice count, ring fill, underruns, and peak amplitude.
588    ///
589    /// # Returns
590    ///
591    /// - `AudioOutputMetrics` - Current audio output telemetry snapshot.
592    #[must_use]
593    pub fn metrics(&self) -> AudioOutputMetrics {
594        let driver: AudioDriverKind = self.get_driver_kind();
595        let state: AudioOutputState = self.get_state();
596        if let Ok(guard) = self.get_core().lock() {
597            AudioOutputMetrics {
598                driver_kind: driver,
599                state,
600                active_voices: guard.get_voices().len(),
601                frames_mixed: guard.get_frames_mixed(),
602                commands_ingested: guard.get_commands_ingested(),
603                ring_buffered_frames: guard.get_ring().get_buffered_frames(),
604                ring_underruns: guard.get_ring().get_underruns(),
605                ring_overruns: guard.get_ring().get_overruns(),
606                clipped_samples: guard.get_clipped_samples(),
607                peak_amplitude: guard.get_peak_amplitude(),
608            }
609        } else {
610            AudioOutputMetrics {
611                driver_kind: driver,
612                state,
613                ..AudioOutputMetrics::default()
614            }
615        }
616    }
617}