maudio 0.1.5

Rust bindings to the miniaudio library
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
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
use std::{marker::PhantomData, mem::MaybeUninit, sync::Arc};

use maudio_sys::ffi as sys;

use crate::{
    audio::sample_rate::SampleRate,
    engine::{
        node_graph::{
            nodes::{private_node, AsNodePtr, NodeRef},
            AsNodeGraphPtr, NodeGraph,
        },
        AllocationCallbacks,
    },
    AsRawRef, Binding, MaResult,
};

/// A node that applies a delay (echo) effect to an audio signal.
///
/// `DelayNode` is one of the custom DSP nodes provided by miniaudio.
/// It mixes the original (dry) signal with a delayed (wet) copy, allowing
/// control over the delay length, feedback (decay), and wet/dry balance.
/// The node is intended to be used as part of a node graph and processes
/// audio in fixed-size frames according to the graph’s format.
///
/// Use [`DelayNodeBuilder`] to initialize
pub struct DelayNode<'a> {
    inner: *mut sys::ma_delay_node,
    alloc_cb: Option<Arc<AllocationCallbacks>>,
    _marker: PhantomData<&'a NodeGraph>,
}

impl Binding for DelayNode<'_> {
    type Raw = *mut sys::ma_delay_node;

    // !!! unimplemented !!!
    fn from_ptr(_raw: Self::Raw) -> Self {
        unimplemented!()
    }

    fn to_raw(&self) -> Self::Raw {
        self.inner
    }
}

#[doc(hidden)]
impl AsNodePtr for DelayNode<'_> {
    type __PtrProvider = private_node::DelayNodeProvider;
}

impl<'a> DelayNode<'a> {
    /// Read the gain of the *wet* (delayed) signal.
    pub fn wet(&self) -> f32 {
        n_delay_ffi::ma_delay_node_get_wet(self)
    }

    /// Sets the gain of the *wet* (delayed) signal.
    ///
    /// The wet signal is the audio after it has passed through the delay.
    /// Higher values make the echo more prominent in the final output.
    /// Values are not clamped.
    pub fn set_wet(&mut self, wet: f32) {
        n_delay_ffi::ma_delay_node_set_wet(self, wet);
    }

    /// Reads the gain of the *dry* (unprocessed) signal.
    pub fn dry(&self) -> f32 {
        n_delay_ffi::ma_delay_node_get_dry(self)
    }

    /// Sets the gain of the *dry* (unprocessed) signal.
    ///
    /// The dry signal is the original input audio before any delay is applied.
    /// Higher values preserve more of the original sound in the final output.
    /// Values are not clamped.
    pub fn set_dry(&mut self, dry: f32) {
        n_delay_ffi::ma_delay_node_set_dry(self, dry);
    }

    /// Reads the feedback amount of the delay line in frames
    pub fn decay_frames(&self) -> f32 {
        n_delay_ffi::ma_delay_node_get_decay(self)
    }

    /// Sets the feedback amount of the delay line in frames
    ///
    /// Higher values cause the delayed signal to repeat longer, while
    /// lower values fade out more quickly. Values near or above `1.0`
    /// may cause self-oscillation.
    pub fn set_decay_frames(&mut self, decay: f32) {
        n_delay_ffi::ma_delay_node_set_decay(self, decay);
    }

    /// Returns a **borrowed view** as a node in the engine's node graph.
    ///
    /// ### What this is for
    ///
    /// Use `as_node()` when you want to:
    /// - connect this to other nodes (effects, mixers, splitters, etc.)
    /// - insert into a custom routing graph
    /// - query node-level state exposed by the graph
    pub fn as_node(&self) -> NodeRef<'a> {
        assert!(!self.to_raw().is_null());
        let ptr = self.to_raw().cast::<sys::ma_node>();
        NodeRef::from_ptr(ptr)
    }

    fn new_with_cfg_alloc_internal<N: AsNodeGraphPtr + ?Sized>(
        node_graph: &N,
        config: &DelayNodeBuilder<N>,
        alloc: Option<Arc<AllocationCallbacks>>,
    ) -> MaResult<Self> {
        let alloc_cb: *const sys::ma_allocation_callbacks =
            alloc.clone().map_or(core::ptr::null(), |c| c.as_raw_ptr());

        let mut mem: Box<std::mem::MaybeUninit<sys::ma_delay_node>> =
            Box::new(MaybeUninit::uninit());

        n_delay_ffi::ma_delay_node_init(
            node_graph,
            config.as_raw_ptr(),
            alloc_cb,
            mem.as_mut_ptr(),
        )?;

        let inner: *mut sys::ma_delay_node = Box::into_raw(mem) as *mut sys::ma_delay_node;

        Ok(Self {
            inner,
            alloc_cb: alloc,
            _marker: PhantomData,
        })
    }

    #[inline]
    fn alloc_cb_ptr(&self) -> *const sys::ma_allocation_callbacks {
        match &self.alloc_cb {
            Some(cb) => cb.as_raw_ptr(),
            None => core::ptr::null(),
        }
    }
}

pub(crate) mod n_delay_ffi {
    use crate::{
        engine::node_graph::{
            nodes::effects::delay::DelayNode, private_node_graph, AsNodeGraphPtr,
        },
        Binding, MaResult, MaudioError,
    };
    use maudio_sys::ffi as sys;

    #[inline]
    pub fn ma_delay_node_init<N: AsNodeGraphPtr + ?Sized>(
        node_graph: &N,
        config: *const sys::ma_delay_node_config,
        alloc_cb: *const sys::ma_allocation_callbacks,
        node: *mut sys::ma_delay_node,
    ) -> MaResult<()> {
        let res = unsafe {
            sys::ma_delay_node_init(
                private_node_graph::node_graph_ptr(node_graph),
                config,
                alloc_cb,
                node,
            )
        };
        MaudioError::check(res)
    }

    #[inline]
    pub fn ma_delay_node_uninit(node: &mut DelayNode) {
        unsafe { sys::ma_delay_node_uninit(node.to_raw(), node.alloc_cb_ptr()) }
    }

    #[inline]
    pub fn ma_delay_node_set_wet(node: &mut DelayNode, wet: f32) {
        unsafe {
            sys::ma_delay_node_set_wet(node.to_raw(), wet);
        }
    }

    pub fn ma_delay_node_get_wet(node: &DelayNode) -> f32 {
        unsafe { sys::ma_delay_node_get_wet(node.to_raw() as *const _) }
    }

    pub fn ma_delay_node_set_dry(node: &mut DelayNode, dry: f32) {
        unsafe {
            sys::ma_delay_node_set_dry(node.to_raw(), dry);
        }
    }

    pub fn ma_delay_node_get_dry(node: &DelayNode) -> f32 {
        unsafe { sys::ma_delay_node_get_dry(node.to_raw() as *const _) }
    }

    pub fn ma_delay_node_set_decay(node: &mut DelayNode, decay: f32) {
        unsafe {
            sys::ma_delay_node_set_decay(node.to_raw(), decay);
        }
    }

    pub fn ma_delay_node_get_decay(node: &DelayNode) -> f32 {
        unsafe { sys::ma_delay_node_get_decay(node.to_raw() as *const _) }
    }
}

impl Drop for DelayNode<'_> {
    fn drop(&mut self) {
        n_delay_ffi::ma_delay_node_uninit(self);
        drop(unsafe { Box::from_raw(self.to_raw()) });
    }
}

/// Builder for creating a [`DelayNode`]
pub struct DelayNodeBuilder<'a, N: AsNodeGraphPtr + ?Sized> {
    inner: sys::ma_delay_node_config,
    node_graph: &'a N,
}

impl<N: AsNodeGraphPtr + ?Sized> AsRawRef for DelayNodeBuilder<'_, N> {
    type Raw = sys::ma_delay_node_config;

    fn as_raw(&self) -> &Self::Raw {
        &self.inner
    }
}

impl<'a, N: AsNodeGraphPtr + ?Sized> DelayNodeBuilder<'a, N> {
    pub fn new(
        node_graph: &'a N,
        channels: u32,
        sample_rate: SampleRate,
        delay_frames: u32,
        decay: f32,
    ) -> Self {
        let inner = unsafe {
            sys::ma_delay_node_config_init(channels, sample_rate.into(), delay_frames, decay)
        };
        Self { inner, node_graph }
    }

    /// Sets the gain of the *wet* (delayed) signal.
    ///
    /// The wet signal is the audio after it has passed through the delay.
    /// Higher values make the echo more prominent in the final output.
    /// Values are not clamped.
    pub fn wet(&mut self, wet: f32) -> &mut Self {
        self.inner.delay.wet = wet;
        self
    }

    /// Sets the gain of the *dry* (unprocessed) signal.
    ///
    /// The dry signal is the original input audio before any delay is applied.
    /// Higher values preserve more of the original sound in the final output.
    /// Values are not clamped.
    pub fn dry(&mut self, dry: f32) -> &mut Self {
        self.inner.delay.dry = dry;
        self
    }

    /// Sets the balance between the dry and wet signals.
    ///
    /// `0.0` is fully dry (no delay audible), and `1.0` is fully wet
    /// (only the delayed signal). Values are clamped to `0.0..=1.0`.
    ///
    /// This overwrites both the wet and dry gains.
    pub fn mix(&mut self, mix: f32) -> &mut Self {
        let mix = mix.clamp(0.0, 1.0);

        self.inner.delay.wet = mix;
        self.inner.delay.dry = 1.0 - mix;

        self
    }

    /// Sets the feedback amount of the delay line.
    ///
    /// Higher values cause the delayed signal to repeat longer, while
    /// lower values fade out more quickly. Values near or above `1.0`
    /// may cause self-oscillation.
    pub fn decay(&mut self, decay: f32) -> &mut Self {
        self.inner.delay.decay = decay;
        self
    }

    /// Emables or disables a delayed start
    pub fn delay_start(&mut self, yes: bool) -> &mut Self {
        let delay_start = yes as u32;
        self.inner.delay.delayStart = delay_start;
        self
    }

    /// Sets the frame at which the delay starts.
    ///
    /// This offsets when the delay begins relative to the input signal.
    pub fn start_frame(&mut self, frame: u32) -> &mut Self {
        self.inner.delay.delayInFrames = frame;
        self
    }

    /// Sets the length of the delay in milliseconds.
    ///
    /// This is a convenience wrapper around `delay_start` that converts
    /// milliseconds to frames using the configured sample rate.
    pub fn delay_milli(&mut self, millis: u32) -> &mut Self {
        self.inner.delay.delayInFrames = self.millis_to_frames(millis);
        self
    }

    /// Sets the delay start offset in milliseconds.
    ///
    /// This is a convenience wrapper around `start_frame` that converts
    /// millisseconds to frames using the configured sample rate.
    pub fn start_milli(&mut self, millis: u32) -> &mut Self {
        self.inner.delay.delayInFrames = self.millis_to_frames(millis);
        self
    }

    pub fn build(&self) -> MaResult<DelayNode<'a>> {
        if self.inner.delay.channels == 0 {
            return Err(crate::MaudioError::from_ma_result(
                sys::ma_result_MA_INVALID_ARGS,
            ));
        }

        DelayNode::new_with_cfg_alloc_internal(self.node_graph, self, None)
    }

    #[inline]
    fn millis_to_frames(&self, millis: u32) -> u32 {
        let sr = self.inner.delay.sampleRate;
        (millis * sr + 500) / 1000
    }
}

#[cfg(test)]
mod test {
    use crate::engine::{node_graph::nodes::private_node, Engine, EngineOps};

    use super::*;

    fn assert_approx_eq(a: f32, b: f32, eps: f32) {
        assert!(
            (a - b).abs() <= eps,
            "expected {a} ≈ {b} (eps={eps}), diff={}",
            (a - b).abs()
        );
    }

    #[test]
    fn test_delay_node_test_basic_init() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();
        let delay = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr44100, 0, 0.0)
            .build()
            .unwrap();

        let _ = delay.wet();
        let _ = delay.dry();
        let _ = delay.decay_frames();

        let _ = delay.as_node();
    }

    #[test]
    fn test_delay_node_test_set_get_wet_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();
        let mut delay = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr44100, 0, 0.0)
            .build()
            .unwrap();

        delay.set_wet(0.25);
        assert_approx_eq(delay.wet(), 0.25, 1e-6);

        delay.set_wet(1.5);
        assert_approx_eq(delay.wet(), 1.5, 1e-6);
    }

    #[test]
    fn test_delay_node_test_set_get_dry_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();
        let mut delay = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr44100, 0, 0.0)
            .build()
            .unwrap();

        delay.set_dry(0.75);
        assert_approx_eq(delay.dry(), 0.75, 1e-6);

        delay.set_dry(-0.5);
        assert_approx_eq(delay.dry(), -0.5, 1e-6);
    }

    #[test]
    fn test_delay_node_test_set_get_decay_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();
        let mut delay = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr44100, 0, 0.0)
            .build()
            .unwrap();

        delay.set_decay_frames(0.0);
        assert_approx_eq(delay.decay_frames(), 0.0, 1e-6);

        delay.set_decay_frames(0.4);
        assert_approx_eq(delay.decay_frames(), 0.4, 1e-6);

        delay.set_decay_frames(1.1);
        assert_approx_eq(delay.decay_frames(), 1.1, 1e-6);
    }

    #[test]
    fn test_delay_node_test_as_node_is_non_null() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();
        let delay = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr44100, 0, 0.0)
            .build()
            .unwrap();

        let node_ref = delay.as_node();
        assert!(!private_node::node_ptr(&node_ref).is_null());
        let _ = node_ref;
    }

    #[test]
    fn test_delay_node_test_mix_clamps_and_overwrites_wet_dry() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();

        let mut b = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr48000, 0, 0.0);

        b.wet(0.123).dry(0.456);
        b.mix(-1.0);
        assert_approx_eq(b.as_raw().delay.wet, 0.0, 1e-6);
        assert_approx_eq(b.as_raw().delay.dry, 1.0, 1e-6);

        b.mix(2.0);
        assert_approx_eq(b.as_raw().delay.wet, 1.0, 1e-6);
        assert_approx_eq(b.as_raw().delay.dry, 0.0, 1e-6);

        b.mix(0.25);
        assert_approx_eq(b.as_raw().delay.wet, 0.25, 1e-6);
        assert_approx_eq(b.as_raw().delay.dry, 0.75, 1e-6);
    }

    #[test]
    fn test_delay_node_test_delay_milli_rounding() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();

        // sr=48k: 1ms -> 48 frames exactly
        let mut b = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr48000, 0, 0.0);
        b.delay_milli(1);
        assert_eq!(b.as_raw().delay.delayInFrames, 48);

        // sr=44.1k: 1ms -> 44.1 frames -> rounds to 44
        let mut b = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr44100, 0, 0.0);
        b.delay_milli(1);
        assert_eq!(b.as_raw().delay.delayInFrames, 44);

        // 2ms -> 88.2 -> rounds to 88
        b.delay_milli(2);
        assert_eq!(b.as_raw().delay.delayInFrames, 88);

        // 3ms -> 132.3 -> rounds to 132
        b.delay_milli(3);
        assert_eq!(b.as_raw().delay.delayInFrames, 132);
    }

    #[test]
    fn test_delay_node_test_start_milli_sets_start_frame_not_flag() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();

        let mut b = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr48000, 0, 0.0);
        b.start_milli(10);

        assert_eq!(b.as_raw().delay.delayStart, 1);
        assert_eq!(b.as_raw().delay.delayInFrames, 480);
    }

    #[test]
    fn test_delay_node_test_create_drop_many_times() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();

        for _ in 0..1_000 {
            let _delay = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr48000, 0, 0.0)
                .wet(0.5)
                .dry(0.5)
                .build()
                .unwrap();
        }
    }

    #[test]
    fn test_delay_node_test_set_get_stress() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();

        let mut delay = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr48000, 10, 0.25)
            .build()
            .unwrap();

        for i in 0..10_000 {
            let w = (i as f32) * 0.0001;
            let d = 1.0 - w;
            let dec = (i as f32) * 0.00001;

            delay.set_wet(w);
            delay.set_dry(d);
            delay.set_decay_frames(dec);

            let _ = delay.wet();
            let _ = delay.dry();
            let _ = delay.decay_frames();
        }
    }

    #[test]
    fn test_delay_node_test_as_node_pointer_stable() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();

        let delay = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr48000, 0, 0.0)
            .build()
            .unwrap();

        let a = private_node::node_ptr(&delay.as_node());
        let b = private_node::node_ptr(&delay.as_node());
        assert_eq!(a, b);
        assert!(!a.is_null());
    }

    #[test]
    fn test_delay_node_test_large_delay_frames_no_ub() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();

        // Pick something "large but not insane" to avoid OOM in CI.
        // If this returns Err that's fine; goal is no crash/UB.
        let res =
            DelayNodeBuilder::new(&node_graph, 2, SampleRate::Sr48000, 48_000 * 2, 0.5).build();
        let _ = res.ok();
    }

    #[test]
    fn test_delay_node_test_drop_before_engine_is_safe() {
        let engine = Engine::new_for_tests().unwrap();
        let node_graph = engine.as_node_graph().unwrap();

        let delay = DelayNodeBuilder::new(&node_graph, 1, SampleRate::Sr48000, 0, 0.0)
            .build()
            .unwrap();

        drop(delay);
        drop(engine);
    }
}