voirs-sdk 0.1.0-rc.1

Unified SDK and public API for VoiRS speech synthesis
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
//! 3D Spatial Audio integration for VoiRS SDK

use crate::{Result, VoirsError};
use std::sync::Arc;
use tokio::sync::RwLock;

/// 3D position in space
#[derive(Debug, Clone, PartialEq)]
pub struct Position3D {
    /// X coordinate (left-right)
    pub x: f32,
    /// Y coordinate (up-down)
    pub y: f32,
    /// Z coordinate (front-back)
    pub z: f32,
}

/// 3D orientation (rotation)
#[derive(Debug, Clone, PartialEq)]
pub struct Orientation3D {
    /// Yaw (rotation around Y-axis) in radians
    pub yaw: f32,
    /// Pitch (rotation around X-axis) in radians
    pub pitch: f32,
    /// Roll (rotation around Z-axis) in radians
    pub roll: f32,
}

/// 3D velocity for Doppler effect
#[derive(Debug, Clone, PartialEq)]
pub struct Velocity3D {
    /// X velocity component
    pub x: f32,
    /// Y velocity component
    pub y: f32,
    /// Z velocity component
    pub z: f32,
}

/// Audio source in 3D space
#[derive(Debug, Clone)]
pub struct AudioSource3D {
    /// Source position
    pub position: Position3D,
    /// Source orientation
    pub orientation: Orientation3D,
    /// Source velocity (for Doppler effect)
    pub velocity: Velocity3D,
    /// Source volume (0.0-1.0)
    pub volume: f32,
    /// Source directivity pattern
    pub directivity: DirectivityPattern,
}

/// Audio listener in 3D space
#[derive(Debug, Clone)]
pub struct AudioListener3D {
    /// Listener position
    pub position: Position3D,
    /// Listener orientation
    pub orientation: Orientation3D,
    /// Listener velocity (for Doppler effect)
    pub velocity: Velocity3D,
}

/// Directivity pattern for audio sources
#[derive(Debug, Clone, PartialEq)]
pub enum DirectivityPattern {
    /// Omnidirectional (equal in all directions)
    Omnidirectional,
    /// Cardioid (heart-shaped, directional)
    Cardioid,
    /// Bidirectional (figure-8 pattern)
    Bidirectional,
    /// Custom pattern with angular coefficients
    Custom(Vec<f32>),
}

/// Room acoustics parameters
#[derive(Debug, Clone)]
pub struct RoomAcoustics {
    /// Room dimensions
    pub dimensions: Position3D,
    /// Absorption coefficients for different frequencies
    pub absorption: FrequencyResponse,
    /// Reverberation time (RT60) in seconds
    pub reverb_time: f32,
    /// Early reflections delay in milliseconds
    pub early_reflections_delay: f32,
    /// Diffusion coefficient (0.0-1.0)
    pub diffusion: f32,
}

/// Frequency response curve
#[derive(Debug, Clone)]
pub struct FrequencyResponse {
    /// Frequency bands in Hz
    pub frequencies: Vec<f32>,
    /// Corresponding response values
    pub responses: Vec<f32>,
}

/// HRTF (Head-Related Transfer Function) configuration
#[derive(Debug, Clone)]
pub struct HrtfConfig {
    /// HRTF dataset to use
    pub dataset: HrtfDataset,
    /// Head circumference in cm (for personalization)
    pub head_circumference: f32,
    /// Interpupillary distance in cm
    pub interpupillary_distance: f32,
    /// Enable crossfeed for better stereo imaging
    pub crossfeed_enabled: bool,
    /// Crossfeed strength (0.0-1.0)
    pub crossfeed_strength: f32,
}

/// HRTF dataset options
#[derive(Debug, Clone, PartialEq)]
pub enum HrtfDataset {
    /// Generic HRTF dataset
    Generic,
    /// MIT KEMAR dataset
    Kemar,
    /// CIPIC database
    Cipic,
    /// Custom dataset
    Custom(String),
}

/// Binaural rendering configuration
#[derive(Debug, Clone)]
pub struct BinauralConfig {
    /// HRTF configuration
    pub hrtf: HrtfConfig,
    /// Enable dynamic range compression
    pub compression_enabled: bool,
    /// Compression ratio (1.0 = no compression)
    pub compression_ratio: f32,
    /// Output sample rate
    pub sample_rate: u32,
    /// Buffer size for processing
    pub buffer_size: usize,
}

/// 3D spatial audio configuration
#[derive(Debug, Clone)]
pub struct SpatialAudioConfig {
    /// Enable spatial audio processing
    pub enabled: bool,
    /// Binaural rendering configuration
    pub binaural: BinauralConfig,
    /// Room acoustics simulation
    pub room_acoustics: Option<RoomAcoustics>,
    /// Speed of sound in m/s
    pub speed_of_sound: f32,
    /// Doppler effect strength (0.0-1.0)
    pub doppler_strength: f32,
    /// Distance attenuation model
    pub distance_model: DistanceModel,
    /// Maximum processing distance
    pub max_distance: f32,
}

/// Distance attenuation models
#[derive(Debug, Clone, PartialEq)]
pub enum DistanceModel {
    /// No attenuation
    None,
    /// Linear attenuation
    Linear,
    /// Inverse distance law
    Inverse,
    /// Inverse square law
    InverseSquare,
}

/// Spatial audio processing result
#[derive(Debug, Clone)]
pub struct SpatialAudioResult {
    /// Processed binaural audio
    pub audio: crate::audio::AudioBuffer,
    /// Applied spatial configuration
    pub config: SpatialAudioConfig,
    /// Processing statistics
    pub stats: SpatialAudioStats,
}

/// Processing statistics for spatial audio
#[derive(Debug, Clone)]
pub struct SpatialAudioStats {
    /// Number of active sources
    pub active_sources: usize,
    /// Processing latency in ms
    pub latency_ms: f32,
    /// CPU usage percentage
    pub cpu_usage: f32,
    /// HRTF interpolation quality
    pub hrtf_quality: f32,
}

/// SDK-integrated spatial audio controller
#[derive(Debug, Clone)]
pub struct SpatialAudioController {
    /// Internal spatial audio processor configuration
    config: Arc<RwLock<SpatialAudioConfig>>,
    /// Active audio sources
    sources: Arc<RwLock<Vec<AudioSource3D>>>,
    /// Audio listener
    listener: Arc<RwLock<AudioListener3D>>,
}

impl SpatialAudioController {
    /// Create new spatial audio controller
    pub async fn new() -> Result<Self> {
        Ok(Self {
            config: Arc::new(RwLock::new(SpatialAudioConfig::default())),
            sources: Arc::new(RwLock::new(Vec::new())),
            listener: Arc::new(RwLock::new(AudioListener3D::default())),
        })
    }

    /// Create with custom configuration
    pub async fn with_config(config: SpatialAudioConfig) -> Result<Self> {
        Ok(Self {
            config: Arc::new(RwLock::new(config)),
            sources: Arc::new(RwLock::new(Vec::new())),
            listener: Arc::new(RwLock::new(AudioListener3D::default())),
        })
    }

    /// Set listener position and orientation
    pub async fn set_listener(
        &self,
        position: Position3D,
        orientation: Orientation3D,
    ) -> Result<()> {
        let mut listener = self.listener.write().await;
        listener.position = position;
        listener.orientation = orientation;
        Ok(())
    }

    /// Add audio source at 3D position
    pub async fn add_source(&self, source: AudioSource3D) -> Result<usize> {
        let mut sources = self.sources.write().await;
        sources.push(source);
        Ok(sources.len() - 1) // Return source ID
    }

    /// Update source position
    pub async fn update_source_position(
        &self,
        source_id: usize,
        position: Position3D,
    ) -> Result<()> {
        let mut sources = self.sources.write().await;
        if let Some(source) = sources.get_mut(source_id) {
            source.position = position;
            Ok(())
        } else {
            Err(VoirsError::ConfigError {
                field: "source_id".to_string(),
                message: format!("Source ID {} not found", source_id),
            })
        }
    }

    /// Remove audio source
    pub async fn remove_source(&self, source_id: usize) -> Result<()> {
        let mut sources = self.sources.write().await;
        if source_id < sources.len() {
            sources.remove(source_id);
            Ok(())
        } else {
            Err(VoirsError::ConfigError {
                field: "source_id".to_string(),
                message: format!("Source ID {} not found", source_id),
            })
        }
    }

    /// Process audio with spatial effects
    pub async fn process_spatial_audio(
        &self,
        audio: &crate::audio::AudioBuffer,
    ) -> Result<SpatialAudioResult> {
        let config = self.config.read().await;
        if !config.enabled {
            return Err(VoirsError::ConfigError {
                field: "spatial".to_string(),
                message: "Spatial audio processing is disabled".to_string(),
            });
        }

        let sources = self.sources.read().await;
        let listener = self.listener.read().await;

        // Mock implementation - in reality would use advanced 3D audio processing
        let processed_audio = self
            .render_binaural_audio(audio, &sources, &listener, &config)
            .await?;

        Ok(SpatialAudioResult {
            audio: processed_audio,
            config: config.clone(),
            stats: SpatialAudioStats {
                active_sources: sources.len(),
                latency_ms: 12.0,
                cpu_usage: 15.0,
                hrtf_quality: 0.92,
            },
        })
    }

    /// Set room acoustics parameters
    pub async fn set_room_acoustics(&self, room: RoomAcoustics) -> Result<()> {
        let mut config = self.config.write().await;
        config.room_acoustics = Some(room);
        Ok(())
    }

    /// Set HRTF configuration
    pub async fn set_hrtf_config(&self, hrtf: HrtfConfig) -> Result<()> {
        let mut config = self.config.write().await;
        config.binaural.hrtf = hrtf;
        Ok(())
    }

    /// Enable or disable spatial audio
    pub async fn set_enabled(&self, enabled: bool) -> Result<()> {
        let mut config = self.config.write().await;
        config.enabled = enabled;
        Ok(())
    }

    /// Check if spatial audio is enabled
    pub async fn is_enabled(&self) -> bool {
        let config = self.config.read().await;
        config.enabled
    }

    /// Get current configuration
    pub async fn get_config(&self) -> SpatialAudioConfig {
        self.config.read().await.clone()
    }

    /// Get active sources
    pub async fn get_sources(&self) -> Vec<AudioSource3D> {
        self.sources.read().await.clone()
    }

    /// Get listener configuration
    pub async fn get_listener(&self) -> AudioListener3D {
        self.listener.read().await.clone()
    }

    /// Apply spatial audio preset
    pub async fn apply_preset(&self, preset_name: &str) -> Result<()> {
        let config = match preset_name {
            "gaming" => SpatialAudioConfig {
                enabled: true,
                binaural: BinauralConfig {
                    hrtf: HrtfConfig {
                        dataset: HrtfDataset::Generic,
                        head_circumference: 56.0,
                        interpupillary_distance: 6.4,
                        crossfeed_enabled: false,
                        crossfeed_strength: 0.0,
                    },
                    compression_enabled: true,
                    compression_ratio: 3.0,
                    sample_rate: 44100,
                    buffer_size: 512,
                },
                room_acoustics: None,
                speed_of_sound: 343.0,
                doppler_strength: 0.8,
                distance_model: DistanceModel::InverseSquare,
                max_distance: 100.0,
            },
            "cinema" => SpatialAudioConfig {
                enabled: true,
                binaural: BinauralConfig {
                    hrtf: HrtfConfig {
                        dataset: HrtfDataset::Kemar,
                        head_circumference: 57.0,
                        interpupillary_distance: 6.5,
                        crossfeed_enabled: true,
                        crossfeed_strength: 0.3,
                    },
                    compression_enabled: false,
                    compression_ratio: 1.0,
                    sample_rate: 48000,
                    buffer_size: 1024,
                },
                room_acoustics: Some(RoomAcoustics::default()),
                speed_of_sound: 343.0,
                doppler_strength: 0.6,
                distance_model: DistanceModel::Inverse,
                max_distance: 50.0,
            },
            "vr" => SpatialAudioConfig {
                enabled: true,
                binaural: BinauralConfig {
                    hrtf: HrtfConfig {
                        dataset: HrtfDataset::Cipic,
                        head_circumference: 55.0,
                        interpupillary_distance: 6.2,
                        crossfeed_enabled: false,
                        crossfeed_strength: 0.0,
                    },
                    compression_enabled: true,
                    compression_ratio: 2.0,
                    sample_rate: 48000,
                    buffer_size: 256,
                },
                room_acoustics: Some(RoomAcoustics::default()),
                speed_of_sound: 343.0,
                doppler_strength: 1.0,
                distance_model: DistanceModel::InverseSquare,
                max_distance: 200.0,
            },
            _ => {
                return Err(VoirsError::ConfigError {
                    field: "preset".to_string(),
                    message: format!("Unknown spatial audio preset: {}", preset_name),
                })
            }
        };

        {
            let mut config_guard = self.config.write().await;
            *config_guard = config;
        }

        Ok(())
    }

    /// List available presets
    pub fn list_presets(&self) -> Vec<String> {
        vec!["gaming".to_string(), "cinema".to_string(), "vr".to_string()]
    }

    // Private helper methods

    /// Render binaural audio from sources with HRTF simulation
    async fn render_binaural_audio(
        &self,
        audio: &crate::audio::AudioBuffer,
        sources: &[AudioSource3D],
        listener: &AudioListener3D,
        config: &SpatialAudioConfig,
    ) -> Result<crate::audio::AudioBuffer> {
        // Create stereo output (binaural)
        let mono_samples = audio.samples();
        let sample_count = mono_samples.len();

        let mut left_channel = vec![0.0f32; sample_count];
        let mut right_channel = vec![0.0f32; sample_count];

        // Process each source with spatial audio
        for source in sources {
            let distance = self.calculate_distance(&source.position, &listener.position);
            let attenuation = self.calculate_attenuation(distance, &config.distance_model);

            // Calculate azimuth and elevation for HRTF
            let (azimuth, elevation) = self.calculate_direction(&source.position, listener);

            // Apply HRTF-based panning and filtering
            let (left_gain, right_gain, left_delay, right_delay) =
                self.calculate_hrtf_parameters(azimuth, elevation, &config.binaural.hrtf);

            // Apply spatializationto each sample
            for (i, &sample) in mono_samples.iter().enumerate() {
                let spatialized_sample = sample * attenuation * source.volume;

                // Apply ITD (Interaural Time Difference) through delay
                let left_idx = i.saturating_sub(left_delay);
                let right_idx = i.saturating_sub(right_delay);

                if left_idx < sample_count {
                    left_channel[left_idx] += spatialized_sample * left_gain;
                }
                if right_idx < sample_count {
                    right_channel[right_idx] += spatialized_sample * right_gain;
                }
            }
        }

        // Apply crossfeed if enabled (for headphone listening)
        if config.binaural.hrtf.crossfeed_enabled {
            self.apply_crossfeed(
                &mut left_channel,
                &mut right_channel,
                config.binaural.hrtf.crossfeed_strength,
            );
        }

        // Interleave stereo channels
        let mut stereo_samples = Vec::with_capacity(sample_count * 2);
        for i in 0..sample_count {
            stereo_samples.push(left_channel[i].clamp(-1.0, 1.0));
            stereo_samples.push(right_channel[i].clamp(-1.0, 1.0));
        }

        Ok(crate::audio::AudioBuffer::new(
            stereo_samples,
            audio.sample_rate(),
            2, // stereo
        ))
    }

    /// Calculate distance between two points
    fn calculate_distance(&self, pos1: &Position3D, pos2: &Position3D) -> f32 {
        let dx = pos1.x - pos2.x;
        let dy = pos1.y - pos2.y;
        let dz = pos1.z - pos2.z;
        (dx * dx + dy * dy + dz * dz).sqrt()
    }

    /// Calculate attenuation based on distance model
    fn calculate_attenuation(&self, distance: f32, model: &DistanceModel) -> f32 {
        match model {
            DistanceModel::None => 1.0,
            DistanceModel::Linear => (1.0 - distance / 100.0).max(0.0),
            DistanceModel::Inverse => 1.0 / (1.0 + distance),
            DistanceModel::InverseSquare => 1.0 / (1.0 + distance * distance),
        }
    }

    /// Calculate direction from listener to source (azimuth and elevation in radians)
    fn calculate_direction(
        &self,
        source_pos: &Position3D,
        listener: &AudioListener3D,
    ) -> (f32, f32) {
        use std::f32::consts::PI;

        // Calculate relative position
        let dx = source_pos.x - listener.position.x;
        let dy = source_pos.y - listener.position.y;
        let dz = source_pos.z - listener.position.z;

        // Rotate relative position by listener orientation (yaw is horizontal rotation)
        let forward_angle = listener.orientation.yaw;
        let rotated_x = dx * forward_angle.cos() - dz * forward_angle.sin();
        let rotated_z = dx * forward_angle.sin() + dz * forward_angle.cos();

        // Calculate azimuth (horizontal angle)
        let azimuth = rotated_z.atan2(rotated_x);

        // Calculate elevation (vertical angle)
        let horizontal_dist = (rotated_x * rotated_x + rotated_z * rotated_z).sqrt();
        let elevation = dy.atan2(horizontal_dist);

        (azimuth, elevation)
    }

    /// Calculate HRTF parameters based on direction
    fn calculate_hrtf_parameters(
        &self,
        azimuth: f32,
        elevation: f32,
        hrtf_config: &HrtfConfig,
    ) -> (f32, f32, usize, usize) {
        use std::f32::consts::PI;

        // Simplified HRTF model based on spherical head approximation
        let head_radius = hrtf_config.head_circumference / (2.0 * PI);

        // Calculate ILD (Interaural Level Difference)
        // Source on the left (-Ï€/2) will be louder in left ear
        let azimuth_normalized = azimuth / PI; // Normalize to -1 to 1
        let left_gain = (0.5 + 0.5 * (-azimuth_normalized)).powf(0.7); // Smoother curve
        let right_gain = (0.5 + 0.5 * azimuth_normalized).powf(0.7);

        // Elevation affects both ears similarly (reduces overall level)
        let elevation_factor = (1.0 - elevation.abs() / (PI / 2.0)) * 0.5 + 0.5;
        let left_gain = left_gain * elevation_factor;
        let right_gain = right_gain * elevation_factor;

        // Calculate ITD (Interaural Time Difference) in samples at 44.1kHz
        // Maximum ITD is about 0.66ms (29 samples at 44.1kHz)
        let speed_of_sound = 343.0; // m/s
        let max_itd_seconds = head_radius / speed_of_sound * 3.0; // Woodworth formula approximation
        let max_itd_samples = (max_itd_seconds * 44100.0) as usize;

        let itd = (azimuth.sin() * max_itd_samples as f32) as i32;
        let (left_delay, right_delay) = if itd > 0 {
            (0, itd as usize) // Sound from right reaches right ear first
        } else {
            ((-itd) as usize, 0) // Sound from left reaches left ear first
        };

        (left_gain, right_gain, left_delay, right_delay)
    }

    /// Apply crossfeed for natural headphone listening
    fn apply_crossfeed(&self, left: &mut [f32], right: &mut [f32], strength: f32) {
        let crossfeed_gain = strength * 0.3;
        let delay_samples = 4; // Small delay for crossfeed

        for i in delay_samples..left.len() {
            let left_original = left[i];
            let right_original = right[i];

            // Mix delayed opposite channel
            left[i] += right[i - delay_samples] * crossfeed_gain;
            right[i] += left_original * crossfeed_gain;
        }
    }
}

/// Builder for spatial audio controller configuration
#[derive(Debug, Clone)]
pub struct SpatialAudioControllerBuilder {
    config: SpatialAudioConfig,
}

impl SpatialAudioControllerBuilder {
    /// Create new builder
    pub fn new() -> Self {
        Self {
            config: SpatialAudioConfig::default(),
        }
    }

    /// Enable or disable spatial audio
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    /// Set HRTF configuration
    pub fn hrtf_config(mut self, hrtf: HrtfConfig) -> Self {
        self.config.binaural.hrtf = hrtf;
        self
    }

    /// Set room acoustics
    pub fn room_acoustics(mut self, room: RoomAcoustics) -> Self {
        self.config.room_acoustics = Some(room);
        self
    }

    /// Set distance model
    pub fn distance_model(mut self, model: DistanceModel) -> Self {
        self.config.distance_model = model;
        self
    }

    /// Set Doppler effect strength
    pub fn doppler_strength(mut self, strength: f32) -> Self {
        self.config.doppler_strength = strength.clamp(0.0, 1.0);
        self
    }

    /// Set maximum processing distance
    pub fn max_distance(mut self, distance: f32) -> Self {
        self.config.max_distance = distance;
        self
    }

    /// Build the spatial audio controller
    pub async fn build(self) -> Result<SpatialAudioController> {
        let controller = SpatialAudioController::with_config(self.config).await?;
        Ok(controller)
    }
}

impl Default for SpatialAudioControllerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for SpatialAudioConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            binaural: BinauralConfig::default(),
            room_acoustics: None,
            speed_of_sound: 343.0,
            doppler_strength: 0.5,
            distance_model: DistanceModel::InverseSquare,
            max_distance: 100.0,
        }
    }
}

impl Default for BinauralConfig {
    fn default() -> Self {
        Self {
            hrtf: HrtfConfig::default(),
            compression_enabled: false,
            compression_ratio: 1.0,
            sample_rate: 44100,
            buffer_size: 512,
        }
    }
}

impl Default for HrtfConfig {
    fn default() -> Self {
        Self {
            dataset: HrtfDataset::Generic,
            head_circumference: 56.0,
            interpupillary_distance: 6.4,
            crossfeed_enabled: false,
            crossfeed_strength: 0.0,
        }
    }
}

impl Default for RoomAcoustics {
    fn default() -> Self {
        Self {
            dimensions: Position3D {
                x: 10.0,
                y: 3.0,
                z: 8.0,
            },
            absorption: FrequencyResponse {
                frequencies: vec![125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0],
                responses: vec![0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4],
            },
            reverb_time: 0.5,
            early_reflections_delay: 20.0,
            diffusion: 0.7,
        }
    }
}

impl Default for Position3D {
    fn default() -> Self {
        Self {
            x: 0.0,
            y: 0.0,
            z: 0.0,
        }
    }
}

impl Default for Orientation3D {
    fn default() -> Self {
        Self {
            yaw: 0.0,
            pitch: 0.0,
            roll: 0.0,
        }
    }
}

impl Default for Velocity3D {
    fn default() -> Self {
        Self {
            x: 0.0,
            y: 0.0,
            z: 0.0,
        }
    }
}

impl Default for AudioListener3D {
    fn default() -> Self {
        Self {
            position: Position3D::default(),
            orientation: Orientation3D::default(),
            velocity: Velocity3D::default(),
        }
    }
}

impl Position3D {
    /// Create new position
    pub fn new(x: f32, y: f32, z: f32) -> Self {
        Self { x, y, z }
    }

    /// Origin position
    pub fn origin() -> Self {
        Self::default()
    }
}

impl Orientation3D {
    /// Create new orientation
    pub fn new(yaw: f32, pitch: f32, roll: f32) -> Self {
        Self { yaw, pitch, roll }
    }

    /// Identity orientation
    pub fn identity() -> Self {
        Self::default()
    }
}

impl AudioSource3D {
    /// Create new audio source
    pub fn new(position: Position3D, volume: f32) -> Self {
        Self {
            position,
            orientation: Orientation3D::default(),
            velocity: Velocity3D::default(),
            volume: volume.clamp(0.0, 1.0),
            directivity: DirectivityPattern::Omnidirectional,
        }
    }

    /// Set directivity pattern
    pub fn with_directivity(mut self, pattern: DirectivityPattern) -> Self {
        self.directivity = pattern;
        self
    }

    /// Set velocity for Doppler effect
    pub fn with_velocity(mut self, velocity: Velocity3D) -> Self {
        self.velocity = velocity;
        self
    }
}

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

    #[tokio::test]
    async fn test_spatial_audio_controller_creation() {
        let controller = SpatialAudioController::new().await.unwrap();
        assert!(controller.is_enabled().await);
    }

    #[tokio::test]
    async fn test_listener_positioning() {
        let controller = SpatialAudioController::new().await.unwrap();
        let position = Position3D::new(1.0, 2.0, 3.0);
        let orientation = Orientation3D::new(0.5, 0.0, 0.0);

        controller
            .set_listener(position.clone(), orientation.clone())
            .await
            .unwrap();

        let listener = controller.get_listener().await;
        assert_eq!(listener.position, position);
        assert_eq!(listener.orientation, orientation);
    }

    #[tokio::test]
    async fn test_source_management() {
        let controller = SpatialAudioController::new().await.unwrap();
        let source = AudioSource3D::new(Position3D::new(5.0, 0.0, 0.0), 0.8);

        let source_id = controller.add_source(source).await.unwrap();
        assert_eq!(source_id, 0);

        let sources = controller.get_sources().await;
        assert_eq!(sources.len(), 1);
        assert_eq!(sources[0].volume, 0.8);

        controller.remove_source(source_id).await.unwrap();
        let sources = controller.get_sources().await;
        assert_eq!(sources.len(), 0);
    }

    #[tokio::test]
    async fn test_preset_application() {
        let controller = SpatialAudioController::new().await.unwrap();
        controller.apply_preset("gaming").await.unwrap();

        let config = controller.get_config().await;
        assert_eq!(config.distance_model, DistanceModel::InverseSquare);
        assert_eq!(config.doppler_strength, 0.8);
    }

    #[tokio::test]
    async fn test_spatial_audio_builder() {
        let controller = SpatialAudioControllerBuilder::new()
            .enabled(true)
            .doppler_strength(0.7)
            .max_distance(150.0)
            .distance_model(DistanceModel::Inverse)
            .build()
            .await
            .unwrap();

        assert!(controller.is_enabled().await);
        let config = controller.get_config().await;
        assert_eq!(config.doppler_strength, 0.7);
        assert_eq!(config.max_distance, 150.0);
        assert_eq!(config.distance_model, DistanceModel::Inverse);
    }

    #[tokio::test]
    async fn test_position_distance_calculation() {
        let controller = SpatialAudioController::new().await.unwrap();
        let pos1 = Position3D::new(0.0, 0.0, 0.0);
        let pos2 = Position3D::new(3.0, 4.0, 0.0);

        let distance = controller.calculate_distance(&pos1, &pos2);
        assert!((distance - 5.0).abs() < 0.001);
    }

    #[tokio::test]
    async fn test_room_acoustics() {
        let controller = SpatialAudioController::new().await.unwrap();
        let room = RoomAcoustics::default();

        controller.set_room_acoustics(room.clone()).await.unwrap();

        let config = controller.get_config().await;
        assert!(config.room_acoustics.is_some());
        assert_eq!(config.room_acoustics.unwrap().reverb_time, 0.5);
    }

    #[tokio::test]
    async fn test_preset_listing() {
        let controller = SpatialAudioController::new().await.unwrap();
        let presets = controller.list_presets();
        assert!(presets.contains(&"gaming".to_string()));
        assert!(presets.contains(&"cinema".to_string()));
        assert!(presets.contains(&"vr".to_string()));
    }
}