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