euv_core/game/audio_output/
impl.rs1use super::*;
2
3impl fmt::Display for AudioOutputError {
5 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
27impl Error for AudioOutputError {}
29
30impl Default for AudioOutputConfig {
32 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
48impl AudioOutputConfig {
50 #[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
71impl StereoPcmRingBuffer {
73 #[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 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 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 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
161impl AudioMixerCore {
163 #[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 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 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 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 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#[cfg(target_os = "macos")]
334impl Drop for CoreAudioAuhalHandle {
335 fn drop(&mut self) {
337 dispose_coreaudio_auhal(self);
338 }
339}
340
341impl NativeAudioDriverSlot {
343 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
356impl fmt::Debug for AudioOutputBackend {
358 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
380impl Default for AudioOutputBackend {
382 fn default() -> Self {
388 Self::new_pull_mixer(AudioOutputConfig::default())
389 }
390}
391
392impl Drop for AudioOutputBackend {
394 fn drop(&mut self) {
396 self.stop();
397 }
398}
399
400impl AudioOutputBackend {
402 #[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 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 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 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 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 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 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 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 pub fn pause(&mut self) {
565 if self.get_state() == AudioOutputState::Running {
566 self.set_state(AudioOutputState::Paused);
567 }
568 }
569
570 pub fn resume(&mut self) {
572 if self.get_state() == AudioOutputState::Paused {
573 self.set_state(AudioOutputState::Running);
574 }
575 }
576
577 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 #[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}