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
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
//! A collection of sounds that can be controlled as a single Sound instance
use std::{cell::Cell, marker::PhantomData, mem::MaybeUninit};

use maudio_sys::ffi as sys;

use crate::{
    audio::{
        dsp::pan::PanMode,
        math::vec3::Vec3,
        spatial::{attenuation::AttenuationModel, cone::Cone, positioning::Positioning},
    },
    engine::{
        node_graph::nodes::{private_node, AsNodePtr, NodeRef},
        private_engine, Engine, EngineOps, EngineRef,
    },
    sound::{sound_builder::SoundState, sound_flags::SoundFlags},
    AsRawRef, Binding, MaResult,
};

pub struct SoundGroup<'a> {
    inner: *mut sys::ma_sound_group,
    _not_sync: PhantomData<Cell<()>>,
    _marker: PhantomData<&'a Engine>,
}

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

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

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

impl SoundGroup<'_> {
    pub fn engine(&mut self) -> Option<EngineRef<'_>> {
        s_group_ffi::ma_sound_group_get_engine(self)
    }

    pub fn start(&mut self) -> MaResult<()> {
        s_group_ffi::ma_sound_group_start(self)
    }

    pub fn stop(&mut self) -> MaResult<()> {
        s_group_ffi::ma_sound_group_stop(self)
    }

    pub fn set_volume(&mut self, volume: f32) {
        s_group_ffi::ma_sound_group_set_volume(self, volume);
    }

    pub fn volume(&self) -> f32 {
        s_group_ffi::ma_sound_group_get_volume(self)
    }

    pub fn pan(&self) -> f32 {
        s_group_ffi::ma_sound_group_get_pan(self)
    }

    pub fn set_pan(&mut self, pan: f32) {
        s_group_ffi::ma_sound_group_set_pan(self, pan);
    }

    pub fn pan_mode(&self) -> MaResult<PanMode> {
        s_group_ffi::ma_sound_group_get_pan_mode(self)
    }

    pub fn set_pan_mode(&mut self, pan_mode: PanMode) {
        s_group_ffi::ma_sound_group_set_pan_mode(self, pan_mode);
    }

    pub fn pitch(&self) -> f32 {
        s_group_ffi::ma_sound_group_get_pitch(self)
    }

    pub fn set_pitch(&mut self, pitch: f32) {
        s_group_ffi::ma_sound_group_set_pitch(self, pitch);
    }

    pub fn spatialization(&self) -> bool {
        s_group_ffi::ma_sound_group_is_spatialization_enabled(self)
    }

    pub fn set_spatialization(&mut self, enabled: bool) {
        s_group_ffi::ma_sound_group_set_spatialization_enabled(self, enabled);
    }

    pub fn pinned_listener(&self) -> u32 {
        s_group_ffi::ma_sound_group_get_pinned_listener_index(self)
    }

    pub fn set_pinned_listener(&mut self, listener: u32) {
        s_group_ffi::ma_sound_group_set_pinned_listener_index(self, listener);
    }

    pub fn listener(&self) -> u32 {
        s_group_ffi::ma_sound_group_get_listener_index(self)
    }

    pub fn direction_to_listener(&self) -> Vec3 {
        s_group_ffi::ma_sound_group_get_direction_to_listener(self)
    }

    pub fn set_position(&mut self, vec: Vec3) {
        s_group_ffi::ma_sound_group_set_position(self, vec);
    }

    pub fn position(&self) -> Vec3 {
        s_group_ffi::ma_sound_group_get_position(self)
    }

    pub fn set_direction(&mut self, vec: Vec3) {
        s_group_ffi::ma_sound_group_set_direction(self, vec);
    }

    pub fn direction(&self) -> Vec3 {
        s_group_ffi::ma_sound_group_get_direction(self)
    }

    pub fn velocity(&self) -> Vec3 {
        s_group_ffi::ma_sound_group_get_velocity(self)
    }

    pub fn set_velocity(&mut self, vec: Vec3) {
        s_group_ffi::ma_sound_group_set_velocity(self, vec);
    }

    pub fn set_attenuation(&mut self, model: AttenuationModel) {
        s_group_ffi::ma_sound_group_set_attenuation_model(self, model);
    }

    pub fn attenuation(&self) -> MaResult<AttenuationModel> {
        s_group_ffi::ma_sound_group_get_attenuation_model(self)
    }

    pub fn positioning(&self) -> MaResult<Positioning> {
        s_group_ffi::ma_sound_group_get_positioning(self)
    }

    pub fn set_positioning(&mut self, positioning: Positioning) {
        s_group_ffi::ma_sound_group_set_positioning(self, positioning);
    }

    pub fn rolloff(&self) -> f32 {
        s_group_ffi::ma_sound_group_get_rolloff(self)
    }

    pub fn set_rolloff(&mut self, rolloff: f32) {
        s_group_ffi::ma_sound_group_set_rolloff(self, rolloff);
    }

    pub fn min_gain(&self) -> f32 {
        s_group_ffi::ma_sound_group_get_min_gain(self)
    }

    pub fn set_min_gain(&mut self, gain: f32) {
        s_group_ffi::ma_sound_group_set_min_gain(self, gain);
    }

    pub fn max_gain(&self) -> f32 {
        s_group_ffi::ma_sound_group_get_max_gain(self)
    }

    pub fn set_max_gain(&mut self, gain: f32) {
        s_group_ffi::ma_sound_group_set_max_gain(self, gain);
    }

    pub fn min_distance(&self) -> f32 {
        s_group_ffi::ma_sound_group_get_min_distance(self)
    }

    pub fn set_min_distance(&mut self, distance: f32) {
        s_group_ffi::ma_sound_group_set_min_distance(self, distance);
    }

    pub fn max_distance(&self) -> f32 {
        s_group_ffi::ma_sound_group_get_max_distance(self)
    }

    pub fn set_max_distance(&mut self, distance: f32) {
        s_group_ffi::ma_sound_group_set_max_distance(self, distance);
    }

    pub fn cone(&self) -> Cone {
        s_group_ffi::ma_sound_group_get_cone(self)
    }

    pub fn set_cone(&mut self, cone: Cone) {
        s_group_ffi::ma_sound_group_set_cone(self, cone);
    }

    pub fn doppler_factor(&self) -> f32 {
        s_group_ffi::ma_sound_group_get_doppler_factor(self)
    }

    pub fn set_doppler_factor(&mut self, factor: f32) {
        s_group_ffi::ma_sound_group_set_doppler_factor(self, factor);
    }

    pub fn directional_attenuation(&mut self) -> f32 {
        s_group_ffi::ma_sound_group_get_directional_attenuation_factor(self)
    }

    pub fn set_directional_attenuation(&mut self, factor: f32) {
        s_group_ffi::ma_sound_group_set_directional_attenuation_factor(self, factor);
    }

    pub fn set_fade_pcm(&mut self, vol_start: f32, vol_end: f32, fade_length_frames: u64) {
        s_group_ffi::ma_sound_group_set_fade_in_pcm_frames(
            self,
            vol_start,
            vol_end,
            fade_length_frames,
        );
    }

    pub fn set_fade_mili(&mut self, vol_start: f32, vol_end: f32, fade_length_mili: u64) {
        s_group_ffi::ma_sound_group_set_fade_in_milliseconds(
            self,
            vol_start,
            vol_end,
            fade_length_mili,
        );
    }

    pub fn current_fade_volume(&mut self) -> f32 {
        s_group_ffi::ma_sound_group_get_current_fade_volume(self)
    }

    pub fn set_start_time_pcm(&mut self, abs_time_frames: u64) {
        s_group_ffi::ma_sound_group_set_start_time_in_pcm_frames(self, abs_time_frames);
    }

    pub fn set_start_time_mili(&mut self, abs_time_millis: u64) {
        s_group_ffi::ma_sound_group_set_start_time_in_milliseconds(self, abs_time_millis);
    }

    pub fn set_stop_time_pcm(&mut self, abs_time_frames: u64) {
        s_group_ffi::ma_sound_group_set_stop_time_in_pcm_frames(self, abs_time_frames);
    }

    pub fn set_stop_time_mili(&mut self, abs_time_millis: u64) {
        s_group_ffi::ma_sound_group_set_stop_time_in_milliseconds(self, abs_time_millis);
    }

    pub fn is_playing(&self) -> bool {
        s_group_ffi::ma_sound_group_is_playing(self)
    }

    pub fn time_pcm(&mut self) -> u64 {
        s_group_ffi::ma_sound_group_get_time_in_pcm_frames(self)
    }

    // Safe to cast as ma_node in version 0.11.23
    pub fn as_node(&self) -> NodeRef<'_> {
        assert!(!self.to_raw().is_null());
        let ptr = self.to_raw().cast::<sys::ma_node>();
        NodeRef::from_ptr(ptr)
    }
}

impl Drop for SoundGroup<'_> {
    fn drop(&mut self) {
        s_group_ffi::ma_sound_group_uninit(self);
        drop(unsafe { Box::from_raw(self.to_raw()) });
    }
}

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

    use crate::{
        audio::{
            dsp::pan::PanMode,
            math::vec3::Vec3,
            spatial::{attenuation::AttenuationModel, cone::Cone, positioning::Positioning},
        },
        engine::{Engine, EngineRef},
        sound::sound_group::{SoundGroup, SoundGroupBuilder},
        AsRawRef, Binding, MaResult, MaudioError,
    };

    pub fn ma_sound_group_init_ex(
        engine: &Engine,
        config: &SoundGroupBuilder,
        s_group: *mut sys::ma_sound_group,
    ) -> MaResult<()> {
        let res =
            unsafe { sys::ma_sound_group_init_ex(engine.to_raw(), config.as_raw_ptr(), s_group) };
        MaudioError::check(res)
    }

    #[inline]
    pub fn ma_sound_group_uninit(s_group: &mut SoundGroup) {
        unsafe { sys::ma_sound_group_uninit(s_group.to_raw()) };
    }

    #[inline]
    pub fn ma_sound_group_get_engine<'a>(s_group: &'a SoundGroup) -> Option<EngineRef<'a>> {
        let ptr = unsafe { sys::ma_sound_group_get_engine(s_group.to_raw() as *const _) };
        if ptr.is_null() {
            None
        } else {
            Some(EngineRef::from_ptr(ptr))
        }
    }

    #[inline]
    pub fn ma_sound_group_start(s_group: &mut SoundGroup) -> MaResult<()> {
        let res = unsafe { sys::ma_sound_group_start(s_group.to_raw()) };
        MaudioError::check(res)
    }

    #[inline]
    pub fn ma_sound_group_stop(s_group: &mut SoundGroup) -> MaResult<()> {
        let res = unsafe { sys::ma_sound_group_stop(s_group.to_raw()) };
        MaudioError::check(res)
    }

    #[inline]
    pub fn ma_sound_group_set_volume(s_group: &mut SoundGroup, volume: f32) {
        unsafe {
            sys::ma_sound_group_set_volume(s_group.to_raw(), volume);
        }
    }

    #[inline]
    pub fn ma_sound_group_get_volume(s_group: &SoundGroup) -> f32 {
        unsafe { sys::ma_sound_group_get_volume(s_group.to_raw() as *const _) }
    }

    #[inline]
    pub fn ma_sound_group_set_pan(s_group: &mut SoundGroup, pan: f32) {
        unsafe { sys::ma_sound_group_set_pan(s_group.to_raw(), pan) };
    }

    #[inline]
    pub fn ma_sound_group_get_pan(s_group: &SoundGroup) -> f32 {
        unsafe { sys::ma_sound_group_get_pan(s_group.to_raw() as *const _) }
    }

    #[inline]
    pub fn ma_sound_group_set_pan_mode(s_group: &mut SoundGroup, pan_mode: PanMode) {
        unsafe { sys::ma_sound_group_set_pan_mode(s_group.to_raw(), pan_mode.into()) }
    }

    #[inline]
    pub fn ma_sound_group_get_pan_mode(s_group: &SoundGroup) -> MaResult<PanMode> {
        let mode = unsafe { sys::ma_sound_group_get_pan_mode(s_group.to_raw() as *const _) };
        mode.try_into()
    }

    #[inline]
    pub fn ma_sound_group_set_pitch(s_group: &mut SoundGroup, pitch: f32) {
        unsafe { sys::ma_sound_group_set_pitch(s_group.to_raw(), pitch) }
    }

    #[inline]
    pub fn ma_sound_group_get_pitch(s_group: &SoundGroup) -> f32 {
        unsafe { sys::ma_sound_group_get_pitch(s_group.to_raw() as *const _) }
    }

    #[inline]
    pub fn ma_sound_group_set_spatialization_enabled(s_group: &mut SoundGroup, enabled: bool) {
        let enabled = enabled as sys::ma_bool32;
        unsafe { sys::ma_sound_group_set_spatialization_enabled(s_group.to_raw(), enabled) }
    }

    #[inline]
    pub fn ma_sound_group_is_spatialization_enabled(s_group: &SoundGroup) -> bool {
        let res =
            unsafe { sys::ma_sound_group_is_spatialization_enabled(s_group.to_raw() as *const _) };
        res == 1
    }

    #[inline]
    pub fn ma_sound_group_set_pinned_listener_index(s_group: &mut SoundGroup, listener_idx: u32) {
        unsafe { sys::ma_sound_group_set_pinned_listener_index(s_group.to_raw(), listener_idx) }
    }

    #[inline]
    pub fn ma_sound_group_get_pinned_listener_index(s_group: &SoundGroup) -> u32 {
        unsafe { sys::ma_sound_group_get_pinned_listener_index(s_group.to_raw() as *const _) }
    }

    #[inline]
    pub fn ma_sound_group_get_listener_index(s_group: &SoundGroup) -> u32 {
        unsafe { sys::ma_sound_group_get_listener_index(s_group.to_raw() as *const _) }
    }

    #[inline]
    pub fn ma_sound_group_get_direction_to_listener(s_group: &SoundGroup) -> Vec3 {
        let vec =
            unsafe { sys::ma_sound_group_get_direction_to_listener(s_group.to_raw() as *const _) };
        vec.into()
    }

    #[inline]
    pub fn ma_sound_group_set_position(s_group: &mut SoundGroup, vec3: Vec3) {
        unsafe {
            sys::ma_sound_group_set_position(s_group.to_raw(), vec3.x, vec3.y, vec3.z);
        }
    }

    #[inline]
    pub fn ma_sound_group_get_position(s_group: &SoundGroup) -> Vec3 {
        let vec = unsafe { sys::ma_sound_group_get_position(s_group.to_raw() as *const _) };
        vec.into()
    }

    #[inline]
    pub fn ma_sound_group_set_direction(s_group: &mut SoundGroup, vec3: Vec3) {
        unsafe { sys::ma_sound_group_set_direction(s_group.to_raw(), vec3.x, vec3.y, vec3.z) }
    }

    #[inline]
    pub fn ma_sound_group_get_direction(s_group: &SoundGroup) -> Vec3 {
        let vec = unsafe { sys::ma_sound_group_get_direction(s_group.to_raw() as *const _) };
        vec.into()
    }

    #[inline]
    pub fn ma_sound_group_set_velocity(s_group: &mut SoundGroup, vec3: Vec3) {
        unsafe { sys::ma_sound_group_set_velocity(s_group.to_raw(), vec3.x, vec3.y, vec3.z) }
    }

    #[inline]
    pub fn ma_sound_group_get_velocity(s_group: &SoundGroup) -> Vec3 {
        let vec = unsafe { sys::ma_sound_group_get_velocity(s_group.to_raw() as *const _) };
        vec.into()
    }

    #[inline]
    pub fn ma_sound_group_set_attenuation_model(s_group: &mut SoundGroup, model: AttenuationModel) {
        unsafe { sys::ma_sound_group_set_attenuation_model(s_group.to_raw(), model.into()) }
    }

    #[inline]
    pub fn ma_sound_group_get_attenuation_model(
        s_group: &SoundGroup,
    ) -> MaResult<AttenuationModel> {
        let model =
            unsafe { sys::ma_sound_group_get_attenuation_model(s_group.to_raw() as *const _) };
        model.try_into()
    }

    #[inline]
    pub fn ma_sound_group_set_positioning(s_group: &mut SoundGroup, positioning: Positioning) {
        unsafe { sys::ma_sound_group_set_positioning(s_group.to_raw(), positioning.into()) }
    }

    #[inline]
    pub fn ma_sound_group_get_positioning(s_group: &SoundGroup) -> MaResult<Positioning> {
        let pos = unsafe { sys::ma_sound_group_get_positioning(s_group.to_raw() as *const _) };
        pos.try_into()
    }

    #[inline]
    pub fn ma_sound_group_set_rolloff(s_group: &mut SoundGroup, rolloff: f32) {
        unsafe { sys::ma_sound_group_set_rolloff(s_group.to_raw(), rolloff) }
    }

    #[inline]
    pub fn ma_sound_group_get_rolloff(s_group: &SoundGroup) -> f32 {
        unsafe { sys::ma_sound_group_get_rolloff(s_group.to_raw() as *const _) }
    }

    #[inline]
    pub fn ma_sound_group_set_min_gain(s_group: &mut SoundGroup, min_gain: f32) {
        unsafe { sys::ma_sound_group_set_min_gain(s_group.to_raw(), min_gain) }
    }

    #[inline]
    pub fn ma_sound_group_get_min_gain(s_group: &SoundGroup) -> f32 {
        unsafe { sys::ma_sound_group_get_min_gain(s_group.to_raw() as *const _) }
    }

    #[inline]
    pub fn ma_sound_group_set_max_gain(s_group: &mut SoundGroup, max_gain: f32) {
        unsafe { sys::ma_sound_group_set_max_gain(s_group.to_raw(), max_gain) }
    }

    #[inline]
    pub fn ma_sound_group_get_max_gain(s_group: &SoundGroup) -> f32 {
        unsafe { sys::ma_sound_group_get_max_gain(s_group.to_raw() as *const _) }
    }

    #[inline]
    pub fn ma_sound_group_set_min_distance(s_group: &mut SoundGroup, min_distance: f32) {
        unsafe { sys::ma_sound_group_set_min_distance(s_group.to_raw(), min_distance) }
    }

    #[inline]
    pub fn ma_sound_group_get_min_distance(s_group: &SoundGroup) -> f32 {
        unsafe { sys::ma_sound_group_get_min_distance(s_group.to_raw() as *const _) }
    }

    #[inline]
    pub fn ma_sound_group_set_max_distance(s_group: &mut SoundGroup, max_distance: f32) {
        unsafe { sys::ma_sound_group_set_max_distance(s_group.to_raw(), max_distance) }
    }

    #[inline]
    pub fn ma_sound_group_get_max_distance(s_group: &SoundGroup) -> f32 {
        unsafe { sys::ma_sound_group_get_max_distance(s_group.to_raw() as *const _) }
    }

    #[inline]
    pub fn ma_sound_group_set_cone(s_group: &mut SoundGroup, cone: Cone) {
        unsafe {
            sys::ma_sound_group_set_cone(
                s_group.to_raw(),
                cone.inner_angle_rad,
                cone.outer_angle_rad,
                cone.outer_gain,
            );
        }
    }

    #[inline]
    pub fn ma_sound_group_get_cone(s_group: &SoundGroup) -> Cone {
        let mut inner = 0.0f32;
        let mut outer = 0.0f32;
        let mut gain = 1.0f32;

        unsafe {
            sys::ma_sound_group_get_cone(
                s_group.to_raw() as *const _,
                &mut inner,
                &mut outer,
                &mut gain,
            );
        }

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

    #[inline]
    pub fn ma_sound_group_set_doppler_factor(s_group: &mut SoundGroup, doppler_factor: f32) {
        unsafe { sys::ma_sound_group_set_doppler_factor(s_group.to_raw(), doppler_factor) }
    }

    #[inline]
    pub fn ma_sound_group_get_doppler_factor(s_group: &SoundGroup) -> f32 {
        unsafe { sys::ma_sound_group_get_doppler_factor(s_group.to_raw() as *const _) }
    }

    #[inline]
    pub fn ma_sound_group_set_directional_attenuation_factor(
        s_group: &mut SoundGroup,
        dir_attenuation_factor: f32,
    ) {
        unsafe {
            sys::ma_sound_group_set_directional_attenuation_factor(
                s_group.to_raw(),
                dir_attenuation_factor,
            );
        }
    }

    #[inline]
    pub fn ma_sound_group_get_directional_attenuation_factor(s_group: &SoundGroup) -> f32 {
        unsafe {
            sys::ma_sound_group_get_directional_attenuation_factor(s_group.to_raw() as *const _)
        }
    }

    #[inline]
    pub fn ma_sound_group_set_fade_in_pcm_frames(
        s_group: &mut SoundGroup,
        volume_start: f32,
        volume_end: f32,
        fade_length_frames: u64,
    ) {
        unsafe {
            sys::ma_sound_group_set_fade_in_pcm_frames(
                s_group.to_raw(),
                volume_start,
                volume_end,
                fade_length_frames,
            )
        };
    }

    #[inline]
    pub fn ma_sound_group_set_fade_in_milliseconds(
        s_group: &mut SoundGroup,
        volume_start: f32,
        volume_end: f32,
        fade_length_mili: u64,
    ) {
        unsafe {
            sys::ma_sound_group_set_fade_in_milliseconds(
                s_group.to_raw(),
                volume_start,
                volume_end,
                fade_length_mili,
            );
        }
    }

    #[inline]
    pub fn ma_sound_group_get_current_fade_volume(s_group: &mut SoundGroup) -> f32 {
        unsafe { sys::ma_sound_group_get_current_fade_volume(s_group.to_raw()) }
    }

    #[inline]
    pub fn ma_sound_group_set_start_time_in_pcm_frames(
        s_group: &mut SoundGroup,
        abs_time_frames: u64,
    ) {
        unsafe {
            sys::ma_sound_group_set_start_time_in_pcm_frames(s_group.to_raw(), abs_time_frames);
        }
    }

    #[inline]
    pub fn ma_sound_group_set_start_time_in_milliseconds(
        s_group: &mut SoundGroup,
        abs_time_mili: u64,
    ) {
        unsafe {
            sys::ma_sound_group_set_start_time_in_milliseconds(s_group.to_raw(), abs_time_mili);
        }
    }

    #[inline]
    pub fn ma_sound_group_set_stop_time_in_pcm_frames(
        s_group: &mut SoundGroup,
        abs_time_frames: u64,
    ) {
        unsafe {
            sys::ma_sound_group_set_stop_time_in_pcm_frames(s_group.to_raw(), abs_time_frames);
        }
    }

    #[inline]
    pub fn ma_sound_group_set_stop_time_in_milliseconds(
        s_group: &mut SoundGroup,
        abs_time_mili: u64,
    ) {
        unsafe {
            sys::ma_sound_group_set_stop_time_in_milliseconds(s_group.to_raw(), abs_time_mili);
        }
    }

    #[inline]
    pub fn ma_sound_group_is_playing(s_group: &SoundGroup) -> bool {
        let res = unsafe { sys::ma_sound_group_is_playing(s_group.to_raw() as *const _) };
        res == 1
    }

    #[inline]
    pub fn ma_sound_group_get_time_in_pcm_frames(s_group: &SoundGroup) -> u64 {
        unsafe { sys::ma_sound_group_get_time_in_pcm_frames(s_group.to_raw() as *const _) }
    }
}

pub struct SoundGroupBuilder<'a> {
    inner: sys::ma_sound_group_config,
    engine: &'a Engine,
    state: SoundState,
}

impl AsRawRef for SoundGroupBuilder<'_> {
    type Raw = sys::ma_sound_group_config;

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

impl<'a> SoundGroupBuilder<'a> {
    pub fn new(engine: &'a Engine) -> Self {
        let inner =
            unsafe { sys::ma_sound_group_config_init_2(private_engine::engine_ptr(engine)) };
        Self {
            inner,
            engine,
            state: SoundState::default(),
        }
    }

    pub fn build(&self) -> MaResult<SoundGroup<'a>> {
        let mut group = self.new_sound_group()?;
        self.configure_sound_group(&mut group);
        Ok(group)
    }

    /// By default, a newly created sound group is attached to the engine's main output graph,
    /// unless [`SoundGroupBuilder::no_default_attachment()`] has been used.
    ///
    /// Calling this method overrides that behavior and immediately attaches the sound group
    /// to a specific node in the graph instead.
    ///
    /// # Parameters
    /// - `node`: The target node to attach the sound group to.
    /// - `input_bus`: The input bus on `node` to connect to.
    ///
    /// # When you do not need this
    /// If the sound group should feed into the engine's default output path,
    /// you do not need to call this method.
    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
    }

    pub fn no_default_attachment(&mut self) -> &mut Self {
        self.inner.flags = SoundFlags::NO_DEFAULT_ATTACHMENT.bits();
        self
    }

    /// Sets the number of input channels for the node.
    ///
    /// Defines how many channels this node expects from its inputs.
    /// A value of `0` lets miniaudio infer the channel count automatically.
    ///
    /// For sound groups, this applies to the mixed input from attached sounds.
    pub fn channels_in(&mut self, ch: u32) -> &mut Self {
        self.inner.channelsIn = ch;
        self
    }

    /// Sets the number of output channels for the node.
    ///
    /// Defines how many channels this node outputs into the graph.
    /// A value of `0` uses the engine's native channel count.
    pub fn channels_out(&mut self, ch: u32) -> &mut Self {
        self.inner.channelsOut = ch;
        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 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
    }

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

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

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

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

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

    /// Sets the `direction` field on the newly created sound
    ///
    /// Equivalent to calling [`SoundGroup::set_direction`]
    pub fn direction(&mut self, direction: Vec3) -> &mut Self {
        self.state.direction = Some(direction);
        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
    }

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

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

        s_group_ffi::ma_sound_group_init_ex(self.engine, self, 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))
    }
}

#[cfg(test)]
mod test {
    use crate::{
        audio::{
            dsp::pan::PanMode,
            math::vec3::Vec3,
            spatial::{attenuation::AttenuationModel, cone::Cone, positioning::Positioning},
        },
        engine::{engine_builder::EngineBuilder, Engine},
    };

    fn approx_eq(a: f32, b: f32, eps: f32) -> bool {
        (a - b).abs() <= eps
    }

    fn assert_approx_eq(a: f32, b: f32, eps: f32) {
        assert!(approx_eq(a, b, eps), "expected ~={b}, got {a} (eps={eps})");
    }

    fn assert_vec3_eq(a: Vec3, b: Vec3, eps: f32) {
        // Adjust field names if your Vec3 differs.
        assert_approx_eq(a.x, b.x, eps);
        assert_approx_eq(a.y, b.y, eps);
        assert_approx_eq(a.z, b.z, eps);
    }

    #[test]
    fn test_sound_group_basic() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();
        let _engine_ref = s_group.engine();
    }

    #[test]
    fn test_sound_group_start_stop_smoke() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        // These are just smoke tests; depending on backend/device, playing() may be false.
        s_group.start().unwrap();
        s_group.stop().unwrap();
    }

    #[test]
    fn test_sound_group_volume_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_volume(0.25);
        let v = s_group.volume();
        assert_approx_eq(v, 0.25, 1e-6);

        s_group.set_volume(1.0);
        let v = s_group.volume();
        assert_approx_eq(v, 1.0, 1e-6);
    }

    #[test]
    fn test_sound_group_pan_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_pan(-0.5);
        assert_approx_eq(s_group.pan(), -0.5, 1e-6);

        s_group.set_pan(0.75);
        assert_approx_eq(s_group.pan(), 0.75, 1e-6);
    }

    #[test]
    fn test_sound_group_pan_mode_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        // Use variants that exist in your PanMode enum.
        // Common miniaudio ones: PanMode::Balance, PanMode::Pan
        s_group.set_pan_mode(PanMode::Balance);
        assert_eq!(s_group.pan_mode().unwrap(), PanMode::Balance);

        s_group.set_pan_mode(PanMode::Pan);
        assert_eq!(s_group.pan_mode().unwrap(), PanMode::Pan);
    }

    #[test]
    fn test_sound_group_pitch_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_pitch(0.5);
        assert_approx_eq(s_group.pitch(), 0.5, 1e-6);

        s_group.set_pitch(1.25);
        assert_approx_eq(s_group.pitch(), 1.25, 1e-6);
    }

    #[test]
    fn test_sound_group_spatialization_toggle() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_spatialization(false);
        assert!(!s_group.spatialization());

        s_group.set_spatialization(true);
        assert!(s_group.spatialization());
    }

    #[test]
    fn test_sound_group_pinned_listener_roundtrip() {
        let engine = EngineBuilder::new()
            .listener_count(2)
            .build_for_tests()
            .unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_pinned_listener(0);
        assert_eq!(s_group.pinned_listener(), 0);
        s_group.set_pinned_listener(1);
        assert_eq!(s_group.pinned_listener(), 1);
    }

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

        let _idx = s_group.listener();
    }

    #[test]
    fn test_sound_group_position_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        let p = Vec3 {
            x: 1.0,
            y: 2.0,
            z: 3.0,
        };
        s_group.set_position(p);
        let got = s_group.position();
        assert_vec3_eq(got, p, 1e-6);
    }

    #[test]
    fn test_sound_group_direction_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        let d = Vec3 {
            x: 0.0,
            y: 0.0,
            z: 1.0,
        };
        s_group.set_direction(d);
        let got = s_group.direction();
        assert_vec3_eq(got, d, 1e-6);
    }

    #[test]
    fn test_sound_group_velocity_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        let v = Vec3 {
            x: -1.0,
            y: 0.5,
            z: 0.25,
        };
        s_group.set_velocity(v);
        let got = s_group.velocity();
        assert_vec3_eq(got, v, 1e-6);
    }

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

        // Typically depends on listener position; just ensure it doesn't crash.
        let _dir = s_group.direction_to_listener();
    }

    #[test]
    fn test_sound_group_attenuation_model_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        // Use variants that exist in your AttenuationModel enum.
        s_group.set_attenuation(AttenuationModel::None);
        assert_eq!(s_group.attenuation().unwrap(), AttenuationModel::None);

        s_group.set_attenuation(AttenuationModel::Inverse);
        assert_eq!(s_group.attenuation().unwrap(), AttenuationModel::Inverse);
    }

    #[test]
    fn test_sound_group_positioning_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_positioning(Positioning::Absolute);
        assert_eq!(s_group.positioning().unwrap(), Positioning::Absolute);

        s_group.set_positioning(Positioning::Relative);
        assert_eq!(s_group.positioning().unwrap(), Positioning::Relative);
    }

    #[test]
    fn test_sound_group_rolloff_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_rolloff(0.75);
        assert_approx_eq(s_group.rolloff(), 0.75, 1e-6);
    }

    #[test]
    fn test_sound_group_min_max_gain_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_min_gain(0.1);
        assert_approx_eq(s_group.min_gain(), 0.1, 1e-6);

        s_group.set_max_gain(2.0);
        assert_approx_eq(s_group.max_gain(), 2.0, 1e-6);
    }

    #[test]
    fn test_sound_group_min_max_distance_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_min_distance(1.25);
        assert_approx_eq(s_group.min_distance(), 1.25, 1e-6);

        s_group.set_max_distance(50.0);
        assert_approx_eq(s_group.max_distance(), 50.0, 1e-6);
    }

    #[test]
    fn test_sound_group_cone_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        let c = Cone {
            inner_angle_rad: 0.5,
            outer_angle_rad: 1.0,
            outer_gain: 0.25,
        };

        s_group.set_cone(c);
        let got = s_group.cone();

        assert_approx_eq(got.inner_angle_rad, c.inner_angle_rad, 1e-6);
        assert_approx_eq(got.outer_angle_rad, c.outer_angle_rad, 1e-6);
        assert_approx_eq(got.outer_gain, c.outer_gain, 1e-6);
    }

    #[test]
    fn test_sound_group_doppler_factor_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_doppler_factor(1.5);
        assert_approx_eq(s_group.doppler_factor(), 1.5, 1e-6);
    }

    #[test]
    fn test_sound_group_directional_attenuation_roundtrip() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_directional_attenuation(0.6);
        assert_approx_eq(s_group.directional_attenuation(), 0.6, 1e-6);
    }

    #[test]
    fn test_sound_group_fade_api_smoke() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        // Not possible to reliably assert current_fade_volume() without running audio;
        // this just ensures the calls are wired correctly.
        s_group.set_fade_pcm(0.0, 1.0, 4800);
        let _v = s_group.current_fade_volume();

        s_group.set_fade_mili(1.0, 0.0, 250);
        let _v2 = s_group.current_fade_volume();
    }

    #[test]
    fn test_sound_group_start_stop_time_api_smoke() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        s_group.set_start_time_pcm(0);
        s_group.set_stop_time_pcm(0);

        s_group.set_start_time_mili(0);
        s_group.set_stop_time_mili(0);
    }

    #[test]
    fn test_sound_group_playing_and_time_pcm_smoke() {
        let engine = Engine::new_for_tests().unwrap();
        let mut s_group = engine.new_sound_group().unwrap();

        let _is_playing = s_group.is_playing();
        let _t = s_group.time_pcm();
    }
}