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
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
//! Builder for constructing a [`Sound`]
//!
//! Use this when the convenience constructors aren’t enough (custom attachment,
//! channel configuration, async loading fence, start-on-build, etc.).
//!
//! ## Source selection (exactly one)
//! A sound is initialized from **at most one** source:
//! - [`SoundBuilder::file_path`]
//! - [`SoundBuilder::data_source`] (via a `DataSource` type)
//! - [`SoundBuilder::no_source`] (no playback source; some flags become invalid)
//!
//! Calling a source setter replaces any previously set source.
//!
//! ## Platform path ownership
//! When using [`SoundBuilder::file_path`], the builder stores an owned, platform-specific
//! copy of the path (UTF-8 `CString` on Unix, wide + NUL on Windows) so the raw pointer
//! inside `ma_sound_config` remains valid until [`SoundBuilder::build`] completes.
//!
//! ## Async loading and fences
//! [`SoundBuilder::fence`] is only valid for file-based sounds. It implicitly enables
//! [`SoundFlags::ASYNC`]. Using a fence with [`SoundBuilder::data_source`] or
//! [`SoundBuilder::no_source`] returns `MA_INVALID_ARGS`.
//!
//! ## Start playing on build
//! [`SoundBuilder::start_playing`] will call `sound.play_sound()` after initialization,
//! but only when a real source is set. It is rejected for [`SoundBuilder::no_source`].
//!
//! ## End notifications
//! [`SoundBuilder::with_end_notifier`] builds the sound and returns an [`EndNotifier`]
//! that becomes `true` once the sound reaches the end callback.
use std::path::Path;

use maudio_sys::ffi as sys;

use crate::{
    audio::{channels::MonoExpansionMode, math::vec3::Vec3},
    data_source::{private_data_source, AsSourcePtr, DataSourceRef},
    engine::{
        node_graph::nodes::{private_node, AsNodePtr},
        Engine, EngineOps,
    },
    sound::{
        notifier::EndNotifier, sound_flags::SoundFlags, sound_group::SoundGroup, Sound, SoundSource,
    },
    util::fence::Fence,
    AsRawRef, Binding, MaResult,
};

/// Builder for constructing a [`Sound`]
///
/// # Examples
///
/// Initialize from a file:
///
/// ```no_run
/// # use std::path::Path;
/// # use maudio::engine::Engine;
/// # use maudio::sound::sound_builder::SoundBuilder;
/// # fn demo(engine: &Engine) -> maudio::MaResult<()> {
/// let sound = SoundBuilder::new(&engine)
///     .file_path(Path::new("assets/click.wav"))
///     .channels_in(1)
///     .channels_out(0) // 0 = engine's native channel count
///     .build()?;
/// # Ok(())
/// # }
/// ```
///
/// Initialize from an existing data source:
///
/// ```no_run
/// # use maudio::engine::Engine;
/// # use maudio::sound::sound_builder::SoundBuilder;
/// # use maudio::data_source::sources::buffer::AudioBuffer;
/// # fn demo(engine: &Engine, ds: &AudioBuffer<f32>) -> maudio::MaResult<()> {
/// let sound = SoundBuilder::new(&engine).data_source(ds).build()?;
/// # Ok(())
/// # }
/// ```
///
/// Attach to a node/bus on init:
///
/// ```no_run
/// # use maudio::engine::Engine;
/// # use maudio::engine::EngineOps;
/// # use maudio::sound::sound_builder::SoundBuilder;
/// # fn demo(engine: &Engine) -> maudio::MaResult<()> {
/// // Attach to the engine's endpoint input bus 0 at creation time.
/// let endpoint = engine.endpoint().expect("engine has an endpoint");
///
/// let sound = SoundBuilder::new(&engine)
///     .file_path("assets/music.ogg".as_ref())
///     .initial_attachment(&endpoint, 0) // redundant here, only as example
///     .build()?;
/// # Ok(())
/// # }
/// ```
///
/// # Notes
/// - `SoundBuilder` is consumed by `build()` and should be used once, matching
///   miniaudio's "fill config → init" workflow.
/// - If you only need a simple sound, prefer the convenience constructors on [`Engine`] / [`Sound`].
pub struct SoundBuilder<'a, 'b> {
    inner: sys::ma_sound_config,
    engine: &'a Engine,
    source: SoundSource<'a>,
    owned_path: OwnedPathBuf,
    pub(crate) fence: Option<Fence>, // Ref count
    flags: SoundFlags,
    group: Option<&'b SoundGroup<'b>>,
    pub(crate) end_notifier: Option<EndNotifier>,
    sound_state: SoundState,
}

impl<'a, 'b> AsRawRef for SoundBuilder<'a, 'b> {
    type Raw = sys::ma_sound_config;

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

#[derive(Default)]
pub(crate) struct SoundState {
    pub(crate) min_distance: Option<f32>,
    pub(crate) max_distance: Option<f32>,
    pub(crate) rolloff: Option<f32>,
    pub(crate) position: Option<Vec3>,
    pub(crate) velocity: Option<Vec3>,
    pub(crate) direction: Option<Vec3>,
    pub(crate) start_playing: bool,
}

// Keeps the ptr to the path alive
#[derive(Default)]
pub(crate) enum OwnedPathBuf {
    #[default]
    None,
    #[cfg(unix)]
    Utf8(std::ffi::CString),
    #[cfg(windows)]
    Wide(Vec<u16>),
}

impl<'a, 'b> SoundBuilder<'a, 'b> {
    pub fn new(engine: &'a Engine) -> Self {
        SoundBuilder::init(engine)
    }

    fn set_end_notifier(&mut self) -> EndNotifier {
        let notifier = EndNotifier::new();
        self.end_notifier = Some(notifier.clone());

        self.inner.pEndCallbackUserData = notifier.as_user_data_ptr();
        self.inner.endCallback = Some(crate::sound::notifier::on_end_callback);

        notifier
    }

    pub fn mono_expansion_mode(&mut self, mode: MonoExpansionMode) -> &mut Self {
        self.inner.monoExpansionMode = mode.into();
        self
    }

    pub fn with_end_notifier(&'a mut self) -> MaResult<(Sound<'a>, EndNotifier)> {
        self.set_source()?;
        let notifier = self.set_end_notifier();

        let sound = self.start_sound()?;

        Ok((sound, notifier))
    }

    fn start_sound(&mut self) -> MaResult<Sound<'a>> {
        if let Some(fence) = self.fence.clone() {
            self.inner.pDoneFence = fence.to_raw()
        };

        let mut sound = match self.source {
            SoundSource::DataSource(_) => {
                if self.fence.is_some() {
                    return Err(crate::MaudioError::from_ma_result(
                        sys::ma_result_MA_INVALID_ARGS,
                    ));
                }
                self.engine.new_sound_with_config_internal(Some(self))?
            }
            #[cfg(unix)]
            SoundSource::FileUtf8(_) => self.engine.new_sound_with_config_internal(Some(self))?,
            #[cfg(windows)]
            SoundSource::FileWide(_) => self.engine.new_sound_with_config_internal(Some(self))?,
            SoundSource::None => {
                self.check_flags_without_source()?;

                if self.fence.is_some() || self.sound_state.start_playing {
                    return Err(crate::MaudioError::from_ma_result(
                        sys::ma_result_MA_INVALID_ARGS,
                    ));
                }
                self.engine.new_sound_with_config_internal(Some(self))?
            }
        };

        self.configure_sound(&mut sound);
        if self.source.is_valid() && self.sound_state.start_playing {
            sound.play_sound()?;
        }
        Ok(sound)
    }

    pub fn build(&mut self) -> MaResult<Sound<'a>> {
        self.set_source()?;
        self.start_sound()
    }

    /// Explicitly sets the sound to have no playback source.
    ///
    /// This is a convenience method for creating a silent sound or clearing a
    /// previously configured source.
    ///
    /// If no source was previously added, this has no effect
    pub fn no_source(&mut self) -> &mut Self {
        self.source = SoundSource::None;
        self
    }

    /// Sets the source of the sound from a path
    ///
    /// A sound can be initialized from **either** a file path **or** a data source,
    /// but not both. Calling this method overrides any previously set data_source.
    ///
    /// The provided path is converted to the platform-specific format required by
    /// miniaudio and is only used during sound initialization.
    pub fn file_path(&mut self, path: &Path) -> &mut Self {
        self.source = SoundSource::None;
        #[cfg(unix)]
        {
            self.source = SoundSource::FileUtf8(path.to_path_buf());
        }
        #[cfg(windows)]
        {
            self.source = SoundSource::FileWide(path.to_path_buf());
        }
        self
    }

    /// Sets the source of the sound as a data source (ma_data_source)
    ///
    /// In miniaudio, a data source is an abstraction used to supply decoded audio data
    /// to the engine. File decoders, procedural generators, and custom audio streams
    /// are all exposed through the `ma_data_source` interface.
    ///
    /// When a data source is provided, the sound will pull audio directly from it
    /// instead of loading from a file path.
    ///
    /// A sound can be initialized from **either** a file path **or** a data source,
    /// but not both. Calling this method overrides any previously set file path.
    pub fn data_source<S: AsSourcePtr + ?Sized>(&mut self, source: &'a S) -> &mut Self {
        self.source = SoundSource::DataSource(DataSourceRef::from_ptr(
            private_data_source::source_ptr(source),
        ));
        self
    }

    pub fn sound_group(&mut self, group: &'b SoundGroup) -> &mut Self {
        self.inner.pInitialAttachment = private_node::node_ptr(&group.as_node());
        self.group = Some(group);

        self
    }

    /// Attach a [`Fence`] that will be signaled when asynchronous sound loading completes.
    ///
    /// This implicitly enables [`SoundFlags::ASYNC`].
    ///
    /// A fence is only meaningful when the sound is created from a file.
    /// Using a fence without a file source will result in a runtime error.
    pub fn fence(&mut self, fence: &Fence) -> &mut Self {
        self.fence = Some(fence.clone());
        self.async_load(true)
    }

    /// By default, a newly created sound is attached to the engine's main output graph,
    /// unless [`SoundFlags::NO_DEFAULT_ATTACHMENT`] is set in `flags`.
    ///
    /// Calling this method allows you to override that behavior (regardless of the flag) and immediately connect
    /// the sound to a specific miniaudio node instead.
    ///
    /// # Inputs
    /// `node` is the target node to attach to
    ///
    /// `input_bus` specifies which input bus on that node the sound should be connected to.
    ///
    /// # When you do NOT need this
    /// If you are simply playing sounds through the engine's default output (the most
    /// common case), you should not call this method. The engine will automatically
    /// attach the sound for you.
    pub fn initial_attachment<N: AsNodePtr + ?Sized>(
        &mut self,
        node: &N,
        input_bus: u32,
    ) -> &mut Self {
        self.inner.pInitialAttachment = private_node::node_ptr(node);
        self.inner.initialAttachmentInputBusIndex = input_bus;
        self
    }

    /// Sets the number of input channels for the sound node.
    ///
    /// The "channel" does not refer to a speaker, sound channel and it does not control spatialization directly.
    ///
    /// Is ignored if source is a [`DataSource`](crate::data_source::DataSource)
    ///
    /// This controls how many channels miniaudio expects from the sound's data source.
    /// In most cases this should be left at `0`, which allows miniaudio to infer the
    /// channel count automatically from the source.
    ///
    /// This is primarily useful for custom or procedural data sources.
    pub fn channels_in(&mut self, ch: u32) -> &mut Self {
        self.inner.channelsIn = ch;
        self
    }

    /// Sets the number of output channels for the sound node.
    ///
    /// The "channel" does not refer to a speaker, sound channel and it does not control spatialization directly.
    ///
    /// This controls how many channels the sound outputs into the node graph.
    /// A value of `0` means "use the engine's native channel count", which is the
    /// recommended default.
    ///
    /// Miniaudio will automatically convert between input and output channel counts
    /// as needed (e.g. mono → stereo).
    pub fn channels_out(&mut self, ch: u32) -> &mut Self {
        self.inner.channelsOut = ch;
        self
    }

    /// Sets the [`SoundFlags`]. Removes any existing ones.
    pub fn flags(&mut self, flags: SoundFlags) -> &mut Self {
        self.inner.flags = flags.bits();
        self.flags = flags;
        self
    }

    /// Sets the volume smoothing time, in PCM frames.
    ///
    /// Larger values smooth abrupt volume changes over a longer period.
    pub fn volume_smooth_frames(&mut self, pcm_frames: u32) -> &mut Self {
        self.inner.volumeSmoothTimeInPCMFrames = pcm_frames;
        self
    }

    /// Sets the first PCM frame that can be played.
    ///
    /// Frames before this point are skipped during playback.
    pub fn range_begin_frames(&mut self, pcm_frames: u64) -> &mut Self {
        self.inner.rangeBegInPCMFrames = pcm_frames;
        self
    }

    /// Sets the last PCM frame that can be played.
    ///
    /// Playback stops when this frame is reached.
    pub fn range_end_frames(&mut self, pcm_frames: u64) -> &mut Self {
        self.inner.rangeEndInPCMFrames = pcm_frames;
        self
    }

    /// Sets the loop start position, in PCM frames.
    ///
    /// Only meaningful when looping is enabled.
    pub fn loop_begin_frames(&mut self, pcm_frames: u64) -> &mut Self {
        self.inner.loopPointBegInPCMFrames = pcm_frames;
        self
    }

    /// Sets the loop end position, in PCM frames.
    ///
    /// When reached, playback jumps back to the loop begin frame.
    pub fn loop_end_frames(&mut self, pcm_frames: u64) -> &mut Self {
        self.inner.loopPointEndInPCMFrames = pcm_frames;
        self
    }

    /// Sets the initial seek position, in PCM frames.
    ///
    /// Playback starts from this frame instead of the beginning.
    pub fn seek_point_frames(&mut self, pcm_frames: u64) -> &mut Self {
        self.inner.initialSeekPointInPCMFrames = pcm_frames;
        self
    }

    // TODO: Is engine time correct?
    /// Sets the volume smoothing time, in PCM frames.
    ///
    /// Alternative to `range_begin_frames`. Interprets `millis` in engine time and converts it to PCM frames using the engine sample rate.
    pub fn volume_smooth_millis(&mut self, millis: f64) -> &mut Self {
        self.inner.volumeSmoothTimeInPCMFrames = self.millis_to_frames(millis) as u32;
        self
    }

    // TODO: Is engine time correct?
    /// Anything before this point is skipped during playback.
    ///
    /// Alternative to `range_begin_frames`. Interprets `millis` in engine time and converts it to PCM frames using the engine sample rate.
    pub fn range_begin_millis(&mut self, millis: f64) -> &mut Self {
        self.inner.rangeBegInPCMFrames = self.millis_to_frames(millis);
        self
    }

    // TODO: Is engine time correct?
    /// Playback stops when this frame is reached.
    ///
    /// Alternative to `range_end_frames`. Interprets `millis` in engine time and converts it to PCM frames using the engine sample rate.
    pub fn range_end_millis(&mut self, millis: f64) -> &mut Self {
        self.inner.rangeEndInPCMFrames = self.millis_to_frames(millis);
        self
    }

    // TODO: Is engine time correct?
    /// Alternative to `loop_begin_frames`. Interprets `millis` in engine time and converts it to PCM frames using the engine sample rate.
    pub fn loop_begin_millis(&mut self, millis: f64) -> &mut Self {
        self.inner.loopPointBegInPCMFrames = self.millis_to_frames(millis);
        self
    }

    // TODO: Is engine time correct?
    /// Alternative to `loop_end_frames`. Interprets `millis` in engine time and converts it to PCM frames using the engine sample rate.
    pub fn loop_end_millis(&mut self, millis: f64) -> &mut Self {
        self.inner.loopPointEndInPCMFrames = self.millis_to_frames(millis);
        self
    }

    // TODO: Is engine time correct?
    /// Alternative to `seek_point_frames`. Interprets `millis` in engine time and converts it to PCM frames using the engine sample rate.
    pub fn seek_point_millis(&mut self, millis: f64) -> &mut Self {
        self.inner.initialSeekPointInPCMFrames = self.millis_to_frames(millis);
        self
    }

    /// Convenience method for calling [`Self::range_begin_frames`] and [`Self::range_end_frames`] in the same call
    pub fn range_frames(&mut self, begin: u64, end: u64) -> &mut Self {
        self.inner.rangeBegInPCMFrames = begin;
        self.inner.rangeEndInPCMFrames = end;
        self
    }

    // TODO: Is engine time correct?
    /// Convenience method for calling [`Self::range_begin_millis`] and [`Self::range_end_millis`] in the same call
    ///
    /// Interprets `millis` in engine time and converts it to PCM frames using the engine sample rate.
    pub fn range_millis(&mut self, begin: f64, end: f64) -> &mut Self {
        self.inner.rangeBegInPCMFrames = self.millis_to_frames(begin);
        self.inner.rangeEndInPCMFrames = self.millis_to_frames(end);
        self
    }

    /// Convenience method for calling [`Self::loop_begin_frames`] and [`Self::loop_end_frames`] in the same call
    pub fn loop_frames(&mut self, begin: u64, end: u64) -> &mut Self {
        self.inner.loopPointBegInPCMFrames = begin;
        self.inner.loopPointEndInPCMFrames = end;
        self
    }

    // TODO: Is engine time correct?
    /// Convenience method for calling [`Self::loop_begin_millis`] and [`Self::loop_end_millis`] in the same call
    ///
    /// Interprets `millis` in engine time and converts it to PCM frames using the engine sample rate.
    pub fn loop_millis(&mut self, begin: f64, end: f64) -> &mut Self {
        self.inner.loopPointBegInPCMFrames = self.millis_to_frames(begin);
        self.inner.loopPointEndInPCMFrames = self.millis_to_frames(end);
        self
    }

    /// Equivalent to adding [SoundFlags::LOOPING]
    ///
    /// Does not modify any other existing flags
    pub fn looping(&mut self, yes: bool) -> &mut Self {
        // self.inner.isLooping is deprecated
        let mut flags = SoundFlags::from_bits(self.inner.flags);
        if yes {
            flags.insert(SoundFlags::LOOPING);
        } else {
            flags.remove(SoundFlags::LOOPING);
        }
        self.inner.flags = flags.bits();
        self.flags = flags;
        self
    }

    /// Equivalent to adding [SoundFlags::STREAM]
    ///
    /// Does not modify any other existing flags
    pub fn streaming(&mut self, yes: bool) -> &mut Self {
        let mut flags = SoundFlags::from_bits(self.inner.flags);
        if yes {
            flags.insert(SoundFlags::STREAM);
        } else {
            flags.remove(SoundFlags::STREAM);
        }
        self.inner.flags = flags.bits();
        self.flags = flags;
        self
    }

    /// Equivalent to adding [SoundFlags::DECODE]
    ///
    /// Does not modify any other existing flags
    pub fn decode(&mut self, yes: bool) -> &mut Self {
        let mut flags = SoundFlags::from_bits(self.inner.flags);
        if yes {
            flags.insert(SoundFlags::DECODE);
        } else {
            flags.remove(SoundFlags::DECODE);
        }
        self.inner.flags = flags.bits();
        self.flags = flags;
        self
    }

    /// Equivalent to adding [SoundFlags::ASYNC]
    ///
    /// Does not modify any other existing flags
    pub fn async_load(&mut self, yes: bool) -> &mut Self {
        let mut flags = SoundFlags::from_bits(self.inner.flags);
        if yes {
            flags.insert(SoundFlags::ASYNC);
        } else {
            flags.remove(SoundFlags::ASYNC);
        }
        self.inner.flags = flags.bits();
        self.flags = flags;
        self
    }

    /// Sets the `min_distance` field on the newly created sound
    ///
    /// Equivalent to calling [`Sound::set_min_distance`]
    pub fn min_distance(&mut self, d: f32) -> &mut Self {
        self.sound_state.min_distance = Some(d);
        self
    }

    /// Sets the `max_distance` field on the newly created sound
    ///
    /// Equivalent to calling [`Sound::set_max_distance`]
    pub fn max_distance(&mut self, d: f32) -> &mut Self {
        self.sound_state.max_distance = Some(d);
        self
    }

    /// Sets the `rolloff` field on the newly created sound
    ///
    /// Equivalent to calling [`Sound::set_rolloff`]
    pub fn rolloff(&mut self, r: f32) -> &mut Self {
        self.sound_state.rolloff = Some(r);
        self
    }

    /// Sets the `position` field on the newly created sound
    ///
    /// Equivalent to calling [`Sound::set_position`]
    pub fn position(&mut self, position: Vec3) -> &mut Self {
        self.sound_state.position = Some(position);
        self
    }

    /// Sets the `velocity` field on the newly created sound
    ///
    /// Equivalent to calling [`Sound::set_velocity`]
    pub fn velocity(&mut self, velocity: Vec3) -> &mut Self {
        self.sound_state.velocity = Some(velocity);
        self
    }

    /// Sets the `direction` field on the newly created sound
    ///
    /// Equivalent to calling [`Sound::set_direction`]
    pub fn direction(&mut self, direction: Vec3) -> &mut Self {
        self.sound_state.direction = Some(direction);
        self
    }

    /// Equivalent to calling [`Sound::play_sound()`] after sound is initialized
    pub fn start_playing(&mut self, yes: bool) -> &mut Self {
        self.sound_state.start_playing = yes;
        self
    }

    #[inline]
    pub(crate) fn millis_to_frames(&self, millis: f64) -> u64 {
        if !millis.is_finite() || millis <= 0.0 {
            return 0;
        }
        let sr = self.engine.sample_rate() as f64;
        (millis.max(0.0) * sr / 1000.0).round() as u64
    }

    #[inline]
    pub(crate) fn seconds_to_frames(&self, seconds: f64) -> u64 {
        if !seconds.is_finite() || seconds <= 0.0 {
            return 0;
        }
        let sr = self.engine.sample_rate() as f64;
        (seconds.max(0.0) * sr).round() as u64
    }

    fn configure_sound(&self, sound: &mut Sound) {
        if let Some(min_d) = self.sound_state.min_distance {
            sound.set_min_distance(min_d)
        };
        if let Some(max_d) = self.sound_state.max_distance {
            sound.set_max_distance(max_d)
        };
        if let Some(r) = self.sound_state.rolloff {
            sound.set_rolloff(r);
        }
        if let Some(p) = self.sound_state.position {
            sound.set_position(p);
        }
        if let Some(v) = self.sound_state.velocity {
            sound.set_velocity(v);
        }
        if let Some(d) = self.sound_state.direction {
            sound.set_direction(d);
        }
    }

    /// Some flags don't make sense without a source.
    fn check_flags_without_source(&self) -> MaResult<()> {
        let invalid_flags: SoundFlags =
            SoundFlags::STREAM | SoundFlags::DECODE | SoundFlags::ASYNC | SoundFlags::WAIT_INIT;

        if self.flags.intersects(invalid_flags) {
            return Err(crate::MaudioError::from_ma_result(
                sys::ma_result_MA_INVALID_ARGS,
            ));
        }

        Ok(())
    }

    /// Sets the source in the config. This way, we can call ma_sound_init_ex for all source types (including None)
    fn set_source(&mut self) -> MaResult<()> {
        let null_fields = |cfg: &mut SoundBuilder| {
            cfg.inner.pDataSource = core::ptr::null_mut();
            cfg.inner.pFilePath = core::ptr::null();
            cfg.inner.pFilePathW = core::ptr::null();
        };
        match self.source {
            SoundSource::None => null_fields(self),
            SoundSource::DataSource(src) => {
                null_fields(self);
                self.inner.pDataSource = private_data_source::source_ptr(&src);
            }
            #[cfg(unix)]
            SoundSource::FileUtf8(ref p) => {
                let cstring = crate::engine::cstring_from_path(p)?;
                null_fields(self);
                self.inner.pFilePath = cstring.as_ptr();
                self.owned_path = OwnedPathBuf::Utf8(cstring); // keep the pointer alive
            }
            #[cfg(windows)]
            SoundSource::FileWide(ref p) => {
                let wide_path = crate::engine::wide_null_terminated(p);
                null_fields(self);
                self.inner.pFilePathW = wide_path.as_ptr();
                self.owned_path = OwnedPathBuf::Wide(wide_path); // keep the pointer alive
            }
        }
        Ok(())
    }
}

impl<'a, 'b> SoundBuilder<'a, 'b> {
    pub(crate) fn init(inner: &'a Engine) -> Self {
        let ptr = unsafe { sys::ma_sound_config_init_2(inner.to_raw()) };
        let state = SoundState::default();
        Self {
            inner: ptr,
            engine: inner,
            source: SoundSource::None,
            owned_path: OwnedPathBuf::None,
            group: None,
            fence: None,
            flags: SoundFlags::NONE,
            end_notifier: None,
            sound_state: state,
        }
    }
}

#[cfg(test)]
mod test {
    use crate::engine::Engine;

    #[test]
    fn sound_builder_test_basic() {
        let engine = Engine::new_for_tests().unwrap();
        let _sound = engine.sound_config().channels_in(1).build().unwrap();
    }
}