euv-core 0.52.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
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
use super::*;

#[cfg(target_os = "macos")]
#[link(name = "AudioToolbox", kind = "framework")]
unsafe extern "C" {
    /// Locates the next registered CoreAudio component matching `desc`.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Previous component handle or null to start searching.
    /// - `*const AudioComponentDescriptionC` - Desired AudioUnit component description.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Matching `AudioComponent` handle or null.
    fn AudioComponentFindNext(
        in_component: *mut c_void,
        in_desc: *const AudioComponentDescriptionC,
    ) -> *mut c_void;
    /// Instantiates a CoreAudio `AudioUnit` from `in_component`.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Discovered `AudioComponent`.
    /// - `*mut *mut c_void` - Output pointer receiving the instantiated `AudioUnit`.
    ///
    /// # Returns
    ///
    /// - `i32` - `noErr` (`0`) on success.
    fn AudioComponentInstanceNew(in_component: *mut c_void, out_instance: *mut *mut c_void) -> i32;
    /// Disposes an instantiated CoreAudio `AudioUnit`.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Active `AudioUnit` handle.
    ///
    /// # Returns
    ///
    /// - `i32` - `noErr` (`0`) on success.
    fn AudioComponentInstanceDispose(in_instance: *mut c_void) -> i32;
    /// Configures a property on a CoreAudio `AudioUnit`.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Active `AudioUnit`.
    /// - `u32` - Property identifier.
    /// - `u32` - Property scope.
    /// - `u32` - Element/bus index.
    /// - `*const c_void` - Property payload pointer.
    /// - `u32` - Property payload byte size.
    ///
    /// # Returns
    ///
    /// - `i32` - `noErr` (`0`) on success.
    fn AudioUnitSetProperty(
        in_unit: *mut c_void,
        in_id: u32,
        in_scope: u32,
        in_element: u32,
        in_data: *const c_void,
        in_data_size: u32,
    ) -> i32;
    /// Initializes an `AudioUnit` for audio rendering.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Configured `AudioUnit`.
    ///
    /// # Returns
    ///
    /// - `i32` - `noErr` (`0`) on success.
    fn AudioUnitInitialize(in_unit: *mut c_void) -> i32;
    /// Uninitializes an `AudioUnit` prior to disposal.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Initialized `AudioUnit`.
    ///
    /// # Returns
    ///
    /// - `i32` - `noErr` (`0`) on success.
    fn AudioUnitUninitialize(in_unit: *mut c_void) -> i32;
    /// Starts hardware streaming on an output `AudioUnit`.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Initialized output `AudioUnit`.
    ///
    /// # Returns
    ///
    /// - `i32` - `noErr` (`0`) on success.
    fn AudioOutputUnitStart(ci: *mut c_void) -> i32;
    /// Stops hardware streaming on an output `AudioUnit`.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Running output `AudioUnit`.
    ///
    /// # Returns
    ///
    /// - `i32` - `noErr` (`0`) on success.
    fn AudioOutputUnitStop(ci: *mut c_void) -> i32;
}

/// Sanitizes a single PCM float sample by zeroing `NaN`, `±Inf`, and subnormal denormal tails.
///
/// # Arguments
///
/// - `f32` - Raw candidate PCM sample.
///
/// # Returns
///
/// - `f32` - Finite denormal-free sample.
#[must_use]
pub fn sanitize_pcm_sample(sample: f32) -> f32 {
    if !sample.is_finite() || sample.abs() < AUDIO_DENORMAL_EPSILON {
        0.0
    } else {
        sample
    }
}

/// Applies a smooth soft-knee anti-clipping limiter guaranteeing output strictly within `[-1.0, 1.0]`.
///
/// # Arguments
///
/// - `f32` - Unbounded summed stereo sample.
///
/// # Returns
///
/// - `(f32, bool)` - Limited sample in `[-1.0, 1.0]` and whether attenuation was applied.
#[must_use]
pub fn soft_limit_pcm_sample(sample: f32) -> (f32, bool) {
    let clean: f32 = sanitize_pcm_sample(sample);
    let magnitude: f32 = clean.abs();
    if magnitude <= AUDIO_SOFT_KNEE_THRESHOLD {
        return (clean, false);
    }
    let headroom: f32 = 1.0 - AUDIO_SOFT_KNEE_THRESHOLD;
    let excess: f32 = (magnitude - AUDIO_SOFT_KNEE_THRESHOLD) / headroom;
    let compressed: f32 = AUDIO_SOFT_KNEE_THRESHOLD + headroom * excess.tanh();
    let bounded: f32 = compressed.min(1.0).copysign(clean);
    (bounded, magnitude > 1.0)
}

/// Computes constant-power `(left_gain, right_gain)` multipliers for stereo `pan` in `[-1.0, 1.0]`.
///
/// # Arguments
///
/// - `f32` - Stereo pan position (`-1.0` full left, `0.0` center, `+1.0` full right).
///
/// # Returns
///
/// - `(f32, f32)` - Constant-power `(left, right)` linear gain factors.
#[must_use]
pub fn equal_power_stereo_gains(pan: f32) -> (f32, f32) {
    let clamped_pan: f32 = if pan.is_finite() {
        pan.clamp(-1.0, 1.0)
    } else {
        0.0
    };
    let angle: f32 = (clamped_pan + 1.0) * 0.25 * PI;
    (angle.cos().max(0.0), angle.sin().max(0.0))
}

/// Returns the default base frequency (Hz) and nominal duration (ms) for a `SoundCue` preset.
///
/// # Arguments
///
/// - `SoundCue` - Sound cue preset.
///
/// # Returns
///
/// - `(f32, u32)` - Tuple `(base_frequency_hz, duration_ms)`.
#[must_use]
pub(crate) fn cue_synth_params(cue: SoundCue) -> (f32, u32) {
    match cue {
        SoundCue::Laser => (880.0, 140),
        SoundCue::Explosion => (110.0, 320),
        SoundCue::Pickup => (587.33, 180),
        SoundCue::Bounce => (240.0, 95),
        SoundCue::Dash => (340.0, 130),
        SoundCue::UiClick => (1_320.0, 18),
        SoundCue::Custom(id) => {
            let offset_hz: f32 = ((id % 24) as f32) * 32.0;
            (220.0 + offset_hz, 160)
        }
    }
}

/// Synthesizes one mono sample for `voice` and advances its phase, noise seed, and frame counter.
///
/// # Arguments
///
/// - `&mut AudioSynthVoice` - Mutable active voice state.
/// - `f32` - Output sample rate in Hertz.
///
/// # Returns
///
/// - `f32` - Finite mono waveform sample in `[-1.0, 1.0]`.
pub(crate) fn synthesize_voice_sample(voice: &mut AudioSynthVoice, sample_rate_hz: f32) -> f32 {
    let elapsed: u32 = voice.get_elapsed_frames();
    let total: u32 = voice.get_duration_frames().max(1);
    if elapsed >= total {
        return 0.0;
    }
    let progress: f32 = (elapsed as f32) / (total as f32);
    let attack_frames: f32 = (sample_rate_hz * 0.004).max(4.0);
    let attack_env: f32 = ((elapsed as f32) / attack_frames).min(1.0);
    let release_env: f32 = (1.0 - progress).powf(1.5);
    let envelope: f32 = attack_env * release_env;
    let (base_hz, _): (f32, u32) = cue_synth_params(voice.get_cue());
    let pitch: f32 = voice.get_pitch();
    let inst_hz: f32 = match voice.get_cue() {
        SoundCue::Laser => base_hz * pitch * (1.0 - 0.65 * progress).max(0.2),
        SoundCue::Pickup => {
            let step: f32 = if progress < 0.45 { 1.0 } else { 1.5 };
            base_hz * pitch * step
        }
        SoundCue::Bounce => base_hz * pitch * (1.0 - 0.35 * progress),
        SoundCue::Dash => base_hz * pitch * (0.7 + 0.8 * progress),
        SoundCue::Explosion | SoundCue::UiClick | SoundCue::Custom(_) => base_hz * pitch,
    };
    let next_phase: f32 = (voice.get_phase() + TAU * inst_hz / sample_rate_hz) % TAU;
    voice.set_phase(next_phase);
    let next_noise: u32 = voice
        .get_noise_state()
        .wrapping_mul(1_664_525)
        .wrapping_add(1_013_904_223);
    voice.set_noise_state(next_noise);
    let white_noise: f32 = ((next_noise >> 9) as f32 / ((1u32 << 23) as f32)) * 2.0 - 1.0;
    let raw_wave: f32 = match voice.get_cue() {
        SoundCue::Laser => next_phase.sin() * 0.65 + ((next_phase / PI) - 1.0) * 0.35,
        SoundCue::Explosion => white_noise * 0.75 + next_phase.sin() * 0.25,
        SoundCue::Pickup => next_phase.sin() * 0.85 + (next_phase * 2.0).sin() * 0.15,
        SoundCue::Bounce => next_phase.sin(),
        SoundCue::Dash => white_noise * 0.45 + next_phase.sin() * 0.55,
        SoundCue::UiClick => next_phase.sin() * 0.8 + (next_phase * 3.0).sin() * 0.2,
        SoundCue::Custom(_) => next_phase.sin(),
    };
    voice.set_elapsed_frames(elapsed.saturating_add(1));
    sanitize_pcm_sample(raw_wave * envelope)
}

/// Real-time CoreAudio AUHAL render callback filling interleaved stereo `f32` output buffers without blocking.
///
/// # Arguments
///
/// - `*mut c_void` - Opaque pointer to boxed `Arc<Mutex<AudioMixerCore>>`.
/// - `*mut u32` - CoreAudio render action flags pointer.
/// - `*const c_void` - CoreAudio audio timestamp pointer.
/// - `u32` - Output bus number.
/// - `u32` - Requested stereo frame count.
/// - `*mut AudioBufferListC` - Output `AudioBufferList` populated in place.
///
/// # Returns
///
/// - `i32` - `noErr` (`0`) on completion.
#[cfg(target_os = "macos")]
pub(crate) unsafe extern "C" fn coreaudio_render_callback(
    in_ref_con: *mut c_void,
    _io_action_flags: *mut u32,
    _in_time_stamp: *const c_void,
    _in_bus_number: u32,
    in_number_frames: u32,
    io_data: *mut AudioBufferListC,
) -> i32 {
    if io_data.is_null() {
        return 0;
    }
    // SAFETY: CoreAudio guarantees `io_data` points to a valid `AudioBufferList` for the callback duration.
    let buffer_list: &mut AudioBufferListC = unsafe { &mut *io_data };
    if buffer_list.number_buffers == 0 {
        return 0;
    }
    let first_buf: &mut AudioBufferC = &mut buffer_list.buffers[0];
    if first_buf.data.is_null() || first_buf.data_byte_size == 0 {
        return 0;
    }
    let max_floats: usize = (first_buf.data_byte_size as usize) / size_of::<f32>();
    let target_floats: usize = ((in_number_frames as usize).saturating_mul(2)).min(max_floats);
    // SAFETY: `first_buf.data` is valid for `first_buf.data_byte_size` bytes as guaranteed by CoreAudio.
    let output_slice: &mut [f32] =
        unsafe { from_raw_parts_mut(first_buf.data.cast::<f32>(), target_floats) };
    if in_ref_con.is_null() {
        output_slice.fill(0.0);
        return 0;
    }
    // SAFETY: `in_ref_con` points to the boxed `Arc<Mutex<AudioMixerCore>>` alive until after `AudioComponentInstanceDispose`.
    let core_arc: &Arc<Mutex<AudioMixerCore>> =
        unsafe { &*in_ref_con.cast::<Arc<Mutex<AudioMixerCore>>>() };
    if let Ok(mut guard) = core_arc.try_lock() {
        let _: usize = guard.pull_interleaved_stereo(output_slice);
    } else {
        output_slice.fill(0.0);
    }
    0
}

/// Initializes and starts a real macOS CoreAudio AUHAL default output unit streaming from `core`.
///
/// # Arguments
///
/// - `AudioOutputConfig` - Sanitized stereo output configuration.
/// - `Arc<Mutex<AudioMixerCore>>` - Shared mixer core pulled by the real-time render callback.
///
/// # Returns
///
/// - `Result<CoreAudioAuhalHandle, AudioOutputError>` - Active AUHAL handle or OS failure status.
#[cfg(target_os = "macos")]
pub(crate) fn open_coreaudio_auhal(
    config: AudioOutputConfig,
    core: Arc<Mutex<AudioMixerCore>>,
) -> Result<CoreAudioAuhalHandle, AudioOutputError> {
    let desc: AudioComponentDescriptionC = AudioComponentDescriptionC {
        component_type: COREAUDIO_UNIT_TYPE_OUTPUT,
        component_sub_type: COREAUDIO_SUBTYPE_DEFAULT_OUTPUT,
        component_manufacturer: COREAUDIO_MANUFACTURER_APPLE,
        component_flags: 0,
        component_flags_mask: 0,
    };
    // SAFETY: `desc` is a valid `AudioComponentDescription` passed by pointer to CoreAudio.
    let component: *mut c_void = unsafe { AudioComponentFindNext(null_mut(), &desc) };
    if component.is_null() {
        return Err(AudioOutputError::DriverUnavailable);
    }
    let mut unit: *mut c_void = null_mut();
    // SAFETY: `component` is non-null and `unit` receives the newly instantiated `AudioUnit`.
    let new_status: i32 = unsafe { AudioComponentInstanceNew(component, &mut unit) };
    if new_status != 0 || unit.is_null() {
        return Err(AudioOutputError::InitializationFailed(new_status));
    }
    let asbd: AudioStreamBasicDescriptionC = AudioStreamBasicDescriptionC {
        sample_rate: config.get_sample_rate_hz() as f64,
        format_id: COREAUDIO_FORMAT_LINEAR_PCM,
        format_flags: COREAUDIO_FLAG_IS_FLOAT | COREAUDIO_FLAG_IS_PACKED,
        bytes_per_packet: 8,
        frames_per_packet: 1,
        bytes_per_frame: 8,
        channels_per_frame: 2,
        bits_per_channel: 32,
        reserved: 0,
    };
    // SAFETY: `unit` is a valid `AudioUnit` and `asbd` matches `AudioStreamBasicDescription`.
    let fmt_status: i32 = unsafe {
        AudioUnitSetProperty(
            unit,
            COREAUDIO_PROP_STREAM_FORMAT,
            COREAUDIO_SCOPE_INPUT,
            COREAUDIO_BUS_OUTPUT,
            (&asbd as *const AudioStreamBasicDescriptionC).cast::<c_void>(),
            size_of::<AudioStreamBasicDescriptionC>() as u32,
        )
    };
    if fmt_status != 0 {
        // SAFETY: `unit` was created by `AudioComponentInstanceNew`.
        let _: i32 = unsafe { AudioComponentInstanceDispose(unit) };
        return Err(AudioOutputError::InitializationFailed(fmt_status));
    }
    let ctx_ptr: *mut c_void = Box::into_raw(Box::new(core)).cast::<c_void>();
    let callback_spec: AuRenderCallbackStructC = AuRenderCallbackStructC {
        input_proc: coreaudio_render_callback,
        input_proc_ref_con: ctx_ptr,
    };
    // SAFETY: `callback_spec` installs our render callback with `ctx_ptr` kept alive until disposal.
    let cb_status: i32 = unsafe {
        AudioUnitSetProperty(
            unit,
            COREAUDIO_PROP_SET_RENDER_CALLBACK,
            COREAUDIO_SCOPE_INPUT,
            COREAUDIO_BUS_OUTPUT,
            (&callback_spec as *const AuRenderCallbackStructC).cast::<c_void>(),
            size_of::<AuRenderCallbackStructC>() as u32,
        )
    };
    if cb_status != 0 {
        // SAFETY: Disposing `unit` before reclaiming `ctx_ptr` guarantees callback is inactive.
        let _: i32 = unsafe { AudioComponentInstanceDispose(unit) };
        // SAFETY: `ctx_ptr` was allocated by `Box::into_raw` above and never started.
        let _: Box<Arc<Mutex<AudioMixerCore>>> =
            unsafe { Box::from_raw(ctx_ptr.cast::<Arc<Mutex<AudioMixerCore>>>()) };
        return Err(AudioOutputError::InitializationFailed(cb_status));
    }
    // SAFETY: `unit` has valid stream format and render callback installed.
    let init_status: i32 = unsafe { AudioUnitInitialize(unit) };
    if init_status != 0 {
        // SAFETY: `unit` failed initialization and is safely disposed before reclaiming `ctx_ptr`.
        let _: i32 = unsafe { AudioComponentInstanceDispose(unit) };
        // SAFETY: `ctx_ptr` is uniquely owned after `unit` disposal.
        let _: Box<Arc<Mutex<AudioMixerCore>>> =
            unsafe { Box::from_raw(ctx_ptr.cast::<Arc<Mutex<AudioMixerCore>>>()) };
        return Err(AudioOutputError::InitializationFailed(init_status));
    }
    // SAFETY: `unit` is initialized and ready for real-time audio streaming.
    let start_status: i32 = unsafe { AudioOutputUnitStart(unit) };
    if start_status != 0 {
        // SAFETY: Uninitialize and dispose `unit` cleanly before freeing `ctx_ptr`.
        let _: i32 = unsafe { AudioUnitUninitialize(unit) };
        let _: i32 = unsafe { AudioComponentInstanceDispose(unit) };
        // SAFETY: `ctx_ptr` is uniquely owned after `unit` disposal.
        let _: Box<Arc<Mutex<AudioMixerCore>>> =
            unsafe { Box::from_raw(ctx_ptr.cast::<Arc<Mutex<AudioMixerCore>>>()) };
        return Err(AudioOutputError::StartFailed(start_status));
    }
    Ok(CoreAudioAuhalHandle {
        audio_unit: unit,
        callback_context: ctx_ptr,
        running: true,
    })
}

/// Stops, uninitializes, and disposes an active macOS CoreAudio AUHAL handle without leaking resources.
///
/// # Arguments
///
/// - `&mut CoreAudioAuhalHandle` - Active CoreAudio handle to tear down.
#[cfg(target_os = "macos")]
pub(crate) fn dispose_coreaudio_auhal(handle: &mut CoreAudioAuhalHandle) {
    let unit: *mut c_void = handle.get_audio_unit();
    if !unit.is_null() {
        if handle.get_running() {
            // SAFETY: `unit` is a running CoreAudio `AudioUnit`.
            let _: i32 = unsafe { AudioOutputUnitStop(unit) };
            handle.set_running(false);
        }
        // SAFETY: `unit` is stopped and safe to uninitialize and dispose.
        let _: i32 = unsafe { AudioUnitUninitialize(unit) };
        let _: i32 = unsafe { AudioComponentInstanceDispose(unit) };
        handle.set_audio_unit(null_mut());
    }
    let ctx_ptr: *mut c_void = handle.get_callback_context();
    if !ctx_ptr.is_null() {
        // SAFETY: `AudioComponentInstanceDispose` has finished so the callback can no longer dereference `ctx_ptr`.
        let _: Box<Arc<Mutex<AudioMixerCore>>> =
            unsafe { Box::from_raw(ctx_ptr.cast::<Arc<Mutex<AudioMixerCore>>>()) };
        handle.set_callback_context(null_mut());
    }
}