maolan-engine 0.2.32

Audio engine for the Maolan DAW with audio/MIDI tracks, routing, export, and out-of-process CLAP/VST3/LV2 plugin support
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
#![cfg(target_os = "macos")]

use crate::audio::io::AudioIO;
use crate::hw::ports;
use coreaudio_sys::{
    AudioBufferList, AudioDeviceCreateIOProcID, AudioDeviceDestroyIOProcID, AudioDeviceID,
    AudioDeviceIOProcID, AudioDeviceStart, AudioDeviceStop, AudioObjectAddPropertyListener,
    AudioObjectPropertyAddress, AudioObjectRemovePropertyListener, AudioTimeStamp, OSStatus,
    UInt32, kAudioDeviceProcessorOverload, kAudioHardwareNoError, kAudioObjectPropertyElementMain,
    kAudioObjectPropertyScopeGlobal,
};
use std::os::raw::c_void;
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;

const OVERLOAD_ADDRESS: AudioObjectPropertyAddress = AudioObjectPropertyAddress {
    mSelector: kAudioDeviceProcessorOverload,
    mScope: kAudioObjectPropertyScopeGlobal,
    mElement: kAudioObjectPropertyElementMain,
};

unsafe extern "C" fn overload_listener(
    _id: coreaudio_sys::AudioObjectID,
    _count: UInt32,
    _addresses: *const AudioObjectPropertyAddress,
    client_data: *mut c_void,
) -> OSStatus {
    let state = &*(client_data as *const SharedIOState);
    if let Ok(mut data) = state.mutex.lock() {
        data.overload = true;
    }
    0
}

pub struct SharedData {
    pub cycle_seq: u64,

    pub input_frames: Vec<Vec<f32>>,

    pub output_frames: Vec<Vec<f32>>,

    pub output_ready: bool,

    pub period_frames: usize,

    pub overload: bool,

    pub discontinuity: bool,

    pub last_host_time_nanos: u64,

    pub sample_rate: u32,

    pub xrun_count: u64,

    pub last_sample_time: f64,
}

pub struct SharedIOState {
    pub condvar: Condvar,
    pub mutex: Mutex<SharedData>,
}

impl SharedIOState {
    pub fn new(
        input_channels: usize,
        output_channels: usize,
        period_frames: usize,
        sample_rate: u32,
    ) -> Self {
        let data = SharedData {
            cycle_seq: 0,
            input_frames: vec![vec![0.0f32; period_frames]; input_channels],
            output_frames: vec![vec![0.0f32; period_frames]; output_channels],
            output_ready: false,
            period_frames,
            overload: false,
            discontinuity: false,
            last_host_time_nanos: 0,
            sample_rate,
            xrun_count: 0,
            last_sample_time: -1.0,
        };
        SharedIOState {
            condvar: Condvar::new(),
            mutex: Mutex::new(data),
        }
    }

    fn xrun_gap(
        last_host_time_nanos: u64,
        current_host_time_nanos: u64,
        sample_rate: u32,
        period_frames: usize,
    ) -> u64 {
        if last_host_time_nanos == 0 || current_host_time_nanos <= last_host_time_nanos {
            return 0;
        }
        let delta_nanos = current_host_time_nanos - last_host_time_nanos;
        let elapsed_frames =
            (delta_nanos as u128 * sample_rate as u128 / 1_000_000_000_u128) as u64;
        if elapsed_frames > period_frames as u64 * 2 {
            elapsed_frames - period_frames as u64
        } else {
            0
        }
    }

    pub fn run_cycle(
        &self,
        input_ports: &[Arc<AudioIO>],
        output_ports: &[Arc<AudioIO>],
        output_gain: f32,
        output_balance: f32,
        plan_slot: Option<&crate::render_plan::PlanSlot>,
    ) -> Result<(), String> {
        let mut data = self
            .mutex
            .lock()
            .map_err(|e| format!("SharedIOState mutex poisoned: {}", e))?;
        let seq_before = data.cycle_seq;
        let timeout = Duration::from_secs(1);
        while data.cycle_seq == seq_before {
            let (guard, wait_result) = self
                .condvar
                .wait_timeout(data, timeout)
                .map_err(|e| format!("condvar wait failed: {}", e))?;
            data = guard;
            if wait_result.timed_out() && data.cycle_seq == seq_before {
                return Err("CoreAudio IOProc cycle timeout (1s)".to_string());
            }
        }

        let frames = data.period_frames;

        let current_nanos = unsafe {
            coreaudio_sys::AudioConvertHostTimeToNanos(coreaudio_sys::AudioGetCurrentHostTime())
        };
        let gap = Self::xrun_gap(
            data.last_host_time_nanos,
            current_nanos,
            data.sample_rate,
            frames,
        );
        if gap > 0 {
            data.xrun_count += 1;

            if let Some(slot) = plan_slot {
                let plan = slot.load();
                for &(_, buf) in &plan.hw_in_map {
                    // Safety: the driver is the sole producer of hw_in arena
                    // buffers, and this write happens before the engine starts
                    // the cycle, so no node reads them concurrently.
                    let arena = unsafe { &mut *plan.buffer_ptr(buf) };
                    let end = frames.min(arena.len());
                    arena[..end].fill(0.0);
                }
            } else {
                ports::fill_ports_from_interleaved(input_ports, frames, false, |_, _| 0.0);
            }

            data.overload = false;
            data.discontinuity = false;

            data.last_host_time_nanos = current_nanos;
            return Ok(());
        }
        data.last_host_time_nanos = current_nanos;

        if let Some(slot) = plan_slot {
            let plan = slot.load();
            for &(ch_idx, buf) in &plan.hw_in_map {
                // Safety: the driver is the sole producer of hw_in arena
                // buffers, and this write happens before the engine starts
                // the cycle, so no node reads them concurrently.
                let arena = unsafe { &mut *plan.buffer_ptr(buf) };
                let end = frames.min(arena.len());
                if let Some(src) = data.input_frames.get(ch_idx) {
                    let copy_len = end.min(src.len());
                    arena[..copy_len].copy_from_slice(&src[..copy_len]);
                    arena[copy_len..end].fill(0.0);
                } else {
                    arena[..end].fill(0.0);
                }
            }
        } else {
            ports::fill_ports_from_interleaved(input_ports, frames, false, |ch, frame| {
                data.input_frames
                    .get(ch)
                    .and_then(|buf| buf.get(frame).copied())
                    .unwrap_or(0.0)
            });
        }

        for ch_buf in data.output_frames.iter_mut() {
            ch_buf[..frames].fill(0.0);
        }
        let mut write_sample = |ch: usize, frame: usize, sample: f32| {
            if let Some(buf) = data.output_frames.get_mut(ch) {
                if let Some(dst) = buf.get_mut(frame) {
                    *dst = sample;
                }
            }
        };
        if let Some(slot) = plan_slot {
            let plan = slot.load();
            ports::write_interleaved_from_arena(
                &plan,
                frames,
                output_gain,
                output_balance,
                &mut write_sample,
            );
        } else {
            ports::write_interleaved_from_ports(
                output_ports,
                frames,
                output_gain,
                output_balance,
                false,
                write_sample,
            );
        }

        data.output_ready = true;

        Ok(())
    }
}

unsafe extern "C" fn io_proc(
    _device: AudioDeviceID,
    _now: *const AudioTimeStamp,
    input_data: *const AudioBufferList,
    input_time: *const AudioTimeStamp,
    output_data: *mut AudioBufferList,
    _output_time: *const AudioTimeStamp,
    client_data: *mut std::ffi::c_void,
) -> OSStatus {
    crate::enable_flush_denormals_to_zero();
    let state = &*(client_data as *const SharedIOState);

    let mut data = match state.mutex.lock() {
        Ok(guard) => guard,
        Err(_) => return 0,
    };

    if !input_time.is_null() {
        let sample_time = (*input_time).mSampleTime;
        if data.last_sample_time >= 0.0 && data.period_frames > 0 {
            let gap = (sample_time - data.last_sample_time).abs();
            if gap > 1.5 * data.period_frames as f64 {
                data.discontinuity = true;
            }
        }
        data.last_sample_time = sample_time;
    }

    if !input_data.is_null() {
        let abl = &*input_data;
        let n_buffers = abl.mNumberBuffers as usize;
        let buffers = std::slice::from_raw_parts(abl.mBuffers.as_ptr(), n_buffers);
        let mut ch_idx = 0usize;
        for buf in buffers {
            let n_channels = buf.mNumberChannels as usize;
            let frame_count = if n_channels > 0 && buf.mDataByteSize > 0 {
                buf.mDataByteSize as usize / (n_channels * std::mem::size_of::<f32>())
            } else {
                0
            };
            let samples = if !buf.mData.is_null() && frame_count > 0 {
                std::slice::from_raw_parts(buf.mData as *const f32, frame_count * n_channels)
            } else {
                &[]
            };

            for sub_ch in 0..n_channels {
                if ch_idx < data.input_frames.len() {
                    let dst = &mut data.input_frames[ch_idx];
                    let copy_len = frame_count.min(dst.len());
                    if n_channels == 1 {
                        dst[..copy_len].copy_from_slice(&samples[..copy_len]);
                    } else {
                        for f in 0..copy_len {
                            dst[f] = samples[f * n_channels + sub_ch];
                        }
                    }

                    if ch_idx == 0 {
                        data.period_frames = frame_count;
                    }
                }
                ch_idx += 1;
            }
        }
    }

    if !output_data.is_null() {
        let abl = &mut *output_data;
        let n_buffers = abl.mNumberBuffers as usize;
        let buffers = std::slice::from_raw_parts_mut(abl.mBuffers.as_mut_ptr(), n_buffers);
        let mut ch_idx = 0usize;
        for buf in buffers {
            let n_channels = buf.mNumberChannels as usize;
            let frame_count = if n_channels > 0 && buf.mDataByteSize > 0 {
                buf.mDataByteSize as usize / (n_channels * std::mem::size_of::<f32>())
            } else {
                0
            };
            let samples = if !buf.mData.is_null() && frame_count > 0 {
                std::slice::from_raw_parts_mut(buf.mData as *mut f32, frame_count * n_channels)
            } else {
                &mut []
            };

            for sub_ch in 0..n_channels {
                if ch_idx < data.output_frames.len() {
                    let src = &data.output_frames[ch_idx];
                    let copy_len = frame_count.min(src.len());
                    if n_channels == 1 {
                        samples[..copy_len].copy_from_slice(&src[..copy_len]);
                    } else {
                        for f in 0..copy_len {
                            samples[f * n_channels + sub_ch] = src[f];
                        }
                    }
                } else {
                    for f in 0..frame_count {
                        if n_channels == 1 {
                            samples[f] = 0.0;
                        } else {
                            samples[f * n_channels + sub_ch] = 0.0;
                        }
                    }
                }
                ch_idx += 1;
            }
        }
    }

    data.output_ready = false;

    data.cycle_seq += 1;

    drop(data);
    state.condvar.notify_one();

    0
}

pub struct IoProcHandle {
    device_id: AudioDeviceID,
    proc_id: AudioDeviceIOProcID,

    has_overload_listener: bool,

    state: Arc<SharedIOState>,
}

impl IoProcHandle {
    pub fn new(device_id: AudioDeviceID, state: Arc<SharedIOState>) -> Result<Self, String> {
        let mut proc_id: AudioDeviceIOProcID = None;

        let client_ptr = Arc::as_ptr(&state) as *mut std::ffi::c_void;

        std::mem::forget(state.clone());

        let status: OSStatus = unsafe {
            AudioDeviceCreateIOProcID(device_id, Some(io_proc), client_ptr, &mut proc_id)
        };
        if status != kAudioHardwareNoError as OSStatus {
            unsafe {
                Arc::from_raw(client_ptr as *const SharedIOState);
            }
            return Err(format!(
                "AudioDeviceCreateIOProcID failed with status {}",
                status
            ));
        }

        let status: OSStatus = unsafe { AudioDeviceStart(device_id, Some(io_proc)) };
        if status != kAudioHardwareNoError as OSStatus {
            unsafe {
                AudioDeviceDestroyIOProcID(device_id, proc_id);
                Arc::from_raw(client_ptr as *const SharedIOState);
            }
            return Err(format!("AudioDeviceStart failed with status {}", status));
        }

        let overload_status: OSStatus = unsafe {
            AudioObjectAddPropertyListener(
                device_id,
                &OVERLOAD_ADDRESS,
                Some(overload_listener),
                client_ptr,
            )
        };
        if overload_status != kAudioHardwareNoError as OSStatus {}

        Ok(IoProcHandle {
            device_id,
            proc_id,
            has_overload_listener: overload_status == kAudioHardwareNoError as OSStatus,
            state,
        })
    }
}

impl Drop for IoProcHandle {
    fn drop(&mut self) {
        unsafe {
            AudioDeviceStop(self.device_id, Some(io_proc));
            AudioDeviceDestroyIOProcID(self.device_id, self.proc_id);

            if self.has_overload_listener {
                let client_ptr = Arc::as_ptr(&self.state) as *mut c_void;
                AudioObjectRemovePropertyListener(
                    self.device_id,
                    &OVERLOAD_ADDRESS,
                    Some(overload_listener),
                    client_ptr,
                );
            }

            let client_ptr = Arc::as_ptr(&self.state) as *const SharedIOState;
            Arc::from_raw(client_ptr);
        }
    }
}