maudio 0.1.3

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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
//! High level audio engine.
//!
//! [`Engine`] is the main entry point for playback and mixing. It wraps
//! miniaudio’s `ma_engine` and provides access to the engine’s global clock,
//! output format (channels + sample rate), and endpoint node.
//!
//! Internally, the engine coordinates:
//! - a resource manager for loading and caching audio data
//! - a node graph for routing, mixing, and processing audio
//! - an output device and global engine clock
//!
//! ## Quick start
//! ```no_run
//! # use maudio::engine::Engine;
//! # fn main() -> maudio::MaResult<()> {
//! let engine = Engine::new()?;
//! // let mut sound = engine.new_sound_from_file("music.ogg")?;
//! // sound.play_sound()?;
//! /* block the main thread while the sound is playing */
//! # Ok(())
//! # }
//! ```
//!
//! ## Resource manager
//! The resource manager handles loading and lifetime management of audio data
//! (for example, decoding audio files and sharing them between sounds).
//!
//! While the resource manager can be used independently in miniaudio, the
//! engine provides a higher-level abstraction that integrates it directly
//! with playback and mixing.
//!
//! ## Node graph
//! Audio flows through the engine’s internal node graph. Each sound is
//! represented as a node, and all nodes ultimately connect to the engine’s
//! endpoint.
//! See [`node_graph::NodeGraph`]
//!
//! Advanced users can access the endpoint node via [`EngineOps::endpoint()`] to
//! attach custom processing or inspect the graph.
//!
//! ## Time
//! The engine maintains a global timeline that advances as audio is processed.
//! Time can be queried or modified in either PCM frames or milliseconds.
//!
//! For sample-accurate control, prefer the PCM-frame APIs.
use std::{cell::Cell, marker::PhantomData, mem::MaybeUninit, path::Path, sync::Arc};

use crate::{
    audio::{
        formats::SampleBuffer, math::vec3::Vec3, sample_rate::SampleRate, spatial::cone::Cone,
    },
    data_source::AsSourcePtr,
    engine::{
        engine_builder::EngineBuilder,
        node_graph::{nodes::NodeRef, NodeGraphRef},
        process_notifier::ProcessState,
        resource::ResourceManagerRef,
    },
    sound::{
        sound_builder::SoundBuilder,
        sound_ffi,
        sound_flags::SoundFlags,
        sound_group::{s_group_cfg_ffi, s_group_ffi, SoundGroup, SoundGroupConfig},
        Sound,
    },
    util::fence::Fence,
    AsRawRef, Binding, MaResult,
};

use maudio_sys::ffi as sys;

pub mod engine_builder;
#[cfg(feature = "engine_host")]
pub mod engine_host;

pub mod node_graph;
pub mod process_notifier;
mod resource;

/// High-level audio engine.
///
/// `Engine` is the main entry point for playback and mixing. Internally it wraps
/// a `ma_engine` from miniaudio, which owns (or coordinates) the output device,
/// the engine’s node graph, and the global engine clock.
///
/// Most users will:
/// - create an [`Engine`]
/// - load or create sounds
/// - control playback and volume
/// - optionally interact with the engine’s endpoint node / node graph for effects
pub struct Engine {
    inner: *mut sys::ma_engine,
    process_notifier: Option<Arc<ProcessState>>,
    _not_sync: PhantomData<Cell<()>>,
}

impl Binding for Engine {
    type Raw = *mut sys::ma_engine;

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

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

/// Borrowed view of the engine
#[derive(Clone, Copy)]
pub struct EngineRef<'a> {
    ptr: *mut sys::ma_engine,
    _marker: PhantomData<&'a ()>,
    _not_sync: PhantomData<Cell<()>>,
}

unsafe impl Send for Engine {}

impl<'a> Binding for EngineRef<'a> {
    type Raw = *mut sys::ma_engine;

    fn from_ptr(raw: Self::Raw) -> Self {
        EngineRef {
            ptr: raw,
            _marker: PhantomData,
            _not_sync: PhantomData,
        }
    }

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

pub(crate) mod private_engine {
    use super::*;
    use maudio_sys::ffi as sys;

    pub trait EnginePtrProvider<T: ?Sized> {
        fn as_engine_ptr(t: &T) -> *mut sys::ma_engine;
    }

    pub struct EngineProvider;
    pub struct EngineRefProvider;

    impl EnginePtrProvider<Engine> for EngineProvider {
        #[inline]
        fn as_engine_ptr(t: &Engine) -> *mut sys::ma_engine {
            t.to_raw()
        }
    }

    impl<'a> EnginePtrProvider<EngineRef<'a>> for EngineRefProvider {
        fn as_engine_ptr(t: &EngineRef<'a>) -> *mut sys::ma_engine {
            t.to_raw()
        }
    }

    pub fn engine_ptr<T: AsEnginePtr + ?Sized>(t: &T) -> *mut sys::ma_engine {
        <T as AsEnginePtr>::__PtrProvider::as_engine_ptr(t)
    }
}

#[doc(hidden)]
pub trait AsEnginePtr {
    type __PtrProvider: private_engine::EnginePtrProvider<Self>;
}

#[doc(hidden)]
impl AsEnginePtr for Engine {
    type __PtrProvider = private_engine::EngineProvider;
}

#[doc(hidden)]
impl AsEnginePtr for EngineRef<'_> {
    type __PtrProvider = private_engine::EngineRefProvider;
}

impl<T: AsEnginePtr + ?Sized> EngineOps for T {}

/// EngineOps trait contains shared methods for [`Engine`] and [`EngineRef`]
pub trait EngineOps: AsEnginePtr {
    /// Sets the master volume (of the output node).
    fn set_volume(&self, volume: f32) -> MaResult<()> {
        engine_ffi::ma_engine_set_volume(self, volume)
    }

    /// Returns the master volume.
    fn volume(&self) -> f32 {
        engine_ffi::ma_engine_get_volume(self)
    }

    /// Sets the master gain in dB.
    fn set_gain_db(&self, db_gain: f32) -> MaResult<()> {
        engine_ffi::ma_engine_set_gain_db(self, db_gain)
    }

    /// Returns the master gain in dB.
    fn gain_db(&self) -> f32 {
        engine_ffi::ma_engine_get_gain_db(self)
    }

    /// Returns the number of listeners.
    fn listener_count(&self) -> u32 {
        engine_ffi::ma_engine_get_listener_count(self)
    }

    /// Returns the index of the closest listener to `position`.
    fn closest_listener(&self, position: Vec3) -> u32 {
        engine_ffi::ma_engine_find_closest_listener(self, position)
    }

    /// Sets the position of `listener`.
    fn set_position(&self, listener: u32, position: Vec3) {
        engine_ffi::ma_engine_listener_set_position(self, listener, position);
    }

    /// Returns the position of `listener`.
    fn position(&self, listener: u32) -> Vec3 {
        engine_ffi::ma_engine_listener_get_position(self, listener)
    }

    /// Sets the facing direction of `listener`.
    fn set_direction(&self, listener: u32, direction: Vec3) {
        engine_ffi::ma_engine_listener_set_direction(self, listener, direction);
    }

    /// Returns the facing direction of `listener`.
    fn direction(&self, listener: u32) -> Vec3 {
        engine_ffi::ma_engine_listener_get_direction(self, listener)
    }

    /// Sets the velocity of `listener`.
    fn set_velocity(&self, listener: u32, position: Vec3) {
        engine_ffi::ma_engine_listener_set_velocity(self, listener, position);
    }

    /// Returns the velocity of `listener`.
    fn velocity(&self, listener: u32) -> Vec3 {
        engine_ffi::ma_engine_listener_get_velocity(self, listener)
    }

    /// Sets the directional cone of `listener`.
    fn set_cone(&self, listener: u32, cone: Cone) {
        engine_ffi::ma_engine_listener_set_cone(self, listener, cone);
    }

    /// Returns the directional cone of `listener`.
    fn cone(&self, listener: u32) -> Cone {
        engine_ffi::ma_engine_listener_get_cone(self, listener)
    }

    /// Sets the world-up vector of `listener`.
    fn set_world_up(&self, listener: u32, up_direction: Vec3) {
        engine_ffi::ma_engine_listener_set_world_up(self, listener, up_direction);
    }

    /// Returns the world-up vector of `listener`.
    fn get_world_up(&self, listener: u32) -> Vec3 {
        engine_ffi::ma_engine_listener_get_world_up(self, listener)
    }

    /// Enables or disables `listener`.
    fn toggle_listener(&self, listener: u32, enabled: bool) {
        engine_ffi::ma_engine_listener_set_enabled(self, listener, enabled);
    }

    /// Returns `true` if `listener` is enabled.
    fn listener_enabled(&self, listener: u32) -> bool {
        engine_ffi::ma_engine_listener_is_enabled(self, listener)
    }

    /// Returns the engine's internal node graph, if available.
    fn as_node_graph(&self) -> Option<NodeGraphRef<'_>> {
        engine_ffi::ma_engine_get_node_graph(self)
    }

    /// Returns the engine's internal resource manager, if available.
    fn resource_manager(&self) -> Option<ResourceManagerRef<'_>> {
        engine_ffi::ma_engine_get_resource_manager(self)
    }

    /// Reads PCM frames into `dst`, returning the number of frames read.
    fn read_pcm_frames_into(&self, dst: &mut [f32]) -> MaResult<usize> {
        engine_ffi::ma_engine_read_pcm_frames_into(self, dst)
    }

    /// This function pulls audio from the engine’s internal node graph and returns
    /// up to `frame_count` frames of interleaved PCM samples.
    ///
    /// - This is a **pull-based render operation**.
    /// - The engine will attempt to render `frame_count` frames, but it may return
    ///   **fewer frames**.
    fn read_pcm_frames(&self, frame_count: u64) -> MaResult<SampleBuffer<f32>> {
        engine_ffi::ma_engine_read_pcm_frames(self, frame_count)
    }

    /// Returns the engine’s **endpoint node**.
    ///
    /// The endpoint node is the final node in the engine’s internal node graph.
    /// All sounds ultimately connect to this node before audio is sent to the
    /// output device.
    fn endpoint(&self) -> Option<NodeRef<'_>> {
        engine_ffi::ma_engine_get_endpoint(self)
    }

    /// Returns the current local time (in PCM frames) of the output node.
    fn time_pcm(&self) -> u64 {
        engine_ffi::ma_engine_get_time_in_pcm_frames(self)
    }

    /// Returns the current local time (in PCM frames) of the output node.
    ///
    /// For sample-accurate work, prefer [`EngineOps::time_pcm()`].
    fn time_mili(&self) -> u64 {
        engine_ffi::ma_engine_get_time_in_milliseconds(self)
    }

    /// Sets the current local time (in PCM frames) of the output node.
    fn set_time_pcm(&self, time: u64) {
        engine_ffi::ma_engine_set_time_in_pcm_frames(self, time);
    }

    /// Sets the current local time (in PCM frames) of the output node.
    ///
    /// Precision may be lower than [`EngineOps::set_time_pcm()`].
    fn set_time_mili(&self, time: u64) {
        engine_ffi::ma_engine_set_time_in_milliseconds(self, time);
    }

    /// Returns the number of output **channels** used by the engine.
    /// and output device.
    fn channels(&self) -> u32 {
        engine_ffi::ma_engine_get_channels(self)
    }

    /// Returns the engine’s **sample rate**, in Hz.
    fn sample_rate(&self) -> u32 {
        engine_ffi::ma_engine_get_sample_rate(self)
    }
}

// These should be available to EngineRef
impl Engine {
    /// Creates a new engine using the default configuration.
    ///
    /// This is a convenience constructor equivalent to using
    /// an [`EngineBuilder`] (`ma_engine_config`) with a default configuration.
    ///
    /// Most applications should start with this method.
    pub fn new() -> MaResult<Self> {
        Self::new_with_config(None)
    }

    pub(crate) fn new_for_tests() -> MaResult<Self> {
        if cfg!(feature = "ci-tests") {
            EngineBuilder::new()
                .no_device(true)
                .set_channels(2)
                .set_sample_rate(SampleRate::Sr44100)
                .build()
        } else {
            Engine::new()
        }
    }

    fn new_with_config(config: Option<&EngineBuilder>) -> MaResult<Self> {
        let mut mem: Box<MaybeUninit<sys::ma_engine>> = Box::new(MaybeUninit::uninit());
        engine_ffi::engine_init(config, mem.as_mut_ptr())?;
        // Safety: If mem is not initialized, engine_init will return an error
        let inner: *mut sys::ma_engine = Box::into_raw(mem) as *mut sys::ma_engine;
        Ok(Self {
            inner,
            process_notifier: None,
            _not_sync: PhantomData,
        })
    }

    /// Equivalent to calling [`SoundBuilder::new()`]
    pub fn sound(&self) -> SoundBuilder<'_> {
        SoundBuilder::init(self)
    }

    pub fn new_sound(&self) -> MaResult<Sound<'_>> {
        self.new_sound_with_config_internal(None)
    }

    pub fn new_sound_from_file(&self, path: &Path) -> MaResult<Sound<'_>> {
        self.new_sound_with_file_internal(path, SoundFlags::NONE, None, None)
    }

    pub fn new_sound_from_source<D: AsSourcePtr + ?Sized>(
        &self,
        source: &D,
    ) -> MaResult<Sound<'_>> {
        self.new_sound_with_source_internal(SoundFlags::NONE, None, source)
    }

    /// Manually starts the engine
    ///
    /// By default, an engine will be created with `no_auto_start` to false.
    /// Setting [`EngineBuilder::no_auto_start()`] will require a manual start
    ///
    /// Start and stop operations on an engine with no device will result in an error
    pub fn start(&self) -> MaResult<()> {
        engine_ffi::ma_engine_start(self)
    }

    /// Manually stops the engine
    ///
    /// Start and stop operations on an engine with no device will result in an error
    pub fn stop(&self) -> MaResult<()> {
        engine_ffi::ma_engine_stop(self)
    }

    pub fn new_sound_from_file_with_group<'a>(
        &'a self,
        path: &Path,
        sound_group: &'a SoundGroup,
        done_fence: Option<&Fence>,
    ) -> MaResult<Sound<'a>> {
        self.new_sound_with_file_internal(path, SoundFlags::NONE, Some(sound_group), done_fence)
    }

    /// Adding a Fence also requires setting the [`SoundFlags::ASYNC`] flag
    pub fn new_sound_from_file_with_flags(
        &self,
        path: &Path,
        flags: SoundFlags,
        done_fence: Option<&Fence>,
    ) -> MaResult<Sound<'_>> {
        self.new_sound_with_file_internal(path, flags, None, done_fence)
    }

    pub(crate) fn new_sound_with_config_internal(
        &self,
        config: Option<&SoundBuilder>,
    ) -> MaResult<Sound<'_>> {
        let temp_config = SoundBuilder::init(self);
        let config = config.unwrap_or(&temp_config);
        let mut mem: Box<MaybeUninit<sys::ma_sound>> = Box::new(MaybeUninit::uninit());

        sound_ffi::ma_sound_init_ex(self, config, mem.as_mut_ptr())?;

        let inner: *mut sys::ma_sound = Box::into_raw(mem) as *mut sys::ma_sound;
        Ok(Sound::from_ptr(inner))
    }

    pub(crate) fn new_sound_with_source_internal<'a, D: AsSourcePtr + ?Sized>(
        &'a self,
        flags: SoundFlags,
        sound_group: Option<&'a SoundGroup>,
        data_source: &D,
    ) -> MaResult<Sound<'a>> {
        let mut mem: Box<MaybeUninit<sys::ma_sound>> = Box::new(MaybeUninit::uninit());

        sound_ffi::ma_sound_init_from_data_source(
            self,
            data_source,
            flags,
            sound_group,
            mem.as_mut_ptr(),
        )?;

        let inner: *mut sys::ma_sound = Box::into_raw(mem) as *mut sys::ma_sound;
        Ok(Sound::from_ptr(inner))
    }

    pub(crate) fn new_sound_with_file_internal<'a>(
        &'a self,
        path: &Path,
        flags: SoundFlags,
        sound_group: Option<&'a SoundGroup>,
        done_fence: Option<&Fence>,
    ) -> MaResult<Sound<'a>> {
        let mut mem: Box<MaybeUninit<sys::ma_sound>> = Box::new(MaybeUninit::uninit());

        Sound::init_from_file_internal(
            mem.as_mut_ptr(),
            self,
            path,
            flags,
            sound_group,
            done_fence,
        )?;

        let inner: *mut sys::ma_sound = Box::into_raw(mem) as *mut sys::ma_sound;
        Ok(Sound::from_ptr(inner))
    }

    pub fn clone_sound(&self, sound: &Sound, flags: SoundFlags) -> MaResult<Sound<'_>> {
        self.new_sound_instance_internal(sound, flags, None)
    }

    fn new_sound_instance_internal<'a>(
        &'a self,
        sound: &Sound,
        flags: SoundFlags,
        sound_group: Option<&mut SoundGroup>,
    ) -> MaResult<Sound<'a>> {
        let mut mem: Box<MaybeUninit<sys::ma_sound>> = Box::new(MaybeUninit::uninit());

        sound_ffi::ma_sound_init_copy(self, sound, flags, sound_group, mem.as_mut_ptr())?;

        let inner: *mut sys::ma_sound = Box::into_raw(mem) as *mut sys::ma_sound;
        Ok(Sound::from_ptr(inner))
    }

    pub fn new_sound_group(&self) -> MaResult<SoundGroup<'_>> {
        let mut mem: Box<MaybeUninit<sys::ma_sound_group>> = Box::new(MaybeUninit::uninit());
        let config = self.new_sound_group_config();

        s_group_ffi::ma_sound_group_init_ex(self, config, mem.as_mut_ptr())?;

        let inner: *mut sys::ma_sound_group = Box::into_raw(mem) as *mut sys::ma_sound_group;
        Ok(SoundGroup::from_ptr(inner))
    }

    pub fn new_sound_group_config(&self) -> SoundGroupConfig {
        s_group_cfg_ffi::ma_sound_group_config_init_2(self)
    }
}

impl Drop for Engine {
    fn drop(&mut self) {
        engine_ffi::engine_uninit(self);
        drop(unsafe { Box::from_raw(self.to_raw()) });
    }
}

#[cfg(unix)]
pub(crate) fn cstring_from_path(path: &Path) -> MaResult<std::ffi::CString> {
    use std::os::unix::ffi::OsStrExt;
    std::ffi::CString::new(path.as_os_str().as_bytes())
        .map_err(|_| crate::MaudioError::new_ma_error(crate::ErrorKinds::InvalidCString))
}

#[cfg(windows)]
pub(crate) fn wide_null_terminated(path: &Path) -> Vec<u16> {
    use std::os::windows::ffi::OsStrExt;

    path.as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect()
}

#[cfg(windows)]
pub(crate) fn wide_null_terminated_name(path: &str) -> Vec<u16> {
    use std::os::windows::prelude::OsStrExt;

    std::ffi::OsStr::new(name)
        .encode_wide()
        .chain(std::iter::once(0))
        .collect()
}
/// Custom memory allocation callbacks for miniaudio.
///
/// Miniaudio allows callers to override how heap memory is allocated and freed
/// by providing a `ma_allocation_callbacks` struct (malloc/realloc/free + user data).
///
/// Types such as `NodeGraph` may accept these callbacks at initialization time.
/// If callbacks are not provided, miniaudio uses its default allocator
/// (typically the system allocator).
///
/// ## Lifetimes when borrowed by other types
///
/// `AllocationCallbacks` itself owns the callback table and does not carry a lifetime.
/// However, types that *borrow* an `AllocationCallbacks` (for example `NodeGraph<'a>`)
/// use a lifetime parameter to ensure the callbacks outlive the initialized object.
///
/// This matters because miniaudio requires the same allocation callbacks to be passed
/// again during uninitialization so it can free any internal allocations consistently.
pub struct AllocationCallbacks {
    inner: sys::ma_allocation_callbacks,
}

impl AsRawRef for AllocationCallbacks {
    type Raw = sys::ma_allocation_callbacks;

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

#[cfg(test)]
mod test {
    use super::*;

    fn assert_f32_eq(a: f32, b: f32) {
        assert!(
            (a - b).abs() <= 1.0e-6,
            "expected {a} ~= {b}, diff={}",
            (a - b).abs()
        );
    }

    #[test]
    fn engine_test_works_with_default() {
        let _engine = Engine::new_for_tests().unwrap();
    }

    fn assert_vec3_eq(a: Vec3, b: Vec3) {
        assert_f32_eq(a.x, b.x);
        assert_f32_eq(a.y, b.y);
        assert_f32_eq(a.z, b.z);
    }

    #[test]
    fn test_engine_test_init_engine_and_sound() {
        let engine = Engine::new_for_tests().unwrap();
        let _sound = engine.new_sound().unwrap();
    }

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

        engine.set_volume(0.25).unwrap();
        assert_f32_eq(engine.volume(), 0.25);

        engine.set_volume(1.0).unwrap();
        assert_f32_eq(engine.volume(), 1.0);
    }

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

        engine.set_gain_db(-6.0).unwrap();
        assert_f32_eq(engine.gain_db(), -6.0);

        engine.set_gain_db(0.0).unwrap();
        assert_f32_eq(engine.gain_db(), 0.0);
    }

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

        let n = engine.listener_count();
        assert!(n >= 1, "engine should have at least 1 listener");

        // Toggle first listener (should always exist if n>=1).
        engine.toggle_listener(0, false);
        assert!(!engine.listener_enabled(0));

        engine.toggle_listener(0, true);
        assert!(engine.listener_enabled(0));
    }

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

        let p = Vec3 {
            x: 1.0,
            y: 2.0,
            z: 3.0,
        };
        engine.set_position(0, p);

        let got = engine.position(0);
        assert_vec3_eq(got, p);
    }

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

        let v = Vec3 {
            x: -1.0,
            y: 0.5,
            z: 10.0,
        };
        engine.set_velocity(0, v);

        let got = engine.velocity(0);
        assert_vec3_eq(got, v);
    }

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

        let up = Vec3 {
            x: 0.0,
            y: 1.0,
            z: 0.0,
        };
        engine.set_world_up(0, up);

        let got = engine.get_world_up(0);
        assert_vec3_eq(got, up);
    }

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

        // Adjust field names if your Cone differs; the point is roundtripping.
        let cone = Cone {
            inner_angle_rad: 0.5,
            outer_angle_rad: 1.0,
            outer_gain: 0.25,
        };

        engine.set_cone(0, cone);
        let got = engine.cone(0);

        assert_f32_eq(got.inner_angle_rad, cone.inner_angle_rad);
        assert_f32_eq(got.outer_angle_rad, cone.outer_angle_rad);
        assert_f32_eq(got.outer_gain, cone.outer_gain);
    }

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

        // If only 1 listener, the only valid answer is 0.
        let n = engine.listener_count();
        if n < 2 {
            let idx = engine.closest_listener(Vec3 {
                x: 100.0,
                y: 0.0,
                z: 0.0,
            });
            assert_eq!(idx, 0);
            return;
        }

        // If >=2 listeners, we can make a meaningful test.
        engine.set_position(
            0,
            Vec3 {
                x: 0.0,
                y: 0.0,
                z: 0.0,
            },
        );
        engine.set_position(
            1,
            Vec3 {
                x: 1000.0,
                y: 0.0,
                z: 0.0,
            },
        );

        let idx = engine.closest_listener(Vec3 {
            x: 0.1,
            y: 0.0,
            z: 0.0,
        });
        assert_eq!(idx, 0);

        let idx = engine.closest_listener(Vec3 {
            x: 999.9,
            y: 0.0,
            z: 0.0,
        });
        assert_eq!(idx, 1);
    }

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

        let graph = engine.as_node_graph();
        assert!(graph.is_some(), "engine should expose a node graph");

        let endpoint = engine.endpoint();
        assert!(endpoint.is_some(), "engine should expose an endpoint node");
    }

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

        let requested = 256u64;
        let buffer = engine.read_pcm_frames(requested).unwrap();
        let frames = buffer.frames() as u64;
        let samples = buffer.as_ref();

        assert!(
            frames <= requested,
            "engine returned more frames than requested"
        );

        let channels = engine.channels() as u64;
        assert!(channels >= 1);

        let expected_len = (frames * channels) as usize;
        assert_eq!(
            samples.len(),
            expected_len,
            "samples must be interleaved: len == frames * channels"
        );
    }

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

        engine.set_time_pcm(12345);
        assert_eq!(engine.time_pcm(), 12345);

        engine.set_time_pcm(0);
        assert_eq!(engine.time_pcm(), 0);
    }

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

        engine.set_time_mili(500);
        assert_eq!(engine.time_mili(), 500);

        engine.set_time_mili(0);
        assert_eq!(engine.time_mili(), 0);
    }

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

        let ch = engine.channels();
        let sr = engine.sample_rate();

        assert!(ch >= 1, "channels must be >= 1");
        assert!(sr >= 8000, "sample rate looks wrong: {sr}");
    }

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

        let dir = Vec3 {
            x: 0.0,
            y: 0.0,
            z: -1.0,
        };
        engine.set_direction(0, dir);

        let got = engine.direction(0);
        assert_vec3_eq(got, dir);
    }
}

pub(crate) mod engine_ffi {
    use maudio_sys::ffi as sys;

    use crate::{
        audio::{formats::SampleBuffer, math::vec3::Vec3, spatial::cone::Cone},
        engine::{
            engine_builder::EngineBuilder,
            node_graph::{nodes::NodeRef, NodeGraphRef},
            private_engine,
            resource::ResourceManagerRef,
            AsEnginePtr, Binding, Engine, EngineOps,
        },
        AsRawRef, MaResult, MaudioError,
    };

    #[inline]
    pub fn engine_init(
        config: Option<&EngineBuilder>,
        engine: *mut sys::ma_engine,
    ) -> MaResult<()> {
        let p_config: *const sys::ma_engine_config =
            config.map_or(core::ptr::null(), |c| c.as_raw_ptr());
        let res = unsafe { sys::ma_engine_init(p_config, engine) };
        MaudioError::check(res)
    }

    #[inline]
    pub fn engine_uninit(engine: &Engine) {
        unsafe {
            sys::ma_engine_uninit(engine.to_raw());
        }
    }

    #[inline]
    pub fn ma_engine_read_pcm_frames_into<E: AsEnginePtr + ?Sized>(
        engine: &E,
        dst: &mut [f32],
    ) -> MaResult<usize> {
        let channels = engine.channels();
        let len = dst.len() as u64;

        if channels == 0 {
            return Err(MaudioError::from_ma_result(sys::ma_result_MA_INVALID_ARGS));
        }

        // May truncate, and that is desired
        let frame_count = len / channels as u64;

        let mut frames_read = 0;
        let res = unsafe {
            sys::ma_engine_read_pcm_frames(
                private_engine::engine_ptr(engine),
                dst.as_mut_ptr() as *mut std::ffi::c_void,
                frame_count,
                &mut frames_read,
            )
        };
        MaudioError::check(res)?;

        Ok(frames_read as usize)
    }

    #[inline]
    pub fn ma_engine_read_pcm_frames<E: AsEnginePtr + ?Sized>(
        engine: &E,
        frame_count: u64,
    ) -> MaResult<SampleBuffer<f32>> {
        let channels = engine.channels();
        let mut buffer = vec![0.0f32; (frame_count * channels as u64) as usize];
        let mut frames_read = 0;
        let res = unsafe {
            sys::ma_engine_read_pcm_frames(
                private_engine::engine_ptr(engine),
                buffer.as_mut_ptr() as *mut std::ffi::c_void,
                frame_count,
                &mut frames_read,
            )
        };
        MaudioError::check(res)?;
        SampleBuffer::<f32>::from_storage(buffer, frames_read as usize, channels)
    }

    #[inline]
    pub fn ma_engine_get_node_graph<'a, E: AsEnginePtr + ?Sized>(
        engine: &'a E,
    ) -> Option<NodeGraphRef<'a>> {
        let ptr = unsafe { sys::ma_engine_get_node_graph(private_engine::engine_ptr(engine)) };
        if ptr.is_null() {
            None
        } else {
            Some(NodeGraphRef::from_ptr(ptr))
        }
    }

    #[inline]
    pub fn ma_engine_get_resource_manager<'a, E: AsEnginePtr + ?Sized>(
        engine: &'a E,
    ) -> Option<ResourceManagerRef<'a>> {
        let ptr =
            unsafe { sys::ma_engine_get_resource_manager(private_engine::engine_ptr(engine)) };
        if ptr.is_null() {
            None
        } else {
            Some(ResourceManagerRef::from_ptr(ptr))
        }
    }

    // AsEnginePtr
    // TODO: Create Device(Ref?)
    #[inline]
    pub fn ma_engine_get_device(engine: &Engine) -> *mut sys::ma_device {
        unsafe { sys::ma_engine_get_device(engine.to_raw()) }
    }

    // AsEnginePtr
    // TODO: Implement Log(Ref?)
    #[inline]
    pub fn ma_engine_get_log(engine: &Engine) -> *mut sys::ma_log {
        unsafe { sys::ma_engine_get_log(engine.to_raw()) }
    }

    #[inline]
    pub fn ma_engine_get_endpoint<'a, E: AsEnginePtr + ?Sized>(
        engine: &'a E,
    ) -> Option<NodeRef<'a>> {
        let ptr = unsafe { sys::ma_engine_get_endpoint(private_engine::engine_ptr(engine)) };
        if ptr.is_null() {
            None
        } else {
            Some(NodeRef::from_ptr(ptr))
        }
    }

    #[inline]
    pub fn ma_engine_get_time_in_pcm_frames<E: AsEnginePtr + ?Sized>(engine: &E) -> u64 {
        unsafe {
            sys::ma_engine_get_time_in_pcm_frames(private_engine::engine_ptr(engine) as *const _)
        }
    }

    #[inline]
    pub fn ma_engine_get_time_in_milliseconds<E: AsEnginePtr + ?Sized>(engine: &E) -> u64 {
        unsafe {
            sys::ma_engine_get_time_in_milliseconds(private_engine::engine_ptr(engine) as *const _)
        }
    }

    #[inline]
    pub fn ma_engine_set_time_in_pcm_frames<E: AsEnginePtr + ?Sized>(engine: &E, time: u64) {
        unsafe { sys::ma_engine_set_time_in_pcm_frames(private_engine::engine_ptr(engine), time) };
    }

    #[inline]
    pub fn ma_engine_set_time_in_milliseconds<E: AsEnginePtr + ?Sized>(engine: &E, time: u64) {
        unsafe {
            sys::ma_engine_set_time_in_milliseconds(private_engine::engine_ptr(engine), time)
        };
    }

    #[inline]
    pub fn ma_engine_get_channels<E: AsEnginePtr + ?Sized>(engine: &E) -> u32 {
        unsafe { sys::ma_engine_get_channels(private_engine::engine_ptr(engine) as *const _) }
    }

    #[inline]
    pub fn ma_engine_get_sample_rate<E: AsEnginePtr + ?Sized>(engine: &E) -> u32 {
        unsafe { sys::ma_engine_get_sample_rate(private_engine::engine_ptr(engine) as *const _) }
    }

    #[inline]
    pub fn ma_engine_start(engine: &Engine) -> MaResult<()> {
        let res = unsafe { sys::ma_engine_start(engine.to_raw()) };
        MaudioError::check(res)
    }

    #[inline]
    pub fn ma_engine_stop(engine: &Engine) -> MaResult<()> {
        let res = unsafe { sys::ma_engine_stop(engine.to_raw()) };
        MaudioError::check(res)
    }

    #[inline]
    pub fn ma_engine_set_volume<E: AsEnginePtr + ?Sized>(engine: &E, volume: f32) -> MaResult<()> {
        let res = unsafe { sys::ma_engine_set_volume(private_engine::engine_ptr(engine), volume) };
        MaudioError::check(res)
    }

    #[inline]
    pub fn ma_engine_get_volume<E: AsEnginePtr + ?Sized>(engine: &E) -> f32 {
        unsafe { sys::ma_engine_get_volume(private_engine::engine_ptr(engine)) }
    }

    #[inline]
    pub fn ma_engine_set_gain_db<E: AsEnginePtr + ?Sized>(
        engine: &E,
        db_gain: f32,
    ) -> MaResult<()> {
        let res =
            unsafe { sys::ma_engine_set_gain_db(private_engine::engine_ptr(engine), db_gain) };
        MaudioError::check(res)
    }

    #[inline]
    pub fn ma_engine_get_gain_db<E: AsEnginePtr + ?Sized>(engine: &E) -> f32 {
        unsafe { sys::ma_engine_get_gain_db(private_engine::engine_ptr(engine)) }
    }

    #[inline]
    pub fn ma_engine_get_listener_count<E: AsEnginePtr + ?Sized>(engine: &E) -> u32 {
        unsafe { sys::ma_engine_get_listener_count(private_engine::engine_ptr(engine) as *const _) }
    }

    #[inline]
    pub fn ma_engine_find_closest_listener<E: AsEnginePtr + ?Sized>(
        engine: &E,
        position: Vec3,
    ) -> u32 {
        unsafe {
            sys::ma_engine_find_closest_listener(
                private_engine::engine_ptr(engine) as *const _,
                position.x,
                position.y,
                position.z,
            )
        }
    }

    #[inline]
    pub fn ma_engine_listener_set_position<E: AsEnginePtr + ?Sized>(
        engine: &E,
        listener: u32,
        position: Vec3,
    ) {
        unsafe {
            sys::ma_engine_listener_set_position(
                private_engine::engine_ptr(engine),
                listener,
                position.x,
                position.y,
                position.z,
            )
        };
    }

    #[inline]
    pub fn ma_engine_listener_get_position<E: AsEnginePtr + ?Sized>(
        engine: &E,
        listener: u32,
    ) -> Vec3 {
        let vec = unsafe {
            sys::ma_engine_listener_get_position(
                private_engine::engine_ptr(engine) as *const _,
                listener,
            )
        };
        vec.into()
    }

    #[inline]
    pub fn ma_engine_listener_set_direction<E: AsEnginePtr + ?Sized>(
        engine: &E,
        listener: u32,
        position: Vec3,
    ) {
        unsafe {
            sys::ma_engine_listener_set_direction(
                private_engine::engine_ptr(engine),
                listener,
                position.x,
                position.y,
                position.z,
            )
        };
    }

    #[inline]
    pub fn ma_engine_listener_get_direction<E: AsEnginePtr + ?Sized>(
        engine: &E,
        listener: u32,
    ) -> Vec3 {
        let vec = unsafe {
            sys::ma_engine_listener_get_direction(
                private_engine::engine_ptr(engine) as *const _,
                listener,
            )
        };
        vec.into()
    }

    #[inline]
    pub fn ma_engine_listener_set_velocity<E: AsEnginePtr + ?Sized>(
        engine: &E,
        listener: u32,
        position: Vec3,
    ) {
        unsafe {
            sys::ma_engine_listener_set_velocity(
                private_engine::engine_ptr(engine),
                listener,
                position.x,
                position.y,
                position.z,
            )
        };
    }

    #[inline]
    pub fn ma_engine_listener_get_velocity<E: AsEnginePtr + ?Sized>(
        engine: &E,
        listener: u32,
    ) -> Vec3 {
        let vec = unsafe {
            sys::ma_engine_listener_get_velocity(
                private_engine::engine_ptr(engine) as *const _,
                listener,
            )
        };
        vec.into()
    }

    #[inline]
    pub fn ma_engine_listener_set_cone<E: AsEnginePtr + ?Sized>(
        engine: &E,
        listener: u32,
        cone: Cone,
    ) {
        unsafe {
            sys::ma_engine_listener_set_cone(
                private_engine::engine_ptr(engine),
                listener,
                cone.inner_angle_rad,
                cone.outer_angle_rad,
                cone.outer_gain,
            )
        };
    }

    #[inline]
    pub fn ma_engine_listener_get_cone<E: AsEnginePtr + ?Sized>(engine: &E, listener: u32) -> Cone {
        let mut inner = 0.0f32;
        let mut outer = 0.0f32;
        let mut gain = 1.0f32;

        unsafe {
            sys::ma_engine_listener_get_cone(
                private_engine::engine_ptr(engine) as *const _,
                listener,
                &mut inner,
                &mut outer,
                &mut gain,
            )
        };

        Cone {
            inner_angle_rad: inner,
            outer_angle_rad: outer,
            outer_gain: gain,
        }
    }

    #[inline]
    pub fn ma_engine_listener_set_world_up<E: AsEnginePtr + ?Sized>(
        engine: &E,
        listener: u32,
        vec: Vec3,
    ) {
        unsafe {
            sys::ma_engine_listener_set_world_up(
                private_engine::engine_ptr(engine),
                listener,
                vec.x,
                vec.y,
                vec.z,
            );
        }
    }

    #[inline]
    pub fn ma_engine_listener_get_world_up<E: AsEnginePtr + ?Sized>(
        engine: &E,
        listener: u32,
    ) -> Vec3 {
        let vec = unsafe {
            sys::ma_engine_listener_get_world_up(
                private_engine::engine_ptr(engine) as *const _,
                listener,
            )
        };
        vec.into()
    }

    #[inline]
    pub fn ma_engine_listener_set_enabled<E: AsEnginePtr + ?Sized>(
        engine: &E,
        listener: u32,
        enabled: bool,
    ) {
        unsafe {
            sys::ma_engine_listener_set_enabled(
                private_engine::engine_ptr(engine),
                listener,
                enabled as u32,
            )
        }
    }

    #[inline]
    pub fn ma_engine_listener_is_enabled<E: AsEnginePtr + ?Sized>(
        engine: &E,
        listener: u32,
    ) -> bool {
        let res = unsafe {
            sys::ma_engine_listener_is_enabled(
                private_engine::engine_ptr(engine) as *const _,
                listener,
            )
        };
        res == 1
    }
}